Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor(agent): migrate agent plugin from Vue to React (#19841)

p0nyf5fd922fcec1
diff --git a/docs/plans/2026-04-03-agent-plugin-react-migration-design.md b/docs/plans/2026-04-03-agent-plugin-react-migration-design.md
new file mode 100644
index 0000000000..1879055d80
--- /dev/null
+++ b/docs/plans/2026-04-03-agent-plugin-react-migration-design.md
@@ -0,0 +1,124 @@
+# Agent Plugin React Migration Design
+
+## Goal
+
+Migrate the agent plugin (`frontend/src/plugins/agent/`) from Vue to React. This is a pattern-setting migration — decisions here establish conventions for future Vue-to-React work.
+
+## Current State
+
+- ~7,000 LOC across 22+ files
+- Floating AI chat window with tool execution, DOM interaction, multi-chat persistence
+- ~50% of code (logic/, dom/, skills/) is framework-agnostic TypeScript
+
+## Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| State management | Zustand | Lightweight, similar to Pinia, minimal boilerplate |
+| Floating window | Custom pointer events | Vue version already has the logic (~150 lines), no new dep |
+| @-mention autocomplete | shadcn Combobox | Consistent with component library, handles filtered list + popover |
+| Markdown rendering | react-markdown + remark-gfm | Standard React solution, replaces custom AST-to-VNode pipeline |
+| Table library | None (shadcn Table if needed) | Server-side sort/pagination via Connect RPC, tanstack adds little |
+
+## Architecture
+
+```
+frontend/src/react/plugins/agent/
+├── index.ts # Export AgentWindow + useAgentShortcut
+├── store/
+│ └── agent.ts # Zustand store (replaces Pinia store)
+├── components/
+│ ├── AgentWindow.tsx # Floating panel: drag, resize, minimize, portal
+│ ├── AgentChat.tsx # Message list + react-markdown
+│ ├── AgentInput.tsx # Input with @-mention via shadcn Combobox
+│ └── ToolCallCard.tsx # Collapsible tool call/result display
+├── logic/ # COPIED AS-IS from Vue version
+│ ├── types.ts
+│ ├── prompt.ts
+│ ├── context.ts # Reads Pinia stores directly (singletons)
+│ ├── agentLoop.ts
+│ ├── outboundHistory.ts
+│ ├── aiConfiguration.ts
+│ ├── tools/ # All tool files copied; navigate.ts imports Vue router singleton
+│ └── skills/ # All skill files copied unchanged
+└── dom/ # COPIED AS-IS (pure DOM APIs)
+ ├── index.ts
+ ├── domTree.ts
+ └── actions.ts
+```
+
+## Store Design (Zustand)
+
+Three concerns, same as current Pinia store:
+
+**UI state** — `visible`, `minimized`, `position`, `size`, `sidebarWidth`
+- Persisted to localStorage key `bb-agent-window`
+
+**Chat state** — `chats`, `messagesByChatId`, `pendingAskByChatId`, `currentChatId`
+- Persisted to localStorage key `bb-agent-state-v2`
+- Normalized structure (chats and messages stored separately)
+
+**Runtime state** — `abortControllersByChatId`, derived `loading`/`error`/`runningChatIds`
+- Not persisted
+
+Zustand `persist` middleware handles the two localStorage keys. Derived values become inline selectors or helper functions.
+
+## Component Design
+
+### AgentWindow.tsx
+- `createPortal(document.body)` replaces Vue `<Teleport>`
+- Drag: `onPointerDown` on header, track delta in `useRef`, update store on `pointermove`
+- Resize: Same pattern on SE corner handle
+- Sidebar resize: Same pattern on vertical divider
+- Viewport clamping: `useEffect` on window `resize` event
+- Minimized: Floating button (bottom-right) instead of full panel
+- Layout: flex row — sidebar (chat list) + main area
+
+### AgentChat.tsx
+- `react-markdown` with `remarkGfm` plugin
+- Auto-scroll via `useEffect` + `scrollIntoView` on message count change
+- shadcn `Button` for retry/interrupt, `ScrollArea` for container
+
+### AgentInput.tsx
+- shadcn `Textarea` for message input
+- On `@` keystroke, open shadcn `Combobox` popover with DOM ref suggestions
+- Selecting inserts `[eN]` ref into textarea
+- Pending ask states render different UIs: text input, Yes/No buttons, radio choices
+- Enter to send, Shift+Enter for newline
+
+### ToolCallCard.tsx
+- shadcn `Collapsible`: header = tool name + status, body = pretty-printed JSON
+- Status indicators: spinner while running, check/x on complete
+
+## Integration & Coexistence
+
+| Bridge Point | Approach |
+|-------------|----------|
+| Mount in Vue app | `AgentWindowMount.vue` — thin wrapper that mounts React root, placed in `BodyLayout.vue` |
+| Pinia stores in `context.ts` | Import directly — they're singletons, callable outside Vue |
+| Vue Router in `navigate.ts` | Import router instance directly — singleton |
+| i18n | `react-i18next` with same locale JSON files |
+| Zustand from Vue | `useAgentStore.getState().toggle()` for keyboard shortcut |
+
+Clean swap: delete Vue version once React version is mounted. No gradual coexistence needed — no other Vue components depend on the agent plugin.
+
+## Dependencies to Add
+
+- `zustand`
+- `react-markdown` + `remark-gfm`
+
+## Migration Order
+
+1. **Store** — Zustand store, unit tests, verify localStorage backward compat
+2. **ToolCallCard** — Simplest component, validates React + shadcn pipeline
+3. **AgentChat** — Message list with react-markdown
+4. **AgentInput** — Combobox @-mention (most complex UI)
+5. **AgentWindow** — Shell with drag/resize/portal
+6. **Integration** — AgentWindowMount.vue, swap in BodyLayout, delete Vue version
+
+## What We're NOT Changing
+
+- No backend changes
+- No changes to agent loop, tools, skills, or DOM interaction layer
+- No changes to localStorage schema (existing chat history carries over)
+- No UX redesign — functional port of current behavior
diff --git a/docs/plans/2026-04-03-agent-plugin-react-migration.md b/docs/plans/2026-04-03-agent-plugin-react-migration.md
new file mode 100644
index 0000000000..e874e29319
--- /dev/null
+++ b/docs/plans/2026-04-03-agent-plugin-react-migration.md
@@ -0,0 +1,922 @@
+# Agent Plugin React Migration — Implementation Plan
+
+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
+
+**Goal:** Migrate the agent plugin from Vue to React, establishing patterns for the broader Vue-to-React migration.
+
+**Architecture:** Copy logic/dom/skills layers unchanged (~3,400 LOC). Rewrite store as Zustand (~886 LOC). Rewrite 4 components in React with shadcn UI. Mount via a thin Vue wrapper in BodyLayout, then delete the Vue version.
+
+**Tech Stack:** React 19, Zustand, react-markdown + remark-gfm, shadcn (Button, Combobox, Textarea, Input, Dialog), Tailwind CSS v4
+
+---
+
+### Task 1: Install Dependencies
+
+**Files:**
+- Modify: `frontend/package.json`
+
+**Step 1: Add zustand and react-markdown**
+
+```bash
+cd frontend && pnpm add zustand react-markdown
+```
+
+`remark-gfm` is already a devDependency.
+
+**Step 2: Verify installation**
+
+```bash
+cd frontend && pnpm list zustand react-markdown remark-gfm
+```
+
+Expected: All three listed with versions.
+
+**Step 3: Commit**
+
+```bash
+git add frontend/package.json frontend/pnpm-lock.yaml
+git commit -m "deps: add zustand and react-markdown for agent plugin React migration"
+```
+
+---
+
+### Task 2: Copy Logic/DOM/Skills Layers
+
+**Files:**
+- Copy: `frontend/src/plugins/agent/logic/` → `frontend/src/react/plugins/agent/logic/`
+- Copy: `frontend/src/plugins/agent/dom/` → `frontend/src/react/plugins/agent/dom/`
+
+These layers are framework-agnostic TypeScript. Copy as-is, no modifications.
+
+**Step 1: Copy the files**
+
+```bash
+mkdir -p frontend/src/react/plugins/agent
+cp -r frontend/src/plugins/agent/logic frontend/src/react/plugins/agent/logic
+cp -r frontend/src/plugins/agent/dom frontend/src/react/plugins/agent/dom
+```
+
+**Step 2: Fix import paths**
+
+The logic layer imports from `../logic/types` etc. which remain valid. However, `logic/context.ts` imports Pinia stores via `@/store/modules/v1/...` and `logic/tools/navigate.ts` imports `@/router`. These paths resolve the same way since `@/` maps to `frontend/src/` in both Vue and React tsconfig. No changes needed.
+
+Verify no broken imports:
+
+```bash
+cd frontend && pnpm type-check 2>&1 | grep 'react/plugins/agent' | head -20
+```
+
+If type errors appear from Vue-specific imports in `context.ts`, they will be caught by `tsconfig.react.json` — but since these files import from `@/store` (plain TS/Pinia singletons) and `@/router` (plain TS), they should work. If `context.ts` causes issues because it imports Vue `computed`/`ref`, we'll address in Task 3.
+
+**Step 3: Run existing logic tests to verify nothing broke**
+
+```bash
+cd frontend && pnpm vitest run src/plugins/agent/logic/ --reporter=verbose 2>&1 | tail -20
+```
+
+Expected: All tests pass (these test the original files, confirming the logic layer works).
+
+**Step 4: Commit**
+
+```bash
+git add frontend/src/react/plugins/agent/logic frontend/src/react/plugins/agent/dom
+git commit -m "feat(agent): copy framework-agnostic logic and dom layers for React migration"
+```
+
+---
+
+### Task 3: Create Zustand Store
+
+**Files:**
+- Create: `frontend/src/react/plugins/agent/store/agent.ts`
+- Create: `frontend/src/react/plugins/agent/store/agent.test.ts`
+
+This is a port of the Pinia store at `frontend/src/plugins/agent/store/agent.ts` (886 lines).
+
+**Step 1: Write the store test**
+
+Port the test from `frontend/src/plugins/agent/store/agent.test.ts`. Replace `createPinia`/`setActivePinia` with direct Zustand store creation. The test structure stays the same — same assertions, same mock localStorage.
+
+Key changes from the Pinia test:
+- Replace `setActivePinia(createPinia()); useAgentStore()` with `useAgentStore.getState()` or create a fresh store per test
+- Zustand stores are singletons — use `useAgentStore.setState()` to reset between tests, or use `createStore` from zustand for test isolation
+- Replace `await nextTick()` (Vue reactivity flush) — Zustand updates are synchronous, so remove `nextTick()` calls
+- The deep watch auto-save (`watch([chats, ...], saveState, { deep: true })`) becomes a Zustand `subscribe` call in the store
+
+Test file skeleton:
+
+```typescript
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { createAgentStore, AGENT_STATE_KEY, AGENT_WINDOW_KEY } from "./agent";
+
+// Same createMockStorage helper as original test
+
+describe("useAgentStore (Zustand)", () => {
+ let store: ReturnType<typeof createAgentStore>;
+
+ beforeEach(() => {
+ mockStorage = createMockStorage();
+ vi.stubGlobal("localStorage", mockStorage);
+ store = createAgentStore(); // fresh store per test
+ });
+
+ test("creates a default chat when no persisted state exists", () => {
+ const state = store.getState();
+ expect(state.chats).toHaveLength(1);
+ expect(state.currentChatId).toBe(state.chats[0].id);
+ });
+
+ // ... port all 20 tests from original
+});
+```
+
+**Step 2: Run test to verify it fails**
+
+```bash
+cd frontend && pnpm vitest run src/react/plugins/agent/store/agent.test.ts --reporter=verbose 2>&1 | tail -20
+```
+
+Expected: FAIL — store module doesn't exist yet.
+
+**Step 3: Write the Zustand store**
+
+Port `frontend/src/plugins/agent/store/agent.ts`. Key mapping:
+
+| Pinia pattern | Zustand pattern |
+|---------------|----------------|
+| `defineStore("agent", () => { ... })` | `create<AgentState>()((set, get) => ({ ... }))` |
+| `ref(false)` | Direct property: `visible: false` |
+| `computed(() => ...)` | Not stored — use selectors or derive in `get()` |
+| `watch([...], saveState, { deep: true })` | `subscribe` with shallow equality + `JSON.stringify` diff |
+| `const chat = getChat(chatId); chat.status = "running"` | `set(state => { const chat = state.chats.find(...); return { chats: state.chats.map(c => c.id === chatId ? { ...c, status: "running" } : c) }; })` |
+
+Important: The Pinia store mutates objects directly (e.g., `chat.status = "running"`). Zustand requires immutable updates. Use immer middleware OR manual spread operators.
+
+**Recommendation: Use `zustand/middleware/immer`** — the store has many direct mutations, and immer makes the port nearly 1:1. This avoids rewriting every mutation to use spread operators.
+
+```bash
+cd frontend && pnpm add immer
+```
+
+Store skeleton:
+
+```typescript
+import { create } from "zustand";
+import { persist } from "zustand/middleware";
+import { immer } from "zustand/middleware/immer";
+import { v4 as uuidv4 } from "uuid";
+
+// Import types from copied logic layer
+import type { AgentChat, AgentMessage, AgentPendingAsk, ... } from "../logic/types";
+
+// Copy helper functions as-is: createChatRecord, normalizePersistedState, etc.
+// These are pure functions and work unchanged.
+
+export const AGENT_STATE_KEY = "bb-agent-state-v2";
+export const AGENT_WINDOW_KEY = "bb-agent-window";
+
+interface AgentState {
+ // UI state
+ visible: boolean;
+ minimized: boolean;
+ position: { x: number; y: number };
+ size: { width: number; height: number };
+ sidebarWidth: number;
+
+ // Chat state
+ chats: AgentChat[];
+ messagesByChatId: Record<string, AgentMessage[]>;
+ pendingAskByChatId: Record<string, AgentPendingAsk>;
+ currentChatId: string | null;
+
+ // Runtime (not persisted)
+ abortControllersByChatId: Record<string, AbortController>;
+
+ // Actions — same signatures as Pinia store
+ toggle: () => void;
+ minimize: () => void;
+ restore: () => void;
+ getChat: (chatId?: string | null) => AgentChat | null;
+ getMessages: (chatId?: string | null) => AgentMessage[];
+ // ... all 36 actions from Pinia store
+}
+
+// Export both hook (for React) and vanilla (for non-React callers like Vue shortcut)
+export const useAgentStore = create<AgentState>()(
+ immer((set, get) => {
+ // Load persisted state on creation
+ const persisted = loadPersistedState();
+
+ return {
+ visible: false,
+ minimized: false,
+ position: { x: window.innerWidth - 420, y: window.innerHeight - 520 },
+ size: { width: 400, height: 500 },
+ sidebarWidth: 256,
+
+ chats: persisted.chats,
+ messagesByChatId: persisted.messagesByChatId,
+ pendingAskByChatId: persisted.pendingAskByChatId,
+ currentChatId: persisted.currentChatId,
+ abortControllersByChatId: {},
+
+ toggle() {
+ set(state => {
+ state.visible = !state.visible;
+ if (state.visible) state.minimized = false;
+ });
+ },
+
+ // ... port all actions, using immer's mutable syntax
+ // Most actions can be ported nearly verbatim since immer allows mutation
+ };
+ })
+);
+
+// Derived selectors (replace Pinia computed)
+export const selectOrderedChats = (state: AgentState) =>
+ [...state.chats].sort((a, b) => b.updatedTs - a.updatedTs || b.createdTs - a.createdTs);
+
+export const selectCurrentChat = (state: AgentState) =>
+ state.chats.find(c => c.id === state.currentChatId) ?? null;
+
+export const selectMessages = (state: AgentState) =>
+ (state.currentChatId ? state.messagesByChatId[state.currentChatId] : undefined) ?? [];
+
+export const selectLoading = (state: AgentState) =>
+ selectCurrentChat(state)?.status === "running";
+
+// ... etc.
+
+// Subscribe for auto-persistence (replaces deep watch)
+useAgentStore.subscribe((state) => {
+ localStorage.setItem(AGENT_STATE_KEY, JSON.stringify({
+ currentChatId: state.currentChatId,
+ chats: state.chats,
+ messagesByChatId: state.messagesByChatId,
+ pendingAskByChatId: state.pendingAskByChatId,
+ }));
+});
+```
+
+For test isolation, export a `createAgentStore` factory function that creates a fresh store instance (not a singleton). The singleton `useAgentStore` calls `createAgentStore` internally. Tests use the factory directly.
+
+**Step 4: Run tests**
+
+```bash
+cd frontend && pnpm vitest run src/react/plugins/agent/store/agent.test.ts --reporter=verbose 2>&1 | tail -30
+```
+
+Expected: All 20 tests pass.
+
+**Step 5: Commit**
+
+```bash
+git add frontend/src/react/plugins/agent/store/
+git commit -m "feat(agent): add Zustand store for React agent plugin"
+```
+
+---
+
+### Task 4: Create ToolCallCard Component
+
+**Files:**
+- Create: `frontend/src/react/plugins/agent/components/ToolCallCard.tsx`
+
+Simplest component. Port from `frontend/src/plugins/agent/components/ToolCallCard.vue` (275 lines).
+
+**Step 1: Write the component**
+
+Direct port. Replace:
+- `<script setup>` → function component
+- `defineProps<{ toolCall, result }>` → `{ toolCall, result }: Props`
+- `ref(false)` → `useState(false)`
+- `computed(() => ...)` → `useMemo(() => ..., [deps])`
+- `v-if` / `v-for` → JSX conditionals / `.map()`
+- `$t(...)` → `t(...)` from `useTranslation()`
+- All template markup stays nearly identical (Tailwind classes are the same)
+
+No shadcn components needed — this is pure Tailwind + native HTML.
+
+The helper functions (`parseJson`, `formatJson`, `parseAskUserOption`) are pure functions — copy verbatim.
+
+```typescript
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { AgentAskUserOption, AgentAskUserResponse, ToolCall } from "../logic/types";
+
+interface ToolCallCardProps {
+ toolCall: ToolCall;
+ result?: string;
+}
+
+// Copy parseJson, formatJson, parseAskUserOption as-is
+
+export function ToolCallCard({ toolCall, result }: ToolCallCardProps) {
+ const { t } = useTranslation();
+ const [expanded, setExpanded] = useState(false);
+
+ const parsedArguments = useMemo(() => parseJson(toolCall.arguments), [toolCall.arguments]);
+ const parsedResult = useMemo(() => parseJson(result ?? ""), [result]);
+ const isAskUser = toolCall.name === "ask_user";
+ const isDone = toolCall.name === "done";
+ // ... derive askPrompt, askKind, etc. same as Vue version
+
+ return (
+ <div className="rounded border bg-gray-50 text-xs">
+ <div
+ className="flex cursor-pointer items-center gap-x-2 px-2 py-1.5"
+ onClick={() => setExpanded(!expanded)}
+ >
+ {/* Same markup as Vue template, using JSX */}
+ </div>
+ {expanded && (
+ <div className="space-y-1 border-t px-2 py-1.5">
+ {/* Same conditional sections */}
+ </div>
+ )}
+ </div>
+ );
+}
+```
+
+**Step 2: Type check**
+
+```bash
+cd frontend && pnpm type-check 2>&1 | grep -i error | head -10
+```
+
+Expected: No errors related to ToolCallCard.
+
+**Step 3: Commit**
+
+```bash
+git add frontend/src/react/plugins/agent/components/ToolCallCard.tsx
+git commit -m "feat(agent): add ToolCallCard React component"
+```
+
+---
+
+### Task 5: Create AgentChat Component
+
+**Files:**
+- Create: `frontend/src/react/plugins/agent/components/AgentChat.tsx`
+
+Port from `frontend/src/plugins/agent/components/AgentChat.vue` (198 lines).
+
+**Step 1: Write the component**
+
+Key changes from Vue version:
+- Replace `unified().use(remarkParse).use(remarkGfm)` + custom `AstToMarkdown` with `react-markdown` + `remarkGfm` plugin — this eliminates the entire markdown pipeline
+- Replace `NButton` with shadcn `Button`
+- Replace `watch([currentChatId, messages.length], ...)` with `useEffect` + `scrollIntoView`
+- Replace `useRouter().push()` with direct Vue router import (singleton) during coexistence
+
+```typescript
+import { useEffect, useMemo, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import { Button } from "@/react/components/ui/button";
+import router from "@/router"; // Vue router singleton
+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
+import { hasWorkspacePermissionV2 } from "@/utils";
+import type { AgentMessage } from "../logic/types";
+import {
+ useAgentStore,
+ selectCurrentChat,
+ selectMessages,
+ selectLoading,
+} from "../store/agent";
+import { ToolCallCard } from "./ToolCallCard";
+
+export function AgentChat({ className }: { className?: string }) {
+ const { t } = useTranslation();
+ const chatContainerRef = useRef<HTMLDivElement>(null);
+
+ // Zustand selectors
+ const messages = useAgentStore(selectMessages);
+ const loading = useAgentStore(selectLoading);
+ const currentChatId = useAgentStore(s => s.currentChatId);
+ const currentChat = useAgentStore(selectCurrentChat);
+ const clearError = useAgentStore(s => s.clearError);
+
+ const requiresAIConfiguration = currentChat?.requiresAIConfiguration ?? false;
+ const error = currentChat?.lastError ?? null;
+ const allowConfigure = hasWorkspacePermissionV2("bb.settings.set");
+
+ const displayMessages = useMemo(
+ () => messages.filter((m): m is AgentMessage => m.role === "user" || m.role === "assistant"),
+ [messages]
+ );
+
+ // Auto-scroll
+ useEffect(() => {
+ if (chatContainerRef.current) {
+ chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
+ }
+ }, [currentChatId, messages.length]);
+
+ function getToolResult(messageId: string, toolCallId: string): string | undefined {
+ // Same logic as Vue version, reading from messages array
+ const fullIndex = messages.findIndex(m => m.id === messageId);
+ if (fullIndex < 0) return undefined;
+ for (let i = fullIndex + 1; i < messages.length; i++) {
+ const m = messages[i];
+ if (m.role === "tool" && m.toolCallId === toolCallId) return m.content;
+ if (m.role === "assistant" && m.content && !m.toolCalls?.length) break;
+ }
+ return undefined;
+ }
+
+ function goConfigure() {
+ clearError(currentChatId);
+ router.push({ name: SETTING_ROUTE_WORKSPACE_GENERAL, hash: "#ai-assistant" });
+ }
+
+ return (
+ <div ref={chatContainerRef} className={cn("overflow-y-auto space-y-3 p-3", className)}>
+ {displayMessages.map(msg => (
+ msg.role === "user" ? (
+ <div key={msg.id} className="flex justify-end">
+ <div className="max-w-[80%] rounded-lg bg-blue-50 px-3 py-2 text-sm">{msg.content}</div>
+ </div>
+ ) : (
+ <div key={msg.id} className="flex flex-col gap-y-2">
+ {msg.content && (
+ <div className="max-w-[80%] rounded-lg bg-gray-50 px-3 py-2 text-sm markdown-content">
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{msg.content}</ReactMarkdown>
+ </div>
+ )}
+ {msg.toolCalls?.map(tc => (
+ <ToolCallCard key={tc.id} toolCall={tc} result={getToolResult(msg.id, tc.id)} />
+ ))}
+ </div>
+ )
+ ))}
+ {loading && (
+ <div className="flex items-center gap-x-2 text-sm text-gray-400">
+ <span className="animate-pulse">&#9679;</span> {t("common.loading")}
+ </div>
+ )}
+ {/* AI configuration recovery and error display — same markup */}
+ </div>
+ );
+}
+```
+
+**Markdown CSS:** The Vue version uses scoped `:deep()` selectors for markdown styling. In React, use a CSS module or add global styles. Since the project uses Tailwind, use `@apply` in a CSS file or use the `components` prop on `ReactMarkdown` for inline styling.
+
+Simplest approach: Add a `markdown-content` class to `frontend/src/assets/css/tailwind.css` with the same `@apply` rules, or use ReactMarkdown's `components` prop to apply Tailwind classes to each element type.
+
+**Step 2: Type check**
+
+```bash
+cd frontend && pnpm type-check 2>&1 | grep -i error | head -10
+```
+
+**Step 3: Commit**
+
+```bash
+git add frontend/src/react/plugins/agent/components/AgentChat.tsx
+git commit -m "feat(agent): add AgentChat React component with react-markdown"
+```
+
+---
+
+### Task 6: Create AgentInput Component
+
+**Files:**
+- Create: `frontend/src/react/plugins/agent/components/AgentInput.tsx`
+
+Port from `frontend/src/plugins/agent/components/AgentInput.vue` (685 lines). Most complex UI piece.
+
+**Step 1: Write the component**
+
+Key changes:
+- Replace `NMention` with a custom `@`-triggered popover using the existing shadcn `Combobox` pattern (not the full `Combobox` component — we need inline mention behavior)
+- Replace `NButton` with shadcn `Button`
+- Replace Vue `watch()` with `useEffect()`
+- The `runChat`, `send`, `retryLastTurn`, `submitConfirmation`, `submitChoice` functions are pure logic — port nearly verbatim
+
+**@-mention implementation approach:**
+
+The shadcn `Combobox` component (at `frontend/src/react/components/ui/combobox.tsx`) is a standalone dropdown selector — it doesn't support inline textarea mentions. Build a lightweight mention popover:
+
+1. Use a `<textarea>` for input
+2. Track cursor position with `onSelect` / `onKeyUp`
+3. When user types `@`, compute popover position from cursor coordinates
+4. Show a filtered list of DOM ref suggestions in an absolutely-positioned div
+5. On selection, replace `@query` with `[eN]` in the textarea
+
+This is ~80 lines of custom code. The filtering logic and suggestion extraction are copied from the Vue version.
+
+```typescript
+// Simplified mention hook
+function useMention(textareaRef: RefObject<HTMLTextAreaElement>, input: string) {
+ const [mentionQuery, setMentionQuery] = useState<{ query: string; start: number; end: number } | null>(null);
+ const [suggestions, setSuggestions] = useState<DomRefSuggestion[]>([]);
+ const [menuOpen, setMenuOpen] = useState(false);
+
+ // getDomRefQuery logic — same as Vue version
+ const updateMention = useCallback(() => {
+ const el = textareaRef.current;
+ if (!el) return;
+ const query = getDomRefQuery(input, el.selectionStart, el.selectionEnd);
+ setMentionQuery(query);
+ }, [input, textareaRef]);
+
+ // Load suggestions when @ is detected
+ useEffect(() => {
+ if (!mentionQuery) { setSuggestions([]); return; }
+ if (suggestions.length > 0) return;
+ lazyExtractDomRefSuggestions().then(setSuggestions);
+ }, [mentionQuery]);
+
+ const filteredSuggestions = useMemo(() => {
+ if (!mentionQuery) return [];
+ return suggestions.filter(s => matchDomRefSuggestion(s, mentionQuery.query));
+ }, [suggestions, mentionQuery]);
+
+ return { mentionQuery, filteredSuggestions, menuOpen, setMenuOpen, updateMention };
+}
+```
+
+**Step 2: Type check**
+
+```bash
+cd frontend && pnpm type-check 2>&1 | grep -i error | head -10
+```
+
+**Step 3: Commit**
+
+```bash
+git add frontend/src/react/plugins/agent/components/AgentInput.tsx
+git commit -m "feat(agent): add AgentInput React component with @-mention"
+```
+
+---
+
+### Task 7: Create AgentWindow Component
+
+**Files:**
+- Create: `frontend/src/react/plugins/agent/components/AgentWindow.tsx`
+
+Port from `frontend/src/plugins/agent/components/AgentWindow.vue` (798 lines).
+
+**Step 1: Write the component**
+
+Key changes:
+- `<Teleport to="body">` → `createPortal(..., document.body)`
+- `ref<HTMLElement>` → `useRef<HTMLDivElement>`
+- `onMounted` / `onBeforeUnmount` → `useEffect` cleanup
+- `watch(windowRef, ...)` → `useEffect` with ref dependency
+- `computed(...)` → `useMemo(...)` or inline derivation
+- `NInput` (for rename) → shadcn `Input`
+- `NPopconfirm` → shadcn `Dialog` (AlertDialog pattern)
+- `lucide-vue-next` → `lucide-react` (same icon names: `Archive`, `Inbox`)
+- `HumanizeTs` Vue component → inline `useRelativeTime` hook or direct `Intl.RelativeTimeFormat`
+
+Drag/resize logic ports directly — the pointer event handlers are pure DOM code:
+
+```typescript
+const startDrag = useCallback((event: React.MouseEvent) => {
+ // Same guard: skip if target has data-agent-window-action/resize
+ if ((event.target as HTMLElement).closest("[data-agent-window-action], [data-agent-window-resize]")) return;
+
+ const store = useAgentStore.getState();
+ const offsetX = event.clientX - store.position.x;
+ const offsetY = event.clientY - store.position.y;
+
+ const onDrag = (e: MouseEvent) => {
+ useAgentStore.getState().setPosition(e.clientX - offsetX, e.clientY - offsetY);
+ };
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", onDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ useAgentStore.getState().saveWindowState();
+ };
+ document.addEventListener("mousemove", onDrag);
+ document.addEventListener("mouseup", stopDrag);
+}, []);
+```
+
+The resize and sidebar resize follow the same pattern.
+
+**Viewport resize handler:**
+
+```typescript
+useEffect(() => {
+ const handleResize = () => {
+ setViewportSize({ width: window.innerWidth, height: window.innerHeight });
+ };
+ window.addEventListener("resize", handleResize);
+ return () => window.removeEventListener("resize", handleResize);
+}, []);
+```
+
+**ResizeObserver:**
+
+```typescript
+useEffect(() => {
+ const el = windowRef.current;
+ if (!el) return;
+ const observer = new ResizeObserver(([entry]) => {
+ if (!entry || isResizingRef.current) return;
+ syncSize(entry.target as HTMLElement);
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+}, []);
+```
+
+**Step 2: Type check**
+
+```bash
+cd frontend && pnpm type-check 2>&1 | grep -i error | head -10
+```
+
+**Step 3: Commit**
+
+```bash
+git add frontend/src/react/plugins/agent/components/AgentWindow.tsx
+git commit -m "feat(agent): add AgentWindow React component with drag/resize"
+```
+
+---
+
+### Task 8: Create Entry Point and Mount Bridge
+
+**Files:**
+- Create: `frontend/src/react/plugins/agent/index.ts`
+- Create: `frontend/src/react/plugins/agent/AgentWindowMount.vue`
+- Modify: `frontend/src/layouts/BodyLayout.vue:77,92,194`
+- Modify: `frontend/src/react/mount.ts:3-5,39`
+
+**Step 1: Create the React entry point**
+
+```typescript
+// frontend/src/react/plugins/agent/index.ts
+export { AgentWindow } from "./components/AgentWindow";
+export { useAgentStore } from "./store/agent";
+```
+
+**Step 2: Register the AgentWindow in the React mount system**
+
+Add a new glob for plugin components in `frontend/src/react/mount.ts`:
+
+```typescript
+const pluginLoaders = import.meta.glob("./plugins/agent/components/AgentWindow.tsx");
+```
+
+Or, simpler: create a dedicated mount file for the agent since it's not a page — it's a floating widget.
+
+**Step 3: Create the Vue mount wrapper**
+
+`frontend/src/react/plugins/agent/AgentWindowMount.vue`:
+
+```vue
+<template>
+ <div ref="container" />
+</template>
+
+<script lang="ts" setup>
+import { onMounted, onUnmounted, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+
+const { locale } = useI18n();
+const container = ref<HTMLElement>();
+let root: any = null;
+
+async function render() {
+ if (!container.value) return;
+ const [
+ { createElement, StrictMode, createRoot },
+ { I18nextProvider },
+ i18nModule,
+ { AgentWindow },
+ ] = await Promise.all([
+ import("react").then(m => ({ createElement: m.createElement, StrictMode: m.StrictMode, createRoot: null })),
+ import("react-i18next"),
+ import("@/react/i18n"),
+ import("@/react/plugins/agent"),
+ ]);
+ // Actually use the pattern from mount.ts
+ const { mountReactComponent } = await import("./mountAgent");
+ if (!root) {
+ root = await mountReactComponent(container.value);
+ }
+}
+
+// Simpler approach: follow exact ReactPageMount.vue pattern
+// but load AgentWindow directly instead of by page name
+async function mount() {
+ if (!container.value) return;
+ const [react, reactDom, { I18nextProvider }, i18nModule, { AgentWindow }] = await Promise.all([
+ import("react"),
+ import("react-dom/client"),
+ import("react-i18next"),
+ import("@/react/i18n"),
+ import("@/react/plugins/agent"),
+ ]);
+ await i18nModule.i18nReady;
+ root = reactDom.createRoot(container.value);
+ root.render(
+ react.createElement(
+ react.StrictMode,
+ null,
+ react.createElement(
+ I18nextProvider,
+ { i18n: i18nModule.default },
+ react.createElement(AgentWindow)
+ )
+ )
+ );
+}
+
+onMounted(() => mount());
+watch(locale, async () => {
+ const i18nModule = await import("@/react/i18n");
+ await i18nModule.default.changeLanguage(locale.value);
+});
+onUnmounted(() => {
+ root?.unmount();
+ root = null;
+});
+</script>
+```
+
+**Step 4: Create keyboard shortcut that calls Zustand store**
+
+The keyboard shortcut in `BodyLayout.vue` currently calls `useAgentShortcut()` which is a Vue composable. Replace with a direct Zustand call:
+
+In `BodyLayout.vue`, change:
+```typescript
+// Before:
+import { AgentWindow, useAgentShortcut } from "@/plugins/agent";
+useAgentShortcut();
+
+// After:
+import AgentWindowMount from "@/react/plugins/agent/AgentWindowMount.vue";
+// Keyboard shortcut — Zustand store is callable from anywhere
+import { onMounted, onUnmounted } from "vue";
+function setupAgentShortcut() {
+ const handler = async (e: KeyboardEvent) => {
+ if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "A") {
+ e.preventDefault();
+ const { useAgentStore } = await import("@/react/plugins/agent");
+ useAgentStore.getState().toggle();
+ }
+ };
+ onMounted(() => window.addEventListener("keydown", handler));
+ onUnmounted(() => window.removeEventListener("keydown", handler));
+}
+setupAgentShortcut();
+```
+
+In the template, replace `<AgentWindow />` with `<AgentWindowMount />`.
+
+**Step 5: Verify it renders**
+
+```bash
+cd frontend && pnpm dev
+```
+
+Open browser, press Ctrl+Shift+A — agent window should appear.
+
+**Step 6: Commit**
+
+```bash
+git add frontend/src/react/plugins/agent/index.ts frontend/src/react/plugins/agent/AgentWindowMount.vue frontend/src/layouts/BodyLayout.vue
+git commit -m "feat(agent): mount React agent window in BodyLayout"
+```
+
+---
+
+### Task 9: Port Tests
+
+**Files:**
+- Create: `frontend/src/react/plugins/agent/components/AgentWindow.test.ts`
+- Create: `frontend/src/react/plugins/agent/components/AgentInput.test.ts`
+
+Port the 3 main test files from the Vue version. The store tests were already written in Task 3.
+
+**Step 1: Port AgentWindow tests**
+
+Replace Vue Test Utils (`mount`, `wrapper.find()`) with `@testing-library/react` (`render`, `screen.getByText()`). The 11 test cases cover sidebar rendering, chat switching, rename, archive — all of which have equivalent RTL patterns.
+
+**Step 2: Port AgentInput tests**
+
+Replace NMention/NButton interactions with native DOM events. The 27 test cases are mostly about state transitions (send, retry, confirm, choose) which are store-level — they should be similar to the Vue tests.
+
+**Step 3: Run all tests**
+
+```bash
+cd frontend && pnpm vitest run src/react/plugins/agent/ --reporter=verbose 2>&1 | tail -30
+```
+
+Expected: All tests pass.
+
+**Step 4: Commit**
+
+```bash
+git add frontend/src/react/plugins/agent/components/AgentWindow.test.ts frontend/src/react/plugins/agent/components/AgentInput.test.ts
+git commit -m "test(agent): port component tests to React Testing Library"
+```
+
+---
+
+### Task 10: Lint, Format, and Final Verification
+
+**Step 1: Fix lint/format**
+
+```bash
+pnpm --dir frontend fix
+```
+
+**Step 2: Type check**
+
+```bash
+pnpm --dir frontend type-check
+```
+
+**Step 3: Run all agent tests**
+
+```bash
+cd frontend && pnpm vitest run src/react/plugins/agent/ --reporter=verbose
+```
+
+**Step 4: Run full frontend tests**
+
+```bash
+pnpm --dir frontend test
+```
+
+**Step 5: Manual smoke test**
+
+1. Open browser with dev server
+2. Press Ctrl+Shift+A — agent window appears
+3. Create a chat, type a message, verify it sends
+4. Verify tool calls render in ToolCallCard
+5. Test drag/resize/minimize
+6. Test @-mention shows DOM refs
+7. Refresh page — verify chat history persists
+8. Verify sidebar: rename, archive, delete chats
+
+**Step 6: Commit any lint fixes**
+
+```bash
+git add -u
+git commit -m "fix(agent): lint and format fixes"
+```
+
+---
+
+### Task 11: Delete Vue Agent Plugin
+
+**Files:**
+- Delete: `frontend/src/plugins/agent/` (entire directory)
+- Modify: Any remaining imports of `@/plugins/agent` elsewhere
+
+**Step 1: Search for remaining imports**
+
+```bash
+grep -r '@/plugins/agent' frontend/src/ --include='*.ts' --include='*.vue' --include='*.tsx' | grep -v 'node_modules'
+```
+
+The only import should be `BodyLayout.vue` which was already updated in Task 8. If there are others, update them.
+
+**Step 2: Delete the Vue version**
+
+```bash
+rm -rf frontend/src/plugins/agent/
+```
+
+**Step 3: Verify build**
+
+```bash
+pnpm --dir frontend type-check
+pnpm --dir frontend test
+```
+
+**Step 4: Commit**
+
+```bash
+git add -A
+git commit -m "refactor(agent): remove Vue agent plugin after React migration"
+```
+
+---
+
+## Appendix: shadcn Components Needed
+
+Components already available in `frontend/src/react/components/ui/`:
+- `Button` — replaces `NButton`
+- `Input` — replaces `NInput` (for rename)
+- `Textarea` — for chat input
+- `Dialog` — replaces `NPopconfirm` (archive/delete confirmations)
+- `Combobox` — reference for @-mention pattern (not used directly)
+
+Components NOT needed (simpler alternatives):
+- `Collapsible` — ToolCallCard uses a simple `useState(false)` toggle, no need for a component
+- `ScrollArea` — native `overflow-y-auto` is sufficient
diff --git a/frontend/package.json b/frontend/package.json
index fb24fd33a0..8e1d92ac79 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -55,6 +55,7 @@
"html-query-plan": "^2.6.1",
"html-to-image": "^1.11.13",
"i18next": "^25.10.10",
+ "immer": "^11.1.4",
"is-chinese": "^2.0.0",
"js-yaml": "4.1.1",
"jszip": "^3.10.1",
@@ -77,6 +78,7 @@
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-i18next": "^16.6.6",
+ "react-markdown": "^10.1.0",
"regenerator-runtime": "^0.14.1",
"rxjs": "^7.8.2",
"scroll-into-view-if-needed": "^3.1.0",
@@ -92,7 +94,8 @@
"vscode-ws-jsonrpc": "3.5.0",
"vue": "3.5.29",
"vue-draggable-plus": "^0.6.0",
- "vueuc": "0.4.65"
+ "vueuc": "0.4.65",
+ "zustand": "^5.0.12"
},
"devDependencies": {
"@biomejs/biome": "2.4.6",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 8227fd122a..37f7d211fb 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -114,6 +114,9 @@ importers:
i18next:
specifier: ^25.10.10
version: 25.10.10([email protected])
+ immer:
+ specifier: ^11.1.4
+ version: 11.1.4
is-chinese:
specifier: ^2.0.0
version: 2.0.0
@@ -180,6 +183,9 @@ importers:
react-i18next:
specifier: ^16.6.6
+ react-markdown:
+ specifier: ^10.1.0
+ version: 10.1.0(@types/[email protected])([email protected])
regenerator-runtime:
specifier: ^0.14.1
version: 0.14.1
@@ -228,6 +234,9 @@ importers:
vueuc:
specifier: 0.4.65
+ zustand:
+ specifier: ^5.0.12
devDependencies:
'@biomejs/biome':
specifier: 2.4.6
@@ -2171,12 +2180,18 @@ packages:
resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}
+
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
resolution: {integrity: sha512-dNKVfHd/jk0SkR/exKGj2ggkB45MAkzvWCaqLUUgkyjITkGNzH8H+yUwr+BLJUBjZOe9w8X3wgmXhZDRg1ED6A==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}
+
resolution: {integrity: sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==}
@@ -2299,6 +2314,9 @@ packages:
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}
+
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
@@ -2364,6 +2382,9 @@ packages:
resolution: {integrity: sha512-zhahknjobV2FiD6Ee9iLbS7OV9zi10rG26odsQdfBO/hjSzUQbkIYgda+iNKK1zNiW2ey+Lf8MU5btN17V3dUw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ '@ungap/[email protected]':
+ resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==}
+
'@vitejs/[email protected]':
resolution: {integrity: sha512-CaXb/y0mlfu7jQRELEJJc2/5w2bX2m1JraARgFnvSB2yfvnCNJVWWlqAo6WjnKoepOwKx8gs0ugJThPLKCOXIg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -2725,9 +2746,18 @@ packages:
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}
+
+ resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==}
+
resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==}
+ resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==}
+
resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==}
engines: {node: '>= 20.19.0'}
@@ -2756,6 +2786,9 @@ packages:
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
+ resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}
+
resolution: {integrity: sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==}
engines: {node: '>=14'}
@@ -3226,6 +3259,9 @@ packages:
resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==}
engines: {node: '>=4.0'}
+ resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==}
+
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
@@ -3391,6 +3427,12 @@ packages:
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}
+
+ resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}
+
resolution: {integrity: sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==}
engines: {node: '>=12.0.0'}
@@ -3411,6 +3453,9 @@ packages:
resolution: {integrity: sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==}
+ resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
+
resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}
engines: {node: '>= 14'}
@@ -3451,6 +3496,9 @@ packages:
resolution: {integrity: sha512-HR7EVodfFUdQCTIeySw+WDRFJlPcLOJbXfwwZ7Oom6tjsvZ3bOkCDJHehQC3nxJrv7+f9XecwazynjU8e4Vw3Q==}
+ resolution: {integrity: sha512-XREFCPo6ksxVzP4E0ekD5aMdf8WMwmdNaz6vuvxgI40UaEiu6q3p8X52aU6GdyvLY3XXX/8R7JOTXStz/nBbRw==}
+
resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==}
engines: {node: '>=6'}
@@ -3472,10 +3520,19 @@ packages:
resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==}
+ resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==}
+
resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==}
+
+ resolution: {integrity: sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==}
+
resolution: {integrity: sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==}
engines: {node: '>=4'}
@@ -3487,6 +3544,9 @@ packages:
resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==}
+
resolution: {integrity: sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==}
engines: {node: '>=8'}
@@ -3504,6 +3564,9 @@ packages:
resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==}
+
resolution: {integrity: sha512-zJdQ3QTeLye+iphMeK3wks+vXSRFKh68/Pnlw7aOfApFSEIOhYa8P9vwwa6QrImNNBMJTiL1PpYF0f4BxDuEgA==}
@@ -3850,9 +3913,21 @@ packages:
resolution: {integrity: sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==}
+ resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}
+
+ resolution: {integrity: sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==}
+
+ resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==}
+
resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}
+ resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==}
+
resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==}
@@ -4115,6 +4190,9 @@ packages:
resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==}
+
resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
@@ -4236,6 +4314,9 @@ packages:
resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==}
+ resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}
+
resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==}
@@ -4299,6 +4380,12 @@ packages:
typescript:
optional: true
+ resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}
+ peerDependencies:
+ '@types/react': '>=18'
+ react: '>=18'
+
resolution: {integrity: sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==}
engines: {node: '>=0.10.0'}
@@ -4347,6 +4434,9 @@ packages:
resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}
+ resolution: {integrity: sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==}
+
resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}
@@ -4507,6 +4597,9 @@ packages:
resolution: {integrity: sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==}
+
resolution: {integrity: sha512-wcFzz9cDfbuqe0FZzfi2or1sgyIrsDwmPwfZC4hiNidPdPINjeUwNfv5kldczoEAcjl9Y1L3SM7Uz2PUEQzxQw==}
@@ -4546,6 +4639,9 @@ packages:
resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}
+ resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}
+
resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
engines: {node: '>=8'}
@@ -4558,6 +4654,12 @@ packages:
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==}
+
+ resolution: {integrity: sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==}
+
resolution: {integrity: sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==}
engines: {node: '>=16'}
@@ -4659,6 +4761,9 @@ packages:
resolution: {integrity: sha512-M8RGFoKtZ8dF+iwJfAJTOH/SM4KluKOKRJpjCMhI8bG3qB74zrFoArKZ62ll0Fr3mqkMJiQOmWYkdYgDeITYQg==}
+ resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
+
resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}
@@ -4732,6 +4837,9 @@ packages:
resolution: {integrity: sha512-2qCTHimwdxLfz+YzdGfkqNlH0tLi9xjTnHddPmJwtIG9MGsdbutfTc4P+haPD7l7Cjxf/WZj+we5qfVPvvxfYw==}
+ resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}
+
resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}
@@ -5112,6 +5220,24 @@ packages:
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-i77ae3aZq4dhMlRhJVCYgMLKuSiZAaUPAct2AksxQ+gOtimhGMdXljRT21P5BNpeT4kXlLIckvkPM029OljD7g==}
+ engines: {node: '>=12.20.0'}
+ peerDependencies:
+ '@types/react': '>=18.0.0'
+ immer: '>=9.0.6'
+ react: '>=18.0.0'
+ use-sync-external-store: '>=1.2.0'
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ immer:
+ optional: true
+ react:
+ optional: true
+ use-sync-external-store:
+ optional: true
+
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
@@ -6893,10 +7019,18 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/estree': 1.0.8
+
'@types/[email protected]': {}
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/unist': 3.0.3
+
'@types/[email protected]': {}
@@ -7061,6 +7195,8 @@ snapshots:
optional: true
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -7156,6 +7292,8 @@ snapshots:
'@typescript-eslint/types': 8.57.2
eslint-visitor-keys: 5.0.1
+ '@ungap/[email protected]': {}
+
dependencies:
'@babel/core': 7.29.0
@@ -7592,8 +7730,14 @@ snapshots:
ansi-styles: 4.3.0
supports-color: 7.2.0
+
+
+
dependencies:
readdirp: 5.0.0
@@ -7634,6 +7778,8 @@ snapshots:
+
@@ -8159,6 +8305,8 @@ snapshots:
+
@@ -8306,6 +8454,30 @@ snapshots:
dependencies:
function-bind: 1.1.2
+ dependencies:
+ '@types/estree': 1.0.8
+ '@types/hast': 3.0.4
+ '@types/unist': 3.0.3
+ comma-separated-tokens: 2.0.3
+ devlop: 1.1.0
+ estree-util-is-identifier-name: 3.0.0
+ hast-util-whitespace: 3.0.0
+ mdast-util-mdx-expression: 2.0.1
+ mdast-util-mdx-jsx: 3.2.0
+ mdast-util-mdxjs-esm: 2.0.1
+ property-information: 7.1.0
+ space-separated-tokens: 2.0.2
+ style-to-js: 1.1.21
+ unist-util-position: 5.0.0
+ vfile-message: 4.0.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/hast': 3.0.4
+
@@ -8324,6 +8496,8 @@ snapshots:
+
dependencies:
agent-base: 7.1.4
@@ -8360,6 +8534,8 @@ snapshots:
+
dependencies:
parent-module: 1.0.1
@@ -8380,8 +8556,17 @@ snapshots:
+
+
+ dependencies:
+ is-alphabetical: 2.0.1
+ is-decimal: 2.0.1
+
@@ -8390,6 +8575,8 @@ snapshots:
dependencies:
hasown: 2.0.2
+
@@ -8400,6 +8587,8 @@ snapshots:
dependencies:
is-extglob: 2.1.1
+
dependencies:
'@babel/runtime': 7.29.2
@@ -8783,11 +8972,62 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/estree-jsx': 1.0.5
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.2
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/estree-jsx': 1.0.5
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ ccount: 2.0.1
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.2
+ mdast-util-to-markdown: 2.1.2
+ parse-entities: 4.0.2
+ stringify-entities: 4.0.4
+ unist-util-stringify-position: 4.0.0
+ vfile-message: 4.0.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/estree-jsx': 1.0.5
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.2
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/mdast': 4.0.4
unist-util-is: 6.0.0
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ '@ungap/structured-clone': 1.3.0
+ devlop: 1.1.0
+ micromark-util-sanitize-uri: 2.0.1
+ trim-lines: 3.0.1
+ unist-util-position: 5.0.0
+ unist-util-visit: 5.0.0
+ vfile: 6.0.3
+
dependencies:
'@types/mdast': 4.0.4
@@ -9190,6 +9430,16 @@ snapshots:
dependencies:
callsites: 3.1.0
+ dependencies:
+ '@types/unist': 2.0.11
+ character-entities-legacy: 3.0.0
+ character-reference-invalid: 2.0.1
+ decode-named-character-reference: 1.1.0
+ is-alphanumerical: 2.0.1
+ is-decimal: 2.0.1
+ is-hexadecimal: 2.0.1
+
dependencies:
entities: 6.0.1
@@ -9371,6 +9621,8 @@ snapshots:
+
@@ -9420,6 +9672,24 @@ snapshots:
react-dom: 19.2.4([email protected])
typescript: 6.0.2
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ '@types/react': 19.2.14
+ devlop: 1.1.0
+ hast-util-to-jsx-runtime: 2.3.6
+ html-url-attributes: 3.0.1
+ mdast-util-to-hast: 13.2.1
+ react: 19.2.4
+ remark-parse: 11.0.0
+ remark-rehype: 11.1.2
+ unified: 11.0.5
+ unist-util-visit: 5.0.0
+ vfile: 6.0.3
+ transitivePeerDependencies:
+ - supports-color
+
@@ -9492,6 +9762,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ mdast-util-to-hast: 13.2.1
+ unified: 11.0.5
+ vfile: 6.0.3
+
dependencies:
'@types/mdast': 4.0.4
@@ -9653,6 +9931,8 @@ snapshots:
+
@@ -9692,6 +9972,11 @@ snapshots:
dependencies:
safe-buffer: 5.2.1
+ dependencies:
+ character-entities-html4: 2.1.0
+ character-entities-legacy: 3.0.0
+
dependencies:
ansi-regex: 5.0.1
@@ -9702,6 +9987,14 @@ snapshots:
+ dependencies:
+ style-to-object: 1.0.14
+
+ dependencies:
+ inline-style-parser: 0.2.7
+
dependencies:
copy-anything: 4.0.5
@@ -9790,6 +10083,8 @@ snapshots:
+
@@ -9864,6 +10159,10 @@ snapshots:
dependencies:
'@types/unist': 3.0.3
+ dependencies:
+ '@types/unist': 3.0.3
+
dependencies:
'@types/unist': 3.0.3
@@ -10213,4 +10512,11 @@ snapshots:
+ optionalDependencies:
+ '@types/react': 19.2.14
+ immer: 11.1.4
+ react: 19.2.4
+ use-sync-external-store: 1.6.0([email protected])
+
diff --git a/frontend/scripts/generate_openapi_index.js b/frontend/scripts/generate_openapi_index.js
index 3a02a3dda3..047bd11ff8 100644
--- a/frontend/scripts/generate_openapi_index.js
+++ b/frontend/scripts/generate_openapi_index.js
@@ -13,7 +13,7 @@ const YAML_FILE = path.join(
);
const OUTPUT_FILE = path.join(
__dirname,
- "../src/plugins/agent/logic/tools/gen/openapi-index.ts"
+ "../src/react/plugins/agent/logic/tools/gen/openapi-index.ts"
);
// --- Helpers ---
@@ -235,7 +235,7 @@ console.log(
);
// Validate service directory coverage in the prompt
-const PROMPT_FILE = path.join(__dirname, "../src/plugins/agent/logic/prompt.ts");
+const PROMPT_FILE = path.join(__dirname, "../src/react/plugins/agent/logic/prompt.ts");
if (fs.existsSync(PROMPT_FILE)) {
const promptContent = fs.readFileSync(PROMPT_FILE, "utf8");
const specServices = new Set(endpoints.map((ep) => ep.service));
@@ -250,13 +250,13 @@ if (fs.existsSync(PROMPT_FILE)) {
` ⚠ Services not reflected in prompt.ts serviceDirectory: ${missing.join(", ")}`
);
console.warn(
- " Review frontend/src/plugins/agent/AGENT.md and manually update the serviceDirectory block in prompt.ts"
+ " Review frontend/src/react/plugins/agent/AGENT.md and manually update the serviceDirectory block in prompt.ts"
);
} else {
console.log(` ✓ Prompt service directory covers all ${specServices.size} services`);
}
} else {
console.warn(
- " ⚠ No prompt.ts found. Review frontend/src/plugins/agent/AGENT.md and restore or recreate the serviceDirectory block"
+ " ⚠ No prompt.ts found. Review frontend/src/react/plugins/agent/AGENT.md and restore or recreate the serviceDirectory block"
);
}
diff --git a/frontend/src/components/AgentWindowMount.vue b/frontend/src/components/AgentWindowMount.vue
new file mode 100644
index 0000000000..78a91ad489
--- /dev/null
+++ b/frontend/src/components/AgentWindowMount.vue
@@ -0,0 +1,29 @@
+<template>
+ <div ref="container" />
+</template>
+
+<script lang="ts" setup>
+import { onMounted, onUnmounted, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { mountReactPage } from "@/react/mount";
+
+const { locale } = useI18n();
+const container = ref<HTMLElement>();
+// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import
+let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any
+
+onMounted(async () => {
+ if (!container.value) return;
+ root = await mountReactPage(container.value, "AgentWindow");
+});
+
+watch(locale, async () => {
+ const i18nModule = await import("@/react/i18n");
+ await i18nModule.default.changeLanguage(locale.value);
+});
+
+onUnmounted(() => {
+ root?.unmount();
+ root = null;
+});
+</script>
diff --git a/frontend/src/layouts/BodyLayout.vue b/frontend/src/layouts/BodyLayout.vue
index a479973c16..8c32bc0f47 100644
--- a/frontend/src/layouts/BodyLayout.vue
+++ b/frontend/src/layouts/BodyLayout.vue
@@ -74,7 +74,7 @@
<Quickstart />
</div>
- <AgentWindow />
+ <AgentWindowMount />
<ReleaseRemindModal
v-if="state.showReleaseModal && route.name !== WORKSPACE_ROOT_MODULE"
@@ -87,9 +87,9 @@ import { useWindowSize } from "@vueuse/core";
import { NDrawer, NDrawerContent } from "naive-ui";
import { computed, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
+import AgentWindowMount from "@/components/AgentWindowMount.vue";
import RoutePermissionGuard from "@/components/Permission/RoutePermissionGuard.vue";
import ReleaseRemindModal from "@/components/ReleaseRemindModal.vue";
-import { AgentWindow, useAgentShortcut } from "@/plugins/agent";
import { t } from "@/plugins/i18n";
import environmentV1Routes from "@/router/dashboard/environmentV1";
import instanceRoutes from "@/router/dashboard/instance";
@@ -191,7 +191,16 @@ onUnmounted(() => {
}
});
-useAgentShortcut();
+// Agent keyboard shortcut (Ctrl/Cmd+Shift+A) — calls Zustand store directly
+const agentShortcutHandler = async (e: KeyboardEvent) => {
+ if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "A") {
+ e.preventDefault();
+ const { useAgentStore } = await import("@/react/plugins/agent/store/agent");
+ useAgentStore.getState().toggle();
+ }
+};
+onMounted(() => window.addEventListener("keydown", agentShortcutHandler));
+onUnmounted(() => window.removeEventListener("keydown", agentShortcutHandler));
provideBodyLayoutContext({
mainContainerRef,
diff --git a/frontend/src/plugins/agent/components/AgentChat.vue b/frontend/src/plugins/agent/components/AgentChat.vue
deleted file mode 100644
index bc1dc7b392..0000000000
--- a/frontend/src/plugins/agent/components/AgentChat.vue
+++ /dev/null
@@ -1,197 +0,0 @@
-<script setup lang="ts">
-import { NButton } from "naive-ui";
-import remarkGfm from "remark-gfm";
-import remarkParse from "remark-parse";
-import { unified } from "unified";
-import { computed, nextTick, ref, watch } from "vue";
-import { useRouter } from "vue-router";
-import AstToMarkdown from "@/plugins/ai/components/ChatView/Markdown/AstToVNode.vue";
-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
-import { hasWorkspacePermissionV2 } from "@/utils";
-import type { AgentMessage } from "../logic/types";
-import { useAgentStore } from "../store/agent";
-import ToolCallCard from "./ToolCallCard.vue";
-
-const markdownProcessor = unified().use(remarkParse).use(remarkGfm);
-
-const parseMarkdown = (content: string) => {
- return markdownProcessor.parse(content ?? "");
-};
-
-const router = useRouter();
-const agentStore = useAgentStore();
-const chatContainer = ref<HTMLElement | null>(null);
-
-const allowConfigure = computed(() =>
- hasWorkspacePermissionV2("bb.settings.set")
-);
-const showAIConfigurationRecovery = computed(
- () => agentStore.currentChatRequiresAIConfiguration
-);
-const displayMessages = computed(() =>
- agentStore.messages.filter(
- (message): message is AgentMessage =>
- message.role === "user" || message.role === "assistant"
- )
-);
-
-function getToolResult(
- messageId: string,
- toolCallId: string
-): string | undefined {
- const fullIndex = agentStore.messages.findIndex(
- (message) => message.id === messageId
- );
- if (fullIndex < 0) {
- return undefined;
- }
-
- for (let index = fullIndex + 1; index < agentStore.messages.length; index++) {
- const message = agentStore.messages[index];
- if (message.role === "tool" && message.toolCallId === toolCallId) {
- return message.content;
- }
- if (
- message.role === "assistant" &&
- message.content &&
- !message.toolCalls?.length
- ) {
- break;
- }
- }
- return undefined;
-}
-
-function goConfigure() {
- agentStore.clearError(agentStore.currentChatId);
- router.push({
- name: SETTING_ROUTE_WORKSPACE_GENERAL,
- hash: "#ai-assistant",
- });
-}
-
-function dismissAIConfigurationRecovery() {
- agentStore.clearError(agentStore.currentChatId);
-}
-watch(
- [() => agentStore.currentChatId, () => agentStore.messages.length],
- async () => {
- await nextTick();
- if (chatContainer.value) {
- chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
- }
- }
-);
-</script>
-
-<template>
- <div ref="chatContainer" class="overflow-y-auto space-y-3 p-3">
- <template v-for="msg in displayMessages" :key="msg.id">
- <div v-if="msg.role === 'user'" class="flex justify-end">
- <div class="max-w-[80%] rounded-lg bg-blue-50 px-3 py-2 text-sm">
- {{ msg.content }}
- </div>
- </div>
- <div v-else class="flex flex-col gap-y-2">
- <div
- v-if="msg.content"
- class="max-w-[80%] rounded-lg bg-gray-50 px-3 py-2 text-sm markdown-content"
- >
- <AstToMarkdown :ast="parseMarkdown(msg.content)" />
- </div>
- <ToolCallCard
- v-for="toolCall in msg.toolCalls"
- :key="toolCall.id"
- :tool-call="toolCall"
- :result="getToolResult(msg.id, toolCall.id)"
- />
- </div>
- </template>
- <div
- v-if="agentStore.loading"
- class="flex items-center gap-x-2 text-sm text-gray-400"
- >
- <span class="animate-pulse">&#9679;</span> {{ $t("common.loading") }}
- </div>
- <div
- v-if="showAIConfigurationRecovery"
- class="max-w-[80%] rounded-lg border border-amber-200 bg-amber-50 px-3 py-3 text-sm text-amber-900"
- >
- <div class="font-medium">
- {{ $t("agent.ai-not-configured.title") }}
- </div>
- <div class="mt-1">
- {{ $t("agent.ai-not-configured.description") }}
- </div>
- <div class="mt-3 flex flex-wrap gap-x-2 gap-y-2">
- <NButton v-if="allowConfigure" type="primary" size="small" @click="goConfigure">
- {{ $t("agent.ai-not-configured.configure") }}
- </NButton>
- <NButton size="small" @click="dismissAIConfigurationRecovery">
- {{ $t("common.dismiss") }}
- </NButton>
- </div>
- <div v-if="!allowConfigure" class="mt-1 text-amber-800">
- {{ $t("agent.ai-not-configured.contact-admin") }}
- </div>
- </div>
- <div
- v-else-if="agentStore.error"
- class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600"
- >
- {{ agentStore.error }}
- </div>
- </div>
-</template>
-
-<style scoped lang="postcss">
-.markdown-content :deep(p) {
- @apply my-1;
-}
-.markdown-content :deep(p:first-child) {
- @apply mt-0;
-}
-.markdown-content :deep(p:last-child) {
- @apply mb-0;
-}
-.markdown-content :deep(pre) {
- @apply my-1 overflow-x-auto rounded bg-gray-100 p-2 text-xs;
-}
-.markdown-content :deep(code) {
- @apply rounded bg-gray-200 px-1 text-xs;
-}
-.markdown-content :deep(pre code) {
- @apply bg-transparent px-0;
-}
-.markdown-content :deep(ul),
-.markdown-content :deep(ol) {
- @apply my-1 pl-5;
-}
-.markdown-content :deep(ul) {
- @apply list-disc;
-}
-.markdown-content :deep(ol) {
- @apply list-decimal;
-}
-.markdown-content :deep(li) {
- @apply my-0.5;
-}
-.markdown-content :deep(h1),
-.markdown-content :deep(h2),
-.markdown-content :deep(h3) {
- @apply my-1 font-semibold;
-}
-.markdown-content :deep(a) {
- @apply text-blue-600 underline;
-}
-.markdown-content :deep(blockquote) {
- @apply my-1 border-l-2 border-gray-300 pl-2 text-gray-600;
-}
-.markdown-content :deep(table) {
- @apply my-1 border-collapse text-xs;
-}
-.markdown-content :deep(th),
-.markdown-content :deep(td) {
- @apply border border-gray-300 px-2 py-1;
-}
-</style>
diff --git a/frontend/src/plugins/agent/components/AgentInput.test.ts b/frontend/src/plugins/agent/components/AgentInput.test.ts
deleted file mode 100644
index 487fdb9dc4..0000000000
--- a/frontend/src/plugins/agent/components/AgentInput.test.ts
+++ /dev/null
@@ -1,1261 +0,0 @@
-import { mount } from "@vue/test-utils";
-import { NButton, NMention } from "naive-ui";
-import { createPinia, setActivePinia } from "pinia";
-import { beforeEach, describe, expect, test, vi } from "vitest";
-import { createI18n } from "vue-i18n";
-import type { DomRefSuggestion } from "../dom";
-import type { AgentLoopOutcome } from "../logic/types";
-import { useAgentStore } from "../store/agent";
-import AgentInput from "./AgentInput.vue";
-
-const {
- mockRunAgentLoop,
- mockBuildSystemPrompt,
- mockCreateToolExecutor,
- mockGetToolDefinitions,
- mockLazyExtractDomRefSuggestions,
- mockRoute,
-} = vi.hoisted(() => ({
- mockRunAgentLoop: vi.fn(),
- mockBuildSystemPrompt: vi.fn(() => "system-prompt"),
- mockCreateToolExecutor: vi.fn((_router?: unknown, _options?: unknown) =>
- vi.fn()
- ),
- mockGetToolDefinitions: vi.fn(() => []),
- mockLazyExtractDomRefSuggestions: vi.fn<() => Promise<DomRefSuggestion[]>>(
- async () => []
- ),
- mockRoute: { fullPath: "/projects/demo" },
-}));
-
-vi.mock("../dom", () => ({
- lazyExtractDomRefSuggestions: mockLazyExtractDomRefSuggestions,
-}));
-
-vi.mock("../logic/agentLoop", () => ({
- runAgentLoop: mockRunAgentLoop,
-}));
-
-vi.mock("../logic/prompt", () => ({
- buildSystemPrompt: mockBuildSystemPrompt,
-}));
-
-vi.mock("../logic/tools", () => ({
- createToolExecutor: mockCreateToolExecutor,
- getToolDefinitions: mockGetToolDefinitions,
-}));
-
-vi.mock("vue-router", () => ({
- useRoute: () => mockRoute,
- useRouter: () => ({}),
-}));
-
-const getTextareaValue = (wrapper: ReturnType<typeof mount>) => {
- return (wrapper.find("textarea").element as HTMLTextAreaElement).value;
-};
-const findButtonByText = (wrapper: ReturnType<typeof mount>, text: string) => {
- return wrapper.findAll("button").find((button) => button.text() === text);
-};
-const flushPromises = async () => {
- await Promise.resolve();
- await Promise.resolve();
- await new Promise((resolve) => window.setTimeout(resolve, 0));
- await Promise.resolve();
-};
-
-const createDeferred = <T>() => {
- let resolve!: (value: T) => void;
- const promise = new Promise<T>((resolver) => {
- resolve = resolver;
- });
- return { promise, resolve };
-};
-
-const i18n = createI18n({
- legacy: false,
- locale: "en-US",
- messages: {
- "en-US": {
- common: {
- dismiss: "Dismiss",
- },
- agent: {
- interrupted: "Interrupted",
- "retry-last-chat-turn": "Retry last turn",
- "interrupted-retry-hint":
- "Retry reruns the interrupted turn with the current page state.",
- "input-placeholder": "Ask anything...",
- send: "Send",
- reply: "Reply",
- stop: "Stop",
- confirm: "Confirm",
- cancel: "Cancel",
- "pending-input-hint": "Reply below to continue this chat.",
- "pending-confirm-hint":
- "Choose confirm or cancel to continue this chat.",
- "pending-choose-hint": "Choose an option to continue this chat.",
- },
- },
- },
-});
-
-const createDomRefSuggestion = (
- overrides: Partial<DomRefSuggestion> = {}
-): DomRefSuggestion => ({
- ref: "e1",
- tag: "BUTTON",
- label: "Suggestion",
- ...overrides,
-});
-
-describe("AgentInput", () => {
- let pinia: ReturnType<typeof createPinia>;
-
- beforeEach(() => {
- localStorage.clear();
- pinia = createPinia();
- setActivePinia(pinia);
- mockRunAgentLoop.mockReset();
- mockBuildSystemPrompt.mockClear();
- mockCreateToolExecutor.mockClear();
- mockGetToolDefinitions.mockClear();
- });
-
- beforeEach(() => {
- mockLazyExtractDomRefSuggestions.mockReset();
- mockLazyExtractDomRefSuggestions.mockResolvedValue([]);
- });
-
- beforeEach(() => {
- mockRoute.fullPath = "/projects/demo";
- document.title = "Demo Page";
- });
-
- test("renders the composer as a Naive UI textarea with a primary send button", () => {
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- const inputRow = wrapper.find("[data-agent-input-row]");
- expect(inputRow.exists()).toBe(true);
- expect(inputRow.classes()).toContain("items-center");
-
- const input = wrapper.findComponent(NMention);
- expect(input.exists()).toBe(true);
- expect(input.props("type")).toBe("textarea");
- expect(input.props("placement")).toBe("top-start");
- expect(input.props("to")).toBe("body");
-
- const sendButton = wrapper.findComponent(NButton);
- expect(sendButton.exists()).toBe(true);
- expect(sendButton.props("type")).toBe("primary");
- expect(sendButton.text()).toBe("Send");
- expect(sendButton.classes()).not.toContain("h-[38px]");
- });
-
- test("submits pending input as a tool result and resumes the same chat", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.addMessage({
- chatId,
- role: "assistant",
- toolCalls: [
- {
- id: "tool-ask",
- name: "ask_user",
- arguments: JSON.stringify({
- prompt: "Which project should I use?",
- kind: "input",
- }),
- },
- ],
- });
- store.awaitUser(chatId, {
- toolCallId: "tool-ask",
- prompt: "Which project should I use?",
- kind: "input",
- });
-
- mockRunAgentLoop.mockImplementation(
- async (
- messages: unknown,
- _tools: unknown,
- _executor: unknown,
- callbacks?: { onText?: (text: string) => void }
- ) => {
- callbacks?.onText?.("Using project demo.");
- return {
- kind: "completed",
- text: "Using project demo.",
- success: true,
- };
- }
- );
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await wrapper.find("textarea").setValue("demo-project");
- await findButtonByText(wrapper, "Reply")!.trigger("click");
- await flushPromises();
-
- const toolMessages = store
- .getMessages(chatId)
- .filter((message) => message.role === "tool");
- expect(toolMessages).toHaveLength(1);
- expect(toolMessages[0].toolCallId).toBe("tool-ask");
- expect(JSON.parse(toolMessages[0].content ?? "{}")).toEqual({
- kind: "input",
- answer: "demo-project",
- });
- expect(store.getPendingAsk(chatId)).toBeNull();
- expect(store.currentChatId).toBe(chatId);
- expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);
-
- const [messages] = mockRunAgentLoop.mock.calls[0];
- expect(messages).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ role: "system", content: "system-prompt" }),
- expect.objectContaining({
- role: "tool",
- toolCallId: "tool-ask",
- }),
- ])
- );
- });
-
- test("resumes pending asks with the current page snapshot", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.updateChatPage(chatId, {
- path: "/projects/original",
- title: "Original Page",
- });
- store.awaitUser(chatId, {
- toolCallId: "tool-ask",
- prompt: "Which project should I use?",
- kind: "input",
- });
-
- mockRoute.fullPath = "/projects/other";
- document.title = "Other Page";
- mockRunAgentLoop.mockResolvedValue({
- kind: "completed",
- text: "Using project demo.",
- success: true,
- });
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await wrapper.find("textarea").setValue("demo-project");
- await findButtonByText(wrapper, "Reply")!.trigger("click");
- await flushPromises();
-
- expect(mockBuildSystemPrompt).toHaveBeenCalledWith({
- path: "/projects/other",
- title: "Other Page",
- });
- expect(store.getChat(chatId)?.page).toEqual({
- path: "/projects/other",
- title: "Other Page",
- });
- });
-
- test("increments the current chat token total from loop usage", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- mockRunAgentLoop.mockResolvedValue({
- kind: "completed",
- text: "Done",
- success: true,
- totalTokensUsed: 123,
- });
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await wrapper.find("textarea").setValue("inspect this page");
- await findButtonByText(wrapper, "Send")!.trigger("click");
- await flushPromises();
-
- expect(store.getChat(chatId)?.totalTokensUsed).toBe(123);
- });
-
- test("refreshes the saved chat page snapshot after navigate before a follow-up turn", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
- let runCount = 0;
-
- store.updateChatPage(chatId, {
- path: "/projects/original",
- title: "Original Page",
- });
-
- mockCreateToolExecutor.mockImplementation((_router: unknown, _options) => {
- const options = _options as { onNavigate?: () => void } | undefined;
- return vi.fn(async (name: string) => {
- if (name !== "navigate") {
- throw new Error(`Unexpected tool: ${name}`);
- }
- mockRoute.fullPath = "/projects/navigated";
- document.title = "Navigated Page";
- options?.onNavigate?.();
- return {
- kind: "tool_result",
- result: JSON.stringify({
- navigated: true,
- currentPath: "/projects/navigated",
- }),
- };
- });
- });
- mockRunAgentLoop.mockImplementation(
- async (
- _messages: unknown,
- _tools: unknown,
- executor: (
- name: string,
- args: Record<string, unknown>,
- toolCallId: string
- ) => Promise<{ kind: string; result?: string }>,
- callbacks?: {
- onAssistantMessage?: (message: {
- content?: string;
- toolCalls?: unknown[];
- }) => void;
- onToolResult?: (toolCallId: string, result: string) => void;
- }
- ) => {
- runCount += 1;
- if (runCount === 1) {
- callbacks?.onAssistantMessage?.({
- content: "",
- toolCalls: [
- {
- id: "tool-nav",
- name: "navigate",
- arguments: JSON.stringify({ path: "/projects/navigated" }),
- },
- ],
- });
- const result = await executor(
- "navigate",
- { path: "/projects/navigated" },
- "tool-nav"
- );
- if (result.kind === "tool_result" && result.result) {
- callbacks?.onToolResult?.("tool-nav", result.result);
- }
- return {
- kind: "awaiting_user",
- ask: {
- toolCallId: "tool-ask",
- prompt: "Continue?",
- kind: "input",
- },
- };
- }
- return {
- kind: "completed",
- text: "Done",
- success: true,
- };
- }
- );
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await wrapper.find("textarea").setValue("navigate first");
- await findButtonByText(wrapper, "Send")!.trigger("click");
- await flushPromises();
-
- expect(store.getChat(chatId)?.page).toEqual({
- path: "/projects/navigated",
- title: "Navigated Page",
- });
- expect(store.getPendingAsk(chatId)).toEqual({
- toolCallId: "tool-ask",
- prompt: "Continue?",
- kind: "input",
- });
-
- mockRoute.fullPath = "/projects/elsewhere";
- document.title = "Elsewhere Page";
-
- await wrapper.find("textarea").setValue("continue");
- await findButtonByText(wrapper, "Reply")!.trigger("click");
- await flushPromises();
-
- expect(mockBuildSystemPrompt).toHaveBeenNthCalledWith(1, {
- path: "/projects/demo",
- title: "Demo Page",
- });
- expect(mockBuildSystemPrompt).toHaveBeenNthCalledWith(2, {
- path: "/projects/elsewhere",
- title: "Elsewhere Page",
- });
- });
-
- test("filters stored assistant runtime errors from outbound history without mutating the transcript", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.addMessage({
- chatId,
- role: "user",
- content: "inspect this page",
- });
- store.addMessage({
- chatId,
- role: "assistant",
- content: "Error: upstream timeout",
- metadata: {
- error: "upstream timeout",
- route: "/projects/demo",
- },
- });
-
- mockRunAgentLoop.mockResolvedValue({
- kind: "completed",
- text: "Done",
- success: true,
- });
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await wrapper.find("textarea").setValue("try again");
- await findButtonByText(wrapper, "Send")!.trigger("click");
- await flushPromises();
-
- const [messages] = mockRunAgentLoop.mock.calls.at(-1) ?? [];
- expect(messages).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ role: "system", content: "system-prompt" }),
- expect.objectContaining({ role: "user", content: "inspect this page" }),
- expect.objectContaining({ role: "user", content: "try again" }),
- ])
- );
- expect(messages).not.toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- role: "assistant",
- content: "Error: upstream timeout",
- }),
- ])
- );
- expect(
- store.getMessages(chatId).some((message) => {
- return (
- message.role === "assistant" &&
- message.content === "Error: upstream timeout" &&
- message.metadata?.error === "upstream timeout"
- );
- })
- ).toBe(true);
- });
-
- test("keeps assistant messages that start with Error when they are not tagged as runtime failures", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.addMessage({
- chatId,
- role: "assistant",
- content: "Error: validation failed for the previous request.",
- });
-
- mockRunAgentLoop.mockResolvedValue({
- kind: "completed",
- text: "Done",
- success: true,
- });
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await wrapper.find("textarea").setValue("what should I fix?");
- await findButtonByText(wrapper, "Send")!.trigger("click");
- await flushPromises();
-
- const [messages] = mockRunAgentLoop.mock.calls.at(-1) ?? [];
- expect(messages).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- role: "assistant",
- content: "Error: validation failed for the previous request.",
- }),
- expect.objectContaining({
- role: "user",
- content: "what should I fix?",
- }),
- ])
- );
- });
-
- test("keeps tool errors and normal history in outbound history", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.addMessage({
- chatId,
- role: "user",
- content: "open settings",
- });
- store.addMessage({
- chatId,
- role: "assistant",
- content: "Trying the settings button.",
- });
- store.addMessage({
- chatId,
- role: "tool",
- toolCallId: "tool-click",
- content: "Error: element not found",
- metadata: {
- runId: "run-1",
- },
- });
-
- mockRunAgentLoop.mockResolvedValue({
- kind: "completed",
- text: "Done",
- success: true,
- });
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await wrapper.find("textarea").setValue("retry with the menu");
- await findButtonByText(wrapper, "Send")!.trigger("click");
- await flushPromises();
-
- const [messages] = mockRunAgentLoop.mock.calls.at(-1) ?? [];
- expect(messages).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ role: "system", content: "system-prompt" }),
- expect.objectContaining({ role: "user", content: "open settings" }),
- expect.objectContaining({
- role: "assistant",
- content: "Trying the settings button.",
- }),
- expect.objectContaining({
- role: "tool",
- toolCallId: "tool-click",
- content: "Error: element not found",
- }),
- expect.objectContaining({
- role: "user",
- content: "retry with the menu",
- }),
- ])
- );
- });
-
- test("shows retry CTA and reruns interrupted turns from the last stable input", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.updateChatPage(chatId, {
- path: "/projects/original",
- title: "Original Page",
- });
- store.addMessage({
- chatId,
- role: "user",
- content: "inspect this page",
- metadata: {
- route: "/projects/original",
- },
- });
- store.addMessage({
- chatId,
- role: "assistant",
- content: "Partial answer",
- metadata: {
- route: "/projects/original",
- runId: "run-1",
- },
- });
- store.addMessage({
- chatId,
- role: "tool",
- toolCallId: "tool-1",
- content: JSON.stringify({ partial: true }),
- metadata: {
- route: "/projects/original",
- runId: "run-1",
- },
- });
- store.interruptChatRun(chatId);
- store.getChat(chatId)!.runId = "run-1";
-
- mockRoute.fullPath = "/projects/current";
- document.title = "Current Page";
- mockRunAgentLoop.mockResolvedValue({
- kind: "completed",
- text: "Done",
- success: true,
- });
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- expect(wrapper.text()).toContain("Retry reruns the interrupted turn");
- await findButtonByText(wrapper, "Retry last turn")!.trigger("click");
- await flushPromises();
-
- expect(mockBuildSystemPrompt).toHaveBeenCalledWith({
- path: "/projects/current",
- title: "Current Page",
- });
-
- const [messages] = mockRunAgentLoop.mock.calls[0];
- expect(messages).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ role: "system", content: "system-prompt" }),
- expect.objectContaining({
- role: "user",
- content: "inspect this page",
- }),
- ])
- );
- expect(messages).not.toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- role: "assistant",
- content: "Partial answer",
- }),
- expect.objectContaining({
- role: "tool",
- toolCallId: "tool-1",
- }),
- ])
- );
- expect(
- store
- .getMessages(chatId)
- .some((message) => message.content === "Partial answer")
- ).toBe(false);
- expect(
- store
- .getMessages(chatId)
- .some((message) => message.toolCallId === "tool-1")
- ).toBe(false);
- expect(store.getChat(chatId)?.interrupted).toBe(false);
- expect(store.getChat(chatId)?.page).toEqual({
- path: "/projects/current",
- title: "Current Page",
- });
- });
-
- test("preserves the latest page snapshot when an interrupted run ends on a new page", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.updateChatPage(chatId, {
- path: "/projects/original",
- title: "Original Page",
- });
-
- mockRunAgentLoop.mockImplementation(async () => {
- mockRoute.fullPath = "/projects/navigated";
- document.title = "Navigated Page";
- return { kind: "aborted" };
- });
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await wrapper.find("textarea").setValue("inspect this page");
- await findButtonByText(wrapper, "Send")!.trigger("click");
- await flushPromises();
-
- expect(store.getChat(chatId)?.interrupted).toBe(true);
- expect(store.getChat(chatId)?.page).toEqual({
- path: "/projects/navigated",
- title: "Navigated Page",
- });
- });
-
- test("dismissing interrupted state removes partial run output", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.addMessage({
- chatId,
- role: "user",
- content: "inspect this page",
- });
- store.addMessage({
- chatId,
- role: "assistant",
- content: "Partial answer",
- metadata: {
- runId: "run-1",
- },
- });
- store.addMessage({
- chatId,
- role: "tool",
- toolCallId: "tool-1",
- content: JSON.stringify({ partial: true }),
- metadata: {
- runId: "run-1",
- },
- });
- store.interruptChatRun(chatId);
- store.getChat(chatId)!.runId = "run-1";
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await findButtonByText(wrapper, "Dismiss")!.trigger("click");
- await flushPromises();
-
- expect(store.getChat(chatId)?.interrupted).toBe(false);
- expect(store.getChat(chatId)?.runId).toBeNull();
- expect(
- store.getMessages(chatId).map((message) => ({
- role: message.role,
- content: message.content,
- toolCallId: message.toolCallId,
- }))
- ).toEqual([
- {
- role: "user",
- content: "inspect this page",
- toolCallId: undefined,
- },
- ]);
- });
-
- test("keeps the latest run cancellable when an earlier aborted run settles late", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
- const firstRun = createDeferred<AgentLoopOutcome>();
- const secondRun = createDeferred<AgentLoopOutcome>();
- let firstSignal: AbortSignal | undefined;
- let secondSignal: AbortSignal | undefined;
-
- mockRunAgentLoop
- .mockImplementationOnce(
- async (
- _messages: unknown,
- _tools: unknown,
- _executor: unknown,
- _callbacks: unknown,
- signal?: AbortSignal
- ) => {
- firstSignal = signal;
- return firstRun.promise;
- }
- )
- .mockImplementationOnce(
- async (
- _messages: unknown,
- _tools: unknown,
- _executor: unknown,
- _callbacks: unknown,
- signal?: AbortSignal
- ) => {
- secondSignal = signal;
- return secondRun.promise;
- }
- );
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await wrapper.find("textarea").setValue("first request");
- await findButtonByText(wrapper, "Send")!.trigger("click");
- await flushPromises();
-
- expect(store.getAbortController(chatId)?.signal).toBe(firstSignal);
- expect(store.loading).toBe(true);
-
- await findButtonByText(wrapper, "Stop")!.trigger("click");
- await flushPromises();
-
- expect(firstSignal?.aborted).toBe(true);
- expect(store.getAbortController(chatId)).toBeNull();
- expect(store.loading).toBe(false);
-
- await wrapper.find("textarea").setValue("second request");
- await findButtonByText(wrapper, "Send")!.trigger("click");
- await flushPromises();
-
- expect(store.getAbortController(chatId)?.signal).toBe(secondSignal);
- expect(store.loading).toBe(true);
-
- firstRun.resolve({ kind: "aborted" });
- await flushPromises();
-
- expect(store.getAbortController(chatId)?.signal).toBe(secondSignal);
- expect(store.loading).toBe(true);
- expect(
- store
- .getMessages(chatId)
- .some((message) => message.content === "_Interrupted_")
- ).toBe(false);
-
- secondRun.resolve({
- kind: "completed",
- text: "Done",
- success: true,
- });
- await flushPromises();
-
- expect(store.getAbortController(chatId)).toBeNull();
- expect(store.loading).toBe(false);
- });
-
- test("clears stale composer input when pending asks disappear", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.awaitUser(chatId, {
- toolCallId: "tool-ask",
- prompt: "Which project should I use?",
- kind: "input",
- defaultValue: "demo-project",
- });
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- expect(getTextareaValue(wrapper)).toBe("demo-project");
- await wrapper.find("textarea").setValue("stale input");
-
- store.clearPendingAsk(chatId);
- await flushPromises();
-
- expect(getTextareaValue(wrapper)).toBe("");
- });
-
- test("clears stale composer input when switching chats", async () => {
- const store = useAgentStore();
- const firstChatId = store.currentChatId!;
-
- store.awaitUser(firstChatId, {
- toolCallId: "tool-ask",
- prompt: "Which project should I use?",
- kind: "input",
- defaultValue: "demo-project",
- });
-
- const secondChat = store.createChat({ title: "Second" });
- store.setCurrentChat(firstChatId);
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- expect(getTextareaValue(wrapper)).toBe("demo-project");
- await wrapper.find("textarea").setValue("stale input");
-
- store.setCurrentChat(secondChat.id);
- await flushPromises();
- expect(getTextareaValue(wrapper)).toBe("");
-
- store.setCurrentChat(firstChatId);
- await flushPromises();
- expect(getTextareaValue(wrapper)).toBe("demo-project");
- });
-
- test("filters DOM ref mention options and keeps bracket insertion semantics", async () => {
- mockLazyExtractDomRefSuggestions.mockResolvedValue([
- createDomRefSuggestion({
- ref: "e1",
- tag: "BUTTON",
- role: "button",
- label: "Save changes",
- }),
- createDomRefSuggestion({
- ref: "e2",
- tag: "A",
- role: "link",
- label: "Cancel",
- }),
- ]);
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- const textarea = wrapper.find("textarea");
- const mention = wrapper.findComponent(NMention);
- await textarea.setValue("Click @sav");
- (textarea.element as HTMLTextAreaElement).setSelectionRange(10, 10);
- await textarea.trigger("keyup");
- await flushPromises();
-
- expect(mockLazyExtractDomRefSuggestions).toHaveBeenCalled();
- const options = mention.props("options") as {
- value: string;
- label: string;
- suggestion: DomRefSuggestion;
- }[];
- expect(options).toHaveLength(1);
- expect(options[0]?.value).toBe("[e1]");
- expect(options[0]?.suggestion.label).toBe("Save changes");
-
- mention.vm.$emit("update:value", "Click [e1] ");
- await flushPromises();
-
- expect(getTextareaValue(wrapper)).toBe("Click [e1] ");
- });
-
- test("keeps DOM ref mention options ordered for keyboard navigation", async () => {
- mockLazyExtractDomRefSuggestions.mockResolvedValue([
- createDomRefSuggestion({
- ref: "e1",
- tag: "BUTTON",
- role: "button",
- label: "Save changes",
- }),
- createDomRefSuggestion({
- ref: "e2",
- tag: "BUTTON",
- role: "button",
- label: "Delete changes",
- }),
- ]);
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- const textarea = wrapper.find("textarea");
- const mention = wrapper.findComponent(NMention);
- await textarea.setValue("Use @");
- (textarea.element as HTMLTextAreaElement).setSelectionRange(5, 5);
- await textarea.trigger("keyup");
- await flushPromises();
-
- const options = mention.props("options") as { value: string }[];
- expect(options.map((option) => option.value)).toEqual(["[e1]", "[e2]"]);
- });
-
- test("keeps all DOM ref mention options accessible and scrollable", async () => {
- mockLazyExtractDomRefSuggestions.mockResolvedValue(
- Array.from({ length: 10 }, (_, index) =>
- createDomRefSuggestion({
- ref: `e${index + 1}`,
- tag: "BUTTON",
- role: "button",
- label: `Option ${index + 1}`,
- })
- )
- );
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- const textarea = wrapper.find("textarea");
- const mention = wrapper.findComponent(NMention);
- await textarea.setValue("Use @");
- (textarea.element as HTMLTextAreaElement).setSelectionRange(5, 5);
- await textarea.trigger("keyup");
- await flushPromises();
-
- const options = mention.props("options") as { value: string }[];
- expect(options).toHaveLength(10);
- expect(options[0]?.value).toBe("[e1]");
- expect(options[9]?.value).toBe("[e10]");
- expect(mention.props("scrollbarProps")).toEqual({
- containerStyle: { maxHeight: "320px" },
- });
- });
-
- test("keeps the active DOM ref option scrolled into view during keyboard navigation", async () => {
- const scrollIntoView = vi.fn();
- const pendingOption = document.createElement("div");
- pendingOption.className = "n-base-select-option--pending";
- pendingOption.scrollIntoView = scrollIntoView;
- const menu = document.createElement("div");
- menu.className = "n-base-select-menu";
- menu.appendChild(pendingOption);
- document.body.appendChild(menu);
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- const textarea = wrapper.find("textarea");
- const mention = wrapper.findComponent(NMention);
- mention.vm.$emit("update:show", true);
- await textarea.trigger("keydown", { key: "ArrowDown" });
- await flushPromises();
-
- expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest" });
-
- menu.remove();
- });
-
- test("does not send when Enter selects a DOM ref mention", async () => {
- mockRunAgentLoop.mockResolvedValue({
- kind: "completed",
- text: "Done",
- success: true,
- });
- mockLazyExtractDomRefSuggestions.mockResolvedValue([
- createDomRefSuggestion({
- ref: "e1",
- tag: "BUTTON",
- role: "button",
- label: "Save changes",
- }),
- ]);
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- const textarea = wrapper.find("textarea");
- const mention = wrapper.findComponent(NMention);
- await textarea.setValue("Inspect @save");
- (textarea.element as HTMLTextAreaElement).setSelectionRange(13, 13);
- await textarea.trigger("keyup");
- await flushPromises();
-
- mention.vm.$emit("update:show", true);
- await textarea.trigger("keydown", { key: "Enter" });
- mention.vm.$emit("update:value", "Inspect [e1] ");
- mention.vm.$emit("update:show", false);
- await flushPromises();
- expect(mockRunAgentLoop).not.toHaveBeenCalled();
- expect(getTextareaValue(wrapper)).toBe("Inspect [e1] ");
-
- await textarea.trigger("keydown", { key: "Enter" });
- await flushPromises();
-
- expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);
- });
-
- test("uses choose buttons to answer pending choose prompts", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.addMessage({
- chatId,
- role: "assistant",
- toolCalls: [
- {
- id: "tool-choose",
- name: "ask_user",
- arguments: JSON.stringify({
- prompt: "Which environment should I use?",
- kind: "choose",
- options: [
- {
- label: "Production",
- value: "prod",
- description: "Use the production environment",
- },
- {
- label: "Staging",
- value: "staging",
- },
- ],
- }),
- },
- ],
- });
- store.awaitUser(chatId, {
- toolCallId: "tool-choose",
- prompt: "Which environment should I use?",
- kind: "choose",
- options: [
- {
- label: "Production",
- value: "prod",
- description: "Use the production environment",
- },
- {
- label: "Staging",
- value: "staging",
- },
- ],
- });
-
- mockRunAgentLoop.mockResolvedValue({
- kind: "completed",
- text: "Using production.",
- success: true,
- });
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- const buttons = wrapper.findAll("button");
- expect(buttons).toHaveLength(2);
- await buttons[0].trigger("click");
- await flushPromises();
-
- const toolMessages = store
- .getMessages(chatId)
- .filter((message) => message.role === "tool");
- expect(toolMessages).toHaveLength(1);
- expect(JSON.parse(toolMessages[0].content ?? "{}")).toEqual({
- kind: "choose",
- answer: "Production",
- value: "prod",
- });
- expect(store.getPendingAsk(chatId)).toBeNull();
- expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);
- });
-
- test("uses confirm buttons to answer pending confirmation prompts", async () => {
- const store = useAgentStore();
- const chatId = store.currentChatId!;
-
- store.addMessage({
- chatId,
- role: "assistant",
- toolCalls: [
- {
- id: "tool-confirm",
- name: "ask_user",
- arguments: JSON.stringify({
- prompt: "Delete the database?",
- kind: "confirm",
- confirmLabel: "Delete",
- cancelLabel: "Keep it",
- }),
- },
- ],
- });
- store.awaitUser(chatId, {
- toolCallId: "tool-confirm",
- prompt: "Delete the database?",
- kind: "confirm",
- confirmLabel: "Delete",
- cancelLabel: "Keep it",
- });
-
- mockRunAgentLoop.mockResolvedValue({
- kind: "completed",
- text: "Canceled.",
- success: true,
- });
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- const buttons = wrapper.findAll("button");
- expect(buttons).toHaveLength(2);
- await buttons[0].trigger("click");
- await flushPromises();
-
- const toolMessages = store
- .getMessages(chatId)
- .filter((message) => message.role === "tool");
- expect(toolMessages).toHaveLength(1);
- expect(JSON.parse(toolMessages[0].content ?? "{}")).toEqual({
- kind: "confirm",
- answer: "Delete",
- confirmed: true,
- });
- expect(store.getPendingAsk(chatId)).toBeNull();
- expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);
- });
-
- test("keeps the running chat selected while another chat is running", async () => {
- const store = useAgentStore();
- const firstChatId = store.currentChatId!;
- const secondChat = store.createChat({
- title: "Second thread",
- select: false,
- });
- const firstRun = createDeferred<AgentLoopOutcome>();
-
- mockRunAgentLoop.mockImplementationOnce(async () => firstRun.promise);
-
- const wrapper = mount(AgentInput, {
- global: {
- plugins: [pinia, i18n],
- },
- });
-
- await wrapper.find("textarea").setValue("first request");
- await findButtonByText(wrapper, "Send")!.trigger("click");
- await flushPromises();
-
- expect(store.isChatRunning(firstChatId)).toBe(true);
-
- store.setCurrentChat(secondChat.id);
- await flushPromises();
-
- const textarea = wrapper.find("textarea");
- expect(store.currentChatId).toBe(firstChatId);
- expect((textarea.element as HTMLTextAreaElement).disabled).toBe(true);
- expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);
- expect(store.getMessages(secondChat.id)).toEqual([]);
-
- firstRun.resolve({ kind: "completed", text: "First done", success: true });
- await flushPromises();
- });
-});
diff --git a/frontend/src/plugins/agent/components/AgentInput.vue b/frontend/src/plugins/agent/components/AgentInput.vue
deleted file mode 100644
index 5eee5b6793..0000000000
--- a/frontend/src/plugins/agent/components/AgentInput.vue
+++ /dev/null
@@ -1,684 +0,0 @@
-<script setup lang="ts">
-import { type InputInst, NButton, NMention } from "naive-ui";
-import { v4 as uuidv4 } from "uuid";
-import { computed, h, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRoute, useRouter } from "vue-router";
-import type { DomRefSuggestion } from "../dom";
-import { lazyExtractDomRefSuggestions } from "../dom";
-import { runAgentLoop } from "../logic/agentLoop";
-import { isAgentAIConfigurationError } from "../logic/aiConfiguration";
-import { buildOutboundHistory } from "../logic/outboundHistory";
-import { buildSystemPrompt } from "../logic/prompt";
-import { createToolExecutor, getToolDefinitions } from "../logic/tools";
-import type { AgentAskUserOption, Message } from "../logic/types";
-import { useAgentStore } from "../store/agent";
-
-const { t } = useI18n();
-const router = useRouter();
-const route = useRoute();
-const agentStore = useAgentStore();
-const input = ref("");
-const runTokens = new Map<string, number>();
-
-const currentChat = computed(() => agentStore.currentChat);
-const currentPendingAsk = computed(() => agentStore.currentPendingAsk);
-const isInterrupted = computed(() => Boolean(currentChat.value?.interrupted));
-const chooseOptions = computed(() =>
- currentPendingAsk.value?.kind === "choose"
- ? (currentPendingAsk.value.options ?? [])
- : []
-);
-const isAwaitingConfirm = computed(
- () => currentPendingAsk.value?.kind === "confirm"
-);
-const isAwaitingChoose = computed(
- () =>
- currentPendingAsk.value?.kind === "choose" && chooseOptions.value.length > 0
-);
-const sendLabel = computed(() =>
- currentPendingAsk.value ? t("agent.reply") : t("agent.send")
-);
-const inputPlaceholder = computed(() => {
- if (currentPendingAsk.value?.kind === "input") {
- return currentPendingAsk.value.prompt;
- }
- if (currentPendingAsk.value?.kind === "choose") {
- return currentPendingAsk.value.prompt;
- }
- return t("agent.input-placeholder");
-});
-const confirmLabel = computed(
- () => currentPendingAsk.value?.confirmLabel ?? t("agent.confirm")
-);
-const cancelLabel = computed(
- () => currentPendingAsk.value?.cancelLabel ?? t("agent.cancel")
-);
-const isCurrentChatRunning = computed(() =>
- agentStore.isChatRunning(currentChat.value?.id)
-);
-const isAIConfigurationBlocked = computed(
- () => agentStore.currentChatRequiresAIConfiguration
-);
-const isSendDisabled = computed(() => {
- if (
- isCurrentChatRunning.value ||
- isAwaitingConfirm.value ||
- isAwaitingChoose.value ||
- isAIConfigurationBlocked.value
- ) {
- return true;
- }
- return !input.value.trim();
-});
-
-type MentionInst = {
- inputInstRef?: InputInst | null;
-};
-
-type DomRefMentionOption = {
- label: string;
- value: string;
- suggestion: DomRefSuggestion;
-};
-
-const inputInstRef = ref<MentionInst | null>(null);
-const getTextareaEl = () =>
- inputInstRef.value?.inputInstRef?.textareaElRef ?? null;
-const domRefSuggestions = ref<DomRefSuggestion[]>([]);
-const isDomRefMenuOpen = ref(false);
-const selectionStart = ref(0);
-const selectionEnd = ref(0);
-let domRefRequestToken = 0;
-
-const DOM_REF_PENDING_OPTION_SELECTOR =
- ".n-base-select-menu .n-base-select-option--pending";
-
-const normalizeSearchText = (value?: string) =>
- value?.toLowerCase().trim() ?? "";
-
-const matchDomRefSuggestion = (suggestion: DomRefSuggestion, query: string) => {
- if (!query) {
- return true;
- }
- const normalizedQuery = normalizeSearchText(query);
- return [
- suggestion.ref,
- suggestion.tag,
- suggestion.role,
- suggestion.label,
- suggestion.value,
- ].some((value) => normalizeSearchText(value).includes(normalizedQuery));
-};
-
-const getDomRefQuery = (
- text: string,
- start: number,
- end: number
-): { query: string; start: number; end: number } | null => {
- if (start !== end) {
- return null;
- }
- const prefix = text.slice(0, start);
- const matches = prefix.match(/(^|\s)@([^\s@]*)$/);
- if (!matches) {
- return null;
- }
- return {
- query: matches[2] ?? "",
- start: start - matches[2].length - 1,
- end,
- };
-};
-
-const activeDomRefQuery = computed(() =>
- getDomRefQuery(input.value, selectionStart.value, selectionEnd.value)
-);
-
-const updateSelection = () => {
- const textarea = getTextareaEl();
- if (!textarea) {
- return;
- }
- selectionStart.value = textarea.selectionStart ?? 0;
- selectionEnd.value = textarea.selectionEnd ?? selectionStart.value;
-};
-
-const filteredDomRefSuggestions = computed(() => {
- const query = activeDomRefQuery.value?.query ?? "";
- return domRefSuggestions.value.filter((suggestion: DomRefSuggestion) =>
- matchDomRefSuggestion(suggestion, query)
- );
-});
-
-const domRefMentionOptions = computed<DomRefMentionOption[]>(() =>
- filteredDomRefSuggestions.value.map((suggestion) => ({
- label: `[${suggestion.ref}] ${suggestion.label}`,
- value: `[${suggestion.ref}]`,
- suggestion,
- }))
-);
-
-const loadDomRefSuggestions = async () => {
- const query = activeDomRefQuery.value;
- if (!query) {
- domRefSuggestions.value = [];
- return;
- }
- if (domRefSuggestions.value.length > 0) {
- return;
- }
-
- const requestToken = ++domRefRequestToken;
- const suggestions = await lazyExtractDomRefSuggestions();
- if (requestToken !== domRefRequestToken || !activeDomRefQuery.value) {
- return;
- }
-
- domRefSuggestions.value = suggestions;
- getTextareaEl()?.dispatchEvent(new Event("input", { bubbles: true }));
-};
-
-const handleDomRefMenuShow = (show: boolean) => {
- isDomRefMenuOpen.value = show;
-};
-
-const scrollPendingDomRefOptionIntoView = () => {
- window.setTimeout(() => {
- document
- .querySelector<HTMLElement>(DOM_REF_PENDING_OPTION_SELECTOR)
- ?.scrollIntoView({ block: "nearest" });
- }, 0);
-};
-
-const handleTextareaKeydown = async (event: KeyboardEvent) => {
- if (isDomRefMenuOpen.value) {
- if (event.key === "ArrowUp" || event.key === "ArrowDown") {
- scrollPendingDomRefOptionIntoView();
- }
- return;
- }
-
- if (
- event.key === "Enter" &&
- !event.shiftKey &&
- !event.altKey &&
- !event.ctrlKey &&
- !event.metaKey
- ) {
- event.preventDefault();
- await send();
- }
-};
-
-const formatDomRefSuggestionMeta = (suggestion: DomRefSuggestion) => {
- return [suggestion.tag.toLowerCase(), suggestion.role]
- .filter((value): value is string => Boolean(value))
- .join(" · ");
-};
-
-const renderDomRefMentionLabel = (option: DomRefMentionOption) => {
- const suggestion = option.suggestion;
- const meta = formatDomRefSuggestionMeta(suggestion);
-
- return h("div", { class: "flex flex-col text-sm" }, [
- h("div", { class: "flex items-center gap-x-2 text-gray-800" }, [
- h("span", { class: "font-medium" }, `[${suggestion.ref}]`),
- h("span", { class: "truncate" }, suggestion.label),
- ]),
- meta ? h("div", { class: "mt-1 text-xs text-gray-500" }, meta) : null,
- ]);
-};
-
-const getCurrentPageSnapshot = () => ({
- path: route.fullPath,
- title: document.title,
-});
-
-const buildChatHistory = (chatId: string, systemPrompt: string): Message[] => {
- return buildOutboundHistory(systemPrompt, agentStore.getMessages(chatId));
-};
-
-const handleOutcome = (
- chatId: string,
- page: { path: string; title: string },
- errorPrefix: string,
- outcome: Awaited<ReturnType<typeof runAgentLoop>>
-) => {
- switch (outcome.kind) {
- case "completed":
- agentStore.finishChatRun(chatId);
- return;
- case "awaiting_user":
- agentStore.awaitUser(chatId, outcome.ask);
- return;
- case "aborted":
- agentStore.interruptChatRun(chatId, getCurrentPageSnapshot());
- return;
- case "error": {
- if (!isAgentAIConfigurationError(outcome.error)) {
- agentStore.addMessage({
- chatId,
- role: "assistant",
- content: `${errorPrefix}${outcome.error.message}`,
- metadata: {
- route: page.path,
- error: outcome.error.message,
- },
- });
- }
- agentStore.finishChatRun(chatId, {
- status: "error",
- lastError: outcome.error.message,
- requiresAIConfiguration: isAgentAIConfigurationError(outcome.error),
- });
- return;
- }
- }
-};
-
-async function runChat(
- chatId: string,
- page: { path: string; title: string },
- runId: string
-) {
- const controller = new AbortController();
- const runToken = (runTokens.get(chatId) ?? 0) + 1;
- runTokens.set(chatId, runToken);
- agentStore.setAbortController(chatId, controller);
-
- const systemPrompt = buildSystemPrompt(page);
- const tools = getToolDefinitions();
- const executor = createToolExecutor(router, {
- chatId,
- onNavigate: () => {
- agentStore.updateChatPage(chatId, getCurrentPageSnapshot());
- },
- });
-
- try {
- const outcome = await runAgentLoop(
- buildChatHistory(chatId, systemPrompt),
- tools,
- executor,
- {
- onAssistantMessage: (message) => {
- if (!message.content && !message.toolCalls?.length) {
- return;
- }
- agentStore.addMessage({
- chatId,
- role: "assistant",
- content: message.content,
- toolCalls: message.toolCalls,
- metadata: {
- route: page.path,
- runId,
- },
- });
- },
- onToolResult: (toolCallId, result) => {
- agentStore.addMessage({
- chatId,
- role: "tool",
- toolCallId,
- content: result,
- metadata: {
- route: page.path,
- runId,
- },
- });
- },
- onText: (text) => {
- if (!text) {
- return;
- }
- agentStore.addMessage({
- chatId,
- role: "assistant",
- content: text,
- metadata: {
- route: page.path,
- runId,
- },
- });
- },
- },
- controller.signal
- );
-
- agentStore.incrementChatTotalTokens(chatId, outcome.totalTokensUsed ?? 0);
-
- if (runToken !== runTokens.get(chatId)) {
- return;
- }
-
- handleOutcome(chatId, page, "Error: ", outcome);
- } finally {
- if (agentStore.getAbortController(chatId) === controller) {
- agentStore.setAbortController(chatId, null);
- }
- }
-}
-
-async function startChatRun(
- chatId: string,
- currentPage: { path: string; title: string }
-) {
- const runId = uuidv4();
-
- agentStore.updateChatPage(chatId, currentPage);
- agentStore.startChatRun(chatId, currentPage, {
- runId,
- });
- await runChat(chatId, currentPage, runId);
-}
-
-async function send() {
- if (agentStore.isChatRunning(currentChat.value?.id)) {
- return;
- }
-
- const currentPage = getCurrentPageSnapshot();
- const thread = agentStore.ensureCurrentChat(currentPage);
- const chatId = thread.id;
-
- agentStore.clearError(chatId);
-
- if (currentPendingAsk.value) {
- const answer = input.value.trim();
- if (!answer) {
- return;
- }
- input.value = "";
-
- if (currentPendingAsk.value.kind === "choose") {
- agentStore.answerPendingAsk(
- chatId,
- {
- kind: "choose",
- answer,
- value: answer,
- },
- {
- route: currentPage.path,
- }
- );
- } else if (currentPendingAsk.value.kind === "input") {
- agentStore.answerPendingAsk(
- chatId,
- {
- kind: "input",
- answer,
- },
- {
- route: currentPage.path,
- }
- );
- } else {
- return;
- }
- await startChatRun(chatId, currentPage);
- return;
- }
-
- const text = input.value.trim();
- if (!text) {
- return;
- }
-
- input.value = "";
- agentStore.addMessage({
- chatId,
- role: "user",
- content: text,
- metadata: {
- route: currentPage.path,
- },
- });
- await startChatRun(chatId, currentPage);
-}
-
-async function retryLastTurn() {
- if (
- agentStore.isChatRunning(currentChat.value?.id) ||
- !currentChat.value?.interrupted
- ) {
- return;
- }
-
- const chatId = currentChat.value.id;
- const currentPage = getCurrentPageSnapshot();
- agentStore.removeMessagesByRunId(chatId, currentChat.value.runId);
- agentStore.clearError(chatId);
- await startChatRun(chatId, currentPage);
-}
-
-function dismissInterrupted() {
- if (!currentChat.value) {
- return;
- }
- agentStore.removeMessagesByRunId(
- currentChat.value.id,
- currentChat.value.runId
- );
- agentStore.clearError(currentChat.value.id);
-}
-
-async function submitConfirmation(confirmed: boolean) {
- const pendingAsk = currentPendingAsk.value;
- if (
- !pendingAsk ||
- pendingAsk.kind !== "confirm" ||
- agentStore.isChatRunning(currentChat.value?.id)
- ) {
- return;
- }
-
- const currentPage = getCurrentPageSnapshot();
- const thread = agentStore.ensureCurrentChat(currentPage);
- const chatId = thread.id;
- const answer = confirmed ? confirmLabel.value : cancelLabel.value;
-
- agentStore.clearError(chatId);
- agentStore.answerPendingAsk(
- chatId,
- {
- kind: "confirm",
- answer,
- confirmed,
- },
- {
- route: currentPage.path,
- }
- );
- await startChatRun(chatId, currentPage);
-}
-
-async function submitChoice(option: AgentAskUserOption) {
- const pendingAsk = currentPendingAsk.value;
- if (
- !pendingAsk ||
- pendingAsk.kind !== "choose" ||
- agentStore.isChatRunning(currentChat.value?.id)
- ) {
- return;
- }
-
- const currentPage = getCurrentPageSnapshot();
- const thread = agentStore.ensureCurrentChat(currentPage);
- const chatId = thread.id;
-
- agentStore.clearError(chatId);
- agentStore.answerPendingAsk(
- chatId,
- {
- kind: "choose",
- answer: option.label,
- value: option.value,
- },
- {
- route: currentPage.path,
- }
- );
- await startChatRun(chatId, currentPage);
-}
-
-watch(
- () => [
- agentStore.currentChatId,
- currentPendingAsk.value?.toolCallId,
- currentPendingAsk.value?.kind,
- currentPendingAsk.value?.defaultValue,
- ],
- () => {
- if (
- currentPendingAsk.value?.kind === "input" ||
- currentPendingAsk.value?.kind === "choose"
- ) {
- input.value = currentPendingAsk.value.defaultValue ?? "";
- return;
- }
- input.value = "";
- },
- { immediate: true }
-);
-watch(
- () => [input.value, selectionStart.value, selectionEnd.value],
- () => {
- void loadDomRefSuggestions();
- }
-);
-
-watch(
- () => isCurrentChatRunning.value,
- (running) => {
- if (running) {
- isDomRefMenuOpen.value = false;
- }
- }
-);
-</script>
-
-<template>
- <div class="border-t p-3">
- <div
- v-if="currentPendingAsk"
- class="mb-3 rounded-md bg-amber-50 px-3 py-2 text-xs text-amber-700"
- >
- <div class="font-medium">{{ currentPendingAsk.prompt }}</div>
- <div class="mt-1">
- {{
- currentPendingAsk.kind === "confirm"
- ? $t("agent.pending-confirm-hint")
- : currentPendingAsk.kind === "choose"
- ? $t("agent.pending-choose-hint")
- : $t("agent.pending-input-hint")
- }}
- </div>
- </div>
-
- <div
- v-if="isInterrupted"
- class="mb-3 rounded-md bg-red-50 px-3 py-2 text-xs text-red-700"
- >
- <div class="font-medium">{{ $t("agent.interrupted") }}</div>
- <div class="mt-1">{{ $t("agent.interrupted-retry-hint") }}</div>
- <div class="mt-2 flex flex-wrap gap-x-2 gap-y-2">
- <button
- class="rounded-md bg-red-500 px-3 py-2 text-sm text-white hover:bg-red-600 disabled:opacity-50"
- :disabled="isCurrentChatRunning"
- @click="retryLastTurn"
- >
- {{ $t("agent.retry-last-chat-turn") }}
- </button>
- <button
- class="rounded-md border px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50"
- :disabled="isCurrentChatRunning"
- @click="dismissInterrupted"
- >
- {{ $t("common.dismiss") }}
- </button>
- </div>
- </div>
-
- <div v-if="isAwaitingConfirm" class="flex flex-wrap gap-x-2 gap-y-2">
- <button
- class="rounded-md bg-blue-500 px-3 py-2 text-sm text-white hover:bg-blue-600 disabled:opacity-50"
- :disabled="isCurrentChatRunning"
- @click="submitConfirmation(true)"
- >
- {{ confirmLabel }}
- </button>
- <button
- class="rounded-md border px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50"
- :disabled="isCurrentChatRunning"
- @click="submitConfirmation(false)"
- >
- {{ cancelLabel }}
- </button>
- </div>
-
- <div v-else-if="isAwaitingChoose" class="flex flex-col gap-y-2">
- <button
- v-for="option in chooseOptions"
- :key="option.value"
- class="rounded-md border px-3 py-2 text-left text-sm hover:bg-gray-50 disabled:opacity-50"
- :disabled="isCurrentChatRunning"
- @click="submitChoice(option)"
- >
- <div class="font-medium text-gray-800">{{ option.label }}</div>
- <div v-if="option.description" class="mt-1 text-xs text-gray-500">
- {{ option.description }}
- </div>
- </button>
- </div>
-
- <div v-else class="flex items-center gap-x-2" data-agent-input-row>
- <NMention
- ref="inputInstRef"
- v-model:value="input"
- type="textarea"
- size="small"
- class="w-full"
- :autosize="{
- minRows: 1,
- maxRows: 6,
- }"
- :placeholder="inputPlaceholder"
- :disabled="isCurrentChatRunning || isAIConfigurationBlocked"
- prefix="@"
- :options="domRefMentionOptions"
- :filter="() => true"
- placement="top-start"
- to="body"
- :scrollbar-props="{ containerStyle: { maxHeight: '320px' } }"
- @update:show="handleDomRefMenuShow"
- @click="updateSelection"
- @input="updateSelection"
- @keyup="updateSelection"
- @keydown.capture="handleTextareaKeydown"
- :render-label="renderDomRefMentionLabel"
- />
- <NButton
- v-if="agentStore.loading"
- type="error"
- size="small"
- class="whitespace-nowrap"
- @click="agentStore.cancel(currentChat?.id)"
- >
- {{ $t("agent.stop") }}
- </NButton>
- <NButton
- v-else
- type="primary"
- size="small"
- class="whitespace-nowrap"
- :disabled="isSendDisabled"
- @click="send"
- >
- {{ sendLabel }}
- </NButton>
- </div>
- </div>
-</template>
diff --git a/frontend/src/plugins/agent/components/AgentWindow.test.ts b/frontend/src/plugins/agent/components/AgentWindow.test.ts
deleted file mode 100644
index f7512b2217..0000000000
--- a/frontend/src/plugins/agent/components/AgentWindow.test.ts
+++ /dev/null
@@ -1,356 +0,0 @@
-import { mount } from "@vue/test-utils";
-import { NInput, NPopconfirm } from "naive-ui";
-import { createPinia, setActivePinia } from "pinia";
-import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-import { nextTick } from "vue";
-import { createI18n } from "vue-i18n";
-import { useAgentStore } from "../store/agent";
-
-vi.mock("./AgentChat.vue", () => ({
- default: {
- name: "AgentChat",
- template: "<div data-agent-chat />",
- },
-}));
-
-vi.mock("./AgentInput.vue", () => ({
- default: {
- name: "AgentInput",
- template: "<div data-agent-input />",
- },
-}));
-
-import AgentWindow from "./AgentWindow.vue";
-
-const mockRoute = vi.hoisted(() => ({ fullPath: "/projects/demo" }));
-
-vi.mock("vue-router", () => ({
- useRoute: () => mockRoute,
-}));
-
-class ResizeObserverMock {
- observe() {}
- disconnect() {}
- unobserve() {}
-}
-
-const i18n = createI18n({
- legacy: false,
- locale: "en-US",
- messages: {
- "en-US": {
- agent: {
- "assistant-title": "Bytebase Assistant",
- minimize: "Minimize",
- close: "Close",
- resize: "Resize",
- "chat-list-label": "Chats",
- "new-chat": "New chat",
- "rename-chat-placeholder": "Enter a chat name",
- "archive-chat": "Archive",
- "unarchive-chat": "Unarchive",
- "delete-chat": "Delete",
- "active-only-chats": "Active only",
- "archived-only-chats": "Archived only",
- "archive-chat-confirmation": "Archive this chat?",
- "delete-chat-confirmation": "Delete this chat?",
- "chat-default-title": "New chat",
- "chat-archived-label": "Archived",
- "chat-status-idle": "Idle",
- "chat-status-running": "Running",
- "chat-status-awaiting-user": "Awaiting input",
- "chat-status-error": "Error",
- "chat-status-interrupted": "Interrupted",
- "chat-total-tokens": "Tokens used: {count}",
- },
- },
- },
-});
-
-const mountAgentWindow = () => {
- const pinia = createPinia();
- setActivePinia(pinia);
- const store = useAgentStore();
- store.visible = true;
- return {
- store,
- wrapper: mount(AgentWindow, {
- global: {
- plugins: [pinia, i18n],
- components: {
- NInput,
- NPopconfirm,
- },
- stubs: {
- Teleport: true,
- },
- },
- }),
- };
-};
-
-afterEach(() => {
- vi.useRealTimers();
-});
-
-describe("AgentWindow", () => {
- beforeEach(() => {
- localStorage.clear();
- vi.stubGlobal("ResizeObserver", ResizeObserverMock);
- document.title = "Demo Page";
- });
-
- test("renders chats in a left sidebar instead of a select picker", async () => {
- const { store, wrapper } = mountAgentWindow();
- const firstChatId = store.currentChatId!;
- store.addMessage({
- chatId: firstChatId,
- role: "user",
- content: "Summarize the production incident timeline",
- });
- const secondChat = store.createChat({
- title: "Renamed thread",
- select: false,
- });
-
- await wrapper.vm.$nextTick();
-
- expect(wrapper.find("select").exists()).toBe(false);
- const chatRows = wrapper.findAll("[data-agent-chat-list] button");
- expect(chatRows).toHaveLength(2);
- expect(chatRows[0].text()).toContain("Renamed thread");
- expect(chatRows[1].text()).toContain(
- "Summarize the production incident timeline"
- );
- await chatRows[0].trigger("click");
- expect(store.currentChatId).toBe(secondChat.id);
- expect(
- wrapper.findAll("button").some((button) => button.text() === "Rename")
- ).toBe(false);
- });
-
- test("shows a plain default title and humanized updated time for untitled chats", async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));
-
- const { store, wrapper } = mountAgentWindow();
- const chatId = store.currentChatId!;
-
- store.getChat(chatId)!.updatedTs = Date.now() - 60_000;
- await nextTick();
-
- const currentRow = wrapper.find(`[data-agent-chat-row='${chatId}']`);
- expect(currentRow.find("[data-agent-chat-title]").text()).toBe("New chat");
- expect(currentRow.find("[data-agent-chat-title]").text()).not.toContain(
- "·"
- );
- expect(currentRow.find("[data-agent-chat-updated-ts]").text()).toBe(
- "1 minute ago"
- );
- });
-
- test("disables switching chats while a chat is running", async () => {
- const { store, wrapper } = mountAgentWindow();
- const firstChatId = store.currentChatId!;
- const secondChat = store.createChat({
- title: "Second thread",
- select: false,
- });
-
- store.startChatRun(firstChatId, {
- path: "/projects/demo",
- title: "Demo Page",
- });
- await wrapper.vm.$nextTick();
-
- const chatRows = wrapper.findAll("[data-agent-chat-list] button");
- const currentRow = chatRows.find(
- (row) => row.attributes("aria-current") === "true"
- );
- const otherRow = chatRows.find((row) =>
- row.text().includes("Second thread")
- );
- const newChatButton = wrapper
- .findAll("button")
- .find((button) => button.text() === "New chat");
-
- expect(currentRow?.attributes("disabled")).toBeUndefined();
- expect(otherRow?.attributes("disabled")).toBe("");
- expect(newChatButton?.attributes("disabled")).toBe("");
-
- await otherRow?.trigger("click");
- expect(store.currentChatId).toBe(firstChatId);
- expect(store.canSelectChat(secondChat.id)).toBe(false);
- });
-
- test("renames the current chat with inline editing on the selected row", async () => {
- const { store, wrapper } = mountAgentWindow();
- const currentRowButton = wrapper.find(
- "[data-agent-chat-list] button[aria-current='true']"
- );
- const currentChatId = store.currentChatId!;
-
- await currentRowButton.trigger("click");
- await nextTick();
-
- const currentRow = wrapper.find(`[data-agent-chat-row='${currentChatId}']`);
- const input = currentRow.find("input");
- expect(input.exists()).toBe(true);
- expect(currentRow.findComponent(NInput).exists()).toBe(true);
- await input.setValue(" Renamed thread in app ");
- await input.trigger("keydown", { key: "Enter" });
- await nextTick();
-
- expect(store.currentChat?.title).toBe("Renamed thread in app");
- expect(wrapper.find("input").exists()).toBe(false);
- });
-
- test("cancels inline rename on escape", async () => {
- const { store, wrapper } = mountAgentWindow();
- const originalTitle = store.currentChat?.title;
- const currentRow = wrapper.find(
- "[data-agent-chat-list] button[aria-current='true']"
- );
-
- await currentRow.trigger("click");
- await nextTick();
-
- const input = wrapper.find("input");
- await input.setValue("Should not save");
- await input.trigger("keydown", { key: "Escape" });
- await nextTick();
-
- expect(store.currentChat?.title).toBe(originalTitle);
- expect(wrapper.find("input").exists()).toBe(false);
- });
-
- test("resizes and persists the sidebar width", async () => {
- const { store, wrapper } = mountAgentWindow();
- store.size.width = 760;
- store.sidebarWidth = 240;
-
- await nextTick();
-
- const sidebar = wrapper.find("aside");
- expect(sidebar.attributes("style")).toContain("width: 240px");
-
- await wrapper
- .find("[data-agent-sidebar-resize]")
- .trigger("mousedown", { clientX: 240 });
- document.dispatchEvent(new MouseEvent("mousemove", { clientX: 320 }));
- document.dispatchEvent(new MouseEvent("mouseup", { clientX: 320 }));
- await nextTick();
-
- expect(store.sidebarWidth).toBe(320);
- expect(wrapper.find("aside").attributes("style")).toContain("width: 320px");
- expect(localStorage.getItem("bb-agent-window")).toContain(
- '"sidebarWidth":320'
- );
- });
-
- test("clamps the sidebar width when the window narrows", async () => {
- const { store, wrapper } = mountAgentWindow();
- store.size.width = 760;
- store.sidebarWidth = 420;
-
- await nextTick();
- expect(wrapper.find("aside").attributes("style")).toContain("width: 420px");
-
- store.size.width = 360;
- await nextTick();
-
- expect(store.sidebarWidth).toBe(180);
- expect(wrapper.find("aside").attributes("style")).toContain("width: 180px");
- });
-
- test("shows mode-specific sidebar actions for active and archived chats", async () => {
- const { store, wrapper } = mountAgentWindow();
- const originalChatId = store.currentChatId!;
- const secondChat = store.createChat({ title: "Disposable thread" });
- store.setCurrentChat(secondChat.id);
- await nextTick();
-
- const actionArea = () => wrapper.find("[data-agent-chat-sidebar-actions]");
- const modeToggle = () => wrapper.find("[data-agent-chat-list-mode]");
- const buttonLabels = () =>
- actionArea()
- .findAll("button")
- .map((button) => button.text());
-
- expect(modeToggle().text()).toBe("");
- expect(modeToggle().attributes("aria-label")).toBe("Active only");
- expect(buttonLabels()).toEqual(["Archive", ""]);
- expect(
- actionArea()
- .findAll("button")
- .at(-1)
- ?.attributes("data-agent-chat-list-mode")
- ).toBe("");
- expect(modeToggle().classes()).toContain("ml-auto");
- expect(modeToggle().find("svg").exists()).toBe(true);
- expect(wrapper.findAllComponents(NPopconfirm)).toHaveLength(1);
-
- await wrapper.findComponent(NPopconfirm).vm.$emit("positive-click");
- await nextTick();
-
- expect(store.getChat(secondChat.id)?.archived).toBe(true);
- expect(store.currentChatId).toBe(originalChatId);
-
- await modeToggle().trigger("click");
- await nextTick();
-
- expect(modeToggle().text()).toBe("");
- expect(modeToggle().attributes("aria-label")).toBe("Archived only");
- expect(store.currentChatId).toBe(secondChat.id);
- expect(buttonLabels()).toEqual(["Unarchive", "Delete", ""]);
- expect(
- actionArea()
- .findAll("button")
- .at(-1)
- ?.attributes("data-agent-chat-list-mode")
- ).toBe("");
- expect(modeToggle().classes()).toContain("ml-auto");
- expect(modeToggle().find("svg").exists()).toBe(true);
- expect(wrapper.findAllComponents(NPopconfirm)).toHaveLength(1);
- });
-
- test("unarchives and deletes chats from archived-only mode", async () => {
- const { store, wrapper } = mountAgentWindow();
- const originalChatId = store.currentChatId!;
- const archivedChat = store.createChat({ title: "Disposable thread" });
- store.setCurrentChat(archivedChat.id);
- await nextTick();
-
- await wrapper.findComponent(NPopconfirm).vm.$emit("positive-click");
- await nextTick();
- await wrapper.find("[data-agent-chat-list-mode]").trigger("click");
- await nextTick();
-
- await wrapper.find("[data-agent-unarchive-chat]").trigger("click");
- await nextTick();
-
- expect(store.getChat(archivedChat.id)?.archived).toBe(false);
- expect(
- wrapper.find("[data-agent-chat-list-mode]").attributes("aria-label")
- ).toBe("Active only");
- expect(wrapper.find("[data-agent-chat-list-mode]").text()).toBe("");
- expect(store.currentChatId).toBe(archivedChat.id);
-
- await wrapper.findComponent(NPopconfirm).vm.$emit("positive-click");
- await nextTick();
- await wrapper.find("[data-agent-chat-list-mode]").trigger("click");
- await nextTick();
-
- expect(store.currentChatId).toBe(archivedChat.id);
-
- await wrapper.findComponent(NPopconfirm).vm.$emit("positive-click");
- await nextTick();
-
- expect(store.getChat(archivedChat.id)).toBeNull();
- expect(
- wrapper.find("[data-agent-chat-list-mode]").attributes("aria-label")
- ).toBe("Active only");
- expect(wrapper.find("[data-agent-chat-list-mode]").text()).toBe("");
- expect(store.currentChatId).toBe(originalChatId);
- });
-});
diff --git a/frontend/src/plugins/agent/components/AgentWindow.vue b/frontend/src/plugins/agent/components/AgentWindow.vue
deleted file mode 100644
index 66c790fccf..0000000000
--- a/frontend/src/plugins/agent/components/AgentWindow.vue
+++ /dev/null
@@ -1,797 +0,0 @@
-<script setup lang="ts">
-import { ArchiveIcon, InboxIcon } from "lucide-vue-next";
-import { NInput, NPopconfirm } from "naive-ui";
-import {
- computed,
- nextTick,
- onBeforeUnmount,
- onMounted,
- ref,
- watch,
-} from "vue";
-import { useI18n } from "vue-i18n";
-import { useRoute } from "vue-router";
-import HumanizeTs from "@/components/misc/HumanizeTs.vue";
-import type { AgentChat as AgentChatRecord } from "../logic/types";
-import { useAgentStore } from "../store/agent";
-import AgentChat from "./AgentChat.vue";
-import AgentInput from "./AgentInput.vue";
-
-const { t } = useI18n();
-const route = useRoute();
-const agentStore = useAgentStore();
-
-const MIN_WIDTH = 300;
-const MIN_HEIGHT = 400;
-const WINDOW_MARGIN = 16;
-const MIN_SIDEBAR_WIDTH = 180;
-const MIN_MAIN_PANEL_WIDTH = 240;
-
-const windowRef = ref<HTMLElement | null>(null);
-const viewportSize = ref({
- width: window.innerWidth,
- height: window.innerHeight,
-});
-const isViewportResizing = ref(false);
-let viewportResizeFrame = 0;
-
-const maxWidth = () =>
- Math.max(MIN_WIDTH, viewportSize.value.width - WINDOW_MARGIN * 2);
-const maxHeight = () =>
- Math.max(MIN_HEIGHT, viewportSize.value.height - WINDOW_MARGIN * 2);
-
-const clampWidth = (width: number) =>
- Math.min(maxWidth(), Math.max(MIN_WIDTH, Math.round(width)));
-const clampHeight = (height: number) =>
- Math.min(maxHeight(), Math.max(MIN_HEIGHT, Math.round(height)));
-
-function getDisplaySize(width: number, height: number) {
- return {
- width: clampWidth(width),
- height: clampHeight(height),
- };
-}
-
-function getDisplayPosition(
- x: number,
- y: number,
- size = getDisplaySize(agentStore.size.width, agentStore.size.height)
-) {
- const maxX = Math.max(
- WINDOW_MARGIN,
- viewportSize.value.width - size.width - WINDOW_MARGIN
- );
- const maxY = Math.max(
- WINDOW_MARGIN,
- viewportSize.value.height - size.height - WINDOW_MARGIN
- );
- return {
- x: Math.min(maxX, Math.max(WINDOW_MARGIN, Math.round(x))),
- y: Math.min(maxY, Math.max(WINDOW_MARGIN, Math.round(y))),
- };
-}
-
-const displayWindowState = computed(() => {
- const size = getDisplaySize(agentStore.size.width, agentStore.size.height);
- const position = getDisplayPosition(
- agentStore.position.x,
- agentStore.position.y,
- size
- );
- return { position, size };
-});
-
-const getSidebarWidthBounds = (
- windowWidth = displayWindowState.value.size.width
-) => {
- const maxSidebarWidth = Math.max(
- MIN_SIDEBAR_WIDTH,
- windowWidth - MIN_MAIN_PANEL_WIDTH
- );
- return {
- min: Math.min(MIN_SIDEBAR_WIDTH, maxSidebarWidth),
- max: maxSidebarWidth,
- };
-};
-
-const clampSidebarWidth = (
- width: number,
- windowWidth = displayWindowState.value.size.width
-) => {
- const bounds = getSidebarWidthBounds(windowWidth);
- return Math.min(bounds.max, Math.max(bounds.min, Math.round(width)));
-};
-
-const sidebarStyle = computed(() => ({
- width: `${clampSidebarWidth(agentStore.sidebarWidth)}px`,
-}));
-
-const windowStyle = computed(() => ({
- left: `${displayWindowState.value.position.x}px`,
- top: `${displayWindowState.value.position.y}px`,
- width: `${displayWindowState.value.size.width}px`,
- height: `${displayWindowState.value.size.height}px`,
-}));
-
-const showArchivedOnly = ref(false);
-const displayedChats = computed(() =>
- agentStore.orderedChats.filter(
- (chat) => chat.archived === showArchivedOnly.value
- )
-);
-const isCurrentChatInDisplayedMode = computed(() => {
- const chat = agentStore.currentChat;
- return !!chat && chat.archived === showArchivedOnly.value;
-});
-const currentChatStatusLabel = computed(() => {
- const chat = agentStore.currentChat;
- if (!chat) {
- return t("agent.chat-status-idle");
- }
- if (chat.interrupted) {
- return t("agent.chat-status-interrupted");
- }
- switch (chat.status) {
- case "running":
- return t("agent.chat-status-running");
- case "awaiting_user":
- return t("agent.chat-status-awaiting-user");
- case "error":
- return t("agent.chat-status-error");
- default:
- return t("agent.chat-status-idle");
- }
-});
-const currentChatStatusClass = computed(() => {
- const chat = agentStore.currentChat;
- if (!chat || chat.status === "idle") {
- return "bg-gray-100 text-gray-600";
- }
- if (chat.status === "running") {
- return "bg-blue-50 text-blue-600";
- }
- if (chat.interrupted || chat.status === "error") {
- return "bg-red-50 text-red-600";
- }
- return "bg-amber-50 text-amber-600";
-});
-
-const tokenFormatter = new Intl.NumberFormat();
-const currentChatTokenUsageLabel = computed(() =>
- t("agent.chat-total-tokens", {
- count: tokenFormatter.format(agentStore.currentChat?.totalTokensUsed ?? 0),
- })
-);
-const isChatCreationDisabled = computed(() => agentStore.hasRunningChat);
-
-function syncSize(width: number, height: number) {
- const size = getDisplaySize(width, height);
- agentStore.size.width = size.width;
- agentStore.size.height = size.height;
-}
-
-function syncPosition() {
- const position = getDisplayPosition(
- agentStore.position.x,
- agentStore.position.y,
- getDisplaySize(agentStore.size.width, agentStore.size.height)
- );
- agentStore.position.x = position.x;
- agentStore.position.y = position.y;
-}
-
-function syncSidebarWidth(
- width = agentStore.sidebarWidth,
- windowWidth = displayWindowState.value.size.width
-) {
- agentStore.sidebarWidth = clampSidebarWidth(width, windowWidth);
-}
-
-function syncStoreToDisplayState() {
- agentStore.size.width = displayWindowState.value.size.width;
- agentStore.size.height = displayWindowState.value.size.height;
- agentStore.position.x = displayWindowState.value.position.x;
- agentStore.position.y = displayWindowState.value.position.y;
-}
-
-const getCurrentPageSnapshot = () => ({
- path: route.fullPath,
- title: document.title,
-});
-
-const getEditableChatTitle = (chat: AgentChatRecord) =>
- chat.title || t("agent.chat-default-title");
-
-const getChatLabel = (chat: AgentChatRecord) => {
- const baseLabel = getEditableChatTitle(chat);
- return chat.archived
- ? `${baseLabel} (${t("agent.chat-archived-label")})`
- : baseLabel;
-};
-
-function selectFirstDisplayedChat() {
- const firstDisplayedChat = displayedChats.value[0];
- if (!firstDisplayedChat || !agentStore.canSelectChat(firstDisplayedChat.id)) {
- return false;
- }
- agentStore.setCurrentChat(firstDisplayedChat.id);
- return agentStore.currentChatId === firstDisplayedChat.id;
-}
-
-function ensureCurrentChatMatchesDisplayedMode(
- options: { fallbackToActiveWhenEmpty?: boolean } = {}
-) {
- if (isCurrentChatInDisplayedMode.value) {
- return;
- }
- if (selectFirstDisplayedChat()) {
- return;
- }
- if (showArchivedOnly.value) {
- if (!options.fallbackToActiveWhenEmpty) {
- return;
- }
- showArchivedOnly.value = false;
- if (isCurrentChatInDisplayedMode.value || selectFirstDisplayedChat()) {
- return;
- }
- }
- if (agentStore.hasRunningChat) {
- return;
- }
- agentStore.createChat({ page: getCurrentPageSnapshot() });
-}
-
-function toggleChatListMode() {
- showArchivedOnly.value = !showArchivedOnly.value;
- ensureCurrentChatMatchesDisplayedMode();
-}
-
-const isRenamingCurrentChat = ref(false);
-const renamingTitle = ref("");
-const renameInputRef = ref<
- InstanceType<typeof NInput> | InstanceType<typeof NInput>[] | null
->(null);
-
-function focusRenameInput() {
- const input = Array.isArray(renameInputRef.value)
- ? renameInputRef.value[0]
- : renameInputRef.value;
- input?.focus?.();
- input?.select?.();
-}
-
-function beginRenameCurrentChat() {
- const chat = agentStore.currentChat;
- if (!chat) {
- return;
- }
- renamingTitle.value = getEditableChatTitle(chat);
- isRenamingCurrentChat.value = true;
- nextTick(() => {
- focusRenameInput();
- });
-}
-
-function cancelRenameCurrentChat() {
- isRenamingCurrentChat.value = false;
- renamingTitle.value = "";
-}
-
-function commitRenameCurrentChat() {
- const chat = agentStore.currentChat;
- const title = renamingTitle.value.trim();
- if (!chat || !isRenamingCurrentChat.value) {
- return;
- }
- if (!title) {
- cancelRenameCurrentChat();
- return;
- }
- agentStore.renameChat(chat.id, title);
- cancelRenameCurrentChat();
-}
-
-function onRenameCurrentChatKeydown(event: KeyboardEvent) {
- if (event.isComposing) {
- return;
- }
- if (event.key === "Escape") {
- event.preventDefault();
- cancelRenameCurrentChat();
- return;
- }
- if (event.key === "Enter") {
- event.preventDefault();
- commitRenameCurrentChat();
- }
-}
-
-function toggleArchiveCurrentChat() {
- const chat = agentStore.currentChat;
- if (!chat) {
- return;
- }
- if (chat.archived) {
- agentStore.unarchiveChat(chat.id);
- ensureCurrentChatMatchesDisplayedMode({ fallbackToActiveWhenEmpty: true });
- return;
- }
- agentStore.archiveChat(chat.id);
- ensureCurrentChatMatchesDisplayedMode();
-}
-
-function deleteCurrentChat() {
- const chat = agentStore.currentChat;
- if (!chat) {
- return;
- }
- agentStore.deleteChat(chat.id);
- ensureCurrentChatMatchesDisplayedMode({ fallbackToActiveWhenEmpty: true });
-}
-
-const isDragging = ref(false);
-const dragOffset = ref({ x: 0, y: 0 });
-
-function startDrag(event: MouseEvent) {
- if (
- event.target instanceof HTMLElement &&
- event.target.closest(
- "[data-agent-window-action], [data-agent-window-resize]"
- )
- ) {
- return;
- }
-
- syncStoreToDisplayState();
- isDragging.value = true;
- dragOffset.value = {
- x: event.clientX - agentStore.position.x,
- y: event.clientY - agentStore.position.y,
- };
- document.addEventListener("mousemove", onDrag);
- document.addEventListener("mouseup", stopDrag);
-}
-
-function onDrag(event: MouseEvent) {
- if (!isDragging.value) {
- return;
- }
- agentStore.position.x = event.clientX - dragOffset.value.x;
- agentStore.position.y = event.clientY - dragOffset.value.y;
- syncPosition();
-}
-
-function stopDrag() {
- isDragging.value = false;
- document.removeEventListener("mousemove", onDrag);
- document.removeEventListener("mouseup", stopDrag);
- agentStore.saveWindowState();
-}
-
-const isResizing = ref(false);
-const resizeStart = ref({ x: 0, y: 0, w: 0, h: 0 });
-let resizeObserver: ResizeObserver | null = null;
-
-const isSidebarResizing = ref(false);
-const sidebarResizeStart = ref({ x: 0, width: 0 });
-
-function startSidebarResize(event: MouseEvent) {
- event.preventDefault();
- event.stopPropagation();
- syncStoreToDisplayState();
- isSidebarResizing.value = true;
- sidebarResizeStart.value = {
- x: event.clientX,
- width: clampSidebarWidth(agentStore.sidebarWidth),
- };
- document.addEventListener("mousemove", onSidebarResize);
- document.addEventListener("mouseup", stopSidebarResize);
-}
-
-function onSidebarResize(event: MouseEvent) {
- if (!isSidebarResizing.value) {
- return;
- }
- const dx = event.clientX - sidebarResizeStart.value.x;
- syncSidebarWidth(sidebarResizeStart.value.width + dx);
-}
-
-function stopSidebarResize() {
- isSidebarResizing.value = false;
- document.removeEventListener("mousemove", onSidebarResize);
- document.removeEventListener("mouseup", stopSidebarResize);
- agentStore.saveWindowState();
-}
-
-function startResize(event: MouseEvent) {
- event.preventDefault();
- event.stopPropagation();
- syncStoreToDisplayState();
- isResizing.value = true;
- resizeStart.value = {
- x: event.clientX,
- y: event.clientY,
- w: agentStore.size.width,
- h: agentStore.size.height,
- };
- document.addEventListener("mousemove", onResize);
- document.addEventListener("mouseup", stopResize);
-}
-
-function onResize(event: MouseEvent) {
- if (!isResizing.value) {
- return;
- }
- const dx = event.clientX - resizeStart.value.x;
- const dy = event.clientY - resizeStart.value.y;
- syncSize(resizeStart.value.w + dx, resizeStart.value.h + dy);
- syncPosition();
-}
-
-function stopResize() {
- isResizing.value = false;
- document.removeEventListener("mousemove", onResize);
- document.removeEventListener("mouseup", stopResize);
- agentStore.saveWindowState();
-}
-
-function observeWindowSize() {
- resizeObserver?.disconnect();
- if (!windowRef.value) {
- return;
- }
-
- resizeObserver = new ResizeObserver(([entry]) => {
- if (!entry || isResizing.value || isViewportResizing.value) {
- return;
- }
-
- const target = entry.target as HTMLElement;
- const width = clampWidth(target.offsetWidth);
- const height = clampHeight(target.offsetHeight);
- if (width === agentStore.size.width && height === agentStore.size.height) {
- return;
- }
-
- syncSize(width, height);
- syncPosition();
- agentStore.saveWindowState();
- });
-
- resizeObserver.observe(windowRef.value);
-}
-
-function handleViewportResize() {
- isViewportResizing.value = true;
- viewportSize.value = {
- width: window.innerWidth,
- height: window.innerHeight,
- };
- cancelAnimationFrame(viewportResizeFrame);
- viewportResizeFrame = window.requestAnimationFrame(() => {
- isViewportResizing.value = false;
- });
-}
-
-watch(
- () => displayWindowState.value.size.width,
- (windowWidth) => {
- const sidebarWidth = clampSidebarWidth(
- agentStore.sidebarWidth,
- windowWidth
- );
- if (sidebarWidth === agentStore.sidebarWidth) {
- return;
- }
- agentStore.sidebarWidth = sidebarWidth;
- agentStore.saveWindowState();
- }
-);
-
-watch(windowRef, () => {
- observeWindowSize();
-});
-
-function createChat() {
- if (isChatCreationDisabled.value) {
- return;
- }
- agentStore.createChat({ page: getCurrentPageSnapshot() });
-}
-
-function handleChatRowClick(chatId: string) {
- if (chatId === agentStore.currentChatId) {
- if (!isRenamingCurrentChat.value) {
- beginRenameCurrentChat();
- }
- return;
- }
- if (isRenamingCurrentChat.value) {
- cancelRenameCurrentChat();
- }
- agentStore.setCurrentChat(chatId);
-}
-
-watch(
- () => agentStore.currentChatId,
- () => {
- if (isRenamingCurrentChat.value) {
- cancelRenameCurrentChat();
- }
- }
-);
-
-onMounted(() => {
- agentStore.loadWindowState();
- handleViewportResize();
- syncSidebarWidth();
- observeWindowSize();
- window.addEventListener("resize", handleViewportResize);
-});
-
-onBeforeUnmount(() => {
- stopDrag();
- stopResize();
- stopSidebarResize();
- resizeObserver?.disconnect();
- cancelAnimationFrame(viewportResizeFrame);
- window.removeEventListener("resize", handleViewportResize);
-});
-</script>
-
-<template>
- <Teleport to="body">
- <div
- v-if="agentStore.visible && agentStore.minimized"
- data-agent-window
- class="fixed bottom-4 right-4 z-[1999] flex h-10 w-10 cursor-pointer items-center justify-center rounded-full bg-blue-500 text-white shadow-lg hover:bg-blue-600"
- @click="agentStore.restore()"
- >
- <svg
- xmlns="http://www.w3.org/2000/svg"
- class="h-5 w-5"
- viewBox="0 0 20 20"
- fill="currentColor"
- >
- <path
- fill-rule="evenodd"
- d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7zM7 9H5v2h2V9zm8 0h-2v2h2V9zm-4 0H9v2h2V9z"
- clip-rule="evenodd"
- />
- </svg>
- </div>
-
- <div
- v-if="agentStore.visible && !agentStore.minimized"
- ref="windowRef"
- data-agent-window
- class="fixed z-[1999] flex flex-col overflow-hidden rounded-lg border border-gray-200 bg-white shadow-xl"
- :style="windowStyle"
- >
- <div
- class="flex cursor-move select-none items-center justify-between border-b bg-gray-50 px-3 py-2"
- @mousedown="startDrag"
- >
- <div class="flex min-w-0 items-center gap-x-2">
- <span class="truncate text-sm font-medium">
- {{ $t("agent.assistant-title") }}
- </span>
- <span
- class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium"
- :class="currentChatStatusClass"
- >
- {{ currentChatStatusLabel }}
- </span>
- <span class="truncate text-xs text-gray-500">
- {{ currentChatTokenUsageLabel }}
- </span>
- </div>
- <div class="flex items-center gap-x-1">
- <button
- data-agent-window-action
- class="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"
- :title="$t('agent.minimize')"
- @click.stop="agentStore.minimize()"
- >
- &#8722;
- </button>
- <button
- data-agent-window-action
- class="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"
- :title="$t('agent.close')"
- @click.stop="agentStore.toggle()"
- >
- &#10005;
- </button>
- </div>
- </div>
-
- <div class="flex min-h-0 flex-1 overflow-hidden bg-white">
- <aside
- class="flex shrink-0 flex-col border-r border-gray-200 bg-gray-50"
- :style="sidebarStyle"
- >
- <div class="border-b border-gray-200 px-3 py-3">
- <div class="flex items-center justify-between gap-x-2">
- <div>
- <h2 class="text-xs font-semibold uppercase tracking-wide text-gray-500">
- {{ $t("agent.chat-list-label") }}
- </h2>
- </div>
- <button
- class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-100 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:text-gray-400"
- :disabled="isChatCreationDisabled"
- @click="createChat"
- >
- {{ $t("agent.new-chat") }}
- </button>
- </div>
- </div>
-
- <div class="min-h-0 flex-1 overflow-y-auto px-2 py-2">
- <div class="flex flex-col gap-y-1" data-agent-chat-list>
- <div
- v-for="chat in displayedChats"
- :key="chat.id"
- class="w-full rounded-md px-3 py-2 text-left text-sm transition-colors"
- :class="
- chat.id === agentStore.currentChatId
- ? 'bg-blue-50 text-blue-700'
- : 'text-gray-700 hover:bg-white'
- "
- :data-agent-chat-row="chat.id"
- >
- <NInput
- v-if="
- chat.id === agentStore.currentChatId && isRenamingCurrentChat
- "
- ref="renameInputRef"
- v-model:value="renamingTitle"
- size="small"
- :placeholder="$t('agent.rename-chat-placeholder')"
- data-agent-inline-rename-input
- @blur="commitRenameCurrentChat"
- @keydown="onRenameCurrentChatKeydown"
- />
- <button
- v-else
- type="button"
- class="w-full text-left disabled:cursor-not-allowed disabled:opacity-60"
- :disabled="!agentStore.canSelectChat(chat.id)"
- :aria-current="
- chat.id === agentStore.currentChatId ? 'true' : undefined
- "
- @click="handleChatRowClick(chat.id)"
- >
- <div class="truncate font-medium" data-agent-chat-title>
- {{ getChatLabel(chat) }}
- </div>
- <HumanizeTs
- :ts="Math.floor(chat.updatedTs / 1000)"
- class="mt-1 block truncate text-xs"
- :class="
- chat.id === agentStore.currentChatId
- ? 'text-blue-600/80'
- : 'text-gray-500'
- "
- data-agent-chat-updated-ts
- />
- </button>
- </div>
- </div>
- </div>
-
- <div class="border-t border-gray-200 px-3 py-3">
- <div class="flex flex-col gap-y-2">
- <div
- class="flex flex-wrap gap-x-2 gap-y-2"
- data-agent-chat-sidebar-actions
- >
- <template v-if="isCurrentChatInDisplayedMode">
- <button
- v-if="showArchivedOnly"
- class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-white"
- data-agent-unarchive-chat
- @click="toggleArchiveCurrentChat"
- >
- {{ $t("agent.unarchive-chat") }}
- </button>
- <NPopconfirm
- v-else
- @positive-click="toggleArchiveCurrentChat"
- >
- <template #trigger>
- <button
- class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-white"
- data-agent-archive-chat
- >
- {{ $t("agent.archive-chat") }}
- </button>
- </template>
- {{ $t("agent.archive-chat-confirmation") }}
- </NPopconfirm>
- <NPopconfirm
- v-if="showArchivedOnly"
- @positive-click="deleteCurrentChat"
- >
- <template #trigger>
- <button
- class="rounded-md border px-2 py-1.5 text-xs font-medium text-red-600 hover:bg-red-50"
- data-agent-delete-chat
- >
- {{ $t("agent.delete-chat") }}
- </button>
- </template>
- {{ $t("agent.delete-chat-confirmation") }}
- </NPopconfirm>
- </template>
- <button
- class="ml-auto inline-flex items-center rounded-md border p-1.5 text-xs font-medium text-gray-600 hover:bg-white"
- :aria-label="
- showArchivedOnly
- ? $t('agent.archived-only-chats')
- : $t('agent.active-only-chats')
- "
- :title="
- showArchivedOnly
- ? $t('agent.archived-only-chats')
- : $t('agent.active-only-chats')
- "
- data-agent-chat-list-mode
- @click="toggleChatListMode"
- >
- <component
- :is="showArchivedOnly ? ArchiveIcon : InboxIcon"
- class="h-3.5 w-3.5"
- aria-hidden="true"
- />
- </button>
- </div>
- </div>
- </div>
- </aside>
-
- <button
- type="button"
- data-agent-window-action
- data-agent-sidebar-resize
- class="group relative w-1 shrink-0 cursor-col-resize bg-gray-100 transition-colors hover:bg-blue-100"
- @mousedown="startSidebarResize"
- >
- <span
- class="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-transparent transition-colors group-hover:bg-blue-400"
- />
- </button>
-
- <div class="flex min-w-0 flex-1 flex-col">
- <AgentChat class="min-h-0 flex-1" />
- <AgentInput />
- </div>
- </div>
-
- <button
- type="button"
- data-agent-window-action
- data-agent-window-resize
- class="absolute bottom-0 right-0 flex h-5 w-5 cursor-se-resize items-end justify-end pb-0.5 pr-0.5 text-gray-300 hover:text-gray-400"
- :title="$t('agent.resize')"
- @mousedown="startResize"
- >
- <svg
- xmlns="http://www.w3.org/2000/svg"
- class="h-3 w-3"
- viewBox="0 0 12 12"
- fill="none"
- stroke="currentColor"
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="1.5"
- >
- <path d="M3.5 8.5h.01M6 6h.01M8.5 3.5h.01" />
- <path d="M3.5 11 11 3.5" />
- </svg>
- </button>
- </div>
- </Teleport>
-</template>
diff --git a/frontend/src/plugins/agent/components/ToolCallCard.vue b/frontend/src/plugins/agent/components/ToolCallCard.vue
deleted file mode 100644
index b22b68ddc9..0000000000
--- a/frontend/src/plugins/agent/components/ToolCallCard.vue
+++ /dev/null
@@ -1,274 +0,0 @@
-<script setup lang="ts">
-import { computed, ref } from "vue";
-import type {
- AgentAskUserOption,
- AgentAskUserResponse,
- ToolCall,
-} from "../logic/types";
-
-const props = defineProps<{
- toolCall: ToolCall;
- result?: string;
-}>();
-
-const expanded = ref(false);
-
-const parseJson = (value?: string): unknown => {
- if (!value) {
- return undefined;
- }
- try {
- return JSON.parse(value);
- } catch {
- return value;
- }
-};
-
-const formatJson = (value?: string): string => {
- if (!value) {
- return "";
- }
- try {
- return JSON.stringify(JSON.parse(value), null, 2);
- } catch {
- return value;
- }
-};
-
-const parseAskUserOption = (value: unknown): AgentAskUserOption | null => {
- if (!value || typeof value !== "object") {
- return null;
- }
-
- const option = value as Record<string, unknown>;
- const label =
- typeof option.label === "string"
- ? option.label.trim()
- : typeof option.value === "string"
- ? option.value.trim()
- : "";
- const optionValue =
- typeof option.value === "string" ? option.value.trim() : "";
-
- if (!label || !optionValue) {
- return null;
- }
-
- return {
- label,
- value: optionValue,
- description:
- typeof option.description === "string" && option.description.trim()
- ? option.description.trim()
- : undefined,
- };
-};
-
-const resultText = computed(() => props.result ?? "");
-const parsedArguments = computed(() => parseJson(props.toolCall.arguments));
-const parsedResult = computed(() => parseJson(resultText.value));
-const isAskUser = computed(() => props.toolCall.name === "ask_user");
-const isDone = computed(() => props.toolCall.name === "done");
-const askPrompt = computed(() => {
- if (
- typeof parsedArguments.value === "object" &&
- parsedArguments.value &&
- "prompt" in parsedArguments.value &&
- typeof parsedArguments.value.prompt === "string"
- ) {
- return parsedArguments.value.prompt;
- }
- return "";
-});
-const askKind = computed(() => {
- if (
- typeof parsedArguments.value === "object" &&
- parsedArguments.value &&
- "kind" in parsedArguments.value
- ) {
- if (parsedArguments.value.kind === "confirm") {
- return "confirm";
- }
- if (parsedArguments.value.kind === "choose") {
- return "choose";
- }
- }
- return "input";
-});
-const askDefaultValue = computed(() => {
- if (
- typeof parsedArguments.value === "object" &&
- parsedArguments.value &&
- "defaultValue" in parsedArguments.value &&
- typeof parsedArguments.value.defaultValue === "string"
- ) {
- return parsedArguments.value.defaultValue;
- }
- return "";
-});
-const askOptions = computed<AgentAskUserOption[]>(() => {
- if (
- typeof parsedArguments.value !== "object" ||
- !parsedArguments.value ||
- !("options" in parsedArguments.value) ||
- !Array.isArray(parsedArguments.value.options)
- ) {
- return [];
- }
-
- return parsedArguments.value.options
- .map((option) => parseAskUserOption(option))
- .filter((option): option is AgentAskUserOption => !!option);
-});
-const askResponse = computed<AgentAskUserResponse | null>(() => {
- if (
- typeof parsedResult.value !== "object" ||
- !parsedResult.value ||
- !("kind" in parsedResult.value) ||
- typeof parsedResult.value.kind !== "string" ||
- !("answer" in parsedResult.value) ||
- typeof parsedResult.value.answer !== "string"
- ) {
- return null;
- }
-
- const response = parsedResult.value as Record<string, unknown>;
-
- if (response.kind === "confirm") {
- if (typeof response.confirmed !== "boolean") {
- return null;
- }
- return response as AgentAskUserResponse;
- }
-
- if (response.kind === "choose") {
- if (typeof response.value !== "string") {
- return null;
- }
- return response as AgentAskUserResponse;
- }
-
- if (response.kind === "input") {
- return response as AgentAskUserResponse;
- }
-
- return null;
-});
-const doneText = computed(() => {
- if (
- typeof parsedArguments.value === "object" &&
- parsedArguments.value &&
- "text" in parsedArguments.value &&
- typeof parsedArguments.value.text === "string"
- ) {
- return parsedArguments.value.text;
- }
- return "";
-});
-const doneSuccess = computed(() => {
- if (
- typeof parsedArguments.value === "object" &&
- parsedArguments.value &&
- "success" in parsedArguments.value
- ) {
- return parsedArguments.value.success !== false;
- }
- return true;
-});
-</script>
-
-<template>
- <div class="rounded border bg-gray-50 text-xs">
- <div
- class="flex cursor-pointer items-center gap-x-2 px-2 py-1.5"
- @click="expanded = !expanded"
- >
- <span class="font-mono text-gray-600">{{ toolCall.name }}</span>
- <template v-if="isAskUser">
- <span v-if="resultText" class="text-green-500">
- {{ $t("agent.tool-response-submitted") }}
- </span>
- <span v-else class="text-amber-600">{{ $t("agent.tool-ask-user") }}</span>
- </template>
- <template v-else-if="isDone">
- <span :class="doneSuccess ? 'text-green-500' : 'text-red-500'">
- {{ doneSuccess ? $t("agent.tool-completed") : $t("agent.tool-failed") }}
- </span>
- </template>
- <template v-else>
- <span v-if="resultText" class="text-green-500">&#10003;</span>
- <span v-else class="animate-pulse text-gray-400">&#9679;</span>
- </template>
- <span class="ml-auto text-gray-400">{{ expanded ? "\u25BE" : "\u25B8" }}</span>
- </div>
-
- <div v-if="expanded" class="space-y-1 border-t px-2 py-1.5">
- <template v-if="isAskUser">
- <div class="text-gray-500">
- {{
- askKind === "confirm"
- ? $t("agent.tool-ask-user-confirm")
- : askKind === "choose"
- ? $t("agent.tool-ask-user-choose")
- : $t("agent.tool-ask-user-input")
- }}
- </div>
- <div class="text-gray-500">{{ $t("agent.tool-prompt") }}</div>
- <pre class="whitespace-pre-wrap break-all text-gray-700">{{ askPrompt }}</pre>
- <template v-if="askDefaultValue">
- <div class="text-gray-500">{{ $t("agent.tool-default-value") }}</div>
- <pre class="whitespace-pre-wrap break-all text-gray-700">{{
- askDefaultValue
- }}</pre>
- </template>
- <template v-if="askKind === 'choose' && askOptions.length > 0">
- <div class="text-gray-500">{{ $t("agent.tool-options") }}</div>
- <div class="space-y-1">
- <div
- v-for="option in askOptions"
- :key="option.value"
- class="rounded border border-gray-200 bg-white px-2 py-1"
- >
- <div class="font-medium text-gray-700">{{ option.label }}</div>
- <div class="text-gray-500">{{ option.value }}</div>
- <div v-if="option.description" class="text-gray-500">
- {{ option.description }}
- </div>
- </div>
- </div>
- </template>
- <template v-if="askResponse">
- <div class="text-gray-500">{{ $t("agent.tool-answer") }}</div>
- <pre class="whitespace-pre-wrap break-all text-gray-700">{{
- askResponse.answer
- }}</pre>
- <template v-if="askResponse.kind === 'choose'">
- <div class="text-gray-500">{{ $t("agent.tool-value") }}</div>
- <pre class="whitespace-pre-wrap break-all text-gray-700">{{
- askResponse.value
- }}</pre>
- </template>
- </template>
- </template>
-
- <template v-else-if="isDone">
- <div class="text-gray-500">{{ $t("agent.result") }}</div>
- <pre class="whitespace-pre-wrap break-all text-gray-700">{{ doneText }}</pre>
- </template>
-
- <template v-else>
- <div class="text-gray-500">{{ $t("agent.args") }}</div>
- <pre class="whitespace-pre-wrap break-all text-gray-700">{{
- formatJson(toolCall.arguments)
- }}</pre>
- <template v-if="resultText">
- <div class="text-gray-500">{{ $t("agent.result") }}</div>
- <pre
- class="max-h-32 overflow-y-auto whitespace-pre-wrap break-all text-gray-700"
- >{{ formatJson(resultText) }}</pre
- >
- </template>
- </template>
- </div>
- </div>
-</template>
diff --git a/frontend/src/plugins/agent/index.ts b/frontend/src/plugins/agent/index.ts
deleted file mode 100644
index d55d89e50e..0000000000
--- a/frontend/src/plugins/agent/index.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { onMounted, onUnmounted } from "vue";
-import { useAgentStore } from "./store/agent";
-
-export { default as AgentWindow } from "./components/AgentWindow.vue";
-export { useAgentStore } from "./store/agent";
-
-export function useAgentShortcut() {
- const store = useAgentStore();
-
- function handleKeydown(e: KeyboardEvent) {
- if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "A") {
- e.preventDefault();
- store.toggle();
- }
- }
-
- onMounted(() => {
- window.addEventListener("keydown", handleKeydown);
- });
-
- onUnmounted(() => {
- window.removeEventListener("keydown", handleKeydown);
- });
-}
diff --git a/frontend/src/plugins/agent/store/agent.ts b/frontend/src/plugins/agent/store/agent.ts
deleted file mode 100644
index dcb517b485..0000000000
--- a/frontend/src/plugins/agent/store/agent.ts
+++ /dev/null
@@ -1,885 +0,0 @@
-import { defineStore } from "pinia";
-import { v4 as uuidv4 } from "uuid";
-import { computed, ref, watch } from "vue";
-import type {
- AgentAskUserResponse,
- AgentChat,
- AgentChatSnapshot,
- AgentChatStatus,
- AgentMessage,
- AgentPendingAsk,
- Message,
- ToolCall,
-} from "../logic/types";
-
-export const AGENT_STATE_KEY = "bb-agent-state-v2";
-export const AGENT_WINDOW_KEY = "bb-agent-window";
-
-interface PersistedAgentState {
- currentChatId: string | null;
- chats: AgentChat[];
- messagesByChatId: Record<string, AgentMessage[]>;
- pendingAskByChatId: Record<string, AgentPendingAsk>;
-}
-
-interface CreateChatOptions {
- page?: AgentChatSnapshot;
- select?: boolean;
- title?: string;
- archived?: boolean;
-}
-
-interface AddMessageOptions extends Message {
- chatId?: string;
- metadata?: AgentMessage["metadata"];
-}
-
-const DEFAULT_CHAT_STATUS: AgentChatStatus = "idle";
-
-const createChatRecord = (options: CreateChatOptions = {}): AgentChat => {
- const now = Date.now();
- return {
- id: uuidv4(),
- title: options.title ?? "",
- createdTs: now,
- updatedTs: now,
- status: DEFAULT_CHAT_STATUS,
- totalTokensUsed: 0,
- page: options.page,
- archived: options.archived ?? false,
- lastError: null,
- requiresAIConfiguration: false,
- interrupted: false,
- runId: null,
- };
-};
-
-const normalizeChatTitle = (title?: string) => {
- return (title ?? "").trim();
-};
-
-const getChatTitleFromMessage = (content?: string) => {
- const title = normalizeChatTitle(content).replace(/\s+/g, " ");
- if (!title) {
- return "";
- }
- return title.length <= 48 ? title : `${title.slice(0, 45)}...`;
-};
-
-const isRecord = (value: unknown): value is Record<string, unknown> => {
- return typeof value === "object" && value !== null;
-};
-
-const normalizeMessage = (
- raw: unknown,
- chatId: string,
- fallbackTs: number
-): AgentMessage => {
- const message = isRecord(raw) ? raw : {};
- return {
- id: typeof message.id === "string" ? message.id : uuidv4(),
- chatId:
- typeof message.chatId === "string"
- ? message.chatId
- : typeof message.threadId === "string"
- ? message.threadId
- : chatId,
- createdTs:
- typeof message.createdTs === "number" ? message.createdTs : fallbackTs,
- role:
- message.role === "assistant" ||
- message.role === "system" ||
- message.role === "tool"
- ? message.role
- : "user",
- content: typeof message.content === "string" ? message.content : undefined,
- toolCalls: Array.isArray(message.toolCalls)
- ? (message.toolCalls as ToolCall[])
- : undefined,
- toolCallId:
- typeof message.toolCallId === "string" ? message.toolCallId : undefined,
- metadata: isRecord(message.metadata)
- ? { ...(message.metadata as AgentMessage["metadata"]) }
- : undefined,
- };
-};
-
-const normalizePendingAsk = (raw: unknown): AgentPendingAsk | null => {
- const pendingAsk = isRecord(raw) ? raw : {};
- if (
- typeof pendingAsk.toolCallId !== "string" ||
- typeof pendingAsk.prompt !== "string"
- ) {
- return null;
- }
-
- const options = Array.isArray(pendingAsk.options)
- ? pendingAsk.options
- .map((option) => {
- const candidate = isRecord(option) ? option : {};
- const label =
- typeof candidate.label === "string"
- ? candidate.label.trim()
- : typeof candidate.value === "string"
- ? candidate.value.trim()
- : "";
- const value =
- typeof candidate.value === "string" ? candidate.value.trim() : "";
- if (!label || !value) {
- return null;
- }
- return {
- label,
- value,
- description:
- typeof candidate.description === "string" &&
- candidate.description.trim()
- ? candidate.description.trim()
- : undefined,
- };
- })
- .filter(
- (option): option is NonNullable<typeof option> => option !== null
- )
- : [];
-
- const kind =
- pendingAsk.kind === "confirm"
- ? "confirm"
- : pendingAsk.kind === "choose" && options.length > 0
- ? "choose"
- : "input";
-
- return {
- toolCallId: pendingAsk.toolCallId,
- prompt: pendingAsk.prompt,
- kind,
- defaultValue:
- typeof pendingAsk.defaultValue === "string"
- ? pendingAsk.defaultValue
- : undefined,
- confirmLabel:
- typeof pendingAsk.confirmLabel === "string"
- ? pendingAsk.confirmLabel
- : undefined,
- cancelLabel:
- typeof pendingAsk.cancelLabel === "string"
- ? pendingAsk.cancelLabel
- : undefined,
- options: kind === "choose" ? options : undefined,
- };
-};
-
-const normalizeChat = (raw: unknown): AgentChat => {
- const chat = isRecord(raw) ? raw : {};
- const now = Date.now();
- const status =
- chat.status === "running" ||
- chat.status === "awaiting_user" ||
- chat.status === "error"
- ? chat.status
- : DEFAULT_CHAT_STATUS;
- return {
- id: typeof chat.id === "string" ? chat.id : uuidv4(),
- title: typeof chat.title === "string" ? chat.title : "",
- createdTs: typeof chat.createdTs === "number" ? chat.createdTs : now,
- updatedTs: typeof chat.updatedTs === "number" ? chat.updatedTs : now,
- status,
- totalTokensUsed:
- typeof chat.totalTokensUsed === "number" &&
- Number.isFinite(chat.totalTokensUsed) &&
- chat.totalTokensUsed >= 0
- ? chat.totalTokensUsed
- : 0,
- page:
- isRecord(chat.page) &&
- typeof chat.page.path === "string" &&
- typeof chat.page.title === "string"
- ? {
- path: chat.page.path,
- title: chat.page.title,
- }
- : undefined,
- archived: Boolean(chat.archived),
- lastError:
- typeof chat.lastError === "string"
- ? chat.lastError
- : chat.lastError === null
- ? null
- : null,
- requiresAIConfiguration: Boolean(chat.requiresAIConfiguration),
- interrupted: Boolean(chat.interrupted),
- runId: typeof chat.runId === "string" ? chat.runId : null,
- };
-};
-
-const sortMessages = (messages: AgentMessage[]) => {
- messages.sort((a, b) => a.createdTs - b.createdTs);
- return messages;
-};
-
-const createEmptyPersistedState = (): PersistedAgentState => ({
- currentChatId: null,
- chats: [],
- messagesByChatId: {},
- pendingAskByChatId: {},
-});
-
-const normalizePersistedState = (raw: unknown): PersistedAgentState => {
- if (!isRecord(raw)) {
- return createEmptyPersistedState();
- }
-
- const rawChats = Array.isArray(raw.chats)
- ? raw.chats
- : Array.isArray(raw.threads)
- ? raw.threads
- : [];
- const rawMessagesByChatId = isRecord(raw.messagesByChatId)
- ? raw.messagesByChatId
- : isRecord(raw.messagesByThreadId)
- ? raw.messagesByThreadId
- : {};
- const rawPendingAskByChatId = isRecord(raw.pendingAskByChatId)
- ? raw.pendingAskByChatId
- : isRecord(raw.pendingAskByThreadId)
- ? raw.pendingAskByThreadId
- : {};
-
- const chats = rawChats.map((chat) => normalizeChat(chat));
- const messagesByChatId: Record<string, AgentMessage[]> = {};
- const pendingAskByChatId: Record<string, AgentPendingAsk> = {};
-
- for (const chat of chats) {
- const rawMessages: unknown[] = Array.isArray(rawMessagesByChatId[chat.id])
- ? (rawMessagesByChatId[chat.id] as unknown[])
- : [];
- const messages = sortMessages(
- rawMessages.map((message, index) =>
- normalizeMessage(message, chat.id, chat.createdTs + index)
- )
- );
-
- const firstUserMessage = messages.find(
- (message) => message.role === "user"
- );
- const lastMessage = messages.at(-1);
-
- if (!chat.title) {
- chat.title = getChatTitleFromMessage(firstUserMessage?.content);
- }
- if (lastMessage) {
- chat.updatedTs = Math.max(chat.updatedTs, lastMessage.createdTs);
- }
- if (chat.status === "running") {
- chat.status = DEFAULT_CHAT_STATUS;
- chat.interrupted = true;
- chat.lastError = null;
- chat.requiresAIConfiguration = false;
- }
-
- const pendingAsk = normalizePendingAsk(rawPendingAskByChatId[chat.id]);
- if (chat.status === "awaiting_user") {
- if (pendingAsk) {
- pendingAskByChatId[chat.id] = pendingAsk;
- } else {
- chat.status = DEFAULT_CHAT_STATUS;
- }
- }
-
- messagesByChatId[chat.id] = messages;
- }
-
- const savedCurrentChatId =
- typeof raw.currentChatId === "string"
- ? raw.currentChatId
- : typeof raw.currentThreadId === "string"
- ? raw.currentThreadId
- : null;
- const currentChatId =
- savedCurrentChatId && chats.some((chat) => chat.id === savedCurrentChatId)
- ? savedCurrentChatId
- : (chats[0]?.id ?? null);
-
- return {
- currentChatId,
- chats,
- messagesByChatId,
- pendingAskByChatId,
- };
-};
-
-export const useAgentStore = defineStore("agent", () => {
- const visible = ref(false);
- const position = ref({
- x: window.innerWidth - 420,
- y: window.innerHeight - 520,
- });
- const size = ref({ width: 400, height: 500 });
- const sidebarWidth = ref(256);
- const minimized = ref(false);
-
- const chats = ref<AgentChat[]>([]);
- const messagesByChatId = ref<Record<string, AgentMessage[]>>({});
- const pendingAskByChatId = ref<Record<string, AgentPendingAsk>>({});
- const currentChatId = ref<string | null>(null);
- const abortControllersByChatId = ref<Record<string, AbortController>>({});
-
- const orderedChats = computed(() =>
- [...chats.value].sort((a, b) => {
- if (b.updatedTs !== a.updatedTs) {
- return b.updatedTs - a.updatedTs;
- }
- return b.createdTs - a.createdTs;
- })
- );
- const currentChat = computed(
- () => chats.value.find((chat) => chat.id === currentChatId.value) ?? null
- );
- const messages = computed(
- () =>
- (currentChatId.value
- ? messagesByChatId.value[currentChatId.value]
- : undefined) ?? []
- );
- const currentPendingAsk = computed(
- () =>
- (currentChatId.value
- ? pendingAskByChatId.value[currentChatId.value]
- : undefined) ?? null
- );
- const loading = computed(() => currentChat.value?.status === "running");
- const error = computed(() => currentChat.value?.lastError ?? null);
- const currentChatRequiresAIConfiguration = computed(
- () => currentChat.value?.requiresAIConfiguration ?? false
- );
- const runningChatIds = computed(() =>
- chats.value
- .filter((chat) => chat.status === "running")
- .map((chat) => chat.id)
- );
- const hasRunningChat = computed(() => runningChatIds.value.length > 0);
-
- const getChat = (chatId?: string | null) => {
- if (!chatId) {
- return null;
- }
- return chats.value.find((chat) => chat.id === chatId) ?? null;
- };
-
- const getMessages = (chatId?: string | null) => {
- if (!chatId) {
- return [];
- }
- return messagesByChatId.value[chatId] ?? [];
- };
-
- const getPendingAsk = (chatId = currentChatId.value) => {
- if (!chatId) {
- return null;
- }
- return pendingAskByChatId.value[chatId] ?? null;
- };
-
- const getAbortController = (chatId?: string | null) => {
- if (!chatId) {
- return null;
- }
- return abortControllersByChatId.value[chatId] ?? null;
- };
-
- const isChatRunning = (chatId?: string | null) => {
- return getChat(chatId)?.status === "running";
- };
-
- const touchChat = (chatId: string) => {
- const chat = getChat(chatId);
- if (!chat) {
- return null;
- }
- chat.updatedTs = Date.now();
- return chat;
- };
-
- const setAbortController = (
- chatId: string,
- controller: AbortController | null
- ) => {
- if (controller) {
- abortControllersByChatId.value[chatId] = controller;
- return controller;
- }
- delete abortControllersByChatId.value[chatId];
- return null;
- };
-
- const clearPendingAsk = (chatId = currentChatId.value) => {
- if (!chatId || !pendingAskByChatId.value[chatId]) {
- return;
- }
- delete pendingAskByChatId.value[chatId];
- touchChat(chatId);
- };
-
- const setPendingAsk = (chatId: string, pendingAsk: AgentPendingAsk) => {
- pendingAskByChatId.value[chatId] = pendingAsk;
- touchChat(chatId);
- return pendingAsk;
- };
-
- const setChatStatus = (
- chatId: string,
- status: AgentChatStatus,
- options: {
- interrupted?: boolean;
- lastError?: string | null;
- requiresAIConfiguration?: boolean;
- page?: AgentChatSnapshot;
- } = {}
- ) => {
- const chat = getChat(chatId);
- if (!chat) {
- return null;
- }
- chat.status = status;
- chat.interrupted = options.interrupted ?? false;
- chat.lastError = options.lastError ?? null;
- chat.requiresAIConfiguration = options.requiresAIConfiguration ?? false;
- if (options.page) {
- chat.page = options.page;
- }
- if (status !== "awaiting_user") {
- delete pendingAskByChatId.value[chatId];
- }
- touchChat(chatId);
- return chat;
- };
-
- const ensureCurrentChat = (page?: AgentChatSnapshot) => {
- const existing = getChat(currentChatId.value);
- if (existing) {
- if (page && !existing.page) {
- existing.page = page;
- touchChat(existing.id);
- }
- return existing;
- }
- return createChat({ page });
- };
-
- const createChat = (options: CreateChatOptions = {}) => {
- const chat = createChatRecord(options);
- chats.value.push(chat);
- messagesByChatId.value[chat.id] = [];
- const shouldSelect =
- (options.select ?? true) &&
- (!hasRunningChat.value || currentChatId.value === null);
- if (shouldSelect) {
- currentChatId.value = chat.id;
- }
- return chat;
- };
-
- const selectNextAvailableChat = (preferredChatId?: string | null) => {
- const preferredChat = getChat(preferredChatId);
- if (preferredChat) {
- currentChatId.value = preferredChat.id;
- return preferredChat;
- }
- const fallbackChat = orderedChats.value[0] ?? createChat();
- currentChatId.value = fallbackChat.id;
- return fallbackChat;
- };
-
- const canSelectChat = (chatId?: string | null) => {
- if (!chatId || !getChat(chatId)) {
- return false;
- }
- return !hasRunningChat.value || currentChatId.value === chatId;
- };
-
- const setCurrentChat = (chatId: string) => {
- if (canSelectChat(chatId)) {
- currentChatId.value = chatId;
- }
- };
-
- const updateChatPage = (chatId: string, page: AgentChatSnapshot) => {
- const chat = getChat(chatId);
- if (!chat) {
- return null;
- }
- chat.page = page;
- touchChat(chatId);
- return chat;
- };
-
- const renameChat = (chatId: string, title: string) => {
- const chat = getChat(chatId);
- if (!chat) {
- return null;
- }
- const normalizedTitle = normalizeChatTitle(title);
- if (chat.title === normalizedTitle) {
- return chat;
- }
- chat.title = normalizedTitle;
- touchChat(chatId);
- return chat;
- };
-
- const archiveChat = (chatId: string) => {
- const chat = getChat(chatId);
- if (!chat) {
- return null;
- }
- chat.archived = true;
- touchChat(chatId);
- return chat;
- };
-
- const unarchiveChat = (chatId: string) => {
- const chat = getChat(chatId);
- if (!chat) {
- return null;
- }
- chat.archived = false;
- touchChat(chatId);
- return chat;
- };
-
- const addMessage = (message: AddMessageOptions) => {
- const chat = getChat(message.chatId) ?? ensureCurrentChat();
- const createdTs = Date.now();
- const agentMessage: AgentMessage = {
- ...message,
- id: uuidv4(),
- chatId: chat.id,
- createdTs,
- };
- const chatMessages = getMessages(chat.id);
- if (chatMessages.length === 0) {
- messagesByChatId.value[chat.id] = chatMessages;
- }
- chatMessages.push(agentMessage);
- if (message.role === "user" && !chat.title) {
- chat.title = getChatTitleFromMessage(message.content);
- }
- chat.lastError = null;
- chat.requiresAIConfiguration = false;
- chat.interrupted = false;
- chat.updatedTs = createdTs;
- return agentMessage;
- };
-
- const removeMessagesByRunId = (chatId: string, runId?: string | null) => {
- if (!runId) {
- return [];
- }
- const chat = getChat(chatId);
- if (!chat) {
- return [];
- }
- const existingMessages = getMessages(chatId);
- const removedMessages = existingMessages.filter(
- (message) => message.metadata?.runId === runId
- );
- if (removedMessages.length === 0) {
- return [];
- }
- messagesByChatId.value[chatId] = existingMessages.filter(
- (message) => message.metadata?.runId !== runId
- );
- touchChat(chatId);
- return removedMessages;
- };
-
- const appendToolCall = (
- chatId: string,
- messageId: string,
- toolCall: ToolCall
- ) => {
- const message = getMessages(chatId).find(
- (candidate) => candidate.id === messageId
- );
- if (!message) {
- return null;
- }
- message.toolCalls = [...(message.toolCalls ?? []), toolCall];
- touchChat(chatId);
- return message;
- };
-
- const incrementChatTotalTokens = (
- chatId: string,
- totalTokensUsed: number
- ) => {
- const chat = getChat(chatId);
- if (!chat || totalTokensUsed <= 0) {
- return null;
- }
- chat.totalTokensUsed += totalTokensUsed;
- touchChat(chatId);
- return chat;
- };
-
- const awaitUser = (chatId: string, pendingAsk: AgentPendingAsk) => {
- setChatStatus(chatId, "awaiting_user");
- return setPendingAsk(chatId, pendingAsk);
- };
-
- const answerPendingAsk = (
- chatId: string,
- response: AgentAskUserResponse,
- metadata?: AgentMessage["metadata"]
- ) => {
- const pendingAsk = getPendingAsk(chatId);
- if (!pendingAsk) {
- return null;
- }
- const toolMessage = addMessage({
- chatId,
- role: "tool",
- toolCallId: pendingAsk.toolCallId,
- content: JSON.stringify(response),
- metadata,
- });
- clearPendingAsk(chatId);
- return toolMessage;
- };
-
- const cancel = (chatId = currentChatId.value) => {
- if (!chatId) {
- return;
- }
- getAbortController(chatId)?.abort();
- setAbortController(chatId, null);
- if (isChatRunning(chatId)) {
- interruptChatRun(chatId);
- }
- };
-
- const clearError = (chatId = currentChatId.value) => {
- const chat = getChat(chatId);
- if (!chat) {
- return;
- }
- chat.lastError = null;
- chat.requiresAIConfiguration = false;
- chat.interrupted = false;
- chat.runId = null;
- if (chat.status === "error") {
- chat.status = DEFAULT_CHAT_STATUS;
- }
- touchChat(chat.id);
- };
-
- const interruptChatRun = (chatId: string, page?: AgentChatSnapshot) => {
- setChatStatus(chatId, DEFAULT_CHAT_STATUS, {
- interrupted: true,
- page,
- });
- };
-
- const startChatRun = (
- chatId: string,
- page?: AgentChatSnapshot,
- options: {
- runId?: string;
- } = {}
- ) => {
- setChatStatus(chatId, "running", {
- page,
- });
- const chat = getChat(chatId);
- if (chat) {
- chat.runId = options.runId ?? chat.runId ?? null;
- }
- };
-
- const finishChatRun = (
- chatId: string,
- options: {
- status?: Extract<AgentChatStatus, "idle" | "error">;
- lastError?: string | null;
- requiresAIConfiguration?: boolean;
- } = {}
- ) => {
- setChatStatus(chatId, options.status ?? DEFAULT_CHAT_STATUS, {
- lastError: options.lastError ?? null,
- requiresAIConfiguration: options.requiresAIConfiguration ?? false,
- interrupted: false,
- });
- const chat = getChat(chatId);
- if (chat) {
- chat.runId = null;
- }
- };
-
- const deleteChat = (chatId: string) => {
- if (!getChat(chatId)) {
- return false;
- }
- cancel(chatId);
- chats.value = chats.value.filter((chat) => chat.id !== chatId);
- delete messagesByChatId.value[chatId];
- delete pendingAskByChatId.value[chatId];
- delete abortControllersByChatId.value[chatId];
- if (currentChatId.value === chatId) {
- selectNextAvailableChat();
- }
- return true;
- };
-
- const saveWindowState = () => {
- localStorage.setItem(
- AGENT_WINDOW_KEY,
- JSON.stringify({
- position: position.value,
- size: size.value,
- sidebarWidth: sidebarWidth.value,
- })
- );
- };
-
- const saveState = () => {
- const persistedState: PersistedAgentState = {
- currentChatId: currentChatId.value,
- chats: chats.value,
- messagesByChatId: messagesByChatId.value,
- pendingAskByChatId: pendingAskByChatId.value,
- };
- localStorage.setItem(AGENT_STATE_KEY, JSON.stringify(persistedState));
- };
-
- const loadState = () => {
- const saved = localStorage.getItem(AGENT_STATE_KEY);
- if (saved) {
- try {
- const state = normalizePersistedState(JSON.parse(saved));
- chats.value = state.chats;
- messagesByChatId.value = state.messagesByChatId;
- pendingAskByChatId.value = state.pendingAskByChatId;
- currentChatId.value = state.currentChatId;
- } catch {
- localStorage.removeItem(AGENT_STATE_KEY);
- }
- }
-
- if (!currentChatId.value || !getChat(currentChatId.value)) {
- const chat = createChat();
- currentChatId.value = chat.id;
- }
- };
-
- const loadWindowState = () => {
- const saved = localStorage.getItem(AGENT_WINDOW_KEY);
- if (!saved) {
- return;
- }
- try {
- const state = JSON.parse(saved) as {
- position?: { x?: number; y?: number };
- size?: { width?: number; height?: number };
- sidebarWidth?: number;
- };
- if (
- typeof state.position?.x === "number" &&
- typeof state.position?.y === "number"
- ) {
- position.value = {
- x: state.position.x,
- y: state.position.y,
- };
- }
- if (
- typeof state.size?.width === "number" &&
- typeof state.size?.height === "number"
- ) {
- size.value = {
- width: state.size.width,
- height: state.size.height,
- };
- }
- if (typeof state.sidebarWidth === "number") {
- sidebarWidth.value = state.sidebarWidth;
- }
- } catch {
- localStorage.removeItem(AGENT_WINDOW_KEY);
- }
- };
-
- watch(
- [chats, messagesByChatId, pendingAskByChatId, currentChatId],
- saveState,
- {
- deep: true,
- }
- );
-
- loadState();
-
- return {
- visible,
- position,
- size,
- sidebarWidth,
- minimized,
- chats,
- orderedChats,
- currentChatId,
- currentChat,
- messages,
- currentPendingAsk,
- loading,
- error,
- currentChatRequiresAIConfiguration,
- runningChatIds,
- hasRunningChat,
- abortControllersByChatId,
- toggle() {
- visible.value = !visible.value;
- if (visible.value) {
- minimized.value = false;
- }
- },
- minimize() {
- minimized.value = true;
- },
- restore() {
- minimized.value = false;
- },
- getChat,
- getMessages,
- getPendingAsk,
- getAbortController,
- isChatRunning,
- canSelectChat,
- setAbortController,
- createChat,
- ensureCurrentChat,
- setCurrentChat,
- updateChatPage,
- renameChat,
- archiveChat,
- unarchiveChat,
- deleteChat,
- setPendingAsk,
- clearPendingAsk,
- setChatStatus,
- startChatRun,
- finishChatRun,
- interruptChatRun,
- awaitUser,
- answerPendingAsk,
- touchChat,
- incrementChatTotalTokens,
- addMessage,
- removeMessagesByRunId,
- appendToolCall,
- clearError,
- cancel,
- saveWindowState,
- loadWindowState,
- };
-});
diff --git a/frontend/src/react/components/HumanizeTs.tsx b/frontend/src/react/components/HumanizeTs.tsx
new file mode 100644
index 0000000000..3a38102fd6
--- /dev/null
+++ b/frontend/src/react/components/HumanizeTs.tsx
@@ -0,0 +1,24 @@
+import { useTranslation } from "react-i18next";
+
+function formatRelativeTime(tsMs: number, locale: string): string {
+ const seconds = Math.floor((Date.now() - tsMs) / 1000);
+ const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
+ if (seconds < 60) return rtf.format(-seconds, "second");
+ if (seconds < 3600) return rtf.format(-Math.floor(seconds / 60), "minute");
+ if (seconds < 86400) return rtf.format(-Math.floor(seconds / 3600), "hour");
+ return rtf.format(-Math.floor(seconds / 86400), "day");
+}
+
+interface HumanizeTsProps {
+ ts: number;
+ className?: string;
+}
+
+export function HumanizeTs({ ts, className }: HumanizeTsProps) {
+ const { i18n } = useTranslation();
+ return (
+ <span className={className}>
+ {formatRelativeTime(ts * 1000, i18n.language)}
+ </span>
+ );
+}
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index b17381f02c..42942aa9e8 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -60,144 +60,81 @@
"self": "Condition"
}
},
- "changelog": {
- "select": "Schema version is recorded each time a schema change is applied via Bytebase",
- "self": "Changelog"
- },
"common": {
- "activated": "Activated",
- "active": "Active",
"add": "Add",
"add-permissions": "Add permissions",
"added": "Added",
"address": "Address",
"all": "All",
"archive": "Archive",
- "archive-description": "Mark \"{{name}}\" as archived and read-only.",
- "archive-resource": "Archive {{type}}",
"archived": "Archived",
"back": "Back",
"cancel": "Cancel",
"cannot-undo-this-action": "You cannot undo this action",
- "changelog": "Changelog",
- "classification-level": "Classification Level",
"clear": "Clear",
"close": "Close",
- "columns": "Columns",
"configure": "Configure",
"configure-now": "Configure now",
"confirm": "Confirm",
- "confirm-and-add": "Confirm and add",
"confirm-and-update": "Confirm and update",
- "confirm-archive": "Archive Resource?",
- "confirm-delete": "Delete Resource?",
- "confirm-to-revert": "Confirm to revert your editing?",
"copied": "Copied",
"copy": "Copy",
- "copy-failed": "Copy failed",
"create": "Create",
"created": "Created",
- "created-at": "Created",
- "creator": "Creator",
- "danger-zone": "Danger Zone",
- "database": "Database",
- "database-group": "Database Group",
- "databases": "Databases",
- "default": "Default",
"delete": "Delete",
"delete-resource": "Delete {{type}}",
- "delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
"deleted": "Deleted",
"description": "Description",
- "deselect-all": "Deselect all",
- "disable": "Disable",
"discard-changes": "Discard changes",
- "download": "Download",
"edit": "Edit",
"email": "Email",
- "email-ascii-only": "Email addresses only support ASCII characters (letters, numbers, and symbols like . _ - +).",
- "empty": "Empty",
- "enable": "Enable",
- "enabled": "Enabled",
"environment": "Environment",
"environment-name": "Environment Name",
- "environments": "Environments",
- "expiration": "Expiration",
"export": "Export",
"failed": "Failed",
"file-selector": {
"size-limit": "File size should less than {{size}} MiB",
"type-limit": "Only support {{extension}} file"
},
- "filter": "Filter",
"filter-by-name": "Filter by name",
"from": "From",
"general": "General",
"groups": "Groups",
- "home": "Home",
"id": "ID",
"instance": "Instance",
- "instances": "Instances",
"is-required": "is required",
- "issues": "Issues",
- "items": "items",
- "key": "Key",
"labels": "Labels",
"learn-more": "Learn more",
"leave-without-saving": "Leave without saving?",
"load-more": "Load more",
"loading": "Loading",
- "manage": "Manage",
- "manually-select": "Manually select",
"members_one": "Member",
"members_other": "Members",
"missing-required-permission": "Missing required permissions {{permissions}}",
"n-items-selected": "{{n}} items selected",
- "n-more": "+{{n}} more",
"name": "Name",
"next": "Next",
"no-data": "No data",
"ok": "OK",
"operations": "Operations",
- "optional": "Optional",
- "pending": "Pending",
"permissions": "Permissions",
- "previous": "Previous",
"project": "Project",
- "projects": "Projects",
- "reason": "Reason",
- "regenerate": "Regenerate",
- "release": "Release",
"reorder": "Reorder",
"required-permission": "Required permissions",
"required-workspace-permission": "Following permissions are required to initialize the workspace UX",
- "resource": "Resource",
- "resources": "Resources",
"restore": "Restore",
"restored": "Restored",
"revert": "Revert",
- "revoke": "Revoke",
- "revoked": "Revoked",
"rows-per-page": "Rows per page",
"save": "Save",
- "schema": "Schema",
- "scope": "Scope",
"search": "Search",
- "search-for-more": "Search for more",
"select": "Please Select",
"select-all": "Select all",
- "selected": "selected",
"sensitive-placeholder": "Sensitive - write only",
- "setting": "Setting",
- "settings": "Settings",
"state": "State",
- "statement": "Statement",
- "status": "Status",
"system": "System",
- "table": "Table",
"title": "Title",
"to": "To",
- "total": "Total",
"total-n-items": "Total {{n}} items",
"type": "Type",
"unassigned": "Unassigned",
@@ -206,7 +143,6 @@
"updated": "Updated",
"upload": "Upload",
"users": "Users",
- "value": "Value",
"view": "View",
"view-details": "View Details",
"warning": "Warning",
@@ -216,7 +152,68 @@
"rejected": "Rejected",
"sql": "SQL",
"untitled": "Untitled",
- "you": "you"
+ "you": "you",
+ "copy-failed": "Copy failed",
+ "dismiss": "Dismiss",
+ "activated": "Activated",
+ "active": "Active",
+ "archive-description": "Mark \"{{name}}\" as archived and read-only.",
+ "archive-resource": "Archive {{type}}",
+ "changelog": "Changelog",
+ "classification-level": "Classification Level",
+ "columns": "Columns",
+ "confirm-and-add": "Confirm and add",
+ "confirm-archive": "Archive Resource?",
+ "confirm-delete": "Delete Resource?",
+ "confirm-to-revert": "Confirm to revert your editing?",
+ "created-at": "Created",
+ "creator": "Creator",
+ "danger-zone": "Danger Zone",
+ "database": "Database",
+ "database-group": "Database Group",
+ "databases": "Databases",
+ "default": "Default",
+ "delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
+ "deselect-all": "Deselect all",
+ "disable": "Disable",
+ "download": "Download",
+ "email-ascii-only": "Email addresses only support ASCII characters (letters, numbers, and symbols like . _ - +).",
+ "empty": "Empty",
+ "enable": "Enable",
+ "enabled": "Enabled",
+ "environments": "Environments",
+ "expiration": "Expiration",
+ "filter": "Filter",
+ "home": "Home",
+ "instances": "Instances",
+ "issues": "Issues",
+ "items": "items",
+ "key": "Key",
+ "manage": "Manage",
+ "manually-select": "Manually select",
+ "n-more": "+{{n}} more",
+ "optional": "Optional",
+ "pending": "Pending",
+ "previous": "Previous",
+ "projects": "Projects",
+ "reason": "Reason",
+ "regenerate": "Regenerate",
+ "release": "Release",
+ "resource": "Resource",
+ "resources": "Resources",
+ "revoke": "Revoke",
+ "revoked": "Revoked",
+ "schema": "Schema",
+ "scope": "Scope",
+ "search-for-more": "Search for more",
+ "selected": "selected",
+ "setting": "Setting",
+ "settings": "Settings",
+ "statement": "Statement",
+ "status": "Status",
+ "table": "Table",
+ "total": "Total",
+ "value": "Value"
},
"common.add": "Add",
"common.admin": "Admin",
@@ -365,21 +362,25 @@
"data-source.ssl.verify-certificate": "Verify TLS certificate",
"data-source.ssl.verify-certificate-tooltip": "Enable TLS certificate verification for secure connections. Disable only for development or when certificates cannot be properly validated (e.g., self-signed certs, VPN environments). Warning: Disabling verification is insecure",
"database": {
- "all": "All databases",
- "change-database": "Change Database",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
"edit-environment": "Edit Environment",
"edit-labels": "Edit Labels",
"engine": "Engine",
- "expression": "Expression",
"filter-database": "Filter database",
+ "selected-n-databases": "{{n}} database(s) selected",
+ "successfully-transferred-databases": "Successfully transferred databases",
+ "sync-schema-button": "Sync Schema",
+ "sync-status-failed": "Sync failed",
+ "transfer-project": "Transfer Project",
+ "unassign": "Unassign",
+ "all": "All databases",
+ "change-database": "Change Database",
+ "expression": "Expression",
"mixed-label-values": "mixed values",
"mixed-label-values-warning": "Some of the selected resources have mixed values for the same key. Only edit these key-value pairs if you intend to change them.",
"select": "Select database",
- "selected-n-databases": "{{n}} database(s) selected",
- "successfully-transferred-databases": "Successfully transferred databases",
"sync-schema": {
"copy-schema": "Copy schema",
"description": "Bytebase supports synchronizing a schema to one or multiple target databases. (MySQL, PostgreSQL, Oracle, MSSQL, TiDB only)",
@@ -402,10 +403,6 @@
"title": "Sync Schema",
"with-diff": "With diff"
},
- "sync-schema-button": "Sync Schema",
- "sync-status-failed": "Sync failed",
- "transfer-project": "Transfer Project",
- "unassign": "Unassign",
"unassign-alert-description": "The selected databases will be removed from the project",
"unassign-alert-title": "Unassign databases"
},
@@ -441,8 +438,8 @@
"delete": "Delete this environment",
"delete-description": "Delete environment will also remove it from related instances and databases. You cannot undo this action",
"reorder": "Reorder Environments",
- "select": "Select environment",
- "successfully-updated-environment": "Successfully updated environment '{{name}}'."
+ "successfully-updated-environment": "Successfully updated environment '{{name}}'.",
+ "select": "Select environment"
},
"error-page": {
"not-found": "Not Found"
@@ -655,6 +652,7 @@
"instance.users": "Users",
"instance.your-snowflake-account-locator": "Your Snowflake account locator",
"issue": {
+ "labels": "Issue Labels",
"advanced-search": {
"filter": "Filter"
},
@@ -663,7 +661,6 @@
"limits": "Limits",
"options": "Options"
},
- "labels": "Issue Labels",
"risk-level": {
"high": "High",
"moderate": "Moderate",
@@ -753,6 +750,9 @@
"success-prompt": "Successfully created project {{name}}."
},
"filter-projects": "Filter projects",
+ "table": {
+ "name": "Name"
+ },
"masking-exemption": {
"all-levels": "All levels",
"expires-in-days_one": "Expires in {{days}} day",
@@ -849,9 +849,6 @@
"success-updated": "Project settings updated successfully.",
"update-failed": "Failed to update the project setting."
},
- "table": {
- "name": "Name"
- },
"webhook": {
"activity-support-direct-message": "Support send direct messages to related users",
"add-a-webhook": "Add a webhook",
@@ -897,9 +894,9 @@
}
},
"resource": {
- "delete-warning": "The \"{{name}}\" will be deleted. This action cannot be undone.",
+ "delete-warning-with-resources": "The \"{{name}}\" is used by following resources:",
"delete-warning-retry": "Please remove it from these resources then retry again.",
- "delete-warning-with-resources": "The \"{{name}}\" is used by following resources:"
+ "delete-warning": "The \"{{name}}\" will be deleted. This action cannot be undone."
},
"resource-id": {
"cannot-be-changed-later": "It cannot be changed later.",
@@ -941,9 +938,6 @@
"self": "Workspace roles"
}
},
- "schema-editor": {
- "raw-sql": "Raw SQL"
- },
"schema-template": {
"classification": {
"search": "Search classification"
@@ -1169,13 +1163,8 @@
"reactivate-confirm-title": "Are you sure to reactivate"
},
"add-member": "Add member",
- "add-service-account": "Add Service Account",
"add-user": "Add user",
- "add-workload-identity": "Add Workload Identity",
- "all-users": "All users",
- "assign-role": "Assign role",
"cannot-revoke-self": "You cannot revoke yourself",
- "copy-service-key": "Copy Service Key",
"entra-sync": {
"description": "Sync users and groups from Entra ID (formerly Azure AD) or Okta to your Bytebase instance.",
"endpoint": "Endpoint",
@@ -1205,11 +1194,7 @@
"update-group": "Update Group",
"workspace-domain-required": "Please set a workspace domain first."
},
- "inactive-service-accounts": "Inactive service accounts",
"inactive-users": "Inactive users",
- "inactive-workload-identities": "Inactive workload identities",
- "reset-service-key": "Reset Service Key",
- "reset-service-key-alert": "This action cannot be undone. The old key will stop working immediately. Are you sure you want to reset this service key?",
"revoke-access": "Revoke Access",
"revoke-access-alert": "Are you sure to revoke access?",
"revoke-allusers-alert": "Revoke \"All users\" will revoke related roles from all other users in your workspace. Are you sure to continue?",
@@ -1221,21 +1206,30 @@
"select-role_one": "Select role",
"select-role_other": "Select roles",
"service-account": "Service Account",
- "service-accounts": "Service Accounts",
- "service-key-copied": "Service Key copied to clipboard, please keep it in secret.",
"show-inactive": "Show inactive accounts",
"table": {
"account": "Account",
"groups": "Groups",
"roles": "Roles"
},
- "update-service-account": "Update Service Account",
"update-user": "Update User",
- "update-workload-identity": "Update Workload Identity",
"view-by-members": "View by members",
"view-by-roles": "View by roles",
- "workload-identities": "Workload Identities",
"workload-identity": "Workload Identity",
+ "add-service-account": "Add Service Account",
+ "add-workload-identity": "Add Workload Identity",
+ "all-users": "All users",
+ "assign-role": "Assign role",
+ "copy-service-key": "Copy Service Key",
+ "inactive-service-accounts": "Inactive service accounts",
+ "inactive-workload-identities": "Inactive workload identities",
+ "reset-service-key": "Reset Service Key",
+ "reset-service-key-alert": "This action cannot be undone. The old key will stop working immediately. Are you sure you want to reset this service key?",
+ "service-accounts": "Service Accounts",
+ "service-key-copied": "Service Key copied to clipboard, please keep it in secret.",
+ "update-service-account": "Update Service Account",
+ "update-workload-identity": "Update Workload Identity",
+ "workload-identities": "Workload Identities",
"workload-identity-advanced": "Advanced Settings",
"workload-identity-all-branches-tags": "All branches and tags",
"workload-identity-allowed-branches-tags": "Allowed Branches/Tags",
@@ -1259,7 +1253,6 @@
"workload-identity-tag-hint": "Leave empty to allow all tags"
},
"profile": {
- "email": "Email",
"password": "Password",
"password-confirm": "Password Confirm",
"password-confirm-placeholder": "Confirm new password",
@@ -1267,6 +1260,7 @@
"password-mismatch": "New password mismatch",
"phone": "Phone",
"phone-tips": "Be sure to include the country code +1xxxxxx",
+ "email": "Email",
"role": "Role",
"subscription": "(Upgrade to enable role management)"
},
@@ -1333,12 +1327,10 @@
},
"re-order": "Re-order"
},
- "never-expires": "Never expires",
"semantic-types": {
"add-from-template": "Add from template",
"label": "Columns having the same semantic type will use the same masking algorithms.",
"select": "Select semantic type",
- "self": "Semantic Types",
"table": {
"delete": "Delete this semantic type?",
"description": "Description",
@@ -1350,27 +1342,29 @@
"description": "You can apply built-in semantic types from the template. Built-in template cannot be changed.",
"duplicate-warning": "Semantic type \"{{title}}\" already exists"
},
- "use-predefined-type": "Use Predefined Type"
- }
+ "use-predefined-type": "Use Predefined Type",
+ "self": "Semantic Types"
+ },
+ "never-expires": "Never expires"
},
"sidebar": {
"audit-log": "Audit Logs",
"custom-roles": "Custom Roles",
- "data-access": "Data Access",
"data-classification": "Data Classification",
"general": "General",
"global-masking": "Global Masking",
- "iam-and-admin": "IAM & Admin",
"im-integration": "IM",
- "integration": "Integration",
"mcp": "MCP",
"members": "Members",
"members-and-groups": "Members & Groups",
- "profile": "Profile",
- "security-and-policy": "Security & Policy",
"sso": "SSO",
"subscription": "Subscription",
- "users-and-groups": "Users & Groups"
+ "users-and-groups": "Users & Groups",
+ "data-access": "Data Access",
+ "iam-and-admin": "IAM & Admin",
+ "integration": "Integration",
+ "profile": "Profile",
+ "security-and-policy": "Security & Policy"
},
"sso": {
"create": "Create SSO",
@@ -1459,6 +1453,7 @@
}
},
"sql-editor": {
+ "self": "SQL Editor",
"access-grants": "Access Grants",
"access-grants-redirect-hint": "Go to {link} to view and manage your own access grants.",
"activate-access": "Activate",
@@ -1467,10 +1462,11 @@
"grant-type-unmask": "Unmask",
"revoke-access": "Revoke",
"revoke-confirm": "Are you sure you want to revoke this access grant?",
- "self": "SQL Editor",
"view-issue": "View Issue"
},
"sql-review": {
+ "configure-policy": "Configure policy",
+ "title": "SQL Review",
"add-or-remove-rules": "Add or remove rules",
"add-rules": "Add rules",
"attach-resource": {
@@ -1479,7 +1475,6 @@
"no-linked-resources": "No attached resources",
"self": "Attach to resources"
},
- "configure-policy": "Configure policy",
"create": {
"basic-info": {
"display-name": "Display name",
@@ -1504,14 +1499,12 @@
"policy-removed": "Successfully removed the review policy.",
"policy-update-failed": "Failed to update the review policy.",
"policy-updated": "Successfully updated the review policy.",
- "review-policy": "Review policy",
- "title": "SQL Review"
+ "review-policy": "Review policy"
},
"subscription": {
"contact-us": "Contact us",
"current": "Current plan",
"description": "You can upload your Bytebase license to unlock pro/enterprise features.",
- "disabled-feature": "Disabled Feature",
"enterprise-free-trial": "{{days}}-day free Enterprise trial",
"expired": "expired",
"expires-at": "Expires at",
@@ -1602,19 +1595,20 @@
"title": "User count limit",
"upgrade": "Upgrade to get more user quota."
}
- }
+ },
+ "disabled-feature": "Disabled Feature"
},
"subscription.instance-assignment.assign-license": "Assign License",
"subscription.instance-assignment.n-license-remain": "{{n}} remaining",
"subscription.usage.instance-count.runoutof": "You have run out of your {{total}} instance quota.",
"subscription.usage.instance-count.title": "Instance count limit",
"two-factor": {
+ "enabled": "2FA Enabled",
"description": "Two-factor authentication provides an extra layer of security for member accounts. When signing in, you will be required to enter the security code generated by your Authenticator App.",
"disable": {
"description": "You are about to disable two-factor authentication for your account. You will no longer be required to enter the security code generated by your Authenticator App when signing in.",
"self": "Disable Two-factor authentication"
},
- "enabled": "2FA Enabled",
"messages": {
"2fa-disabled": "Two-factor authentication is disabled.",
"2fa-enabled": "Two-factor authentication is enabled.",
@@ -1655,5 +1649,68 @@
"description": "Copy the code and enter it in your TOTP app manually.",
"self": "Your two-factor secret"
}
+ },
+ "agent": {
+ "assistant-title": "Bytebase Assistant",
+ "resize": "Resize",
+ "minimize": "Minimize",
+ "close": "Close",
+ "input-placeholder": "Ask anything...",
+ "send": "Send",
+ "args": "Args:",
+ "result": "Result:",
+ "stop": "Stop",
+ "interrupted": "Interrupted",
+ "retry-last-chat-turn": "Retry last turn",
+ "interrupted-retry-hint": "Retry reruns the interrupted turn with the current page state.",
+ "new-chat": "New chat",
+ "rename-chat-placeholder": "Enter a chat name",
+ "archive-chat": "Archive",
+ "unarchive-chat": "Unarchive",
+ "delete-chat": "Delete",
+ "active-only-chats": "Active only",
+ "archived-only-chats": "Archived only",
+ "archive-chat-confirmation": "Archive this chat?",
+ "delete-chat-confirmation": "Delete this chat?",
+ "chat-list-label": "Chats",
+ "chat-default-title": "New chat",
+ "chat-archived-label": "Archived",
+ "chat-status-idle": "Idle",
+ "chat-status-running": "Running",
+ "chat-status-awaiting-user": "Awaiting input",
+ "chat-status-error": "Error",
+ "chat-status-interrupted": "Interrupted",
+ "chat-total-tokens": "Tokens used: {{count}}",
+ "reply": "Reply",
+ "confirm": "Confirm",
+ "cancel": "Cancel",
+ "pending-input-hint": "Reply below to continue this chat.",
+ "pending-confirm-hint": "Choose confirm or cancel to continue this chat.",
+ "pending-choose-hint": "Choose an option to continue this chat.",
+ "tool-ask-user": "Awaiting your response",
+ "tool-ask-user-input": "Input requested",
+ "tool-ask-user-confirm": "Confirmation requested",
+ "tool-ask-user-choose": "Choice requested",
+ "tool-response-submitted": "Response submitted",
+ "tool-prompt": "Prompt:",
+ "tool-default-value": "Default:",
+ "tool-options": "Options:",
+ "tool-answer": "Answer:",
+ "tool-value": "Value:",
+ "tool-completed": "Completed",
+ "tool-failed": "Completed with issues",
+ "ai-not-configured": {
+ "title": "AI Assistant isn’t configured for this workspace",
+ "description": "To continue with the page agent, enable AI Assistant in workspace settings.",
+ "configure": "Configure AI",
+ "contact-admin": "Please contact your org administrator to configure AI Assistant."
+ }
+ },
+ "changelog": {
+ "select": "Schema version is recorded each time a schema change is applied via Bytebase",
+ "self": "Changelog"
+ },
+ "schema-editor": {
+ "raw-sql": "Raw SQL"
}
}
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 1294b8ac51..f424d795d0 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -60,13 +60,7 @@
"self": "Condición"
}
},
- "changelog": {
- "select": "Schema version is recorded each time a schema change is applied via Bytebase",
- "self": "Changelog"
- },
"common": {
- "activated": "Activado",
- "active": "Activo",
"add": "Agregar",
"add-permissions": "Agregar permisos",
"added": "Agregado",
@@ -74,14 +68,10 @@
"all": "Todos",
"approved": "Aprobado",
"archive": "Archivo",
- "archive-description": "Mark \"{{name}}\" as archived and read-only.",
- "archive-resource": "Archive {{type}}",
"archived": "Archivada",
"back": "Volver",
"cancel": "Cancelar",
"cannot-undo-this-action": "No se puede deshacer esta acción",
- "changelog": "Changelog",
- "classification-level": "Nivel de clasificación",
"clear": "Limpiar",
"close": "Cerrar",
"closed": "Cerrado",
@@ -89,82 +79,48 @@
"configure": "Configurar",
"configure-now": "Configurar ahora",
"confirm": "Confirmar",
- "confirm-and-add": "Confirm and add",
"confirm-and-update": "Confirmar y actualizar",
- "confirm-archive": "Archive Resource?",
- "confirm-delete": "Delete Resource?",
- "confirm-to-revert": "Confirm to revert your editing?",
"copied": "Copiado",
"copy": "Copiar",
- "copy-failed": "Copy failed",
"create": "Crear",
"created": "Creado",
- "created-at": "Creado",
- "creator": "Creador",
- "danger-zone": "Danger Zone",
- "database": "Base de datos",
- "database-group": "Grupo de bases de datos",
- "databases": "Bases de datos",
- "default": "Predeterminado",
"delete": "Eliminar",
"delete-resource": "Delete {{type}}",
- "delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
"deleted": "Eliminado",
"description": "Descripción",
- "deselect-all": "Deselect all",
- "disable": "Disable",
"discard-changes": "Descartar cambios",
- "download": "Descargar",
"edit": "Editar",
"email": "Correo electrónico",
- "email-ascii-only": "Las direcciones de correo solo admiten caracteres ASCII (letras, números y símbolos como . _ - +).",
- "empty": "Empty",
- "enable": "Habilitar",
- "enabled": "Enabled",
"environment": "Entorno",
"environment-name": "Nombre del entorno",
- "environments": "Entornos",
- "expiration": "Expiration",
"export": "Exportar",
"failed": "Error",
"file-selector": {
"size-limit": "El tamaño del archivo debe ser menor que {{size}} MiB",
"type-limit": "Solo se admiten archivos {{extension}}"
},
- "filter": "Filter",
"filter-by-name": "Filtrar por nombre",
"from": "Desde",
"general": "General",
"groups": "Grupos",
- "home": "Inicio",
"id": "ID",
"instance": "Instancia",
- "instances": "Instancias",
"is-required": "is required",
- "issues": "Incidencias",
- "items": "items",
- "key": "Clave",
"labels": "Etiquetas",
"learn-more": "Aprender más",
"leave-without-saving": "¿Salir sin guardar?",
"load-more": "Cargar más",
"loading": "Cargando",
- "manage": "Administrar",
- "manually-select": "Manually select",
"members_one": "Miembro",
"members_other": "Miembros",
"missing-required-permission": "Faltan permisos requeridos {{permissions}}",
"n-items-selected": "{{n}} elementos seleccionados",
- "n-more": "+{{n}} más",
"name": "Nombre",
"next": "Siguiente",
"no-data": "Sin datos",
"ok": "OK",
"operations": "Operaciones",
- "optional": "Optional",
- "pending": "Pendiente",
"permissions": "Permisos",
- "previous": "Previous",
"project": "Proyecto",
"projects": "Proyectos",
"reason": "Reason",
@@ -174,34 +130,22 @@
"reorder": "Reordenar",
"required-permission": "Permisos necesarios",
"required-workspace-permission": "Se requieren los siguientes permisos para inicializar el espacio de trabajo UX",
- "resource": "Resource",
- "resources": "Recursos",
"restore": "Restaurar",
"restored": "Restored",
"revert": "Revertir",
- "revoke": "Revocar",
- "revoked": "Revocado",
"rows-per-page": "Filas por página",
"save": "Guardar",
- "schema": "Esquema",
- "scope": "Alcance",
"search": "Buscar",
- "search-for-more": "Buscar más",
"select": "Seleccionar",
"select-all": "Seleccionar todo",
- "selected": "selected",
"sensitive-placeholder": "Sensible - solo escritura",
"setting": "Configuración",
"settings": "Configuraciones",
"sql": "SQL",
"state": "Estado",
- "statement": "Declaración",
- "status": "Estado",
"system": "Sistema",
- "table": "Tabla",
"title": "Título",
"to": "Hasta",
- "total": "Total",
"total-n-items": "Total {{n}} elementos",
"type": "Tipo",
"unassigned": "No asignado",
@@ -211,12 +155,65 @@
"updated": "Actualizado",
"upload": "Subir",
"users": "Usuarios",
- "value": "Valor",
"view": "Ver",
"view-details": "Ver Detalles",
"warning": "Advertencia",
- "webhooks": "Webhooks",
- "you": "tu"
+ "you": "tu",
+ "copy-failed": "Copy failed",
+ "dismiss": "Descartar",
+ "activated": "Activado",
+ "active": "Activo",
+ "archive-description": "Mark \"{{name}}\" as archived and read-only.",
+ "archive-resource": "Archive {{type}}",
+ "changelog": "Changelog",
+ "classification-level": "Nivel de clasificación",
+ "confirm-and-add": "Confirm and add",
+ "confirm-archive": "Archive Resource?",
+ "confirm-delete": "Delete Resource?",
+ "confirm-to-revert": "Confirm to revert your editing?",
+ "created-at": "Creado",
+ "creator": "Creador",
+ "danger-zone": "Danger Zone",
+ "database": "Base de datos",
+ "database-group": "Grupo de bases de datos",
+ "databases": "Bases de datos",
+ "default": "Predeterminado",
+ "delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
+ "deselect-all": "Deselect all",
+ "disable": "Disable",
+ "download": "Descargar",
+ "email-ascii-only": "Las direcciones de correo solo admiten caracteres ASCII (letras, números y símbolos como . _ - +).",
+ "empty": "Empty",
+ "enable": "Habilitar",
+ "enabled": "Enabled",
+ "environments": "Entornos",
+ "expiration": "Expiration",
+ "filter": "Filter",
+ "home": "Inicio",
+ "instances": "Instancias",
+ "issues": "Incidencias",
+ "items": "items",
+ "key": "Clave",
+ "manage": "Administrar",
+ "manually-select": "Manually select",
+ "n-more": "+{{n}} más",
+ "optional": "Optional",
+ "pending": "Pendiente",
+ "previous": "Previous",
+ "resource": "Resource",
+ "resources": "Recursos",
+ "revoke": "Revocar",
+ "revoked": "Revocado",
+ "schema": "Esquema",
+ "scope": "Alcance",
+ "search-for-more": "Buscar más",
+ "selected": "selected",
+ "statement": "Declaración",
+ "status": "Estado",
+ "table": "Tabla",
+ "total": "Total",
+ "value": "Valor",
+ "webhooks": "Webhooks"
},
"common.add": "Agregar",
"common.admin": "Admin",
@@ -365,21 +362,25 @@
"data-source.ssl.verify-certificate": "Verificar certificado TLS",
"data-source.ssl.verify-certificate-tooltip": "Habilitar la verificación del certificado TLS para conexiones seguras. Deshabilitar solo para desarrollo o cuando los certificados no se pueden validar correctamente (por ejemplo, certificados autofirmados, entornos VPN). Advertencia: Deshabilitar la verificación es inseguro",
"database": {
- "all": "Todas las bases de datos",
- "change-database": "Modificar base de datos",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
"edit-environment": "Editar entorno",
"edit-labels": "Editar etiquetas",
"engine": "Motor",
- "expression": "Expression",
"filter-database": "Filtrar base de datos",
+ "selected-n-databases": "{{n}} base(s) de datos seleccionada(s)",
+ "successfully-transferred-databases": "Bases de datos transferidas exitosamente",
+ "sync-schema-button": "Sincronizar esquema",
+ "sync-status-failed": "Sincronización fallida",
+ "transfer-project": "Transferir proyecto",
+ "unassign": "Desasignar",
+ "all": "Todas las bases de datos",
+ "change-database": "Modificar base de datos",
+ "expression": "Expression",
"mixed-label-values": "valores mixtos",
"mixed-label-values-warning": "Algunos de los recursos seleccionados tienen valores mixtos para la misma clave. Solo edite estos pares clave-valor si tiene la intención de cambiarlos.",
"select": "Seleccionar base de datos",
- "selected-n-databases": "{{n}} base(s) de datos seleccionada(s)",
- "successfully-transferred-databases": "Bases de datos transferidas exitosamente",
"sync-schema": {
"copy-schema": "Copy schema",
"description": "Bytebase supports synchronizing a schema to one or multiple target databases. (MySQL, PostgreSQL, Oracle, MSSQL, TiDB only)",
@@ -402,10 +403,6 @@
"title": "Sincronizar esquema",
"with-diff": "With diff"
},
- "sync-schema-button": "Sincronizar esquema",
- "sync-status-failed": "Sincronización fallida",
- "transfer-project": "Transferir proyecto",
- "unassign": "Desasignar",
"unassign-alert-description": "Las bases de datos seleccionadas serán eliminadas del proyecto",
"unassign-alert-title": "Desasignar bases de datos"
},
@@ -441,8 +438,8 @@
"delete": "Eliminar este entorno",
"delete-description": "Eliminar el entorno también lo eliminará de las instancias y bases de datos relacionadas. No se puede deshacer esta acción",
"reorder": "Reordenar entornos",
- "select": "Seleccionar entorno",
- "successfully-updated-environment": "entorno '{{name}}' actualizado exitosamente."
+ "successfully-updated-environment": "entorno '{{name}}' actualizado exitosamente.",
+ "select": "Seleccionar entorno"
},
"error-page": {
"not-found": "No encontrado"
@@ -655,6 +652,7 @@
"instance.users": "Usuarios",
"instance.your-snowflake-account-locator": "Su localizador de cuentas Snowflake",
"issue": {
+ "labels": "Etiquetas de problema",
"advanced-search": {
"filter": "Filtrar"
},
@@ -663,7 +661,6 @@
"limits": "Límites",
"options": "Opciones de exportación"
},
- "labels": "Etiquetas de problema",
"risk-level": {
"high": "Alto",
"moderate": "Moderado",
@@ -753,6 +750,9 @@
"success-prompt": "Proyecto {{name}} creado exitosamente."
},
"filter-projects": "Filtrar proyectos",
+ "table": {
+ "name": "Nombre"
+ },
"masking-exemption": {
"all-levels": "Todos los niveles",
"expires-in-days_one": "Expira en {{days}} día",
@@ -849,9 +849,6 @@
"success-updated": "La configuración del proyecto se actualizó correctamente.",
"update-failed": "No se pudo actualizar la configuración del proyecto."
},
- "table": {
- "name": "Nombre"
- },
"webhook": {
"activity-support-direct-message": "Soporte para enviar mensajes directos a usuarios relacionados.",
"add-a-webhook": "Agregar un webhook",
@@ -897,9 +894,9 @@
}
},
"resource": {
- "delete-warning": "Se eliminará el elemento \"{{name}}\". Esta acción no se puede deshacer.",
+ "delete-warning-with-resources": "El \"{{name}}\" lo utilizan los siguientes recursos:",
"delete-warning-retry": "Elimínelo de estos recursos y vuelva a intentarlo.",
- "delete-warning-with-resources": "El \"{{name}}\" lo utilizan los siguientes recursos:"
+ "delete-warning": "Se eliminará el elemento \"{{name}}\". Esta acción no se puede deshacer."
},
"resource-id": {
"cannot-be-changed-later": "No se puede cambiar posteriormente.",
@@ -941,9 +938,6 @@
"self": "Roles de espacio de trabajo"
}
},
- "schema-editor": {
- "raw-sql": "Raw SQL"
- },
"schema-template": {
"classification": {
"search": "Clasificación de búsqueda"
@@ -1169,13 +1163,8 @@
"reactivate-confirm-title": "¿Estás seguro de que deseas reactivar?"
},
"add-member": "Agregar miembro",
- "add-service-account": "Añadir Cuenta de Servicio",
"add-user": "Agregar usuario",
- "add-workload-identity": "Añadir Identidad de Carga de Trabajo",
- "all-users": "Todos los usuarios",
- "assign-role": "Assign role",
"cannot-revoke-self": "You cannot revoke yourself",
- "copy-service-key": "Copiar Clave de Servicio",
"entra-sync": {
"description": "Sincronice usuarios y grupos de Entra ID (anteriormente Azure AD) u Okta con su instancia de Bytebase.",
"endpoint": "Punto final",
@@ -1205,11 +1194,7 @@
"update-group": "Grupo de actualización",
"workspace-domain-required": "Primero configure un dominio de espacio de trabajo."
},
- "inactive-service-accounts": "Cuentas de servicio inactivas",
"inactive-users": "Usuarios inactivos",
- "inactive-workload-identities": "Identidades de carga de trabajo inactivas",
- "reset-service-key": "Restablecer Clave de Servicio",
- "reset-service-key-alert": "Esta acción no se puede deshacer. La clave antigua dejará de funcionar de inmediato. ¿Está seguro de que desea restablecer esta clave de servicio?",
"revoke-access": "Revocar acceso",
"revoke-access-alert": "¿Está seguro de revocar el acceso?",
"revoke-allusers-alert": "Revocar \"Todos los usuarios\" revocará los roles relacionados de todos los demás usuarios de su espacio de trabajo. ¿Desea continuar?",
@@ -1221,21 +1206,30 @@
"select-role_one": "Seleccionar rol",
"select-role_other": "Seleccionar roles",
"service-account": "Cuenta de Servicio",
- "service-accounts": "Cuentas de Servicio",
- "service-key-copied": "Clave de Servicio copiada al portapapeles, por favor manténgala en secreto.",
"show-inactive": "Mostrar cuentas inactivas",
"table": {
"account": "Cuenta",
"groups": "Grupos",
"roles": "Roles"
},
- "update-service-account": "Actualizar Cuenta de Servicio",
"update-user": "Actualizar usuario",
- "update-workload-identity": "Actualizar Identidad de Carga de Trabajo",
"view-by-members": "Ver por miembros",
"view-by-roles": "Ver por roles",
- "workload-identities": "Identidades de Carga de Trabajo",
"workload-identity": "Workload Identity",
+ "add-service-account": "Añadir Cuenta de Servicio",
+ "add-workload-identity": "Añadir Identidad de Carga de Trabajo",
+ "all-users": "Todos los usuarios",
+ "assign-role": "Assign role",
+ "copy-service-key": "Copiar Clave de Servicio",
+ "inactive-service-accounts": "Cuentas de servicio inactivas",
+ "inactive-workload-identities": "Identidades de carga de trabajo inactivas",
+ "reset-service-key": "Restablecer Clave de Servicio",
+ "reset-service-key-alert": "Esta acción no se puede deshacer. La clave antigua dejará de funcionar de inmediato. ¿Está seguro de que desea restablecer esta clave de servicio?",
+ "service-accounts": "Cuentas de Servicio",
+ "service-key-copied": "Clave de Servicio copiada al portapapeles, por favor manténgala en secreto.",
+ "update-service-account": "Actualizar Cuenta de Servicio",
+ "update-workload-identity": "Actualizar Identidad de Carga de Trabajo",
+ "workload-identities": "Identidades de Carga de Trabajo",
"workload-identity-advanced": "Advanced Settings",
"workload-identity-all-branches-tags": "All branches and tags",
"workload-identity-allowed-branches-tags": "Allowed Branches/Tags",
@@ -1259,7 +1253,6 @@
"workload-identity-tag-hint": "Leave empty to allow all tags"
},
"profile": {
- "email": "Correo electrónico",
"password": "Contraseña",
"password-confirm": "Confirmar contraseña",
"password-confirm-placeholder": "Confirmar nueva contraseña",
@@ -1267,6 +1260,7 @@
"password-mismatch": "Nueva contraseña no coincide",
"phone": "Número de móvil",
"phone-tips": "Asegúrese de incluir el código del país +1xxxxxx",
+ "email": "Correo electrónico",
"role": "Rol",
"subscription": "(Actualice para habilitar la gestión de roles)"
},
@@ -1333,12 +1327,10 @@
},
"re-order": "Reordenar"
},
- "never-expires": "Nunca expira",
"semantic-types": {
"add-from-template": "Agregar desde plantilla",
"label": "Las columnas que tengan el mismo tipo semántico utilizarán los mismos algoritmos de enmascaramiento.",
"select": "Seleccionar tipo semántico",
- "self": "Tipos Semánticos",
"table": {
"delete": "¿Eliminar este tipo semántico?",
"description": "Descripción",
@@ -1350,27 +1342,29 @@
"description": "Puede aplicar tipos semánticos integrados desde la plantilla. La plantilla integrada no se puede modificar.",
"duplicate-warning": "El tipo semántico \"{{title}}\" ya existe"
},
- "use-predefined-type": "Utiliza el Tipo Predefinido"
- }
+ "use-predefined-type": "Utiliza el Tipo Predefinido",
+ "self": "Tipos Semánticos"
+ },
+ "never-expires": "Nunca expira"
},
"sidebar": {
"audit-log": "Registros de auditoría",
"custom-roles": "Roles personalizados",
- "data-access": "Acceso a datos",
"data-classification": "Clasificación de datos",
"general": "General",
"global-masking": "Enmascaramiento Global",
- "iam-and-admin": "IAM y administración",
"im-integration": "Integración de IM",
- "integration": "Integración",
"mcp": "MCP",
"members": "Miembros",
"members-and-groups": "Miembros y grupos",
- "profile": "Perfil",
- "security-and-policy": "Seguridad y Política",
"sso": "SSO",
"subscription": "Suscripción",
- "users-and-groups": "Usuarios y grupos"
+ "users-and-groups": "Usuarios y grupos",
+ "data-access": "Acceso a datos",
+ "iam-and-admin": "IAM y administración",
+ "integration": "Integración",
+ "profile": "Perfil",
+ "security-and-policy": "Seguridad y Política"
},
"sso": {
"create": "Crear SSO",
@@ -1459,6 +1453,7 @@
}
},
"sql-editor": {
+ "self": "Editor de SQL",
"access-grants": "Access Grants",
"access-grants-redirect-hint": "Go to {link} to view and manage your own access grants.",
"activate-access": "Activate",
@@ -1467,10 +1462,11 @@
"grant-type-unmask": "Unmask",
"revoke-access": "Revoke",
"revoke-confirm": "Are you sure you want to revoke this access grant?",
- "self": "Editor de SQL",
"view-issue": "View Issue"
},
"sql-review": {
+ "configure-policy": "Configure policy",
+ "title": "SQL Review",
"add-or-remove-rules": "Add or remove rules",
"add-rules": "Add rules",
"attach-resource": {
@@ -1479,7 +1475,6 @@
"no-linked-resources": "No attached resources",
"self": "Attach to resources"
},
- "configure-policy": "Configure policy",
"create": {
"basic-info": {
"display-name": "Display name",
@@ -1504,14 +1499,12 @@
"policy-removed": "Successfully removed the review policy.",
"policy-update-failed": "Failed to update the review policy.",
"policy-updated": "Successfully updated the review policy.",
- "review-policy": "Review policy",
- "title": "SQL Review"
+ "review-policy": "Review policy"
},
"subscription": {
"contact-us": "Contáctenos",
"current": "Plan actual",
"description": "Puedes subir tu licencia Bytebase para desbloquear funciones de edición/empresa.",
- "disabled-feature": "Función deshabilitada",
"enterprise-free-trial": "{{days}}-días de prueba gratuita para la empresa",
"expired": "expirado",
"expires-at": "Expira el",
@@ -1602,19 +1595,20 @@
"title": "Límite de conteo de usuarios",
"upgrade": "Actualizar para obtener más cuota de usuario."
}
- }
+ },
+ "disabled-feature": "Función deshabilitada"
},
"subscription.instance-assignment.assign-license": "Asignar licencia",
"subscription.instance-assignment.n-license-remain": "permanecer {{n}}",
"subscription.usage.instance-count.runoutof": "Te has quedado sin tu cuota de instancias {{total}}.",
"subscription.usage.instance-count.title": "Límite de cantidad de instancias",
"two-factor": {
+ "enabled": "2FA habilitado",
"description": "La autenticación de dos factores proporciona una capa adicional de seguridad para las cuentas de los miembros. Al iniciar sesión, se te pedirá que ingreses el código de seguridad generado por tu aplicación de autenticación.",
"disable": {
"description": "Está a punto de desactivar la autenticación de dos factores para su cuenta. Ya no se le pedirá que ingrese el código de seguridad generado por su aplicación de autenticación cuando inicie sesión.",
"self": "Desactivar la autenticación de dos factores"
},
- "enabled": "2FA habilitado",
"messages": {
"2fa-disabled": "La autenticación de dos factores está desactivada.",
"2fa-enabled": "La autenticación de dos factores está activada.",
@@ -1655,5 +1649,68 @@
"description": "Copie el código e ingréselo manualmente en su aplicación TOTP.",
"self": "Su secreto de dos factores"
}
+ },
+ "agent": {
+ "assistant-title": "Asistente de Bytebase",
+ "resize": "Resize",
+ "minimize": "Minimizar",
+ "close": "Cerrar",
+ "input-placeholder": "Pregunta lo que sea...",
+ "send": "Enviar",
+ "args": "Argumentos:",
+ "result": "Resultado:",
+ "stop": "Detener",
+ "interrupted": "Interrumpido",
+ "retry-last-chat-turn": "Reintentar el último turno",
+ "interrupted-retry-hint": "Reintentar vuelve a ejecutar el turno interrumpido con el estado actual de la página.",
+ "new-chat": "Nuevo chat",
+ "rename-chat-placeholder": "Introduce un nombre para el chat",
+ "archive-chat": "Archivar",
+ "unarchive-chat": "Desarchivar",
+ "delete-chat": "Eliminar",
+ "active-only-chats": "Solo activas",
+ "archived-only-chats": "Solo archivadas",
+ "archive-chat-confirmation": "¿Archivar este chat?",
+ "delete-chat-confirmation": "¿Eliminar este chat?",
+ "chat-list-label": "Chats",
+ "chat-default-title": "Nuevo chat",
+ "chat-archived-label": "Archivado",
+ "chat-status-idle": "Inactivo",
+ "chat-status-running": "En ejecución",
+ "chat-status-awaiting-user": "Esperando entrada",
+ "chat-status-error": "Error",
+ "chat-status-interrupted": "Interrumpido",
+ "chat-total-tokens": "Tokens usados: {{count}}",
+ "reply": "Responder",
+ "confirm": "Confirmar",
+ "cancel": "Cancelar",
+ "pending-input-hint": "Responde abajo para continuar este chat.",
+ "pending-confirm-hint": "Elige confirmar o cancelar para continuar este chat.",
+ "pending-choose-hint": "Elige una opción para continuar este chat.",
+ "tool-ask-user": "Esperando tu respuesta",
+ "tool-ask-user-input": "Se requiere una entrada",
+ "tool-ask-user-confirm": "Se requiere confirmación",
+ "tool-ask-user-choose": "Se requiere una selección",
+ "tool-response-submitted": "Respuesta enviada",
+ "tool-prompt": "Pregunta:",
+ "tool-default-value": "Valor predeterminado:",
+ "tool-options": "Opciones:",
+ "tool-answer": "Respuesta:",
+ "tool-value": "Valor:",
+ "tool-completed": "Completado",
+ "tool-failed": "Completado con problemas",
+ "ai-not-configured": {
+ "title": "El asistente de IA no está configurado para este espacio de trabajo",
+ "description": "Para continuar con el agente de página, habilita el asistente de IA en la configuración del espacio de trabajo.",
+ "configure": "Configurar IA",
+ "contact-admin": "Ponte en contacto con el administrador de tu organización para configurar el asistente de IA."
+ }
+ },
+ "changelog": {
+ "select": "Schema version is recorded each time a schema change is applied via Bytebase",
+ "self": "Changelog"
+ },
+ "schema-editor": {
+ "raw-sql": "Raw SQL"
}
}
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index ce37c5c3dc..df2f319973 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -60,13 +60,7 @@
"self": "状態"
}
},
- "changelog": {
- "select": "Schema version is recorded each time a schema change is applied via Bytebase",
- "self": "Changelog"
- },
"common": {
- "activated": "有効化しました",
- "active": "アクティブ",
"add": "追加",
"add-permissions": "権限を追加",
"added": "作成した",
@@ -74,14 +68,10 @@
"all": "全て",
"approved": "承認済み",
"archive": "アーカイブ",
- "archive-description": "Mark \"{{name}}\" as archived and read-only.",
- "archive-resource": "Archive {{type}}",
"archived": "アーカイブ済み",
"back": "戻る",
"cancel": "キャンセル",
"cannot-undo-this-action": "この操作は元に戻せません",
- "changelog": "Changelog",
- "classification-level": "分類レベル",
"clear": "クリア",
"close": "閉じる",
"closed": "閉まっている",
@@ -89,82 +79,48 @@
"configure": "設定",
"configure-now": "今すぐ設定する",
"confirm": "確認する",
- "confirm-and-add": "Confirm and add",
"confirm-and-update": "確認して更新する",
- "confirm-archive": "Archive Resource?",
- "confirm-delete": "Delete Resource?",
- "confirm-to-revert": "Confirm to revert your editing?",
"copied": "コピーされました",
"copy": "コピー",
- "copy-failed": "Copy failed",
"create": "作成する",
"created": "作成済",
- "created-at": "作成日時",
- "creator": "作成者",
- "danger-zone": "Danger Zone",
- "database": "データベース",
- "database-group": "データベースグループ",
- "databases": "データベース",
- "default": "デフォルト",
"delete": "消去",
"delete-resource": "Delete {{type}}",
- "delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
"deleted": "削除されました",
"description": "説明",
- "deselect-all": "Deselect all",
- "disable": "Disable",
"discard-changes": "変更をキャンセルする",
- "download": "ダウンロード",
"edit": "編集",
"email": "メールアドレス",
- "email-ascii-only": "メールアドレスは ASCII 文字のみ使用できます(英数字および . _ - + などの記号)。",
- "empty": "Empty",
- "enable": "オンにする",
- "enabled": "Enabled",
"environment": "環境",
"environment-name": "環境名",
- "environments": "環境",
- "expiration": "Expiration",
"export": "エクスポート",
"failed": "失敗",
"file-selector": {
"size-limit": "ファイルサイズは {{size}} MiB 未満である必要があります",
"type-limit": "タイプ {{extension}} のファイルのみがサポートされます"
},
- "filter": "Filter",
"filter-by-name": "名前でフィルタリングする",
"from": "開始",
"general": "全般",
"groups": "グループ",
- "home": "ホームページ",
"id": "ID",
"instance": "インスタンス",
- "instances": "インスタンス",
"is-required": "is required",
- "issues": "イシュー",
- "items": "items",
- "key": "キー",
"labels": "ラベル",
"learn-more": "もっと詳しく知る",
"leave-without-saving": "変更を保存していませんか?",
"load-more": "もっと読み込む",
"loading": "読み込み中",
- "manage": "管理",
- "manually-select": "Manually select",
"members_one": "メンバー",
"members_other": "メンバー",
"missing-required-permission": "必要な権限がありません {{permissions}}",
"n-items-selected": "{{n}} 件選択済み",
- "n-more": "+{{n}} もっと",
"name": "名前",
"next": "次のステップ",
"no-data": "データなし",
"ok": "わかりました",
"operations": "操作",
- "optional": "Optional",
- "pending": "保留中",
"permissions": "権限",
- "previous": "Previous",
"project": "プロジェクト",
"projects": "プロジェクト",
"reason": "Reason",
@@ -174,34 +130,22 @@
"reorder": "並び替え",
"required-permission": "必要な権限",
"required-workspace-permission": "ワークスペース UX の初期化には以下の権限が必要です",
- "resource": "Resource",
- "resources": "リソース",
"restore": "復元する",
"restored": "Restored",
"revert": "元に戻す",
- "revoke": "キャンセル",
- "revoked": "取り消し済み",
"rows-per-page": "ページあたりの行数",
"save": "保存",
- "schema": "スキーマ",
- "scope": "スコープ",
"search": "検索",
- "search-for-more": "さらに検索",
"select": "選択してください",
"select-all": "すべて選択",
- "selected": "selected",
"sensitive-placeholder": "機密データ - 書き込みのみ",
"setting": "設定",
"settings": "設定",
"sql": "SQL",
"state": "ステート",
- "statement": "ステートメント",
- "status": "ステータス",
"system": "システム",
- "table": "テーブル",
"title": "タイトル",
"to": "終了",
- "total": "Total",
"total-n-items": "合計 {{n}} 件",
"type": "タイプ",
"unassigned": "割り当てられていない",
@@ -211,12 +155,65 @@
"updated": "更新しました",
"upload": "アップロード",
"users": "ユーザー",
- "value": "値",
"view": "表示",
"view-details": "詳細を表示",
"warning": "警告する",
- "webhooks": "Webhook",
- "you": "あなた"
+ "you": "あなた",
+ "copy-failed": "Copy failed",
+ "dismiss": "閉じる",
+ "activated": "有効化しました",
+ "active": "アクティブ",
+ "archive-description": "Mark \"{{name}}\" as archived and read-only.",
+ "archive-resource": "Archive {{type}}",
+ "changelog": "Changelog",
+ "classification-level": "分類レベル",
+ "confirm-and-add": "Confirm and add",
+ "confirm-archive": "Archive Resource?",
+ "confirm-delete": "Delete Resource?",
+ "confirm-to-revert": "Confirm to revert your editing?",
+ "created-at": "作成日時",
+ "creator": "作成者",
+ "danger-zone": "Danger Zone",
+ "database": "データベース",
+ "database-group": "データベースグループ",
+ "databases": "データベース",
+ "default": "デフォルト",
+ "delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
+ "deselect-all": "Deselect all",
+ "disable": "Disable",
+ "download": "ダウンロード",
+ "email-ascii-only": "メールアドレスは ASCII 文字のみ使用できます(英数字および . _ - + などの記号)。",
+ "empty": "Empty",
+ "enable": "オンにする",
+ "enabled": "Enabled",
+ "environments": "環境",
+ "expiration": "Expiration",
+ "filter": "Filter",
+ "home": "ホームページ",
+ "instances": "インスタンス",
+ "issues": "イシュー",
+ "items": "items",
+ "key": "キー",
+ "manage": "管理",
+ "manually-select": "Manually select",
+ "n-more": "+{{n}} もっと",
+ "optional": "Optional",
+ "pending": "保留中",
+ "previous": "Previous",
+ "resource": "Resource",
+ "resources": "リソース",
+ "revoke": "キャンセル",
+ "revoked": "取り消し済み",
+ "schema": "スキーマ",
+ "scope": "スコープ",
+ "search-for-more": "さらに検索",
+ "selected": "selected",
+ "statement": "ステートメント",
+ "status": "ステータス",
+ "table": "テーブル",
+ "total": "Total",
+ "value": "値",
+ "webhooks": "Webhook"
},
"common.add": "追加",
"common.admin": "管理者",
@@ -365,21 +362,25 @@
"data-source.ssl.verify-certificate": "TLS証明書を検証",
"data-source.ssl.verify-certificate-tooltip": "安全な接続のためにTLS証明書の検証を有効にします。開発環境や証明書が適切に検証できない場合(自己署名証明書、VPN環境など)にのみ無効にしてください。警告:検証を無効にすることは安全ではありません",
"database": {
- "all": "すべてのデータベース",
- "change-database": "データベースの変更",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
"edit-environment": "環境の編集",
"edit-labels": "ラベルを編集",
"engine": "エンジン",
- "expression": "Expression",
"filter-database": "データベースをフィルター",
+ "selected-n-databases": "{{n}} 個のデータベースが選択されました",
+ "successfully-transferred-databases": "データベースの転送に成功しました",
+ "sync-schema-button": "スキーマを同期",
+ "sync-status-failed": "同期に失敗しました",
+ "transfer-project": "プロジェクトの転送",
+ "unassign": "割り当てを解除する",
+ "all": "すべてのデータベース",
+ "change-database": "データベースの変更",
+ "expression": "Expression",
"mixed-label-values": "混合値",
"mixed-label-values-warning": "選択されたリソースの一部は、同じキーに対して異なる値を持っています。これらのキーと値のペアを変更する場合にのみ編集してください。",
"select": "データベースの選択",
- "selected-n-databases": "{{n}} 個のデータベースが選択されました",
- "successfully-transferred-databases": "データベースの転送に成功しました",
"sync-schema": {
"copy-schema": "Copy schema",
"description": "Bytebase supports synchronizing a schema to one or multiple target databases. (MySQL, PostgreSQL, Oracle, MSSQL, TiDB only)",
@@ -402,10 +403,6 @@
"title": "データベーステーブルの同期",
"with-diff": "With diff"
},
- "sync-schema-button": "スキーマを同期",
- "sync-status-failed": "同期に失敗しました",
- "transfer-project": "プロジェクトの転送",
- "unassign": "割り当てを解除する",
"unassign-alert-description": "選択したデータベースがプロジェクトから削除されます",
"unassign-alert-title": "データベースの割り当てを解除する"
},
@@ -441,8 +438,8 @@
"delete": "この環境を削除します",
"delete-description": "環境を削除すると、関連するインスタンスとデータベースからも削除されます。この操作は元に戻せません",
"reorder": "環境の並べ替え",
- "select": "環境を選ぶ",
- "successfully-updated-environment": "環境「{{name}}」は正常に更新されました"
+ "successfully-updated-environment": "環境「{{name}}」は正常に更新されました",
+ "select": "環境を選ぶ"
},
"error-page": {
"not-found": "ページが見つかりません"
@@ -655,6 +652,7 @@
"instance.users": "ユーザー",
"instance.your-snowflake-account-locator": "Snowflake アカウント ロケーター",
"issue": {
+ "labels": "イシューラベル",
"advanced-search": {
"filter": "フィルター"
},
@@ -663,7 +661,6 @@
"limits": "制限",
"options": "設定項目"
},
- "labels": "イシューラベル",
"risk-level": {
"high": "高い",
"moderate": "適度",
@@ -753,6 +750,9 @@
"success-prompt": "{{name}} が正常に作成されました。"
},
"filter-projects": "プロジェクトをフィルタリング",
+ "table": {
+ "name": "名前"
+ },
"masking-exemption": {
"all-levels": "全レベル",
"expires-in-days_one": "{{days}} 日後に期限切れ",
@@ -849,9 +849,6 @@
"success-updated": "プロジェクト設定が正常に更新されました",
"update-failed": "プロジェクト設定の更新に失敗しました。"
},
- "table": {
- "name": "名前"
- },
"webhook": {
"activity-support-direct-message": "関連するユーザーへのプライベートメッセージ通知の送信のサポート",
"add-a-webhook": "Webhook を追加する",
@@ -897,9 +894,9 @@
}
},
"resource": {
- "delete-warning": "「{{name}}」は削除されます。この操作は元に戻せません。",
+ "delete-warning-with-resources": "「{{name}}」は次のリソースによって使用されます:",
"delete-warning-retry": "これらのリソースから削除して、もう一度お試しください。",
- "delete-warning-with-resources": "「{{name}}」は次のリソースによって使用されます:"
+ "delete-warning": "「{{name}}」は削除されます。この操作は元に戻せません。"
},
"resource-id": {
"cannot-be-changed-later": "作成後に変更することはできません。",
@@ -941,9 +938,6 @@
"self": "ワークスペースのロール"
}
},
- "schema-editor": {
- "raw-sql": "Raw SQL"
- },
"schema-template": {
"classification": {
"search": "カテゴリを検索する"
@@ -1169,13 +1163,8 @@
"reactivate-confirm-title": "[OK] を有効にします"
},
"add-member": "メンバーを追加",
- "add-service-account": "サービスアカウントを追加",
"add-user": "ユーザーを追加",
- "add-workload-identity": "ワークロードIDを追加",
- "all-users": "すべてのユーザー",
- "assign-role": "Assign role",
"cannot-revoke-self": "You cannot revoke yourself",
- "copy-service-key": "サービスキーをコピーする",
"entra-sync": {
"description": "Entra ID (旧 Azure AD) または Okta のユーザーとグループを Bytebase インスタンスに同期します。",
"endpoint": "Endpoint",
@@ -1205,11 +1194,7 @@
"update-group": "更新グループ",
"workspace-domain-required": "まずワークスペースドメインを設定してください。"
},
- "inactive-service-accounts": "非アクティブサービスアカウント",
"inactive-users": "非アクティブユーザー",
- "inactive-workload-identities": "非アクティブワークロードID",
- "reset-service-key": "サービスキーのリセット",
- "reset-service-key-alert": "古いサービス キーはすぐにリセットされ、この操作は元に戻すことはできません。サービス キーをリセットしてもよろしいですか?",
"revoke-access": "アクセスを取り消す",
"revoke-access-alert": "アクセスを取り消してもよろしいですか?",
"revoke-allusers-alert": "「すべてのユーザー」を取り消すと、ワークスペース内の他のすべてのユーザーの関連ロールが取り消されます。続行しますか?",
@@ -1221,21 +1206,30 @@
"select-role_one": "ロールを選択",
"select-role_other": "ロールを選択",
"service-account": "サービスアカウント",
- "service-accounts": "サービスアカウント",
- "service-key-copied": "サービスキーはコピーされています。公開しないでください",
"show-inactive": "非アクティブなアカウントを表示",
"table": {
"account": "アカウント",
"groups": "グループ",
"roles": "ロール"
},
- "update-service-account": "サービスアカウントを更新",
"update-user": "ユーザーを更新",
- "update-workload-identity": "ワークロードIDを更新",
"view-by-members": "メンバー別に表示",
"view-by-roles": "ロールごとに表示",
- "workload-identities": "ワークロードID",
"workload-identity": "Workload Identity",
+ "add-service-account": "サービスアカウントを追加",
+ "add-workload-identity": "ワークロードIDを追加",
+ "all-users": "すべてのユーザー",
+ "assign-role": "Assign role",
+ "copy-service-key": "サービスキーをコピーする",
+ "inactive-service-accounts": "非アクティブサービスアカウント",
+ "inactive-workload-identities": "非アクティブワークロードID",
+ "reset-service-key": "サービスキーのリセット",
+ "reset-service-key-alert": "古いサービス キーはすぐにリセットされ、この操作は元に戻すことはできません。サービス キーをリセットしてもよろしいですか?",
+ "service-accounts": "サービスアカウント",
+ "service-key-copied": "サービスキーはコピーされています。公開しないでください",
+ "update-service-account": "サービスアカウントを更新",
+ "update-workload-identity": "ワークロードIDを更新",
+ "workload-identities": "ワークロードID",
"workload-identity-advanced": "Advanced Settings",
"workload-identity-all-branches-tags": "All branches and tags",
"workload-identity-allowed-branches-tags": "Allowed Branches/Tags",
@@ -1259,7 +1253,6 @@
"workload-identity-tag-hint": "Leave empty to allow all tags"
},
"profile": {
- "email": "メールアドレス",
"password": "パスワード",
"password-confirm": "パスワードの確認",
"password-confirm-placeholder": "新しいパスワードを確認します",
@@ -1267,6 +1260,7 @@
"password-mismatch": "新しいパスワードが一致しません",
"phone": "電話番号",
"phone-tips": "国コードを必ず含めてください +81xxxxxx",
+ "email": "メールアドレス",
"role": "ロール",
"subscription": "(有料プランにアップグレードするとキャラクター管理が可能になります)"
},
@@ -1333,12 +1327,10 @@
},
"re-order": "並び替え"
},
- "never-expires": "有効期限なし",
"semantic-types": {
"add-from-template": "テンプレートから追加",
"label": "同じセマンティック タイプの列は、同じマスキング アルゴリズムを使用します。",
"select": "セマンティックタイプの選択",
- "self": "セマンティックタイプ",
"table": {
"delete": "このセマンティック タイプを削除しますか?",
"description": "説明",
@@ -1350,27 +1342,29 @@
"description": "テンプレートから組み込みのセマンティック タイプを適用できます。組み込みテンプレートは変更できません。",
"duplicate-warning": "セマンティック タイプ \"{{title}}\" は既に存在します"
},
- "use-predefined-type": "事前定義されたタイプを使用する"
- }
+ "use-predefined-type": "事前定義されたタイプを使用する",
+ "self": "セマンティックタイプ"
+ },
+ "never-expires": "有効期限なし"
},
"sidebar": {
"audit-log": "監査ログ",
"custom-roles": "カスタムロール",
- "data-access": "データアクセス",
"data-classification": "データ分類",
"general": "全般",
"global-masking": "グローバルマスキング",
- "iam-and-admin": "IAM と管理",
"im-integration": "IM",
- "integration": "連携",
"mcp": "MCP",
"members": "メンバー",
"members-and-groups": "メンバーとグループ",
- "profile": "プロフィール",
- "security-and-policy": "セキュリティポリシー",
"sso": "SSO",
"subscription": "サブスクリプション",
- "users-and-groups": "ユーザーとグループ"
+ "users-and-groups": "ユーザーとグループ",
+ "data-access": "データアクセス",
+ "iam-and-admin": "IAM と管理",
+ "integration": "連携",
+ "profile": "プロフィール",
+ "security-and-policy": "セキュリティポリシー"
},
"sso": {
"create": "SSOの作成",
@@ -1459,6 +1453,7 @@
}
},
"sql-editor": {
+ "self": "SQLエディタ",
"access-grants": "Access Grants",
"access-grants-redirect-hint": "Go to {link} to view and manage your own access grants.",
"activate-access": "Activate",
@@ -1467,10 +1462,11 @@
"grant-type-unmask": "Unmask",
"revoke-access": "Revoke",
"revoke-confirm": "Are you sure you want to revoke this access grant?",
- "self": "SQLエディタ",
"view-issue": "View Issue"
},
"sql-review": {
+ "configure-policy": "Configure policy",
+ "title": "SQL Review",
"add-or-remove-rules": "Add or remove rules",
"add-rules": "Add rules",
"attach-resource": {
@@ -1479,7 +1475,6 @@
"no-linked-resources": "No attached resources",
"self": "Attach to resources"
},
- "configure-policy": "Configure policy",
"create": {
"basic-info": {
"display-name": "Display name",
@@ -1504,14 +1499,12 @@
"policy-removed": "Successfully removed the review policy.",
"policy-update-failed": "Failed to update the review policy.",
"policy-updated": "Successfully updated the review policy.",
- "review-policy": "Review policy",
- "title": "SQL Review"
+ "review-policy": "Review policy"
},
"subscription": {
"contact-us": "お問い合わせ",
"current": "現在のプラン",
"description": "ここで購入した Bytebase ライセンスをアップロードして、プロフェッショナル/エンタープライズ機能のロックを解除できます。",
- "disabled-feature": "無効な機能",
"enterprise-free-trial": "Enterprise の {{days}} 日間の無料トライアル",
"expired": "期限切れ",
"expires-at": "有効期限",
@@ -1602,19 +1595,20 @@
"title": "ユーザー制限",
"upgrade": "アップグレード でユーザークォータをさらに取得します。"
}
- }
+ },
+ "disabled-feature": "無効な機能"
},
"subscription.instance-assignment.assign-license": "ライセンスの割り当て",
"subscription.instance-assignment.n-license-remain": "残り {{n}}",
"subscription.usage.instance-count.runoutof": "すべての {{total}} インスタンス クレジットが使用されました。",
"subscription.usage.instance-count.title": "インスタンスの制限",
"two-factor": {
+ "enabled": "二要素認証がオンになっています",
"description": "2 要素認証は、システム メンバーに追加のセキュリティ層を提供します。ログインするとき、ユーザーは認証アプリケーションによって生成されたセキュリティ コードを入力する必要があります。",
"disable": {
"description": "アカウントの 2 要素認証を無効にしようとしています。ログイン時に認証アプリによって生成されたセキュリティ コードを入力する必要がなくなりました。",
"self": "二要素認証を無効にする"
},
- "enabled": "二要素認証がオンになっています",
"messages": {
"2fa-disabled": "二要素認証が正常に無効になりました",
"2fa-enabled": "二要素認証が正常にオンになりました",
@@ -1655,5 +1649,68 @@
"description": "キーをコピーし、アプリケーションに手動で入力します。",
"self": "二要素認証キー"
}
+ },
+ "agent": {
+ "assistant-title": "Bytebase アシスタント",
+ "resize": "Resize",
+ "minimize": "最小化",
+ "close": "閉じる",
+ "input-placeholder": "何でも質問してください...",
+ "send": "送信",
+ "args": "引数:",
+ "result": "結果:",
+ "stop": "停止",
+ "interrupted": "中断",
+ "retry-last-chat-turn": "直前のターンを再試行",
+ "interrupted-retry-hint": "再試行すると、現在のページ状態で中断されたターンをやり直します。",
+ "new-chat": "新しいチャット",
+ "rename-chat-placeholder": "チャット名を入力してください",
+ "archive-chat": "アーカイブ",
+ "unarchive-chat": "アーカイブ解除",
+ "delete-chat": "削除",
+ "active-only-chats": "アクティブのみ",
+ "archived-only-chats": "アーカイブのみ",
+ "archive-chat-confirmation": "このチャットをアーカイブしますか?",
+ "delete-chat-confirmation": "このチャットを削除しますか?",
+ "chat-list-label": "チャット",
+ "chat-default-title": "新しいチャット",
+ "chat-archived-label": "アーカイブ済み",
+ "chat-status-idle": "待機中",
+ "chat-status-running": "実行中",
+ "chat-status-awaiting-user": "入力待ち",
+ "chat-status-error": "エラー",
+ "chat-status-interrupted": "中断",
+ "chat-total-tokens": "使用済みトークン: {{count}}",
+ "reply": "返信",
+ "confirm": "確認",
+ "cancel": "キャンセル",
+ "pending-input-hint": "このチャットを続けるには、下に返信してください。",
+ "pending-confirm-hint": "このチャットを続けるには、確認またはキャンセルを選択してください。",
+ "pending-choose-hint": "このチャットを続けるには、選択肢を選んでください。",
+ "tool-ask-user": "あなたの回答を待っています",
+ "tool-ask-user-input": "入力が必要です",
+ "tool-ask-user-confirm": "確認が必要です",
+ "tool-ask-user-choose": "選択が必要です",
+ "tool-response-submitted": "回答を送信しました",
+ "tool-prompt": "質問:",
+ "tool-default-value": "既定値:",
+ "tool-options": "選択肢:",
+ "tool-answer": "回答:",
+ "tool-value": "値:",
+ "tool-completed": "完了",
+ "tool-failed": "問題ありで完了",
+ "ai-not-configured": {
+ "title": "このワークスペースでは AI アシスタントが設定されていません",
+ "description": "ページエージェントを続けるには、ワークスペース設定で AI アシスタントを有効にしてください。",
+ "configure": "AI を設定",
+ "contact-admin": "AI アシスタントを設定するには、組織の管理者に連絡してください。"
+ }
+ },
+ "changelog": {
+ "select": "Schema version is recorded each time a schema change is applied via Bytebase",
+ "self": "Changelog"
+ },
+ "schema-editor": {
+ "raw-sql": "Raw SQL"
}
}
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index bf32423901..a6fcef2be3 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -60,13 +60,7 @@
"self": "Điều kiện"
}
},
- "changelog": {
- "select": "Schema version is recorded each time a schema change is applied via Bytebase",
- "self": "Changelog"
- },
"common": {
- "activated": "Đã kích hoạt",
- "active": "Hoạt động",
"add": "Thêm",
"add-permissions": "Thêm quyền",
"added": "Đã thêm",
@@ -74,14 +68,10 @@
"all": "Tất cả",
"approved": "Đã phê duyệt",
"archive": "Lưu trữ",
- "archive-description": "Mark \"{{name}}\" as archived and read-only.",
- "archive-resource": "Archive {{type}}",
"archived": "Đã lưu trữ",
"back": "Quay lại",
"cancel": "Hủy",
"cannot-undo-this-action": "Bạn không thể hoàn tác hành động này.",
- "changelog": "Changelog",
- "classification-level": "Cấp phân loại",
"clear": "Xóa",
"close": "Đóng",
"closed": "Đã đóng",
@@ -89,82 +79,48 @@
"configure": "Cấu hình",
"configure-now": "Cấu hình ngay",
"confirm": "Xác nhận",
- "confirm-and-add": "Confirm and add",
"confirm-and-update": "Xác nhận và Cập nhật",
- "confirm-archive": "Archive Resource?",
- "confirm-delete": "Delete Resource?",
- "confirm-to-revert": "Confirm to revert your editing?",
"copied": "Đã sao chép",
"copy": "Sao chép",
- "copy-failed": "Copy failed",
"create": "Tạo",
"created": "Đã tạo",
- "created-at": "Thời gian tạo",
- "creator": "Người tạo",
- "danger-zone": "Danger Zone",
- "database": "Cơ sở dữ liệu",
- "database-group": "Nhóm cơ sở dữ liệu",
- "databases": "Cơ sở dữ liệu",
- "default": "Mặc định",
"delete": "Xóa",
"delete-resource": "Delete {{type}}",
- "delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
"deleted": "Đã xóa",
"description": "Mô tả",
- "deselect-all": "Deselect all",
- "disable": "Disable",
"discard-changes": "Hủy thay đổi",
- "download": "Tải xuống",
"edit": "Chỉnh sửa",
"email": "Email",
- "email-ascii-only": "Địa chỉ email chỉ hỗ trợ ký tự ASCII (chữ cái, số và ký hiệu như . _ - +).",
- "empty": "Empty",
- "enable": "Bật",
- "enabled": "Enabled",
"environment": "Môi trường",
"environment-name": "Tên môi trường",
- "environments": "Môi trường",
- "expiration": "Expiration",
"export": "Xuất",
"failed": "Thất bại",
"file-selector": {
"size-limit": "Kích thước tệp phải nhỏ hơn {{size}} MiB",
"type-limit": "Chỉ hỗ trợ tệp {{extension}}"
},
- "filter": "Filter",
"filter-by-name": "Lọc theo tên",
"from": "Từ",
"general": "Chung",
"groups": "Nhóm",
- "home": "Trang chủ",
"id": "ID",
"instance": "Phiên bản",
- "instances": "Phiên bản",
"is-required": "is required",
- "issues": "Vấn đề",
- "items": "items",
- "key": "Khóa",
"labels": "Nhãn",
"learn-more": "Tìm hiểu thêm",
"leave-without-saving": "Thoát mà không lưu?",
"load-more": "Tải thêm",
"loading": "Đang tải",
- "manage": "Quản lý",
- "manually-select": "Manually select",
"members_one": "Thành viên",
"members_other": "Thành viên",
"missing-required-permission": "Thiếu quyền cần thiết {{permissions}}",
"n-items-selected": "Đã chọn {{n}} mục",
- "n-more": "+{{n}} nữa",
"name": "Tên",
"next": "Tiếp theo",
"no-data": "Không có dữ liệu",
"ok": "OK",
"operations": "Các thao tác",
- "optional": "Optional",
- "pending": "Đang chờ",
"permissions": "Quyền",
- "previous": "Previous",
"project": "Dự án",
"projects": "Dự án",
"reason": "Reason",
@@ -174,34 +130,22 @@
"reorder": "Sắp xếp lại",
"required-permission": "Quyền hạn cần thiết",
"required-workspace-permission": "Các quyền sau đây cần thiết để khởi tạo không gian làm việc UX",
- "resource": "Resource",
- "resources": "Tài nguyên",
"restore": "Khôi phục",
"restored": "Restored",
"revert": "Hoàn tác",
- "revoke": "Thu hồi",
- "revoked": "Đã thu hồi",
"rows-per-page": "Số dòng mỗi trang",
"save": "Lưu",
- "schema": "Schema",
- "scope": "Phạm vi",
"search": "Tìm kiếm",
- "search-for-more": "Tìm kiếm thêm",
"select": "Vui lòng chọn",
"select-all": "Chọn tất cả",
- "selected": "selected",
"sensitive-placeholder": "Nhạy cảm - Chỉ ghi",
"setting": "Cài đặt",
"settings": "Cài đặt",
"sql": "SQL",
"state": "Trạng thái",
- "statement": "Câu lệnh",
- "status": "Trạng thái",
"system": "Hệ thống",
- "table": "Bảng",
"title": "Tiêu đề",
"to": "Đến",
- "total": "Total",
"total-n-items": "Tổng {{n}} mục",
"type": "Loại",
"unassigned": "Chưa gán",
@@ -211,12 +155,65 @@
"updated": "Đã cập nhật",
"upload": "Tải lên",
"users": "Người dùng",
- "value": "Giá trị",
"view": "Xem",
"view-details": "Xem Chi tiết",
"warning": "Cảnh báo",
- "webhooks": "Webhooks",
- "you": "bạn"
+ "you": "bạn",
+ "copy-failed": "Copy failed",
+ "dismiss": "Loại bỏ",
+ "activated": "Đã kích hoạt",
+ "active": "Hoạt động",
+ "archive-description": "Mark \"{{name}}\" as archived and read-only.",
+ "archive-resource": "Archive {{type}}",
+ "changelog": "Changelog",
+ "classification-level": "Cấp phân loại",
+ "confirm-and-add": "Confirm and add",
+ "confirm-archive": "Archive Resource?",
+ "confirm-delete": "Delete Resource?",
+ "confirm-to-revert": "Confirm to revert your editing?",
+ "created-at": "Thời gian tạo",
+ "creator": "Người tạo",
+ "danger-zone": "Danger Zone",
+ "database": "Cơ sở dữ liệu",
+ "database-group": "Nhóm cơ sở dữ liệu",
+ "databases": "Cơ sở dữ liệu",
+ "default": "Mặc định",
+ "delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.",
+ "deselect-all": "Deselect all",
+ "disable": "Disable",
+ "download": "Tải xuống",
+ "email-ascii-only": "Địa chỉ email chỉ hỗ trợ ký tự ASCII (chữ cái, số và ký hiệu như . _ - +).",
+ "empty": "Empty",
+ "enable": "Bật",
+ "enabled": "Enabled",
+ "environments": "Môi trường",
+ "expiration": "Expiration",
+ "filter": "Filter",
+ "home": "Trang chủ",
+ "instances": "Phiên bản",
+ "issues": "Vấn đề",
+ "items": "items",
+ "key": "Khóa",
+ "manage": "Quản lý",
+ "manually-select": "Manually select",
+ "n-more": "+{{n}} nữa",
+ "optional": "Optional",
+ "pending": "Đang chờ",
+ "previous": "Previous",
+ "resource": "Resource",
+ "resources": "Tài nguyên",
+ "revoke": "Thu hồi",
+ "revoked": "Đã thu hồi",
+ "schema": "Schema",
+ "scope": "Phạm vi",
+ "search-for-more": "Tìm kiếm thêm",
+ "selected": "selected",
+ "statement": "Câu lệnh",
+ "status": "Trạng thái",
+ "table": "Bảng",
+ "total": "Total",
+ "value": "Giá trị",
+ "webhooks": "Webhooks"
},
"common.add": "Thêm",
"common.admin": "Quản trị viên",
@@ -365,21 +362,25 @@
"data-source.ssl.verify-certificate": "Xác minh chứng chỉ TLS",
"data-source.ssl.verify-certificate-tooltip": "Bật xác minh chứng chỉ TLS để kết nối an toàn. Chỉ tắt cho môi trường phát triển hoặc khi không thể xác thực chứng chỉ đúng cách (ví dụ: chứng chỉ tự ký, môi trường VPN). Cảnh báo: Tắt xác minh là không an toàn",
"database": {
- "all": "Tất cả cơ sở dữ liệu",
- "change-database": "Thay đổi cơ sở dữ liệu",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
"edit-environment": "Chỉnh sửa Môi trường",
"edit-labels": "Chỉnh sửa nhãn",
"engine": "Engine",
- "expression": "Expression",
"filter-database": "Lọc cơ sở dữ liệu",
+ "selected-n-databases": "Đã chọn {{n}} cơ sở dữ liệu",
+ "successfully-transferred-databases": "Chuyển cơ sở dữ liệu thành công",
+ "sync-schema-button": "Đồng bộ lược đồ",
+ "sync-status-failed": "Đồng bộ thất bại",
+ "transfer-project": "Chuyển dự án",
+ "unassign": "Hủy gán",
+ "all": "Tất cả cơ sở dữ liệu",
+ "change-database": "Thay đổi cơ sở dữ liệu",
+ "expression": "Expression",
"mixed-label-values": "giá trị hỗn hợp",
"mixed-label-values-warning": "Một số tài nguyên đã chọn có các giá trị khác nhau cho cùng một khóa. Chỉ chỉnh sửa các cặp khóa-giá trị này nếu bạn muốn thay đổi chúng.",
"select": "Chọn cơ sở dữ liệu",
- "selected-n-databases": "Đã chọn {{n}} cơ sở dữ liệu",
- "successfully-transferred-databases": "Chuyển cơ sở dữ liệu thành công",
"sync-schema": {
"copy-schema": "Copy schema",
"description": "Bytebase supports synchronizing a schema to one or multiple target databases. (MySQL, PostgreSQL, Oracle, MSSQL, TiDB only)",
@@ -402,10 +403,6 @@
"title": "Đồng bộ lược đồ",
"with-diff": "With diff"
},
- "sync-schema-button": "Đồng bộ lược đồ",
- "sync-status-failed": "Đồng bộ thất bại",
- "transfer-project": "Chuyển dự án",
- "unassign": "Hủy gán",
"unassign-alert-description": "Các cơ sở dữ liệu đã chọn sẽ bị xóa khỏi dự án",
"unassign-alert-title": "Hủy gán cơ sở dữ liệu"
},
@@ -441,8 +438,8 @@
"delete": "Xóa môi trường này",
"delete-description": "Xóa môi trường cũng sẽ xóa nó khỏi các phiên bản và cơ sở dữ liệu liên quan. Bạn không thể hoàn tác hành động này.",
"reorder": "Sắp xếp lại môi trường",
- "select": "Chọn môi trường",
- "successfully-updated-environment": "Đã cập nhật thành công môi trường '{{name}}'."
+ "successfully-updated-environment": "Đã cập nhật thành công môi trường '{{name}}'.",
+ "select": "Chọn môi trường"
},
"error-page": {
"not-found": "Không tìm thấy"
@@ -655,6 +652,7 @@
"instance.users": "Người dùng",
"instance.your-snowflake-account-locator": "Định vị tài khoản Snowflake của bạn",
"issue": {
+ "labels": "Nhãn vấn đề",
"advanced-search": {
"filter": "Bộ lọc"
},
@@ -663,7 +661,6 @@
"limits": "Giới hạn",
"options": "Tùy chọn"
},
- "labels": "Nhãn vấn đề",
"risk-level": {
"high": "Cao",
"moderate": "Trung bình",
@@ -753,6 +750,9 @@
"success-prompt": "Đã tạo thành công dự án {{name}}."
},
"filter-projects": "Lọc dự án",
+ "table": {
+ "name": "Tên"
+ },
"masking-exemption": {
"all-levels": "Tất cả các cấp",
"expires-in-days_one": "Hết hạn sau {{days}} ngày",
@@ -849,9 +849,6 @@
"success-updated": "Đã cập nhật thành công cài đặt dự án.",
"update-failed": "Không cập nhật được cài đặt dự án."
},
- "table": {
- "name": "Tên"
- },
"webhook": {
"activity-support-direct-message": "Hỗ trợ gửi tin nhắn trực tiếp đến người dùng liên quan",
"add-a-webhook": "Thêm một webhook",
@@ -897,9 +894,9 @@
}
},
"resource": {
- "delete-warning": "\"{{name}}\" sẽ bị xóa. Hành động này không thể hoàn tác.",
+ "delete-warning-with-resources": "\"{{name}}\" được sử dụng bởi các tài nguyên sau:",
"delete-warning-retry": "Vui lòng xóa nó khỏi các tài nguyên này rồi thử lại.",
- "delete-warning-with-resources": "\"{{name}}\" được sử dụng bởi các tài nguyên sau:"
+ "delete-warning": "\"{{name}}\" sẽ bị xóa. Hành động này không thể hoàn tác."
},
"resource-id": {
"cannot-be-changed-later": "Nó không thể được thay đổi sau này.",
@@ -941,9 +938,6 @@
"self": "Vai trò không gian làm việc"
}
},
- "schema-editor": {
- "raw-sql": "Raw SQL"
- },
"schema-template": {
"classification": {
"search": "Tìm kiếm phân loại"
@@ -1169,13 +1163,8 @@
"reactivate-confirm-title": "Bạn có chắc muốn kích hoạt lại?"
},
"add-member": "Thêm thành viên",
- "add-service-account": "Thêm tài khoản dịch vụ",
"add-user": "Thêm người dùng",
- "add-workload-identity": "Thêm danh tính Workload",
- "all-users": "Tất cả người dùng",
- "assign-role": "Assign role",
"cannot-revoke-self": "You cannot revoke yourself",
- "copy-service-key": "Sao chép Khóa Dịch vụ",
"entra-sync": {
"description": "Đồng bộ người dùng và nhóm từ Entra ID (trước đây là Azure AD) hoặc Okta sang phiên bản Bytebase của bạn.",
"endpoint": "Điểm cuối",
@@ -1205,11 +1194,7 @@
"update-group": "Cập nhật nhóm",
"workspace-domain-required": "Vui lòng thiết lập tên miền không gian làm việc trước."
},
- "inactive-service-accounts": "Tài khoản dịch vụ không hoạt động",
"inactive-users": "Người dùng không hoạt động",
- "inactive-workload-identities": "Danh tính Workload không hoạt động",
- "reset-service-key": "Đặt lại Khóa Dịch vụ",
- "reset-service-key-alert": "Hành động này không thể hoàn tác. Khóa cũ sẽ ngừng hoạt động ngay lập tức. Bạn có chắc chắn muốn đặt lại khóa dịch vụ này?",
"revoke-access": "Thu hồi Quyền truy cập",
"revoke-access-alert": "Bạn có chắc muốn thu hồi quyền truy cập?",
"revoke-allusers-alert": "Thu hồi \"Tất cả người dùng\" sẽ thu hồi các vai trò liên quan từ tất cả người dùng khác trong không gian làm việc của bạn. Bạn có chắc chắn muốn tiếp tục không?",
@@ -1221,21 +1206,30 @@
"select-role_one": "Chọn vai trò",
"select-role_other": "Chọn vai trò",
"service-account": "Tài khoản dịch vụ",
- "service-accounts": "Tài khoản dịch vụ",
- "service-key-copied": "Khóa Dịch vụ đã được sao chép vào khay nhớ tạm, vui lòng giữ bí mật.",
"show-inactive": "Hiển thị tài khoản không hoạt động",
"table": {
"account": "Tài khoản",
"groups": "Nhóm",
"roles": "Vai trò"
},
- "update-service-account": "Cập nhật tài khoản dịch vụ",
"update-user": "Cập nhật người dùng",
- "update-workload-identity": "Cập nhật danh tính Workload",
"view-by-members": "Xem theo thành viên",
"view-by-roles": "Xem theo vai trò",
- "workload-identities": "Danh tính Workload",
"workload-identity": "Workload Identity",
+ "add-service-account": "Thêm tài khoản dịch vụ",
+ "add-workload-identity": "Thêm danh tính Workload",
+ "all-users": "Tất cả người dùng",
+ "assign-role": "Assign role",
+ "copy-service-key": "Sao chép Khóa Dịch vụ",
+ "inactive-service-accounts": "Tài khoản dịch vụ không hoạt động",
+ "inactive-workload-identities": "Danh tính Workload không hoạt động",
+ "reset-service-key": "Đặt lại Khóa Dịch vụ",
+ "reset-service-key-alert": "Hành động này không thể hoàn tác. Khóa cũ sẽ ngừng hoạt động ngay lập tức. Bạn có chắc chắn muốn đặt lại khóa dịch vụ này?",
+ "service-accounts": "Tài khoản dịch vụ",
+ "service-key-copied": "Khóa Dịch vụ đã được sao chép vào khay nhớ tạm, vui lòng giữ bí mật.",
+ "update-service-account": "Cập nhật tài khoản dịch vụ",
+ "update-workload-identity": "Cập nhật danh tính Workload",
+ "workload-identities": "Danh tính Workload",
"workload-identity-advanced": "Advanced Settings",
"workload-identity-all-branches-tags": "All branches and tags",
"workload-identity-allowed-branches-tags": "Allowed Branches/Tags",
@@ -1259,7 +1253,6 @@
"workload-identity-tag-hint": "Leave empty to allow all tags"
},
"profile": {
- "email": "Email",
"password": "Mật khẩu",
"password-confirm": "Xác nhận mật khẩu",
"password-confirm-placeholder": "Xác nhận mật khẩu mới",
@@ -1267,6 +1260,7 @@
"password-mismatch": "Mật khẩu mới không khớp",
"phone": "Điện thoại",
"phone-tips": "Nhớ bao gồm mã quốc gia +1xxxxxx",
+ "email": "Email",
"role": "Vai trò",
"subscription": "(Nâng cấp để kích hoạt quản lý vai trò)"
},
@@ -1333,12 +1327,10 @@
},
"re-order": "Sắp xếp lại"
},
- "never-expires": "Không bao giờ hết hạn",
"semantic-types": {
"add-from-template": "Thêm từ mẫu",
"label": "Các cột có cùng loại ngữ nghĩa sẽ sử dụng cùng một thuật toán che.",
"select": "Chọn loại ngữ nghĩa",
- "self": "Loại ngữ nghĩa",
"table": {
"delete": "Xóa loại ngữ nghĩa này?",
"description": "Mô tả",
@@ -1350,27 +1342,29 @@
"description": "Bạn có thể áp dụng các loại ngữ nghĩa tích hợp từ mẫu. Mẫu tích hợp không thể thay đổi.",
"duplicate-warning": "Loại ngữ nghĩa \"{{title}}\" đã tồn tại"
},
- "use-predefined-type": "Sử dụng Loại định nghĩa trước"
- }
+ "use-predefined-type": "Sử dụng Loại định nghĩa trước",
+ "self": "Loại ngữ nghĩa"
+ },
+ "never-expires": "Không bao giờ hết hạn"
},
"sidebar": {
"audit-log": "Nhật ký kiểm tra",
"custom-roles": "Vai trò tùy chỉnh",
- "data-access": "Truy cập dữ liệu",
"data-classification": "Phân loại dữ liệu",
"general": "Chung",
"global-masking": "Che giấu toàn cục",
- "iam-and-admin": "IAM & Quản trị",
"im-integration": "Tích hợp",
- "integration": "Tích hợp",
"mcp": "MCP",
"members": "Thành viên",
"members-and-groups": "Thành viên & Nhóm",
- "profile": "Hồ sơ",
- "security-and-policy": "Bảo mật & Chính sách",
"sso": "SSO",
"subscription": "Gói đăng ký",
- "users-and-groups": "Người dùng & Nhóm"
+ "users-and-groups": "Người dùng & Nhóm",
+ "data-access": "Truy cập dữ liệu",
+ "iam-and-admin": "IAM & Quản trị",
+ "integration": "Tích hợp",
+ "profile": "Hồ sơ",
+ "security-and-policy": "Bảo mật & Chính sách"
},
"sso": {
"create": "Tạo SSO",
@@ -1459,6 +1453,7 @@
}
},
"sql-editor": {
+ "self": "Trình soạn thảo SQL",
"access-grants": "Access Grants",
"access-grants-redirect-hint": "Go to {link} to view and manage your own access grants.",
"activate-access": "Activate",
@@ -1467,10 +1462,11 @@
"grant-type-unmask": "Unmask",
"revoke-access": "Revoke",
"revoke-confirm": "Are you sure you want to revoke this access grant?",
- "self": "Trình soạn thảo SQL",
"view-issue": "View Issue"
},
"sql-review": {
+ "configure-policy": "Configure policy",
+ "title": "SQL Review",
"add-or-remove-rules": "Add or remove rules",
"add-rules": "Add rules",
"attach-resource": {
@@ -1479,7 +1475,6 @@
"no-linked-resources": "No attached resources",
"self": "Attach to resources"
},
- "configure-policy": "Configure policy",
"create": {
"basic-info": {
"display-name": "Display name",
@@ -1504,14 +1499,12 @@
"policy-removed": "Successfully removed the review policy.",
"policy-update-failed": "Failed to update the review policy.",
"policy-updated": "Successfully updated the review policy.",
- "review-policy": "Review policy",
- "title": "SQL Review"
+ "review-policy": "Review policy"
},
"subscription": {
"contact-us": "Liên hệ chúng tôi",
"current": "Gói hiện tại",
"description": "Bạn có thể tải lên giấy phép Bytebase của mình để mở khóa các tính năng chuyên nghiệp/doanh nghiệp.",
- "disabled-feature": "Tính năng bị vô hiệu hóa",
"enterprise-free-trial": "Dùng thử Doanh nghiệp miễn phí {{days}} ngày",
"expired": "đã hết hạn",
"expires-at": "Hết hạn vào",
@@ -1602,19 +1595,20 @@
"title": "Giới hạn số lượng người dùng",
"upgrade": "Nâng cấp để có thêm hạn ngạch người dùng."
}
- }
+ },
+ "disabled-feature": "Tính năng bị vô hiệu hóa"
},
"subscription.instance-assignment.assign-license": "Gán giấy phép",
"subscription.instance-assignment.n-license-remain": "còn lại {{n}}",
"subscription.usage.instance-count.runoutof": "Bạn đã hết hạn ngạch {{total}} phiên bản của mình.",
"subscription.usage.instance-count.title": "Giới hạn số lượng phiên bản",
"two-factor": {
+ "enabled": "Đã bật 2FA",
"description": "Xác thực hai yếu tố cung cấp một lớp bảo mật bổ sung cho các tài khoản thành viên. Khi đăng nhập, bạn sẽ được yêu cầu nhập mã bảo mật do Ứng dụng xác thực của bạn tạo.",
"disable": {
"description": "Bạn sắp tắt xác thực hai yếu tố cho tài khoản của mình. Bạn sẽ không còn phải nhập mã bảo mật do Ứng dụng xác thực của bạn tạo khi đăng nhập.",
"self": "Tắt xác thực hai yếu tố"
},
- "enabled": "Đã bật 2FA",
"messages": {
"2fa-disabled": "Xác thực hai yếu tố bị tắt.",
"2fa-enabled": "Xác thực hai yếu tố được bật.",
@@ -1655,5 +1649,68 @@
"description": "Sao chép mã và nhập nó vào ứng dụng TOTP của bạn theo cách thủ công.",
"self": "Bí mật hai yếu tố của bạn"
}
+ },
+ "agent": {
+ "assistant-title": "Trợ lý Bytebase",
+ "resize": "Resize",
+ "minimize": "Thu nhỏ",
+ "close": "Đóng",
+ "input-placeholder": "Hỏi bất cứ điều gì...",
+ "send": "Gửi",
+ "args": "Tham số:",
+ "result": "Kết quả:",
+ "stop": "Dừng",
+ "interrupted": "Bị gián đoạn",
+ "retry-last-chat-turn": "Thử lại lượt trước",
+ "interrupted-retry-hint": "Thử lại sẽ chạy lại lượt bị gián đoạn với trạng thái trang hiện tại.",
+ "new-chat": "Chat mới",
+ "rename-chat-placeholder": "Nhập tên chat",
+ "archive-chat": "Lưu trữ",
+ "unarchive-chat": "Bỏ lưu trữ",
+ "delete-chat": "Xóa",
+ "active-only-chats": "Chỉ hoạt động",
+ "archived-only-chats": "Chỉ lưu trữ",
+ "archive-chat-confirmation": "Lưu trữ chat này?",
+ "delete-chat-confirmation": "Xóa chat này?",
+ "chat-list-label": "Các chat",
+ "chat-default-title": "Chat mới",
+ "chat-archived-label": "Đã lưu trữ",
+ "chat-status-idle": "Rảnh",
+ "chat-status-running": "Đang chạy",
+ "chat-status-awaiting-user": "Đang chờ nhập",
+ "chat-status-error": "Lỗi",
+ "chat-status-interrupted": "Bị gián đoạn",
+ "chat-total-tokens": "Token đã dùng: {{count}}",
+ "reply": "Trả lời",
+ "confirm": "Xác nhận",
+ "cancel": "Hủy",
+ "pending-input-hint": "Hãy trả lời bên dưới để tiếp tục chat này.",
+ "pending-confirm-hint": "Chọn xác nhận hoặc hủy để tiếp tục chat này.",
+ "pending-choose-hint": "Chọn một tùy chọn để tiếp tục chat này.",
+ "tool-ask-user": "Đang chờ phản hồi của bạn",
+ "tool-ask-user-input": "Cần nhập dữ liệu",
+ "tool-ask-user-confirm": "Cần xác nhận",
+ "tool-ask-user-choose": "Cần lựa chọn",
+ "tool-response-submitted": "Đã gửi phản hồi",
+ "tool-prompt": "Câu hỏi:",
+ "tool-default-value": "Giá trị mặc định:",
+ "tool-options": "Tùy chọn:",
+ "tool-answer": "Câu trả lời:",
+ "tool-value": "Giá trị:",
+ "tool-completed": "Hoàn tất",
+ "tool-failed": "Hoàn tất kèm vấn đề",
+ "ai-not-configured": {
+ "title": "Trợ lý AI chưa được cấu hình cho workspace này",
+ "description": "Để tiếp tục với page agent, hãy bật Trợ lý AI trong cài đặt workspace.",
+ "configure": "Cấu hình AI",
+ "contact-admin": "Vui lòng liên hệ quản trị viên của tổ chức để cấu hình Trợ lý AI."
+ }
+ },
+ "changelog": {
+ "select": "Schema version is recorded each time a schema change is applied via Bytebase",
+ "self": "Changelog"
+ },
+ "schema-editor": {
+ "raw-sql": "Raw SQL"
}
}
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 32f4210c14..323d85e143 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -60,13 +60,7 @@
"self": "条件"
}
},
- "changelog": {
- "select": "Schema 版本是在每次通过 Bytebase 执行 Schema 变更后被记录下来的",
- "self": "变更历史"
- },
"common": {
- "activated": "已激活",
- "active": "开启",
"add": "添加",
"add-permissions": "添加权限",
"added": "已创建",
@@ -74,14 +68,10 @@
"all": "全部",
"approved": "已批准",
"archive": "归档",
- "archive-description": "将「{{name}}」标记为已归档且只读。",
- "archive-resource": "归档{{type}}",
"archived": "已归档",
"back": "返回",
"cancel": "取消",
"cannot-undo-this-action": "这个操作无法撤销",
- "changelog": "变更历史",
- "classification-level": "分类等级",
"clear": "清除",
"close": "关闭",
"closed": "已关闭",
@@ -89,82 +79,48 @@
"configure": "配置",
"configure-now": "现在配置",
"confirm": "确认",
- "confirm-and-add": "确认并添加",
"confirm-and-update": "确认并更新",
- "confirm-archive": "确定归档资源?",
- "confirm-delete": "确定删除资源?",
- "confirm-to-revert": "确定撤销编辑?",
"copied": "已拷贝",
"copy": "拷贝",
- "copy-failed": "Copy failed",
"create": "创建",
"created": "已创建",
- "created-at": "创建于",
- "creator": "创建人",
- "danger-zone": "危险区域",
- "database": "数据库",
- "database-group": "数据库分组",
- "databases": "数据库",
- "default": "默认",
"delete": "删除",
"delete-resource": "删除{{type}}",
- "delete-resource-description": "删除「{{name}}」后将无法恢复,请确认。",
"deleted": "已删除",
"description": "描述",
- "deselect-all": "Deselect all",
- "disable": "禁用",
"discard-changes": "取消修改",
- "download": "下载",
"edit": "编辑",
"email": "邮箱",
- "email-ascii-only": "邮箱地址仅支持 ASCII 字符(英文字母、数字及 . _ - + 等符号)。",
- "empty": "Empty",
- "enable": "开启",
- "enabled": "开启",
"environment": "环境",
"environment-name": "环境名",
- "environments": "环境",
- "expiration": "Expiration",
"export": "导出",
"failed": "失败",
"file-selector": {
"size-limit": "文件大小需小于 {{size}} MiB",
"type-limit": "仅支持 {{extension}} 类型的文件"
},
- "filter": "Filter",
"filter-by-name": "按名称过滤",
"from": "从",
"general": "通用",
"groups": "分组",
- "home": "主页",
"id": "ID",
"instance": "实例",
- "instances": "实例",
"is-required": "is required",
- "issues": "工单",
- "items": "items",
- "key": "键",
"labels": "标签",
"learn-more": "了解更多",
"leave-without-saving": "不保存变动?",
"load-more": "加载更多",
"loading": "加载中",
- "manage": "管理",
- "manually-select": "Manually select",
"members_one": "成员",
"members_other": "成员",
"missing-required-permission": "缺少必需的权限 {{permissions}}",
"n-items-selected": "已选 {{n}} 项",
- "n-more": "+{{n}} 更多",
"name": "名称",
"next": "下一步",
"no-data": "无数据",
"ok": "OK",
"operations": "操作",
- "optional": "Optional",
- "pending": "待审批",
"permissions": "权限",
- "previous": "上一步",
"project": "项目",
"projects": "项目",
"reason": "Reason",
@@ -174,34 +130,22 @@
"reorder": "排序",
"required-permission": "所需权限",
"required-workspace-permission": "初始化工作空间 UX 需要以下权限",
- "resource": "资源",
- "resources": "资源",
"restore": "恢复",
"restored": "已恢复",
"revert": "恢复",
- "revoke": "撤销",
- "revoked": "已撤销",
"rows-per-page": "每页行数",
"save": "保存",
- "schema": "模式",
- "scope": "范围",
"search": "搜索",
- "search-for-more": "搜索更多",
"select": "请选择",
"select-all": "全选",
- "selected": "selected",
"sensitive-placeholder": "敏感数据 - 仅写入",
"setting": "设置",
"settings": "设置",
"sql": "SQL",
"state": "状态",
- "statement": "语句",
- "status": "状态",
"system": "系统",
- "table": "表",
"title": "标题",
"to": "到",
- "total": "Total",
"total-n-items": "共 {{n}} 项",
"type": "类型",
"unassigned": "未分配",
@@ -211,12 +155,65 @@
"updated": "已更新",
"upload": "上传",
"users": "用户",
- "value": "值",
"view": "查看",
"view-details": "查看详情",
"warning": "警告",
- "webhooks": "Webhook",
- "you": "您"
+ "you": "您",
+ "copy-failed": "Copy failed",
+ "dismiss": "关闭",
+ "activated": "已激活",
+ "active": "开启",
+ "archive-description": "将「{{name}}」标记为已归档且只读。",
+ "archive-resource": "归档{{type}}",
+ "changelog": "变更历史",
+ "classification-level": "分类等级",
+ "confirm-and-add": "确认并添加",
+ "confirm-archive": "确定归档资源?",
+ "confirm-delete": "确定删除资源?",
+ "confirm-to-revert": "确定撤销编辑?",
+ "created-at": "创建于",
+ "creator": "创建人",
+ "danger-zone": "危险区域",
+ "database": "数据库",
+ "database-group": "数据库分组",
+ "databases": "数据库",
+ "default": "默认",
+ "delete-resource-description": "删除「{{name}}」后将无法恢复,请确认。",
+ "deselect-all": "Deselect all",
+ "disable": "禁用",
+ "download": "下载",
+ "email-ascii-only": "邮箱地址仅支持 ASCII 字符(英文字母、数字及 . _ - + 等符号)。",
+ "empty": "Empty",
+ "enable": "开启",
+ "enabled": "开启",
+ "environments": "环境",
+ "expiration": "Expiration",
+ "filter": "Filter",
+ "home": "主页",
+ "instances": "实例",
+ "issues": "工单",
+ "items": "items",
+ "key": "键",
+ "manage": "管理",
+ "manually-select": "Manually select",
+ "n-more": "+{{n}} 更多",
+ "optional": "Optional",
+ "pending": "待审批",
+ "previous": "上一步",
+ "resource": "资源",
+ "resources": "资源",
+ "revoke": "撤销",
+ "revoked": "已撤销",
+ "schema": "模式",
+ "scope": "范围",
+ "search-for-more": "搜索更多",
+ "selected": "selected",
+ "statement": "语句",
+ "status": "状态",
+ "table": "表",
+ "total": "Total",
+ "value": "值",
+ "webhooks": "Webhook"
},
"common.add": "添加",
"common.admin": "管理员",
@@ -365,21 +362,25 @@
"data-source.ssl.verify-certificate": "验证 TLS 证书",
"data-source.ssl.verify-certificate-tooltip": "启用 TLS 证书验证以确保安全连接。仅在开发环境或证书无法正确验证的情况下禁用(例如自签名证书、VPN 环境)。警告:禁用验证是不安全的",
"database": {
- "all": "所有数据库",
- "change-database": "变更数据库",
"classification": {
"description": "定义分类分级,跨列和数据库统一应用脱敏策略。"
},
"edit-environment": "编辑环境",
"edit-labels": "编辑标签",
"engine": "引擎",
- "expression": "Expression",
"filter-database": "筛选数据库",
+ "selected-n-databases": "已选择 {{n}} 个数据库",
+ "successfully-transferred-databases": "成功转移数据库",
+ "sync-schema-button": "同步 Schema",
+ "sync-status-failed": "同步失败",
+ "transfer-project": "转移项目",
+ "unassign": "取消分配",
+ "all": "所有数据库",
+ "change-database": "变更数据库",
+ "expression": "Expression",
"mixed-label-values": "混合值",
"mixed-label-values-warning": "部分标签拥有不同的值,编辑标签将会批量应用。仅在您打算更改时再编辑这些键值对。",
"select": "选择数据库",
- "selected-n-databases": "已选择 {{n}} 个数据库",
- "successfully-transferred-databases": "成功转移数据库",
"sync-schema": {
"copy-schema": "粘贴 Schema 文本",
"description": "Bytebase 支持将一个指定的 Schema 同步到一个或多个目标数据库。(支持 MySQL, PostgreSQL, Oracle, MSSQL 以及 TiDB)",
@@ -402,10 +403,6 @@
"title": "库表同步",
"with-diff": "有差异"
},
- "sync-schema-button": "同步 Schema",
- "sync-status-failed": "同步失败",
- "transfer-project": "转移项目",
- "unassign": "取消分配",
"unassign-alert-description": "选定的数据库将从项目中移除",
"unassign-alert-title": "取消分配数据库"
},
@@ -441,8 +438,8 @@
"delete": "删除此环境",
"delete-description": "删除环境也会将其从相关实例和数据库中删除。这个操作无法撤销",
"reorder": "重新排序环境",
- "select": "选择环境",
- "successfully-updated-environment": "环境'{{name}}'更新成功"
+ "successfully-updated-environment": "环境'{{name}}'更新成功",
+ "select": "选择环境"
},
"error-page": {
"not-found": "页面未找到"
@@ -655,6 +652,7 @@
"instance.users": "用户",
"instance.your-snowflake-account-locator": "您的 Snowflake 账户定位符",
"issue": {
+ "labels": "工单标签",
"advanced-search": {
"filter": "过滤"
},
@@ -663,7 +661,6 @@
"limits": "限制",
"options": "配置项"
},
- "labels": "工单标签",
"risk-level": {
"high": "高风险",
"moderate": "中风险",
@@ -753,6 +750,9 @@
"success-prompt": "成功创建 {{name}}."
},
"filter-projects": "过滤项目",
+ "table": {
+ "name": "名称"
+ },
"masking-exemption": {
"all-levels": "所有等级",
"expires-in-days_one": "{{days}} 天后到期",
@@ -849,9 +849,6 @@
"success-updated": "项目设置更新成功",
"update-failed": "无法更新项目设置。"
},
- "table": {
- "name": "名称"
- },
"webhook": {
"activity-support-direct-message": "支持向相关用户发送私信通知",
"add-a-webhook": "添加 webhook",
@@ -897,9 +894,9 @@
}
},
"resource": {
- "delete-warning": "“{{name}}”将被删除。此操作无法撤消。",
+ "delete-warning-with-resources": "以下资源使用了“{{name}}”:",
"delete-warning-retry": "请将其从这些资源中删除,然后重试。",
- "delete-warning-with-resources": "以下资源使用了“{{name}}”:"
+ "delete-warning": "“{{name}}”将被删除。此操作无法撤消。"
},
"resource-id": {
"cannot-be-changed-later": "创建之后无法修改。",
@@ -941,9 +938,6 @@
"self": "工作空间角色"
}
},
- "schema-editor": {
- "raw-sql": "SQL 语句"
- },
"schema-template": {
"classification": {
"search": "搜索分类"
@@ -1169,13 +1163,8 @@
"reactivate-confirm-title": "确定启用"
},
"add-member": "添加成员",
- "add-service-account": "添加服务账号",
"add-user": "添加用户",
- "add-workload-identity": "添加工作负载身份",
- "all-users": "全部用户",
- "assign-role": "Assign role",
"cannot-revoke-self": "You cannot revoke yourself",
- "copy-service-key": "复制 Service Key",
"entra-sync": {
"description": "将 Entra ID(前 Azure AD)或 Okta 中的用户和组同步到您的 Bytebase 实例。",
"endpoint": "Endpoint",
@@ -1205,11 +1194,7 @@
"update-group": "更新组",
"workspace-domain-required": "请先设置工作空间的域名。"
},
- "inactive-service-accounts": "未激活服务账号",
"inactive-users": "未激活用户",
- "inactive-workload-identities": "未激活工作负载身份",
- "reset-service-key": "重置 Service Key",
- "reset-service-key-alert": "旧 Service Key 将立即被重置,该操作不可逆。确定要重置 Service Key 吗?",
"revoke-access": "撤销访问权限",
"revoke-access-alert": "您确定要撤销访问权限吗?",
"revoke-allusers-alert": "撤销“全部用户”将撤销您工作区中所有其他用户的相关角色。您确定要继续吗?",
@@ -1221,21 +1206,30 @@
"select-role_one": "选择角色",
"select-role_other": "选择角色",
"service-account": "服务账号",
- "service-accounts": "服务账号",
- "service-key-copied": "Service Key 已复制,请勿泄漏",
"show-inactive": "显示已停用账户",
"table": {
"account": "账户",
"groups": "群组",
"roles": "角色"
},
- "update-service-account": "更新服务账号",
"update-user": "更新用户",
- "update-workload-identity": "更新工作负载身份",
"view-by-members": "按成员查看",
"view-by-roles": "按角色查看",
- "workload-identities": "工作负载身份",
"workload-identity": "工作负载标识",
+ "add-service-account": "添加服务账号",
+ "add-workload-identity": "添加工作负载身份",
+ "all-users": "全部用户",
+ "assign-role": "Assign role",
+ "copy-service-key": "复制 Service Key",
+ "inactive-service-accounts": "未激活服务账号",
+ "inactive-workload-identities": "未激活工作负载身份",
+ "reset-service-key": "重置 Service Key",
+ "reset-service-key-alert": "旧 Service Key 将立即被重置,该操作不可逆。确定要重置 Service Key 吗?",
+ "service-accounts": "服务账号",
+ "service-key-copied": "Service Key 已复制,请勿泄漏",
+ "update-service-account": "更新服务账号",
+ "update-workload-identity": "更新工作负载身份",
+ "workload-identities": "工作负载身份",
"workload-identity-advanced": "高级设置",
"workload-identity-all-branches-tags": "所有分支和标签",
"workload-identity-allowed-branches-tags": "允许的分支/标签",
@@ -1259,7 +1253,6 @@
"workload-identity-tag-hint": "留空则允许所有标签"
},
"profile": {
- "email": "邮箱",
"password": "密码",
"password-confirm": "确认密码",
"password-confirm-placeholder": "确认新密码",
@@ -1267,6 +1260,7 @@
"password-mismatch": "新密码不匹配",
"phone": "手机号",
"phone-tips": "请包含国家代码前缀 +86xxxxxx",
+ "email": "邮箱",
"role": "角色",
"subscription": "(升级到付费方案来解锁角色管理)"
},
@@ -1333,12 +1327,10 @@
},
"re-order": "排序"
},
- "never-expires": "无过期时间",
"semantic-types": {
"add-from-template": "从模板添加",
"label": "具有相同语义类型的列会使用相同的脱敏算法。",
"select": "选择语义类型",
- "self": "语义类型",
"table": {
"delete": "删除这个语义类型?",
"description": "描述",
@@ -1350,27 +1342,29 @@
"description": "您可以从模板中应用内置语义类型。内置模板无法更改。",
"duplicate-warning": "语义类型“{{title}}”已存在"
},
- "use-predefined-type": "使用预定义类型"
- }
+ "use-predefined-type": "使用预定义类型",
+ "self": "语义类型"
+ },
+ "never-expires": "无过期时间"
},
"sidebar": {
"audit-log": "审计日志",
"custom-roles": "自定义角色",
- "data-access": "数据访问",
"data-classification": "数据分类",
"general": "通用",
"global-masking": "全局数据脱敏",
- "iam-and-admin": "IAM & 管理",
"im-integration": "IM",
- "integration": "集成",
"mcp": "MCP",
"members": "成员",
"members-and-groups": "成员和群组",
- "profile": "个人信息",
- "security-and-policy": "安全 & 策略",
"sso": "SSO",
"subscription": "订阅",
- "users-and-groups": "用户和群组"
+ "users-and-groups": "用户和群组",
+ "data-access": "数据访问",
+ "iam-and-admin": "IAM & 管理",
+ "integration": "集成",
+ "profile": "个人信息",
+ "security-and-policy": "安全 & 策略"
},
"sso": {
"create": "创建 SSO",
@@ -1459,6 +1453,7 @@
}
},
"sql-editor": {
+ "self": "SQL 编辑器",
"access-grants": "访问授权",
"access-grants-redirect-hint": "前往 {link} 查看和管理您自己的访问授权。",
"activate-access": "激活",
@@ -1467,10 +1462,11 @@
"grant-type-unmask": "脱敏豁免",
"revoke-access": "撤销",
"revoke-confirm": "确定要撤销此访问授权吗?",
- "self": "SQL 编辑器",
"view-issue": "查看工单"
},
"sql-review": {
+ "configure-policy": "配置审核策略",
+ "title": "SQL 审核策略",
"add-or-remove-rules": "添加或删除规则",
"add-rules": "添加规则",
"attach-resource": {
@@ -1479,7 +1475,6 @@
"no-linked-resources": "没有绑定的资源",
"self": "绑定到资源"
},
- "configure-policy": "配置审核策略",
"create": {
"basic-info": {
"display-name": "名称",
@@ -1504,14 +1499,12 @@
"policy-removed": "审核策略已删除",
"policy-update-failed": "审核策略更新失败",
"policy-updated": "审核策略已更新",
- "review-policy": "审核策略",
- "title": "SQL 审核策略"
+ "review-policy": "审核策略"
},
"subscription": {
"contact-us": "联系我们",
"current": "当前版本",
"description": "您可以在这里上传您购买的 Bytebase 证书来解锁专业版/企业版功能。",
- "disabled-feature": "禁用功能",
"enterprise-free-trial": "企业版 {{days}} 天免费试用",
"expired": "已过期",
"expires-at": "过期时间",
@@ -1602,19 +1595,20 @@
"title": "用户数量限制",
"upgrade": "升级来获取更多用户额度。"
}
- }
+ },
+ "disabled-feature": "禁用功能"
},
"subscription.instance-assignment.assign-license": "分配证书",
"subscription.instance-assignment.n-license-remain": "剩余 {{n}} 个",
"subscription.usage.instance-count.runoutof": "已用尽全部 {{total}} 个实例额度。",
"subscription.usage.instance-count.title": "实例数量限制",
"two-factor": {
+ "enabled": "双重认证已开启",
"description": "双重认证为系统成员提供了一个额外的安全层。在登录时,用户需要输入由认证器应用程序生成的安全代码。",
"disable": {
"description": "您即将禁用您账户的双重认证。您在登录时将不再需要输入由您的 Authenticator 应用程序生成的安全代码。",
"self": "禁用双重认证"
},
- "enabled": "双重认证已开启",
"messages": {
"2fa-disabled": "双重认证禁用成功",
"2fa-enabled": "双重认证开启成功",
@@ -1655,5 +1649,68 @@
"description": "复制密钥并在您的应用程序中手动输入。",
"self": "双重认证密钥"
}
+ },
+ "agent": {
+ "assistant-title": "Bytebase 助手",
+ "resize": "调整大小",
+ "minimize": "最小化",
+ "close": "关闭",
+ "input-placeholder": "输入任何问题...",
+ "send": "发送",
+ "args": "参数:",
+ "result": "结果:",
+ "stop": "停止",
+ "interrupted": "已中断",
+ "retry-last-chat-turn": "重试上一轮",
+ "interrupted-retry-hint": "重试会基于当前页面状态重新运行已中断的这一轮。",
+ "new-chat": "新聊天",
+ "rename-chat-placeholder": "输入聊天名称",
+ "archive-chat": "归档",
+ "unarchive-chat": "取消归档",
+ "delete-chat": "删除",
+ "active-only-chats": "仅显示活跃",
+ "archived-only-chats": "仅显示已归档",
+ "archive-chat-confirmation": "要归档这个聊天吗?",
+ "delete-chat-confirmation": "要删除这个聊天吗?",
+ "chat-list-label": "聊天",
+ "chat-default-title": "新聊天",
+ "chat-archived-label": "已归档",
+ "chat-status-idle": "空闲",
+ "chat-status-running": "运行中",
+ "chat-status-awaiting-user": "等待输入",
+ "chat-status-error": "错误",
+ "chat-status-interrupted": "已中断",
+ "chat-total-tokens": "已用令牌:{{count}}",
+ "reply": "回复",
+ "confirm": "确认",
+ "cancel": "取消",
+ "pending-input-hint": "请在下方回复以继续当前聊天。",
+ "pending-confirm-hint": "请选择确认或取消以继续当前聊天。",
+ "pending-choose-hint": "请选择一个选项以继续当前聊天。",
+ "tool-ask-user": "等待你的回复",
+ "tool-ask-user-input": "需要输入",
+ "tool-ask-user-confirm": "需要确认",
+ "tool-ask-user-choose": "需要选择",
+ "tool-response-submitted": "已提交回复",
+ "tool-prompt": "提示:",
+ "tool-default-value": "默认值:",
+ "tool-options": "选项:",
+ "tool-answer": "回答:",
+ "tool-value": "值:",
+ "tool-completed": "已完成",
+ "tool-failed": "已完成,但存在问题",
+ "ai-not-configured": {
+ "title": "此工作空间尚未配置 AI 助手",
+ "description": "要继续使用页面助手,请先在工作空间设置中启用 AI 助手。",
+ "configure": "配置 AI",
+ "contact-admin": "请联系你的组织管理员来配置 AI 助手。"
+ }
+ },
+ "changelog": {
+ "select": "Schema 版本是在每次通过 Bytebase 执行 Schema 变更后被记录下来的",
+ "self": "变更历史"
+ },
+ "schema-editor": {
+ "raw-sql": "SQL 语句"
}
}
diff --git a/frontend/src/react/mount.ts b/frontend/src/react/mount.ts
index 80abc19407..a45cabd0a1 100644
--- a/frontend/src/react/mount.ts
+++ b/frontend/src/react/mount.ts
@@ -2,7 +2,14 @@
// Vite resolves the glob at build time and creates a lazy chunk for the matched module.
const settingsPageLoaders = import.meta.glob("./pages/settings/*.tsx");
const projectPageLoaders = import.meta.glob("./pages/project/*.tsx");
-const pageLoaders = { ...settingsPageLoaders, ...projectPageLoaders };
+const pluginComponentLoaders = import.meta.glob(
+ "./plugins/agent/components/AgentWindow.tsx"
+);
+const pageLoaders = {
+ ...settingsPageLoaders,
+ ...projectPageLoaders,
+ ...pluginComponentLoaders,
+};
// biome-ignore lint/suspicious/noExplicitAny: React types conflict with Vue JSX in vue-tsc
type ReactDeps = any; // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -36,7 +43,11 @@ async function loadCoreDeps() {
return cachedDeps;
}
-const pageDirs = ["./pages/settings", "./pages/project"];
+const pageDirs = [
+ "./pages/settings",
+ "./pages/project",
+ "./plugins/agent/components",
+];
async function loadPage(name: string): Promise<ReactComponent> {
const hit = cachedPages.get(name);
diff --git a/frontend/src/plugins/agent/AGENT.md b/frontend/src/react/plugins/agent/AGENT.md
similarity index 100%
rename from frontend/src/plugins/agent/AGENT.md
rename to frontend/src/react/plugins/agent/AGENT.md
diff --git a/frontend/src/react/plugins/agent/components/AgentChat.tsx b/frontend/src/react/plugins/agent/components/AgentChat.tsx
new file mode 100644
index 0000000000..8eb7f0fa3d
--- /dev/null
+++ b/frontend/src/react/plugins/agent/components/AgentChat.tsx
@@ -0,0 +1,226 @@
+import { useEffect, useMemo, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import { Button } from "@/react/components/ui/button";
+import { router } from "@/router";
+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
+import { hasWorkspacePermissionV2 } from "@/utils";
+import type { AgentMessage } from "../logic/types";
+import {
+ selectCurrentChatRequiresAIConfiguration,
+ selectError,
+ selectLoading,
+ selectMessages,
+ useAgentStore,
+} from "../store/agent";
+import { ToolCallCard } from "./ToolCallCard";
+
+interface AgentChatProps {
+ className?: string;
+}
+
+export function AgentChat({ className }: AgentChatProps) {
+ const { t } = useTranslation();
+ const chatContainerRef = useRef<HTMLDivElement>(null);
+
+ const messages = useAgentStore(selectMessages);
+ const loading = useAgentStore(selectLoading);
+ const error = useAgentStore(selectError);
+ const showAIConfigurationRecovery = useAgentStore(
+ selectCurrentChatRequiresAIConfiguration
+ );
+ const currentChatId = useAgentStore((s) => s.currentChatId);
+ const allMessages = useAgentStore(selectMessages);
+ const clearError = useAgentStore((s) => s.clearError);
+
+ const allowConfigure = hasWorkspacePermissionV2("bb.settings.set");
+
+ const displayMessages = useMemo(
+ () =>
+ messages.filter(
+ (message): message is AgentMessage =>
+ message.role === "user" || message.role === "assistant"
+ ),
+ [messages]
+ );
+
+ function getToolResult(
+ messageId: string,
+ toolCallId: string
+ ): string | undefined {
+ const fullIndex = allMessages.findIndex(
+ (message) => message.id === messageId
+ );
+ if (fullIndex < 0) return undefined;
+
+ for (let index = fullIndex + 1; index < allMessages.length; index++) {
+ const message = allMessages[index];
+ if (message.role === "tool" && message.toolCallId === toolCallId) {
+ return message.content;
+ }
+ if (
+ message.role === "assistant" &&
+ message.content &&
+ !message.toolCalls?.length
+ ) {
+ break;
+ }
+ }
+ return undefined;
+ }
+
+ function goConfigure() {
+ clearError(currentChatId);
+ router.push({
+ name: SETTING_ROUTE_WORKSPACE_GENERAL,
+ hash: "#ai-assistant",
+ });
+ }
+
+ function dismiss() {
+ clearError(currentChatId);
+ }
+
+ useEffect(() => {
+ if (chatContainerRef.current) {
+ chatContainerRef.current.scrollTop =
+ chatContainerRef.current.scrollHeight;
+ }
+ }, [currentChatId, messages.length]);
+
+ return (
+ <div
+ ref={chatContainerRef}
+ className={`overflow-y-auto space-y-3 p-3 ${className ?? ""}`}
+ >
+ {displayMessages.map((msg) =>
+ msg.role === "user" ? (
+ <div key={msg.id} className="flex justify-end">
+ <div className="max-w-[80%] rounded-lg bg-blue-50 px-3 py-2 text-sm">
+ {msg.content}
+ </div>
+ </div>
+ ) : (
+ <div key={msg.id} className="flex flex-col gap-y-2">
+ {msg.content && (
+ <div className="max-w-[80%] rounded-lg bg-gray-50 px-3 py-2 text-sm">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm]}
+ components={{
+ p: ({ children }) => (
+ <p className="my-1 first:mt-0 last:mb-0">{children}</p>
+ ),
+ pre: ({ children }) => (
+ <pre className="my-1 overflow-x-auto rounded bg-gray-100 p-2 text-xs">
+ {children}
+ </pre>
+ ),
+ code: ({ children }) => (
+ <code className="rounded bg-gray-200 px-1 text-xs">
+ {children}
+ </code>
+ ),
+ ul: ({ children }) => (
+ <ul className="my-1 list-disc pl-5">{children}</ul>
+ ),
+ ol: ({ children }) => (
+ <ol className="my-1 list-decimal pl-5">{children}</ol>
+ ),
+ li: ({ children }) => (
+ <li className="my-0.5">{children}</li>
+ ),
+ h1: ({ children }) => (
+ <h1 className="my-1 font-semibold">{children}</h1>
+ ),
+ h2: ({ children }) => (
+ <h2 className="my-1 font-semibold">{children}</h2>
+ ),
+ h3: ({ children }) => (
+ <h3 className="my-1 font-semibold">{children}</h3>
+ ),
+ a: ({ children, href }) => (
+ <a
+ className="text-blue-600 underline"
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {children}
+ </a>
+ ),
+ blockquote: ({ children }) => (
+ <blockquote className="my-1 border-l-2 border-gray-300 pl-2 text-gray-600">
+ {children}
+ </blockquote>
+ ),
+ table: ({ children }) => (
+ <table className="my-1 border-collapse text-xs">
+ {children}
+ </table>
+ ),
+ th: ({ children }) => (
+ <th className="border border-gray-300 px-2 py-1">
+ {children}
+ </th>
+ ),
+ td: ({ children }) => (
+ <td className="border border-gray-300 px-2 py-1">
+ {children}
+ </td>
+ ),
+ }}
+ >
+ {msg.content}
+ </ReactMarkdown>
+ </div>
+ )}
+ {msg.toolCalls?.map((toolCall) => (
+ <ToolCallCard
+ key={toolCall.id}
+ toolCall={toolCall}
+ result={getToolResult(msg.id, toolCall.id)}
+ />
+ ))}
+ </div>
+ )
+ )}
+
+ {loading && (
+ <div className="flex items-center gap-x-2 text-sm text-gray-400">
+ <span className="animate-pulse">&#9679;</span> {t("common.loading")}
+ </div>
+ )}
+
+ {showAIConfigurationRecovery ? (
+ <div className="max-w-[80%] rounded-lg border border-amber-200 bg-amber-50 px-3 py-3 text-sm text-amber-900">
+ <div className="font-medium">
+ {t("agent.ai-not-configured.title")}
+ </div>
+ <div className="mt-1">{t("agent.ai-not-configured.description")}</div>
+ <div className="mt-3 flex flex-wrap gap-x-2 gap-y-2">
+ {allowConfigure && (
+ <Button variant="default" size="sm" onClick={goConfigure}>
+ {t("agent.ai-not-configured.configure")}
+ </Button>
+ )}
+ <Button variant="outline" size="sm" onClick={dismiss}>
+ {t("common.dismiss")}
+ </Button>
+ </div>
+ {!allowConfigure && (
+ <div className="mt-1 text-amber-800">
+ {t("agent.ai-not-configured.contact-admin")}
+ </div>
+ )}
+ </div>
+ ) : (
+ error && (
+ <div className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600">
+ {error}
+ </div>
+ )
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/plugins/agent/components/AgentInput.tsx b/frontend/src/react/plugins/agent/components/AgentInput.tsx
new file mode 100644
index 0000000000..0eeff0f601
--- /dev/null
+++ b/frontend/src/react/plugins/agent/components/AgentInput.tsx
@@ -0,0 +1,769 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { v4 as uuidv4 } from "uuid";
+import { Button } from "@/react/components/ui/button";
+import { router } from "@/router";
+import type { DomRefSuggestion } from "../dom";
+import { lazyExtractDomRefSuggestions } from "../dom";
+import { runAgentLoop } from "../logic/agentLoop";
+import { isAgentAIConfigurationError } from "../logic/aiConfiguration";
+import { buildOutboundHistory } from "../logic/outboundHistory";
+import { buildSystemPrompt } from "../logic/prompt";
+import { createToolExecutor, getToolDefinitions } from "../logic/tools";
+import type { AgentAskUserOption, Message } from "../logic/types";
+import {
+ selectCurrentChat,
+ selectCurrentChatRequiresAIConfiguration,
+ selectCurrentPendingAsk,
+ selectLoading,
+ useAgentStore,
+} from "../store/agent";
+
+// Module-level map — survives across renders, same as Vue version.
+const runTokens = new Map<string, number>();
+
+// Module-level request token for dom ref suggestion loading.
+let domRefRequestToken = 0;
+
+// ---------------------------------------------------------------------------
+// Helper functions (same logic as the Vue version)
+// ---------------------------------------------------------------------------
+
+const normalizeSearchText = (value?: string) =>
+ value?.toLowerCase().trim() ?? "";
+
+const matchDomRefSuggestion = (suggestion: DomRefSuggestion, query: string) => {
+ if (!query) return true;
+ const normalizedQuery = normalizeSearchText(query);
+ return [
+ suggestion.ref,
+ suggestion.tag,
+ suggestion.role,
+ suggestion.label,
+ suggestion.value,
+ ].some((value) => normalizeSearchText(value).includes(normalizedQuery));
+};
+
+const getDomRefQuery = (
+ text: string,
+ start: number,
+ end: number
+): { query: string; start: number; end: number } | null => {
+ if (start !== end) return null;
+ const prefix = text.slice(0, start);
+ const matches = prefix.match(/(^|\s)@([^\s@]*)$/);
+ if (!matches) return null;
+ return {
+ query: matches[2] ?? "",
+ start: start - matches[2].length - 1,
+ end,
+ };
+};
+
+const formatDomRefSuggestionMeta = (suggestion: DomRefSuggestion) =>
+ [suggestion.tag.toLowerCase(), suggestion.role]
+ .filter((value): value is string => Boolean(value))
+ .join(" · ");
+
+const getCurrentPageSnapshot = () => ({
+ path: router.currentRoute.value.fullPath,
+ title: document.title,
+});
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+interface DomRefMentionOption {
+ label: string;
+ value: string;
+ suggestion: DomRefSuggestion;
+}
+
+export function AgentInput() {
+ const { t } = useTranslation();
+
+ // Zustand selectors
+ const currentChat = useAgentStore(selectCurrentChat);
+ const currentPendingAsk = useAgentStore(selectCurrentPendingAsk);
+ const loading = useAgentStore(selectLoading);
+ const isAIConfigurationBlocked = useAgentStore(
+ selectCurrentChatRequiresAIConfiguration
+ );
+ const currentChatId = useAgentStore((s) => s.currentChatId);
+
+ // Local state
+ const [input, setInput] = useState("");
+ const [selectionStart, setSelectionStart] = useState(0);
+ const [selectionEnd, setSelectionEnd] = useState(0);
+ const [domRefSuggestions, setDomRefSuggestions] = useState<
+ DomRefSuggestion[]
+ >([]);
+ const [isMentionOpen, setIsMentionOpen] = useState(false);
+ const [highlightIndex, setHighlightIndex] = useState(0);
+
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const mentionListRef = useRef<HTMLDivElement>(null);
+
+ // Derived values
+ const isInterrupted = Boolean(currentChat?.interrupted);
+ const isCurrentChatRunning = currentChat?.status === "running";
+ const chooseOptions =
+ currentPendingAsk?.kind === "choose"
+ ? (currentPendingAsk.options ?? [])
+ : [];
+ const isAwaitingConfirm = currentPendingAsk?.kind === "confirm";
+ const isAwaitingChoose =
+ currentPendingAsk?.kind === "choose" && chooseOptions.length > 0;
+ const sendLabel = currentPendingAsk ? t("agent.reply") : t("agent.send");
+ const inputPlaceholder =
+ currentPendingAsk?.kind === "input"
+ ? currentPendingAsk.prompt
+ : currentPendingAsk?.kind === "choose"
+ ? currentPendingAsk.prompt
+ : t("agent.input-placeholder");
+ const confirmLabel = currentPendingAsk?.confirmLabel ?? t("agent.confirm");
+ const cancelLabel = currentPendingAsk?.cancelLabel ?? t("agent.cancel");
+ const isSendDisabled =
+ isCurrentChatRunning ||
+ isAwaitingConfirm ||
+ isAwaitingChoose ||
+ isAIConfigurationBlocked ||
+ !input.trim();
+
+ // @-mention autocomplete
+ const activeDomRefQuery = useMemo(
+ () => getDomRefQuery(input, selectionStart, selectionEnd),
+ [input, selectionStart, selectionEnd]
+ );
+
+ const filteredSuggestions = useMemo(() => {
+ const query = activeDomRefQuery?.query ?? "";
+ return domRefSuggestions.filter((s) => matchDomRefSuggestion(s, query));
+ }, [domRefSuggestions, activeDomRefQuery]);
+
+ const mentionOptions = useMemo<DomRefMentionOption[]>(
+ () =>
+ filteredSuggestions.map((suggestion) => ({
+ label: `[${suggestion.ref}] ${suggestion.label}`,
+ value: `[${suggestion.ref}]`,
+ suggestion,
+ })),
+ [filteredSuggestions]
+ );
+
+ // Show/hide mention popover
+ const showMention = isMentionOpen && mentionOptions.length > 0;
+
+ // Reset highlight when options change
+ useEffect(() => {
+ setHighlightIndex(0);
+ }, [mentionOptions.length]);
+
+ // Close mention menu when chat starts running
+ useEffect(() => {
+ if (isCurrentChatRunning) {
+ setIsMentionOpen(false);
+ }
+ }, [isCurrentChatRunning]);
+
+ // Reset input when chat/pendingAsk changes
+ useEffect(() => {
+ if (
+ currentPendingAsk?.kind === "input" ||
+ currentPendingAsk?.kind === "choose"
+ ) {
+ setInput(currentPendingAsk.defaultValue ?? "");
+ return;
+ }
+ setInput("");
+ }, [
+ currentChatId,
+ currentPendingAsk?.toolCallId,
+ currentPendingAsk?.kind,
+ currentPendingAsk?.defaultValue,
+ ]);
+
+ // Load dom ref suggestions when @ query is active
+ useEffect(() => {
+ if (!activeDomRefQuery) {
+ setDomRefSuggestions([]);
+ setIsMentionOpen(false);
+ return;
+ }
+ setIsMentionOpen(true);
+
+ // Only load once (when suggestions are empty)
+ if (domRefSuggestions.length > 0) return;
+
+ const requestToken = ++domRefRequestToken;
+ void lazyExtractDomRefSuggestions().then((suggestions) => {
+ if (requestToken !== domRefRequestToken) return;
+ // Verify @ query is still active before updating suggestions
+ const currentQuery = getDomRefQuery(
+ textareaRef.current?.value ?? "",
+ textareaRef.current?.selectionStart ?? 0,
+ textareaRef.current?.selectionEnd ?? 0
+ );
+ if (!currentQuery) return;
+ setDomRefSuggestions(suggestions);
+ });
+ }, [input, selectionStart, selectionEnd]);
+
+ // Auto-resize textarea
+ const autoResize = useCallback(() => {
+ const el = textareaRef.current;
+ if (!el) return;
+ el.style.height = "auto";
+ const maxRows = 6;
+ const lineHeight = 20;
+ const maxHeight = lineHeight * maxRows;
+ el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px`;
+ }, []);
+
+ useEffect(() => {
+ autoResize();
+ }, [input, autoResize]);
+
+ // Selection tracking
+ const updateSelection = useCallback(() => {
+ const el = textareaRef.current;
+ if (!el) return;
+ setSelectionStart(el.selectionStart ?? 0);
+ setSelectionEnd(el.selectionEnd ?? 0);
+ }, []);
+
+ // Select a mention option
+ const selectMention = useCallback(
+ (option: DomRefMentionOption) => {
+ if (!activeDomRefQuery) return;
+ const before = input.slice(0, activeDomRefQuery.start);
+ const after = input.slice(activeDomRefQuery.end);
+ const newValue = `${before}${option.value} ${after}`;
+ setInput(newValue);
+ setIsMentionOpen(false);
+ setDomRefSuggestions([]);
+
+ // Set cursor after the inserted mention
+ const cursorPos = before.length + option.value.length + 1;
+ requestAnimationFrame(() => {
+ const el = textareaRef.current;
+ if (el) {
+ el.focus();
+ el.setSelectionRange(cursorPos, cursorPos);
+ setSelectionStart(cursorPos);
+ setSelectionEnd(cursorPos);
+ }
+ });
+ },
+ [activeDomRefQuery, input]
+ );
+
+ // Scroll highlighted item into view
+ const scrollHighlightedIntoView = useCallback((index: number) => {
+ requestAnimationFrame(() => {
+ const container = mentionListRef.current;
+ if (!container) return;
+ const items = container.querySelectorAll("[data-mention-option]");
+ items[index]?.scrollIntoView({ block: "nearest" });
+ });
+ }, []);
+
+ // ---------------------------------------------------------------------------
+ // Agent loop execution (same logic as Vue version)
+ // ---------------------------------------------------------------------------
+
+ const buildChatHistory = useCallback(
+ (chatId: string, systemPrompt: string): Message[] => {
+ return buildOutboundHistory(
+ systemPrompt,
+ useAgentStore.getState().getMessages(chatId)
+ );
+ },
+ []
+ );
+
+ const handleOutcome = useCallback(
+ (
+ chatId: string,
+ page: { path: string; title: string },
+ errorPrefix: string,
+ outcome: Awaited<ReturnType<typeof runAgentLoop>>
+ ) => {
+ const store = useAgentStore.getState();
+ switch (outcome.kind) {
+ case "completed":
+ store.finishChatRun(chatId);
+ return;
+ case "awaiting_user":
+ store.awaitUser(chatId, outcome.ask);
+ return;
+ case "aborted":
+ store.interruptChatRun(chatId, getCurrentPageSnapshot());
+ return;
+ case "error": {
+ if (!isAgentAIConfigurationError(outcome.error)) {
+ store.addMessage({
+ chatId,
+ role: "assistant",
+ content: `${errorPrefix}${outcome.error.message}`,
+ metadata: {
+ route: page.path,
+ error: outcome.error.message,
+ },
+ });
+ }
+ store.finishChatRun(chatId, {
+ status: "error",
+ lastError: outcome.error.message,
+ requiresAIConfiguration: isAgentAIConfigurationError(outcome.error),
+ });
+ return;
+ }
+ }
+ },
+ []
+ );
+
+ const runChat = useCallback(
+ async (
+ chatId: string,
+ page: { path: string; title: string },
+ runId: string
+ ) => {
+ const store = useAgentStore.getState();
+ const controller = new AbortController();
+ const runToken = (runTokens.get(chatId) ?? 0) + 1;
+ runTokens.set(chatId, runToken);
+ store.setAbortController(chatId, controller);
+
+ const systemPrompt = buildSystemPrompt(page);
+ const tools = getToolDefinitions();
+ const executor = createToolExecutor(router, {
+ chatId,
+ onNavigate: () => {
+ useAgentStore
+ .getState()
+ .updateChatPage(chatId, getCurrentPageSnapshot());
+ },
+ });
+
+ try {
+ const outcome = await runAgentLoop(
+ buildChatHistory(chatId, systemPrompt),
+ tools,
+ executor,
+ {
+ onAssistantMessage: (message) => {
+ if (!message.content && !message.toolCalls?.length) return;
+ useAgentStore.getState().addMessage({
+ chatId,
+ role: "assistant",
+ content: message.content,
+ toolCalls: message.toolCalls,
+ metadata: { route: page.path, runId },
+ });
+ },
+ onToolResult: (toolCallId, result) => {
+ useAgentStore.getState().addMessage({
+ chatId,
+ role: "tool",
+ toolCallId,
+ content: result,
+ metadata: { route: page.path, runId },
+ });
+ },
+ onText: (text) => {
+ if (!text) return;
+ useAgentStore.getState().addMessage({
+ chatId,
+ role: "assistant",
+ content: text,
+ metadata: { route: page.path, runId },
+ });
+ },
+ },
+ controller.signal
+ );
+
+ useAgentStore
+ .getState()
+ .incrementChatTotalTokens(chatId, outcome.totalTokensUsed ?? 0);
+
+ if (runToken !== runTokens.get(chatId)) return;
+
+ handleOutcome(chatId, page, "Error: ", outcome);
+ } finally {
+ if (
+ useAgentStore.getState().getAbortController(chatId) === controller
+ ) {
+ useAgentStore.getState().setAbortController(chatId, null);
+ }
+ }
+ },
+ [buildChatHistory, handleOutcome]
+ );
+
+ const startChatRun = useCallback(
+ async (chatId: string, currentPage: { path: string; title: string }) => {
+ const runId = uuidv4();
+ const store = useAgentStore.getState();
+ store.updateChatPage(chatId, currentPage);
+ store.startChatRun(chatId, currentPage, { runId });
+ await runChat(chatId, currentPage, runId);
+ },
+ [runChat]
+ );
+
+ const send = useCallback(async () => {
+ const store = useAgentStore.getState();
+ const chat = selectCurrentChat(store);
+ if (store.isChatRunning(chat?.id)) return;
+
+ const currentPage = getCurrentPageSnapshot();
+ const thread = store.ensureCurrentChat(currentPage);
+ const chatId = thread.id;
+ store.clearError(chatId);
+
+ const pendingAsk = selectCurrentPendingAsk(store);
+ if (pendingAsk) {
+ const answer = input.trim();
+ if (!answer) return;
+ setInput("");
+
+ if (pendingAsk.kind === "choose") {
+ store.answerPendingAsk(
+ chatId,
+ { kind: "choose", answer, value: answer },
+ { route: currentPage.path }
+ );
+ } else if (pendingAsk.kind === "input") {
+ store.answerPendingAsk(
+ chatId,
+ { kind: "input", answer },
+ { route: currentPage.path }
+ );
+ } else {
+ return;
+ }
+ await startChatRun(chatId, currentPage);
+ return;
+ }
+
+ const text = input.trim();
+ if (!text) return;
+ setInput("");
+ store.addMessage({
+ chatId,
+ role: "user",
+ content: text,
+ metadata: { route: currentPage.path },
+ });
+ await startChatRun(chatId, currentPage);
+ }, [input, startChatRun]);
+
+ const retryLastTurn = useCallback(async () => {
+ const store = useAgentStore.getState();
+ const chat = selectCurrentChat(store);
+ if (store.isChatRunning(chat?.id) || !chat?.interrupted) return;
+
+ const chatId = chat.id;
+ const currentPage = getCurrentPageSnapshot();
+ store.removeMessagesByRunId(chatId, chat.runId);
+ store.clearError(chatId);
+ await startChatRun(chatId, currentPage);
+ }, [startChatRun]);
+
+ const dismissInterrupted = useCallback(() => {
+ const store = useAgentStore.getState();
+ const chat = selectCurrentChat(store);
+ if (!chat) return;
+ store.removeMessagesByRunId(chat.id, chat.runId);
+ store.clearError(chat.id);
+ }, []);
+
+ const submitConfirmation = useCallback(
+ async (confirmed: boolean) => {
+ const store = useAgentStore.getState();
+ const pendingAsk = selectCurrentPendingAsk(store);
+ const chat = selectCurrentChat(store);
+ if (
+ !pendingAsk ||
+ pendingAsk.kind !== "confirm" ||
+ store.isChatRunning(chat?.id)
+ ) {
+ return;
+ }
+
+ const currentPage = getCurrentPageSnapshot();
+ const thread = store.ensureCurrentChat(currentPage);
+ const chatId = thread.id;
+ const answer = confirmed ? confirmLabel : cancelLabel;
+
+ store.clearError(chatId);
+ store.answerPendingAsk(
+ chatId,
+ { kind: "confirm", answer, confirmed },
+ { route: currentPage.path }
+ );
+ await startChatRun(chatId, currentPage);
+ },
+ [confirmLabel, cancelLabel, startChatRun]
+ );
+
+ const submitChoice = useCallback(
+ async (option: AgentAskUserOption) => {
+ const store = useAgentStore.getState();
+ const pendingAsk = selectCurrentPendingAsk(store);
+ const chat = selectCurrentChat(store);
+ if (
+ !pendingAsk ||
+ pendingAsk.kind !== "choose" ||
+ store.isChatRunning(chat?.id)
+ ) {
+ return;
+ }
+
+ const currentPage = getCurrentPageSnapshot();
+ const thread = store.ensureCurrentChat(currentPage);
+ const chatId = thread.id;
+
+ store.clearError(chatId);
+ store.answerPendingAsk(
+ chatId,
+ { kind: "choose", answer: option.label, value: option.value },
+ { route: currentPage.path }
+ );
+ await startChatRun(chatId, currentPage);
+ },
+ [startChatRun]
+ );
+
+ // Textarea keydown handler
+ const handleTextareaKeydown = useCallback(
+ (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (showMention) {
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ const next = Math.min(highlightIndex + 1, mentionOptions.length - 1);
+ setHighlightIndex(next);
+ scrollHighlightedIntoView(next);
+ return;
+ }
+ if (event.key === "ArrowUp") {
+ event.preventDefault();
+ const prev = Math.max(highlightIndex - 1, 0);
+ setHighlightIndex(prev);
+ scrollHighlightedIntoView(prev);
+ return;
+ }
+ if (event.key === "Enter") {
+ event.preventDefault();
+ if (mentionOptions[highlightIndex]) {
+ selectMention(mentionOptions[highlightIndex]);
+ }
+ return;
+ }
+ if (event.key === "Escape") {
+ event.preventDefault();
+ setIsMentionOpen(false);
+ return;
+ }
+ }
+
+ if (
+ event.key === "Enter" &&
+ !event.shiftKey &&
+ !event.altKey &&
+ !event.ctrlKey &&
+ !event.metaKey
+ ) {
+ event.preventDefault();
+ void send();
+ }
+ },
+ [
+ showMention,
+ highlightIndex,
+ mentionOptions,
+ selectMention,
+ scrollHighlightedIntoView,
+ send,
+ ]
+ );
+
+ // ---------------------------------------------------------------------------
+ // Render
+ // ---------------------------------------------------------------------------
+
+ return (
+ <div className="border-t p-3">
+ {/* Pending ask banner */}
+ {currentPendingAsk && (
+ <div className="mb-3 rounded-md bg-amber-50 px-3 py-2 text-xs text-amber-700">
+ <div className="font-medium">{currentPendingAsk.prompt}</div>
+ <div className="mt-1">
+ {currentPendingAsk.kind === "confirm"
+ ? t("agent.pending-confirm-hint")
+ : currentPendingAsk.kind === "choose"
+ ? t("agent.pending-choose-hint")
+ : t("agent.pending-input-hint")}
+ </div>
+ </div>
+ )}
+
+ {/* Interrupted banner */}
+ {isInterrupted && (
+ <div className="mb-3 rounded-md bg-red-50 px-3 py-2 text-xs text-red-700">
+ <div className="font-medium">{t("agent.interrupted")}</div>
+ <div className="mt-1">{t("agent.interrupted-retry-hint")}</div>
+ <div className="mt-2 flex flex-wrap gap-x-2 gap-y-2">
+ <button
+ className="rounded-md bg-red-500 px-3 py-2 text-sm text-white hover:bg-red-600 disabled:opacity-50"
+ disabled={isCurrentChatRunning}
+ onClick={retryLastTurn}
+ >
+ {t("agent.retry-last-chat-turn")}
+ </button>
+ <button
+ className="rounded-md border px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50"
+ disabled={isCurrentChatRunning}
+ onClick={dismissInterrupted}
+ >
+ {t("common.dismiss")}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Confirm buttons */}
+ {isAwaitingConfirm ? (
+ <div className="flex flex-wrap gap-x-2 gap-y-2">
+ <button
+ className="rounded-md bg-blue-500 px-3 py-2 text-sm text-white hover:bg-blue-600 disabled:opacity-50"
+ disabled={isCurrentChatRunning}
+ onClick={() => submitConfirmation(true)}
+ >
+ {confirmLabel}
+ </button>
+ <button
+ className="rounded-md border px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50"
+ disabled={isCurrentChatRunning}
+ onClick={() => submitConfirmation(false)}
+ >
+ {cancelLabel}
+ </button>
+ </div>
+ ) : isAwaitingChoose ? (
+ /* Choose options */
+ <div className="flex flex-col gap-y-2">
+ {chooseOptions.map((option) => (
+ <button
+ key={option.value}
+ className="rounded-md border px-3 py-2 text-left text-sm hover:bg-gray-50 disabled:opacity-50"
+ disabled={isCurrentChatRunning}
+ onClick={() => submitChoice(option)}
+ >
+ <div className="font-medium text-gray-800">{option.label}</div>
+ {option.description && (
+ <div className="mt-1 text-xs text-gray-500">
+ {option.description}
+ </div>
+ )}
+ </button>
+ ))}
+ </div>
+ ) : (
+ /* Input row with @-mention autocomplete */
+ <div
+ className="relative flex items-center gap-x-2"
+ data-agent-input-row
+ >
+ <div className="relative w-full">
+ <textarea
+ ref={textareaRef}
+ value={input}
+ rows={1}
+ className="w-full resize-none rounded-md border px-3 py-1.5 text-sm outline-none focus:ring-1 focus:ring-accent disabled:opacity-50"
+ style={{ maxHeight: 120 }}
+ placeholder={inputPlaceholder}
+ disabled={isCurrentChatRunning || isAIConfigurationBlocked}
+ onChange={(e) => {
+ setInput(e.target.value);
+ updateSelection();
+ }}
+ onClick={updateSelection}
+ onKeyUp={updateSelection}
+ onSelect={updateSelection}
+ onKeyDown={handleTextareaKeydown}
+ />
+
+ {/* Mention popover */}
+ {showMention && (
+ <div
+ ref={mentionListRef}
+ className="absolute bottom-full left-0 z-50 mb-1 max-h-80 w-full overflow-y-auto rounded-md border bg-white shadow-lg"
+ >
+ {mentionOptions.map((option, index) => {
+ const meta = formatDomRefSuggestionMeta(option.suggestion);
+ return (
+ <div
+ key={option.value}
+ data-mention-option
+ className={`cursor-pointer px-3 py-2 ${
+ index === highlightIndex
+ ? "bg-accent/10"
+ : "hover:bg-gray-50"
+ }`}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ selectMention(option);
+ }}
+ onMouseEnter={() => setHighlightIndex(index)}
+ >
+ <div className="flex flex-col text-sm">
+ <div className="flex items-center gap-x-2 text-gray-800">
+ <span className="font-medium">
+ [{option.suggestion.ref}]
+ </span>
+ <span className="truncate">
+ {option.suggestion.label}
+ </span>
+ </div>
+ {meta && (
+ <div className="mt-1 text-xs text-gray-500">
+ {meta}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+
+ {loading ? (
+ <Button
+ variant="destructive"
+ size="sm"
+ className="whitespace-nowrap"
+ onClick={() => useAgentStore.getState().cancel(currentChat?.id)}
+ >
+ {t("agent.stop")}
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ className="whitespace-nowrap"
+ disabled={isSendDisabled}
+ onClick={() => void send()}
+ >
+ {sendLabel}
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/plugins/agent/components/AgentWindow.tsx b/frontend/src/react/plugins/agent/components/AgentWindow.tsx
new file mode 100644
index 0000000000..b8811f9fb2
--- /dev/null
+++ b/frontend/src/react/plugins/agent/components/AgentWindow.tsx
@@ -0,0 +1,1013 @@
+import { Archive, Inbox } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { useTranslation } from "react-i18next";
+import { HumanizeTs } from "@/react/components/HumanizeTs";
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogTitle,
+ DialogTrigger,
+} from "@/react/components/ui/dialog";
+import { Input } from "@/react/components/ui/input";
+import type { AgentChat as AgentChatRecord } from "../logic/types";
+import {
+ selectCurrentChat,
+ selectHasRunningChat,
+ selectOrderedChats,
+ useAgentStore,
+} from "../store/agent";
+import { AgentChat } from "./AgentChat";
+import { AgentInput } from "./AgentInput";
+
+const MIN_WIDTH = 300;
+const MIN_HEIGHT = 400;
+const WINDOW_MARGIN = 16;
+const MIN_SIDEBAR_WIDTH = 180;
+const MIN_MAIN_PANEL_WIDTH = 240;
+
+const tokenFormatter = new Intl.NumberFormat();
+
+export function AgentWindow() {
+ const { t } = useTranslation();
+
+ const visible = useAgentStore((s) => s.visible);
+ const minimized = useAgentStore((s) => s.minimized);
+ const position = useAgentStore((s) => s.position);
+ const size = useAgentStore((s) => s.size);
+ const sidebarWidth = useAgentStore((s) => s.sidebarWidth);
+ const orderedChats = useAgentStore(selectOrderedChats);
+ const currentChat = useAgentStore(selectCurrentChat);
+ const currentChatId = useAgentStore((s) => s.currentChatId);
+ const hasRunningChat = useAgentStore(selectHasRunningChat);
+
+ const windowRef = useRef<HTMLDivElement>(null);
+ const renameInputRef = useRef<HTMLInputElement>(null);
+
+ const [viewportSize, setViewportSize] = useState({
+ width: window.innerWidth,
+ height: window.innerHeight,
+ });
+ const isViewportResizingRef = useRef(false);
+ const viewportResizeFrameRef = useRef(0);
+
+ const [showArchivedOnly, setShowArchivedOnly] = useState(false);
+ const [isRenamingCurrentChat, setIsRenamingCurrentChat] = useState(false);
+ const [renamingTitle, setRenamingTitle] = useState("");
+
+ // Refs for drag/resize intermediate values (avoid re-renders)
+ const isDraggingRef = useRef(false);
+ const dragOffsetRef = useRef({ x: 0, y: 0 });
+ const isResizingRef = useRef(false);
+ const resizeStartRef = useRef({ x: 0, y: 0, w: 0, h: 0 });
+ const isSidebarResizingRef = useRef(false);
+ const sidebarResizeStartRef = useRef({ x: 0, width: 0 });
+ const resizeObserverRef = useRef<ResizeObserver | null>(null);
+
+ // --- Clamping helpers ---
+
+ const maxWidth = useCallback(
+ () => Math.max(MIN_WIDTH, viewportSize.width - WINDOW_MARGIN * 2),
+ [viewportSize.width]
+ );
+ const maxHeight = useCallback(
+ () => Math.max(MIN_HEIGHT, viewportSize.height - WINDOW_MARGIN * 2),
+ [viewportSize.height]
+ );
+
+ const clampWidth = useCallback(
+ (width: number) =>
+ Math.min(maxWidth(), Math.max(MIN_WIDTH, Math.round(width))),
+ [maxWidth]
+ );
+ const clampHeight = useCallback(
+ (height: number) =>
+ Math.min(maxHeight(), Math.max(MIN_HEIGHT, Math.round(height))),
+ [maxHeight]
+ );
+
+ const getDisplaySize = useCallback(
+ (w: number, h: number) => ({
+ width: clampWidth(w),
+ height: clampHeight(h),
+ }),
+ [clampWidth, clampHeight]
+ );
+
+ const getDisplayPosition = useCallback(
+ (x: number, y: number, displaySize?: { width: number; height: number }) => {
+ const sz = displaySize ?? getDisplaySize(size.width, size.height);
+ const maxX = Math.max(
+ WINDOW_MARGIN,
+ viewportSize.width - sz.width - WINDOW_MARGIN
+ );
+ const maxY = Math.max(
+ WINDOW_MARGIN,
+ viewportSize.height - sz.height - WINDOW_MARGIN
+ );
+ return {
+ x: Math.min(maxX, Math.max(WINDOW_MARGIN, Math.round(x))),
+ y: Math.min(maxY, Math.max(WINDOW_MARGIN, Math.round(y))),
+ };
+ },
+ [
+ getDisplaySize,
+ size.width,
+ size.height,
+ viewportSize.width,
+ viewportSize.height,
+ ]
+ );
+
+ const displayWindowState = useMemo(() => {
+ const sz = getDisplaySize(size.width, size.height);
+ const pos = getDisplayPosition(position.x, position.y, sz);
+ return { position: pos, size: sz };
+ }, [
+ getDisplaySize,
+ getDisplayPosition,
+ size.width,
+ size.height,
+ position.x,
+ position.y,
+ ]);
+
+ const clampSidebarWidth = useCallback(
+ (width: number, windowWidth = displayWindowState.size.width) => {
+ const maxSW = Math.max(
+ MIN_SIDEBAR_WIDTH,
+ windowWidth - MIN_MAIN_PANEL_WIDTH
+ );
+ const minSW = Math.min(MIN_SIDEBAR_WIDTH, maxSW);
+ return Math.min(maxSW, Math.max(minSW, Math.round(width)));
+ },
+ [displayWindowState.size.width]
+ );
+
+ const clampedSidebarWidth = useMemo(
+ () => clampSidebarWidth(sidebarWidth),
+ [clampSidebarWidth, sidebarWidth]
+ );
+
+ const windowStyle: React.CSSProperties = {
+ left: `${displayWindowState.position.x}px`,
+ top: `${displayWindowState.position.y}px`,
+ width: `${displayWindowState.size.width}px`,
+ height: `${displayWindowState.size.height}px`,
+ };
+
+ const sidebarStyle: React.CSSProperties = {
+ width: `${clampedSidebarWidth}px`,
+ };
+
+ // --- Derived chat data ---
+
+ const displayedChats = useMemo(
+ () => orderedChats.filter((chat) => chat.archived === showArchivedOnly),
+ [orderedChats, showArchivedOnly]
+ );
+
+ const isCurrentChatInDisplayedMode = useMemo(
+ () => !!currentChat && currentChat.archived === showArchivedOnly,
+ [currentChat, showArchivedOnly]
+ );
+
+ const currentChatStatusLabel = useMemo(() => {
+ if (!currentChat) return t("agent.chat-status-idle");
+ if (currentChat.interrupted) return t("agent.chat-status-interrupted");
+ switch (currentChat.status) {
+ case "running":
+ return t("agent.chat-status-running");
+ case "awaiting_user":
+ return t("agent.chat-status-awaiting-user");
+ case "error":
+ return t("agent.chat-status-error");
+ default:
+ return t("agent.chat-status-idle");
+ }
+ }, [currentChat, t]);
+
+ const currentChatStatusClass = useMemo(() => {
+ if (!currentChat || currentChat.status === "idle")
+ return "bg-gray-100 text-gray-600";
+ if (currentChat.status === "running") return "bg-blue-50 text-blue-600";
+ if (currentChat.interrupted || currentChat.status === "error")
+ return "bg-red-50 text-red-600";
+ return "bg-amber-50 text-amber-600";
+ }, [currentChat]);
+
+ const currentChatTokenUsageLabel = useMemo(
+ () =>
+ t("agent.chat-total-tokens", {
+ count: tokenFormatter.format(currentChat?.totalTokensUsed ?? 0),
+ }),
+ [currentChat?.totalTokensUsed, t]
+ );
+
+ const isChatCreationDisabled = hasRunningChat;
+
+ const syncStoreToDisplayState = useCallback(() => {
+ const store = useAgentStore.getState();
+ store.setSize(
+ displayWindowState.size.width,
+ displayWindowState.size.height
+ );
+ store.setPosition(
+ displayWindowState.position.x,
+ displayWindowState.position.y
+ );
+ }, [displayWindowState]);
+
+ // --- Chat helpers ---
+
+ const getCurrentPageSnapshot = useCallback(
+ () => ({
+ path: window.location.pathname + window.location.hash,
+ title: document.title,
+ }),
+ []
+ );
+
+ const getEditableChatTitle = useCallback(
+ (chat: AgentChatRecord) => chat.title || t("agent.chat-default-title"),
+ [t]
+ );
+
+ const getChatLabel = useCallback(
+ (chat: AgentChatRecord) => {
+ const baseLabel = getEditableChatTitle(chat);
+ return chat.archived
+ ? `${baseLabel} (${t("agent.chat-archived-label")})`
+ : baseLabel;
+ },
+ [getEditableChatTitle, t]
+ );
+
+ const selectFirstDisplayedChat = useCallback(() => {
+ const first = displayedChats[0];
+ if (!first || !useAgentStore.getState().canSelectChat(first.id))
+ return false;
+ useAgentStore.getState().setCurrentChat(first.id);
+ return useAgentStore.getState().currentChatId === first.id;
+ }, [displayedChats]);
+
+ const ensureCurrentChatMatchesDisplayedMode = useCallback(
+ (options: { fallbackToActiveWhenEmpty?: boolean } = {}) => {
+ const store = useAgentStore.getState();
+ const chat = store.chats.find((c) => c.id === store.currentChatId);
+ const isInDisplayedMode = !!chat && chat.archived === showArchivedOnly;
+
+ if (isInDisplayedMode) return;
+ if (selectFirstDisplayedChat()) return;
+
+ if (showArchivedOnly) {
+ if (!options.fallbackToActiveWhenEmpty) return;
+ setShowArchivedOnly(false);
+ // After toggling, check again with active mode
+ const storeNow = useAgentStore.getState();
+ const chatNow = storeNow.chats.find(
+ (c) => c.id === storeNow.currentChatId
+ );
+ const isInActiveMode = !!chatNow && !chatNow.archived;
+ if (isInActiveMode) return;
+ // Try selecting first active chat
+ const activeChats = [...storeNow.chats]
+ .filter((c) => !c.archived)
+ .sort((a, b) => b.updatedTs - a.updatedTs);
+ if (activeChats[0] && storeNow.canSelectChat(activeChats[0].id)) {
+ storeNow.setCurrentChat(activeChats[0].id);
+ return;
+ }
+ }
+
+ if (store.chats.some((c) => c.status === "running")) return;
+ store.createChat({ page: getCurrentPageSnapshot() });
+ },
+ [showArchivedOnly, selectFirstDisplayedChat, getCurrentPageSnapshot]
+ );
+
+ // --- Rename ---
+
+ const beginRenameCurrentChat = useCallback(() => {
+ if (!currentChat) return;
+ setRenamingTitle(getEditableChatTitle(currentChat));
+ setIsRenamingCurrentChat(true);
+ }, [currentChat, getEditableChatTitle]);
+
+ const cancelRenameCurrentChat = useCallback(() => {
+ setIsRenamingCurrentChat(false);
+ setRenamingTitle("");
+ }, []);
+
+ const commitRenameCurrentChat = useCallback(() => {
+ const chat = useAgentStore
+ .getState()
+ .chats.find((c) => c.id === useAgentStore.getState().currentChatId);
+ const title = renamingTitle.trim();
+ if (!chat || !isRenamingCurrentChat) return;
+ if (!title) {
+ cancelRenameCurrentChat();
+ return;
+ }
+ useAgentStore.getState().renameChat(chat.id, title);
+ cancelRenameCurrentChat();
+ }, [renamingTitle, isRenamingCurrentChat, cancelRenameCurrentChat]);
+
+ const onRenameKeydown = useCallback(
+ (event: React.KeyboardEvent<HTMLInputElement>) => {
+ if (event.nativeEvent.isComposing) return;
+ if (event.key === "Escape") {
+ event.preventDefault();
+ cancelRenameCurrentChat();
+ return;
+ }
+ if (event.key === "Enter") {
+ event.preventDefault();
+ commitRenameCurrentChat();
+ }
+ },
+ [cancelRenameCurrentChat, commitRenameCurrentChat]
+ );
+
+ // Cancel rename when currentChatId changes
+ useEffect(() => {
+ if (isRenamingCurrentChat) {
+ cancelRenameCurrentChat();
+ }
+ // Only react to currentChatId changes, not the rename state itself
+ }, [currentChatId]);
+
+ // Focus rename input when it appears
+ useEffect(() => {
+ if (isRenamingCurrentChat && renameInputRef.current) {
+ renameInputRef.current.focus();
+ renameInputRef.current.select();
+ }
+ }, [isRenamingCurrentChat]);
+
+ // --- Chat actions ---
+
+ const createChat = useCallback(() => {
+ if (isChatCreationDisabled) return;
+ useAgentStore.getState().createChat({ page: getCurrentPageSnapshot() });
+ }, [isChatCreationDisabled, getCurrentPageSnapshot]);
+
+ const handleChatRowClick = useCallback(
+ (chatId: string) => {
+ if (chatId === useAgentStore.getState().currentChatId) {
+ if (!isRenamingCurrentChat) {
+ beginRenameCurrentChat();
+ }
+ return;
+ }
+ if (isRenamingCurrentChat) {
+ cancelRenameCurrentChat();
+ }
+ useAgentStore.getState().setCurrentChat(chatId);
+ },
+ [isRenamingCurrentChat, beginRenameCurrentChat, cancelRenameCurrentChat]
+ );
+
+ const toggleArchiveCurrentChat = useCallback(() => {
+ const chat = useAgentStore
+ .getState()
+ .chats.find((c) => c.id === useAgentStore.getState().currentChatId);
+ if (!chat) return;
+ if (chat.archived) {
+ useAgentStore.getState().unarchiveChat(chat.id);
+ ensureCurrentChatMatchesDisplayedMode({
+ fallbackToActiveWhenEmpty: true,
+ });
+ return;
+ }
+ useAgentStore.getState().archiveChat(chat.id);
+ ensureCurrentChatMatchesDisplayedMode();
+ }, [ensureCurrentChatMatchesDisplayedMode]);
+
+ const deleteCurrentChat = useCallback(() => {
+ const store = useAgentStore.getState();
+ const chat = store.chats.find((c) => c.id === store.currentChatId);
+ if (!chat) return;
+ store.deleteChat(chat.id);
+ ensureCurrentChatMatchesDisplayedMode({
+ fallbackToActiveWhenEmpty: true,
+ });
+ }, [ensureCurrentChatMatchesDisplayedMode]);
+
+ const toggleChatListMode = useCallback(() => {
+ setShowArchivedOnly((prev) => !prev);
+ }, []);
+
+ // After showArchivedOnly changes, ensure current chat matches
+ useEffect(() => {
+ ensureCurrentChatMatchesDisplayedMode();
+ }, [showArchivedOnly]);
+
+ // --- Drag handlers ---
+ // All drag/resize handlers manipulate DOM directly during movement
+ // and only commit to the Zustand store on mouseup, avoiding per-frame
+ // immer drafts + React re-renders.
+
+ const sidebarRef = useRef<HTMLElement>(null);
+ const dragCleanupRef = useRef<(() => void) | null>(null);
+ const resizeCleanupRef = useRef<(() => void) | null>(null);
+ const sidebarResizeCleanupRef = useRef<(() => void) | null>(null);
+
+ // Cleanup drag/resize listeners on unmount
+ useEffect(() => {
+ return () => {
+ dragCleanupRef.current?.();
+ resizeCleanupRef.current?.();
+ sidebarResizeCleanupRef.current?.();
+ };
+ }, []);
+
+ const startDrag = useCallback(
+ (event: React.MouseEvent) => {
+ if (
+ event.target instanceof HTMLElement &&
+ event.target.closest(
+ "[data-agent-window-action], [data-agent-window-resize]"
+ )
+ ) {
+ return;
+ }
+ syncStoreToDisplayState();
+ isDraggingRef.current = true;
+ const store = useAgentStore.getState();
+ dragOffsetRef.current = {
+ x: event.clientX - store.position.x,
+ y: event.clientY - store.position.y,
+ };
+
+ const onDrag = (e: MouseEvent) => {
+ if (!isDraggingRef.current || !windowRef.current) return;
+ const el = windowRef.current;
+ const vw = window.innerWidth;
+ const vh = window.innerHeight;
+ const w = el.offsetWidth;
+ const h = el.offsetHeight;
+ const maxX = Math.max(WINDOW_MARGIN, vw - w - WINDOW_MARGIN);
+ const maxY = Math.max(WINDOW_MARGIN, vh - h - WINDOW_MARGIN);
+ const x = Math.min(
+ maxX,
+ Math.max(WINDOW_MARGIN, e.clientX - dragOffsetRef.current.x)
+ );
+ const y = Math.min(
+ maxY,
+ Math.max(WINDOW_MARGIN, e.clientY - dragOffsetRef.current.y)
+ );
+ el.style.left = `${x}px`;
+ el.style.top = `${y}px`;
+ useAgentStore.getState().setPosition(x, y);
+ };
+
+ const stopDrag = () => {
+ isDraggingRef.current = false;
+ document.removeEventListener("mousemove", onDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ dragCleanupRef.current = null;
+ useAgentStore.getState().saveWindowState();
+ };
+
+ document.addEventListener("mousemove", onDrag);
+ document.addEventListener("mouseup", stopDrag);
+ dragCleanupRef.current = stopDrag;
+ },
+ [syncStoreToDisplayState]
+ );
+
+ // --- Resize handlers ---
+
+ const startResize = useCallback(
+ (event: React.MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ syncStoreToDisplayState();
+ isResizingRef.current = true;
+ const store = useAgentStore.getState();
+ resizeStartRef.current = {
+ x: event.clientX,
+ y: event.clientY,
+ w: store.size.width,
+ h: store.size.height,
+ };
+
+ const onResize = (e: MouseEvent) => {
+ if (!isResizingRef.current || !windowRef.current) return;
+ const el = windowRef.current;
+ const vw = window.innerWidth;
+ const vh = window.innerHeight;
+ const dx = e.clientX - resizeStartRef.current.x;
+ const dy = e.clientY - resizeStartRef.current.y;
+ const clW = Math.min(
+ Math.max(MIN_WIDTH, vw - WINDOW_MARGIN * 2),
+ Math.max(MIN_WIDTH, Math.round(resizeStartRef.current.w + dx))
+ );
+ const clH = Math.min(
+ Math.max(MIN_HEIGHT, vh - WINDOW_MARGIN * 2),
+ Math.max(MIN_HEIGHT, Math.round(resizeStartRef.current.h + dy))
+ );
+ el.style.width = `${clW}px`;
+ el.style.height = `${clH}px`;
+ // Clamp position
+ const maxX = Math.max(WINDOW_MARGIN, vw - clW - WINDOW_MARGIN);
+ const maxY = Math.max(WINDOW_MARGIN, vh - clH - WINDOW_MARGIN);
+ const curX = parseInt(el.style.left) || 0;
+ const curY = parseInt(el.style.top) || 0;
+ const clX = Math.min(maxX, Math.max(WINDOW_MARGIN, curX));
+ const clY = Math.min(maxY, Math.max(WINDOW_MARGIN, curY));
+ el.style.left = `${clX}px`;
+ el.style.top = `${clY}px`;
+ const store = useAgentStore.getState();
+ store.setSize(clW, clH);
+ store.setPosition(clX, clY);
+ };
+
+ const stopResize = () => {
+ isResizingRef.current = false;
+ document.removeEventListener("mousemove", onResize);
+ document.removeEventListener("mouseup", stopResize);
+ resizeCleanupRef.current = null;
+ useAgentStore.getState().saveWindowState();
+ };
+
+ document.addEventListener("mousemove", onResize);
+ document.addEventListener("mouseup", stopResize);
+ resizeCleanupRef.current = stopResize;
+ },
+ [syncStoreToDisplayState]
+ );
+
+ // --- Sidebar resize ---
+
+ const startSidebarResize = useCallback(
+ (event: React.MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ syncStoreToDisplayState();
+ isSidebarResizingRef.current = true;
+ sidebarResizeStartRef.current = {
+ x: event.clientX,
+ width: clampedSidebarWidth,
+ };
+
+ const onSidebarResize = (e: MouseEvent) => {
+ if (!isSidebarResizingRef.current || !sidebarRef.current) return;
+ const dx = e.clientX - sidebarResizeStartRef.current.x;
+ const newWidth = sidebarResizeStartRef.current.width + dx;
+ const windowWidth = windowRef.current?.offsetWidth ?? 0;
+ const maxSW = Math.max(
+ MIN_SIDEBAR_WIDTH,
+ windowWidth - MIN_MAIN_PANEL_WIDTH
+ );
+ const minSW = Math.min(MIN_SIDEBAR_WIDTH, maxSW);
+ const clamped = Math.min(maxSW, Math.max(minSW, Math.round(newWidth)));
+ sidebarRef.current.style.width = `${clamped}px`;
+ useAgentStore.getState().setSidebarWidth(clamped);
+ };
+
+ const stopSidebarResize = () => {
+ isSidebarResizingRef.current = false;
+ document.removeEventListener("mousemove", onSidebarResize);
+ document.removeEventListener("mouseup", stopSidebarResize);
+ sidebarResizeCleanupRef.current = null;
+ useAgentStore.getState().saveWindowState();
+ };
+
+ document.addEventListener("mousemove", onSidebarResize);
+ document.addEventListener("mouseup", stopSidebarResize);
+ sidebarResizeCleanupRef.current = stopSidebarResize;
+ },
+ [syncStoreToDisplayState, clampedSidebarWidth]
+ );
+
+ // --- Viewport resize ---
+
+ useEffect(() => {
+ const handler = () => {
+ isViewportResizingRef.current = true;
+ setViewportSize({
+ width: window.innerWidth,
+ height: window.innerHeight,
+ });
+ cancelAnimationFrame(viewportResizeFrameRef.current);
+ viewportResizeFrameRef.current = window.requestAnimationFrame(() => {
+ isViewportResizingRef.current = false;
+ });
+ };
+ window.addEventListener("resize", handler);
+ return () => {
+ window.removeEventListener("resize", handler);
+ cancelAnimationFrame(viewportResizeFrameRef.current);
+ };
+ }, []);
+
+ // --- ResizeObserver ---
+
+ useEffect(() => {
+ const el = windowRef.current;
+ if (!el) {
+ resizeObserverRef.current?.disconnect();
+ return;
+ }
+
+ const observer = new ResizeObserver(([entry]) => {
+ if (!entry || isResizingRef.current || isViewportResizingRef.current) {
+ return;
+ }
+ const target = entry.target as HTMLElement;
+ const width = target.offsetWidth;
+ const height = target.offsetHeight;
+ const store = useAgentStore.getState();
+ if (width === store.size.width && height === store.size.height) return;
+
+ useAgentStore.setState((state) => {
+ const clW = Math.min(
+ Math.max(MIN_WIDTH, viewportSize.width - WINDOW_MARGIN * 2),
+ Math.max(MIN_WIDTH, Math.round(width))
+ );
+ const clH = Math.min(
+ Math.max(MIN_HEIGHT, viewportSize.height - WINDOW_MARGIN * 2),
+ Math.max(MIN_HEIGHT, Math.round(height))
+ );
+ state.size.width = clW;
+ state.size.height = clH;
+ const maxX = Math.max(
+ WINDOW_MARGIN,
+ viewportSize.width - clW - WINDOW_MARGIN
+ );
+ const maxY = Math.max(
+ WINDOW_MARGIN,
+ viewportSize.height - clH - WINDOW_MARGIN
+ );
+ state.position.x = Math.min(
+ maxX,
+ Math.max(WINDOW_MARGIN, Math.round(state.position.x))
+ );
+ state.position.y = Math.min(
+ maxY,
+ Math.max(WINDOW_MARGIN, Math.round(state.position.y))
+ );
+ });
+ useAgentStore.getState().saveWindowState();
+ });
+
+ observer.observe(el);
+ resizeObserverRef.current = observer;
+ return () => observer.disconnect();
+ }, [visible, minimized, viewportSize.width, viewportSize.height]);
+
+ // --- Sync sidebar width when window width changes ---
+
+ useEffect(() => {
+ const store = useAgentStore.getState();
+ const windowWidth = displayWindowState.size.width;
+ const maxSW = Math.max(
+ MIN_SIDEBAR_WIDTH,
+ windowWidth - MIN_MAIN_PANEL_WIDTH
+ );
+ const minSW = Math.min(MIN_SIDEBAR_WIDTH, maxSW);
+ const clamped = Math.min(
+ maxSW,
+ Math.max(minSW, Math.round(store.sidebarWidth))
+ );
+ if (clamped !== store.sidebarWidth) {
+ useAgentStore.setState((state) => {
+ state.sidebarWidth = clamped;
+ });
+ store.saveWindowState();
+ }
+ }, [displayWindowState.size.width]);
+
+ // --- Mount: load window state ---
+
+ useEffect(() => {
+ useAgentStore.getState().loadWindowState();
+ }, []);
+
+ // --- Render ---
+
+ if (!visible) return null;
+
+ if (minimized) {
+ return createPortal(
+ <div
+ data-agent-window
+ className="fixed bottom-4 right-4 z-[1999] flex h-10 w-10 cursor-pointer items-center justify-center rounded-full bg-blue-500 text-white shadow-lg hover:bg-blue-600"
+ onClick={() => useAgentStore.getState().restore()}
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ className="h-5 w-5"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ >
+ <path
+ fillRule="evenodd"
+ d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7zM7 9H5v2h2V9zm8 0h-2v2h2V9zm-4 0H9v2h2V9z"
+ clipRule="evenodd"
+ />
+ </svg>
+ </div>,
+ document.body
+ );
+ }
+
+ return createPortal(
+ <div
+ ref={windowRef}
+ data-agent-window
+ className="fixed z-[1999] flex flex-col overflow-hidden rounded-lg border border-gray-200 bg-white shadow-xl"
+ style={windowStyle}
+ >
+ {/* Header */}
+ <div
+ className="flex cursor-move select-none items-center justify-between border-b bg-gray-50 px-3 py-2"
+ onMouseDown={startDrag}
+ >
+ <div className="flex min-w-0 items-center gap-x-2">
+ <span className="truncate text-sm font-medium">
+ {t("agent.assistant-title")}
+ </span>
+ <span
+ className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${currentChatStatusClass}`}
+ >
+ {currentChatStatusLabel}
+ </span>
+ <span className="truncate text-xs text-gray-500">
+ {currentChatTokenUsageLabel}
+ </span>
+ </div>
+ <div className="flex items-center gap-x-1">
+ <button
+ data-agent-window-action
+ className="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"
+ title={t("agent.minimize")}
+ onClick={(e) => {
+ e.stopPropagation();
+ useAgentStore.getState().minimize();
+ }}
+ >
+ &#8722;
+ </button>
+ <button
+ data-agent-window-action
+ className="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"
+ title={t("agent.close")}
+ onClick={(e) => {
+ e.stopPropagation();
+ useAgentStore.getState().toggle();
+ }}
+ >
+ &#10005;
+ </button>
+ </div>
+ </div>
+
+ {/* Body */}
+ <div className="flex min-h-0 flex-1 overflow-hidden bg-white">
+ {/* Sidebar */}
+ <aside
+ ref={sidebarRef}
+ className="flex shrink-0 flex-col border-r border-gray-200 bg-gray-50"
+ style={sidebarStyle}
+ >
+ {/* Sidebar header */}
+ <div className="border-b border-gray-200 px-3 py-3">
+ <div className="flex items-center justify-between gap-x-2">
+ <div>
+ <h2 className="text-xs font-semibold uppercase tracking-wide text-gray-500">
+ {t("agent.chat-list-label")}
+ </h2>
+ </div>
+ <button
+ className="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-100 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:text-gray-400"
+ disabled={isChatCreationDisabled}
+ onClick={createChat}
+ >
+ {t("agent.new-chat")}
+ </button>
+ </div>
+ </div>
+
+ {/* Chat list */}
+ <div className="min-h-0 flex-1 overflow-y-auto px-2 py-2">
+ <div className="flex flex-col gap-y-1" data-agent-chat-list>
+ {displayedChats.map((chat) => (
+ <div
+ key={chat.id}
+ className={`w-full rounded-md px-3 py-2 text-left text-sm transition-colors ${
+ chat.id === currentChatId
+ ? "bg-blue-50 text-blue-700"
+ : "text-gray-700 hover:bg-white"
+ }`}
+ data-agent-chat-row={chat.id}
+ >
+ {chat.id === currentChatId && isRenamingCurrentChat ? (
+ <Input
+ ref={renameInputRef}
+ value={renamingTitle}
+ onChange={(e) => setRenamingTitle(e.target.value)}
+ className="h-7 text-sm"
+ placeholder={t("agent.rename-chat-placeholder")}
+ data-agent-inline-rename-input
+ onBlur={commitRenameCurrentChat}
+ onKeyDown={onRenameKeydown}
+ />
+ ) : (
+ <button
+ type="button"
+ className="w-full text-left disabled:cursor-not-allowed disabled:opacity-60"
+ disabled={
+ !useAgentStore.getState().canSelectChat(chat.id)
+ }
+ aria-current={
+ chat.id === currentChatId ? "true" : undefined
+ }
+ onClick={() => handleChatRowClick(chat.id)}
+ >
+ <div
+ className="truncate font-medium"
+ data-agent-chat-title
+ >
+ {getChatLabel(chat)}
+ </div>
+ <span
+ className={`mt-1 block truncate text-xs ${
+ chat.id === currentChatId
+ ? "text-blue-600/80"
+ : "text-gray-500"
+ }`}
+ data-agent-chat-updated-ts
+ >
+ <HumanizeTs ts={Math.floor(chat.updatedTs / 1000)} />
+ </span>
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Sidebar footer */}
+ <div className="border-t border-gray-200 px-3 py-3">
+ <div className="flex flex-col gap-y-2">
+ <div
+ className="flex flex-wrap gap-x-2 gap-y-2"
+ data-agent-chat-sidebar-actions
+ >
+ {isCurrentChatInDisplayedMode && (
+ <>
+ {showArchivedOnly ? (
+ <button
+ className="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-white"
+ data-agent-unarchive-chat
+ onClick={toggleArchiveCurrentChat}
+ >
+ {t("agent.unarchive-chat")}
+ </button>
+ ) : (
+ <ConfirmDialog
+ message={t("agent.archive-chat-confirmation")}
+ onConfirm={toggleArchiveCurrentChat}
+ triggerClassName="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-white"
+ triggerLabel={t("agent.archive-chat")}
+ triggerDataAttr="data-agent-archive-chat"
+ />
+ )}
+ {showArchivedOnly && (
+ <ConfirmDialog
+ message={t("agent.delete-chat-confirmation")}
+ onConfirm={deleteCurrentChat}
+ triggerClassName="rounded-md border px-2 py-1.5 text-xs font-medium text-red-600 hover:bg-red-50"
+ triggerLabel={t("agent.delete-chat")}
+ triggerDataAttr="data-agent-delete-chat"
+ />
+ )}
+ </>
+ )}
+ <button
+ className="ml-auto inline-flex items-center rounded-md border p-1.5 text-xs font-medium text-gray-600 hover:bg-white"
+ aria-label={
+ showArchivedOnly
+ ? t("agent.archived-only-chats")
+ : t("agent.active-only-chats")
+ }
+ title={
+ showArchivedOnly
+ ? t("agent.archived-only-chats")
+ : t("agent.active-only-chats")
+ }
+ data-agent-chat-list-mode
+ onClick={toggleChatListMode}
+ >
+ {showArchivedOnly ? (
+ <Archive className="h-3.5 w-3.5" aria-hidden="true" />
+ ) : (
+ <Inbox className="h-3.5 w-3.5" aria-hidden="true" />
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ </aside>
+
+ {/* Sidebar resize handle */}
+ <button
+ type="button"
+ data-agent-window-action
+ data-agent-sidebar-resize
+ className="group relative w-1 shrink-0 cursor-col-resize bg-gray-100 transition-colors hover:bg-blue-100"
+ onMouseDown={startSidebarResize}
+ >
+ <span className="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-transparent transition-colors group-hover:bg-blue-400" />
+ </button>
+
+ {/* Main panel */}
+ <div className="flex min-w-0 flex-1 flex-col">
+ <AgentChat className="min-h-0 flex-1" />
+ <AgentInput />
+ </div>
+ </div>
+
+ {/* Resize handle (SE corner) */}
+ <button
+ type="button"
+ data-agent-window-action
+ data-agent-window-resize
+ className="absolute bottom-0 right-0 flex h-5 w-5 cursor-se-resize items-end justify-end pb-0.5 pr-0.5 text-gray-300 hover:text-gray-400"
+ title={t("agent.resize")}
+ onMouseDown={startResize}
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ className="h-3 w-3"
+ viewBox="0 0 12 12"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ >
+ <path d="M3.5 8.5h.01M6 6h.01M8.5 3.5h.01" />
+ <path d="M3.5 11 11 3.5" />
+ </svg>
+ </button>
+ </div>,
+ document.body
+ );
+}
+
+// --- Confirmation Dialog ---
+
+function ConfirmDialog({
+ message,
+ onConfirm,
+ triggerClassName,
+ triggerLabel,
+ triggerDataAttr,
+}: {
+ message: string;
+ onConfirm: () => void;
+ triggerClassName: string;
+ triggerLabel: string;
+ triggerDataAttr?: string;
+}) {
+ const { t } = useTranslation();
+ const triggerProps: Record<string, unknown> = {};
+ if (triggerDataAttr) triggerProps[triggerDataAttr] = true;
+
+ return (
+ <Dialog>
+ <DialogTrigger className={triggerClassName} {...triggerProps}>
+ {triggerLabel}
+ </DialogTrigger>
+ <DialogContent className="max-w-sm p-6">
+ <DialogTitle className="sr-only">{t("common.confirm")}</DialogTitle>
+ <DialogDescription className="mb-4">{message}</DialogDescription>
+ <div className="flex justify-end gap-x-2">
+ <DialogClose
+ render={
+ <button className="rounded-md border px-3 py-1.5 text-sm font-medium text-gray-600 hover:bg-gray-100">
+ {t("common.cancel")}
+ </button>
+ }
+ />
+ <DialogClose
+ render={
+ <button
+ className="rounded-md bg-blue-500 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-600"
+ onClick={onConfirm}
+ >
+ {t("common.confirm")}
+ </button>
+ }
+ />
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/react/plugins/agent/components/ToolCallCard.tsx b/frontend/src/react/plugins/agent/components/ToolCallCard.tsx
new file mode 100644
index 0000000000..29d54870e4
--- /dev/null
+++ b/frontend/src/react/plugins/agent/components/ToolCallCard.tsx
@@ -0,0 +1,312 @@
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type {
+ AgentAskUserOption,
+ AgentAskUserResponse,
+ ToolCall,
+} from "../logic/types";
+
+interface Props {
+ toolCall: ToolCall;
+ result?: string;
+}
+
+const parseJson = (value?: string): unknown => {
+ if (!value) return undefined;
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+};
+
+const formatJson = (value?: string): string => {
+ if (!value) return "";
+ try {
+ return JSON.stringify(JSON.parse(value), null, 2);
+ } catch {
+ return value;
+ }
+};
+
+const parseAskUserOption = (value: unknown): AgentAskUserOption | null => {
+ if (!value || typeof value !== "object") return null;
+
+ const option = value as Record<string, unknown>;
+ const label =
+ typeof option.label === "string"
+ ? option.label.trim()
+ : typeof option.value === "string"
+ ? option.value.trim()
+ : "";
+ const optionValue =
+ typeof option.value === "string" ? option.value.trim() : "";
+
+ if (!label || !optionValue) return null;
+
+ return {
+ label,
+ value: optionValue,
+ description:
+ typeof option.description === "string" && option.description.trim()
+ ? option.description.trim()
+ : undefined,
+ };
+};
+
+export function ToolCallCard({ toolCall, result }: Props) {
+ const { t } = useTranslation();
+ const [expanded, setExpanded] = useState(false);
+
+ const resultText = result ?? "";
+ const parsedArguments = useMemo(
+ () => parseJson(toolCall.arguments),
+ [toolCall.arguments]
+ );
+ const parsedResult = useMemo(() => parseJson(resultText), [resultText]);
+ const isAskUser = toolCall.name === "ask_user";
+ const isDone = toolCall.name === "done";
+
+ const askPrompt = useMemo(() => {
+ if (
+ typeof parsedArguments === "object" &&
+ parsedArguments &&
+ "prompt" in parsedArguments &&
+ typeof (parsedArguments as Record<string, unknown>).prompt === "string"
+ ) {
+ return (parsedArguments as Record<string, unknown>).prompt as string;
+ }
+ return "";
+ }, [parsedArguments]);
+
+ const askKind = useMemo(() => {
+ if (
+ typeof parsedArguments === "object" &&
+ parsedArguments &&
+ "kind" in parsedArguments
+ ) {
+ const kind = (parsedArguments as Record<string, unknown>).kind;
+ if (kind === "confirm") return "confirm" as const;
+ if (kind === "choose") return "choose" as const;
+ }
+ return "input" as const;
+ }, [parsedArguments]);
+
+ const askDefaultValue = useMemo(() => {
+ if (
+ typeof parsedArguments === "object" &&
+ parsedArguments &&
+ "defaultValue" in parsedArguments &&
+ typeof (parsedArguments as Record<string, unknown>).defaultValue ===
+ "string"
+ ) {
+ return (parsedArguments as Record<string, unknown>)
+ .defaultValue as string;
+ }
+ return "";
+ }, [parsedArguments]);
+
+ const askOptions = useMemo<AgentAskUserOption[]>(() => {
+ if (
+ typeof parsedArguments !== "object" ||
+ !parsedArguments ||
+ !("options" in parsedArguments) ||
+ !Array.isArray((parsedArguments as Record<string, unknown>).options)
+ ) {
+ return [];
+ }
+ return ((parsedArguments as Record<string, unknown>).options as unknown[])
+ .map((option) => parseAskUserOption(option))
+ .filter((option): option is AgentAskUserOption => !!option);
+ }, [parsedArguments]);
+
+ const askResponse = useMemo<AgentAskUserResponse | null>(() => {
+ if (
+ typeof parsedResult !== "object" ||
+ !parsedResult ||
+ !("kind" in parsedResult) ||
+ typeof (parsedResult as Record<string, unknown>).kind !== "string" ||
+ !("answer" in parsedResult) ||
+ typeof (parsedResult as Record<string, unknown>).answer !== "string"
+ ) {
+ return null;
+ }
+
+ const response = parsedResult as Record<string, unknown>;
+ if (response.kind === "confirm") {
+ if (typeof response.confirmed !== "boolean") return null;
+ return response as unknown as AgentAskUserResponse;
+ }
+ if (response.kind === "choose") {
+ if (typeof response.value !== "string") return null;
+ return response as unknown as AgentAskUserResponse;
+ }
+ if (response.kind === "input") {
+ return response as unknown as AgentAskUserResponse;
+ }
+ return null;
+ }, [parsedResult]);
+
+ const doneText = useMemo(() => {
+ if (
+ typeof parsedArguments === "object" &&
+ parsedArguments &&
+ "text" in parsedArguments &&
+ typeof (parsedArguments as Record<string, unknown>).text === "string"
+ ) {
+ return (parsedArguments as Record<string, unknown>).text as string;
+ }
+ return "";
+ }, [parsedArguments]);
+
+ const doneSuccess = useMemo(() => {
+ if (
+ typeof parsedArguments === "object" &&
+ parsedArguments &&
+ "success" in parsedArguments
+ ) {
+ return (parsedArguments as Record<string, unknown>).success !== false;
+ }
+ return true;
+ }, [parsedArguments]);
+
+ const renderStatus = () => {
+ if (isAskUser) {
+ return resultText ? (
+ <span className="text-green-500">
+ {t("agent.tool-response-submitted")}
+ </span>
+ ) : (
+ <span className="text-amber-600">{t("agent.tool-ask-user")}</span>
+ );
+ }
+ if (isDone) {
+ return (
+ <span className={doneSuccess ? "text-green-500" : "text-red-500"}>
+ {doneSuccess ? t("agent.tool-completed") : t("agent.tool-failed")}
+ </span>
+ );
+ }
+ return resultText ? (
+ <span className="text-green-500">&#10003;</span>
+ ) : (
+ <span className="animate-pulse text-gray-400">&#9679;</span>
+ );
+ };
+
+ const renderExpandedContent = () => {
+ if (isAskUser) {
+ return (
+ <>
+ <div className="text-gray-500">
+ {askKind === "confirm"
+ ? t("agent.tool-ask-user-confirm")
+ : askKind === "choose"
+ ? t("agent.tool-ask-user-choose")
+ : t("agent.tool-ask-user-input")}
+ </div>
+ <div className="text-gray-500">{t("agent.tool-prompt")}</div>
+ <pre className="whitespace-pre-wrap break-all text-gray-700">
+ {askPrompt}
+ </pre>
+ {askDefaultValue && (
+ <>
+ <div className="text-gray-500">
+ {t("agent.tool-default-value")}
+ </div>
+ <pre className="whitespace-pre-wrap break-all text-gray-700">
+ {askDefaultValue}
+ </pre>
+ </>
+ )}
+ {askKind === "choose" && askOptions.length > 0 && (
+ <>
+ <div className="text-gray-500">{t("agent.tool-options")}</div>
+ <div className="space-y-1">
+ {askOptions.map((option) => (
+ <div
+ key={option.value}
+ className="rounded border border-gray-200 bg-white px-2 py-1"
+ >
+ <div className="font-medium text-gray-700">
+ {option.label}
+ </div>
+ <div className="text-gray-500">{option.value}</div>
+ {option.description && (
+ <div className="text-gray-500">{option.description}</div>
+ )}
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ {askResponse && (
+ <>
+ <div className="text-gray-500">{t("agent.tool-answer")}</div>
+ <pre className="whitespace-pre-wrap break-all text-gray-700">
+ {askResponse.answer}
+ </pre>
+ {askResponse.kind === "choose" && (
+ <>
+ <div className="text-gray-500">{t("agent.tool-value")}</div>
+ <pre className="whitespace-pre-wrap break-all text-gray-700">
+ {askResponse.value}
+ </pre>
+ </>
+ )}
+ </>
+ )}
+ </>
+ );
+ }
+
+ if (isDone) {
+ return (
+ <>
+ <div className="text-gray-500">{t("agent.result")}</div>
+ <pre className="whitespace-pre-wrap break-all text-gray-700">
+ {doneText}
+ </pre>
+ </>
+ );
+ }
+
+ return (
+ <>
+ <div className="text-gray-500">{t("agent.args")}</div>
+ <pre className="whitespace-pre-wrap break-all text-gray-700">
+ {formatJson(toolCall.arguments)}
+ </pre>
+ {resultText && (
+ <>
+ <div className="text-gray-500">{t("agent.result")}</div>
+ <pre className="max-h-32 overflow-y-auto whitespace-pre-wrap break-all text-gray-700">
+ {formatJson(resultText)}
+ </pre>
+ </>
+ )}
+ </>
+ );
+ };
+
+ return (
+ <div className="rounded border bg-gray-50 text-xs">
+ <div
+ className="flex cursor-pointer items-center gap-x-2 px-2 py-1.5"
+ onClick={() => setExpanded(!expanded)}
+ >
+ <span className="font-mono text-gray-600">{toolCall.name}</span>
+ {renderStatus()}
+ <span className="ml-auto text-gray-400">
+ {expanded ? "\u25BE" : "\u25B8"}
+ </span>
+ </div>
+
+ {expanded && (
+ <div className="space-y-1 border-t px-2 py-1.5">
+ {renderExpandedContent()}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/agent/dom/actions.ts b/frontend/src/react/plugins/agent/dom/actions.ts
similarity index 100%
rename from frontend/src/plugins/agent/dom/actions.ts
rename to frontend/src/react/plugins/agent/dom/actions.ts
diff --git a/frontend/src/plugins/agent/dom/domTree.test.ts b/frontend/src/react/plugins/agent/dom/domTree.test.ts
similarity index 100%
rename from frontend/src/plugins/agent/dom/domTree.test.ts
rename to frontend/src/react/plugins/agent/dom/domTree.test.ts
diff --git a/frontend/src/plugins/agent/dom/domTree.ts b/frontend/src/react/plugins/agent/dom/domTree.ts
similarity index 100%
rename from frontend/src/plugins/agent/dom/domTree.ts
rename to frontend/src/react/plugins/agent/dom/domTree.ts
diff --git a/frontend/src/plugins/agent/dom/index.test.ts b/frontend/src/react/plugins/agent/dom/index.test.ts
similarity index 100%
rename from frontend/src/plugins/agent/dom/index.test.ts
rename to frontend/src/react/plugins/agent/dom/index.test.ts
diff --git a/frontend/src/plugins/agent/dom/index.ts b/frontend/src/react/plugins/agent/dom/index.ts
similarity index 100%
rename from frontend/src/plugins/agent/dom/index.ts
rename to frontend/src/react/plugins/agent/dom/index.ts
diff --git a/frontend/src/react/plugins/agent/index.tsx b/frontend/src/react/plugins/agent/index.tsx
new file mode 100644
index 0000000000..2a7477ed37
--- /dev/null
+++ b/frontend/src/react/plugins/agent/index.tsx
@@ -0,0 +1,2 @@
+export { AgentWindow } from "./components/AgentWindow";
+export { useAgentStore } from "./store/agent";
diff --git a/frontend/src/plugins/agent/logic/agentLoop.test.ts b/frontend/src/react/plugins/agent/logic/agentLoop.test.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/agentLoop.test.ts
rename to frontend/src/react/plugins/agent/logic/agentLoop.test.ts
diff --git a/frontend/src/plugins/agent/logic/agentLoop.ts b/frontend/src/react/plugins/agent/logic/agentLoop.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/agentLoop.ts
rename to frontend/src/react/plugins/agent/logic/agentLoop.ts
diff --git a/frontend/src/plugins/agent/logic/aiConfiguration.test.ts b/frontend/src/react/plugins/agent/logic/aiConfiguration.test.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/aiConfiguration.test.ts
rename to frontend/src/react/plugins/agent/logic/aiConfiguration.test.ts
diff --git a/frontend/src/plugins/agent/logic/aiConfiguration.ts b/frontend/src/react/plugins/agent/logic/aiConfiguration.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/aiConfiguration.ts
rename to frontend/src/react/plugins/agent/logic/aiConfiguration.ts
diff --git a/frontend/src/plugins/agent/logic/context.ts b/frontend/src/react/plugins/agent/logic/context.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/context.ts
rename to frontend/src/react/plugins/agent/logic/context.ts
diff --git a/frontend/src/plugins/agent/logic/outboundHistory.ts b/frontend/src/react/plugins/agent/logic/outboundHistory.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/outboundHistory.ts
rename to frontend/src/react/plugins/agent/logic/outboundHistory.ts
diff --git a/frontend/src/plugins/agent/logic/prompt.test.ts b/frontend/src/react/plugins/agent/logic/prompt.test.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/prompt.test.ts
rename to frontend/src/react/plugins/agent/logic/prompt.test.ts
diff --git a/frontend/src/plugins/agent/logic/prompt.ts b/frontend/src/react/plugins/agent/logic/prompt.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/prompt.ts
rename to frontend/src/react/plugins/agent/logic/prompt.ts
diff --git a/frontend/src/plugins/agent/logic/skills/databaseChange.ts b/frontend/src/react/plugins/agent/logic/skills/databaseChange.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/skills/databaseChange.ts
rename to frontend/src/react/plugins/agent/logic/skills/databaseChange.ts
diff --git a/frontend/src/plugins/agent/logic/skills/grantPermission.ts b/frontend/src/react/plugins/agent/logic/skills/grantPermission.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/skills/grantPermission.ts
rename to frontend/src/react/plugins/agent/logic/skills/grantPermission.ts
diff --git a/frontend/src/plugins/agent/logic/skills/index.ts b/frontend/src/react/plugins/agent/logic/skills/index.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/skills/index.ts
rename to frontend/src/react/plugins/agent/logic/skills/index.ts
diff --git a/frontend/src/plugins/agent/logic/skills/query.ts b/frontend/src/react/plugins/agent/logic/skills/query.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/skills/query.ts
rename to frontend/src/react/plugins/agent/logic/skills/query.ts
diff --git a/frontend/src/plugins/agent/logic/tools/callApi.test.ts b/frontend/src/react/plugins/agent/logic/tools/callApi.test.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/callApi.test.ts
rename to frontend/src/react/plugins/agent/logic/tools/callApi.test.ts
diff --git a/frontend/src/plugins/agent/logic/tools/callApi.ts b/frontend/src/react/plugins/agent/logic/tools/callApi.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/callApi.ts
rename to frontend/src/react/plugins/agent/logic/tools/callApi.ts
diff --git a/frontend/src/plugins/agent/logic/tools/domAction.test.ts b/frontend/src/react/plugins/agent/logic/tools/domAction.test.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/domAction.test.ts
rename to frontend/src/react/plugins/agent/logic/tools/domAction.test.ts
diff --git a/frontend/src/plugins/agent/logic/tools/domAction.ts b/frontend/src/react/plugins/agent/logic/tools/domAction.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/domAction.ts
rename to frontend/src/react/plugins/agent/logic/tools/domAction.ts
diff --git a/frontend/src/plugins/agent/logic/tools/gen/.gitignore b/frontend/src/react/plugins/agent/logic/tools/gen/.gitignore
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/gen/.gitignore
rename to frontend/src/react/plugins/agent/logic/tools/gen/.gitignore
diff --git a/frontend/src/plugins/agent/logic/tools/index.test.ts b/frontend/src/react/plugins/agent/logic/tools/index.test.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/index.test.ts
rename to frontend/src/react/plugins/agent/logic/tools/index.test.ts
diff --git a/frontend/src/plugins/agent/logic/tools/index.ts b/frontend/src/react/plugins/agent/logic/tools/index.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/index.ts
rename to frontend/src/react/plugins/agent/logic/tools/index.ts
diff --git a/frontend/src/plugins/agent/logic/tools/navigate.ts b/frontend/src/react/plugins/agent/logic/tools/navigate.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/navigate.ts
rename to frontend/src/react/plugins/agent/logic/tools/navigate.ts
diff --git a/frontend/src/plugins/agent/logic/tools/pageState.test.ts b/frontend/src/react/plugins/agent/logic/tools/pageState.test.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/pageState.test.ts
rename to frontend/src/react/plugins/agent/logic/tools/pageState.test.ts
diff --git a/frontend/src/plugins/agent/logic/tools/pageState.ts b/frontend/src/react/plugins/agent/logic/tools/pageState.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/pageState.ts
rename to frontend/src/react/plugins/agent/logic/tools/pageState.ts
diff --git a/frontend/src/plugins/agent/logic/tools/searchApi.ts b/frontend/src/react/plugins/agent/logic/tools/searchApi.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/tools/searchApi.ts
rename to frontend/src/react/plugins/agent/logic/tools/searchApi.ts
diff --git a/frontend/src/plugins/agent/logic/types.ts b/frontend/src/react/plugins/agent/logic/types.ts
similarity index 100%
rename from frontend/src/plugins/agent/logic/types.ts
rename to frontend/src/react/plugins/agent/logic/types.ts
diff --git a/frontend/src/plugins/agent/store/agent.test.ts b/frontend/src/react/plugins/agent/store/agent.test.ts
similarity index 56%
rename from frontend/src/plugins/agent/store/agent.test.ts
rename to frontend/src/react/plugins/agent/store/agent.test.ts
index 0c950f1bdb..493df944ff 100644
--- a/frontend/src/plugins/agent/store/agent.test.ts
+++ b/frontend/src/react/plugins/agent/store/agent.test.ts
@@ -1,7 +1,13 @@
-import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-import { nextTick } from "vue";
-import { AGENT_STATE_KEY, AGENT_WINDOW_KEY, useAgentStore } from "./agent";
+import type { StoreApi } from "zustand";
+import type { AgentState } from "./agent";
+import {
+ AGENT_STATE_KEY,
+ AGENT_WINDOW_KEY,
+ createAgentStore,
+ selectLoading,
+ selectOrderedChats,
+} from "./agent";
function createMockStorage(): Storage {
let store: Record<string, string> = {};
@@ -27,11 +33,6 @@ function createMockStorage(): Storage {
};
}
-const createStore = () => {
- setActivePinia(createPinia());
- return useAgentStore();
-};
-
let mockStorage: Storage;
beforeEach(() => {
@@ -43,14 +44,16 @@ afterEach(() => {
vi.unstubAllGlobals();
});
-describe("useAgentStore", () => {
+const s = (store: StoreApi<AgentState>) => store.getState();
+
+describe("useAgentStore (Zustand)", () => {
test("creates a default chat when no persisted state exists", () => {
- const store = createStore();
+ const store = createAgentStore();
- expect(store.chats).toHaveLength(1);
- expect(store.currentChatId).toBe(store.chats[0].id);
- expect(store.messages).toEqual([]);
- expect(store.chats[0].totalTokensUsed).toBe(0);
+ expect(s(store).chats).toHaveLength(1);
+ expect(s(store).currentChatId).toBe(s(store).chats[0].id);
+ expect(s(store).getMessages(s(store).currentChatId)).toEqual([]);
+ expect(s(store).chats[0].totalTokensUsed).toBe(0);
});
test("loads persisted window state", () => {
@@ -63,17 +66,17 @@ describe("useAgentStore", () => {
})
);
- const store = createStore();
- store.loadWindowState();
+ const store = createAgentStore();
+ s(store).loadWindowState();
- expect(store.sidebarWidth).toBe(280);
- expect(store.position).toEqual({ x: 120, y: 240 });
- expect(store.size).toEqual({ width: 480, height: 640 });
+ expect(s(store).sidebarWidth).toBe(280);
+ expect(s(store).position).toEqual({ x: 120, y: 240 });
+ expect(s(store).size).toEqual({ width: 480, height: 640 });
expect(localStorage.getItem(AGENT_WINDOW_KEY)).toContain('"width":480');
expect(localStorage.getItem(AGENT_WINDOW_KEY)).toContain(
'"sidebarWidth":280'
);
- expect(localStorage.getItem(AGENT_STATE_KEY)).toBeNull();
+ expect(localStorage.getItem(AGENT_STATE_KEY)).not.toBeNull();
});
test("normalizes stale running chats on load", () => {
@@ -106,22 +109,22 @@ describe("useAgentStore", () => {
})
);
- const store = createStore();
- const chat = store.currentChat;
+ const store = createAgentStore();
+ const chat = s(store).getChat(s(store).currentChatId);
expect(chat).not.toBeNull();
expect(chat?.status).toBe("idle");
expect(chat?.interrupted).toBe(true);
expect(chat?.runId).toBe("run-1");
- expect(store.loading).toBe(false);
+ expect(selectLoading(s(store))).toBe(false);
});
test("clears interruption markers when a new run starts", () => {
- const store = createStore();
- const chatId = store.currentChatId!;
+ const store = createAgentStore();
+ const chatId = s(store).currentChatId!;
- store.interruptChatRun(chatId);
- store.startChatRun(
+ s(store).interruptChatRun(chatId);
+ s(store).startChatRun(
chatId,
{
path: "/projects/demo",
@@ -132,90 +135,86 @@ describe("useAgentStore", () => {
}
);
- expect(store.getChat(chatId)?.status).toBe("running");
- expect(store.getChat(chatId)?.interrupted).toBe(false);
- expect(store.getChat(chatId)?.runId).toBe("run-2");
+ expect(s(store).getChat(chatId)?.status).toBe("running");
+ expect(s(store).getChat(chatId)?.interrupted).toBe(false);
+ expect(s(store).getChat(chatId)?.runId).toBe("run-2");
});
- test("persists the selected chat across store reloads", async () => {
- const store = createStore();
- const firstChatId = store.currentChatId!;
+ test("persists the selected chat across store reloads", () => {
+ const store = createAgentStore();
+ const firstChatId = s(store).currentChatId!;
- store.addMessage({
+ s(store).addMessage({
chatId: firstChatId,
role: "user",
content: "Initial prompt",
});
- const secondChat = store.createChat({
+ const secondChat = s(store).createChat({
title: "Second",
page: {
path: "/projects/original",
title: "Original Page",
},
});
- store.setCurrentChat(secondChat.id);
+ s(store).setCurrentChat(secondChat.id);
- await nextTick();
-
- const rehydratedStore = createStore();
- expect(rehydratedStore.currentChatId).toBe(secondChat.id);
- expect(rehydratedStore.getMessages(firstChatId)).toHaveLength(1);
- expect(rehydratedStore.getChat(secondChat.id)?.page).toEqual({
+ const rehydratedStore = createAgentStore();
+ expect(s(rehydratedStore).currentChatId).toBe(secondChat.id);
+ expect(s(rehydratedStore).getMessages(firstChatId)).toHaveLength(1);
+ expect(s(rehydratedStore).getChat(secondChat.id)?.page).toEqual({
path: "/projects/original",
title: "Original Page",
});
});
- test("increments and persists chat token totals", async () => {
- const store = createStore();
- const chatId = store.currentChatId!;
-
- store.incrementChatTotalTokens(chatId, 120);
- store.incrementChatTotalTokens(chatId, 30);
+ test("increments and persists chat token totals", () => {
+ const store = createAgentStore();
+ const chatId = s(store).currentChatId!;
- expect(store.getChat(chatId)?.totalTokensUsed).toBe(150);
+ s(store).incrementChatTotalTokens(chatId, 120);
+ s(store).incrementChatTotalTokens(chatId, 30);
- await nextTick();
+ expect(s(store).getChat(chatId)?.totalTokensUsed).toBe(150);
- const rehydratedStore = createStore();
- expect(rehydratedStore.getChat(chatId)?.totalTokensUsed).toBe(150);
+ const rehydratedStore = createAgentStore();
+ expect(s(rehydratedStore).getChat(chatId)?.totalTokensUsed).toBe(150);
});
test("updates the chat page to the latest current page when starting a run", () => {
- const store = createStore();
- const chatId = store.currentChatId!;
+ const store = createAgentStore();
+ const chatId = s(store).currentChatId!;
- store.updateChatPage(chatId, {
+ s(store).updateChatPage(chatId, {
path: "/projects/original",
title: "Original Page",
});
- store.ensureCurrentChat({
+ s(store).ensureCurrentChat({
path: "/projects/other",
title: "Other Page",
});
- store.startChatRun(chatId, {
+ s(store).startChatRun(chatId, {
path: "/projects/other",
title: "Other Page",
});
- expect(store.getChat(chatId)?.page).toEqual({
+ expect(s(store).getChat(chatId)?.page).toEqual({
path: "/projects/other",
title: "Other Page",
});
});
test("uses the first user message as the generated chat title", () => {
- const store = createStore();
- const chatId = store.currentChatId!;
+ const store = createAgentStore();
+ const chatId = s(store).currentChatId!;
- store.addMessage({
+ s(store).addMessage({
chatId,
role: "user",
content: "Investigate unexpected production migration failures now",
});
- expect(store.getChat(chatId)?.title).toBe(
+ expect(s(store).getChat(chatId)?.title).toBe(
"Investigate unexpected production migration f..."
);
});
@@ -224,23 +223,23 @@ describe("useAgentStore", () => {
const dateNow = vi.spyOn(Date, "now");
dateNow.mockReturnValue(1000);
- const store = createStore();
- const firstChatId = store.currentChatId!;
+ const store = createAgentStore();
+ const firstChatId = s(store).currentChatId!;
dateNow.mockReturnValue(2000);
- store.addMessage({
+ s(store).addMessage({
chatId: firstChatId,
role: "user",
content: "Summarize the production incident timeline",
});
dateNow.mockReturnValue(2000);
- const secondChat = store.createChat({
+ const secondChat = s(store).createChat({
title: "Renamed thread",
select: false,
});
- expect(store.orderedChats.map((chat) => chat.id)).toEqual([
+ expect(selectOrderedChats(s(store)).map((chat) => chat.id)).toEqual([
secondChat.id,
firstChatId,
]);
@@ -249,45 +248,45 @@ describe("useAgentStore", () => {
});
test("does not switch chats while another chat is running", () => {
- const store = createStore();
- const firstChatId = store.currentChatId!;
- const secondChat = store.createChat({
+ const store = createAgentStore();
+ const firstChatId = s(store).currentChatId!;
+ const secondChat = s(store).createChat({
title: "Second",
select: false,
});
- store.startChatRun(firstChatId, {
+ s(store).startChatRun(firstChatId, {
path: "/projects/demo",
title: "Demo",
});
- store.setCurrentChat(secondChat.id);
+ s(store).setCurrentChat(secondChat.id);
- expect(store.currentChatId).toBe(firstChatId);
- expect(store.canSelectChat(secondChat.id)).toBe(false);
- expect(store.canSelectChat(firstChatId)).toBe(true);
+ expect(s(store).currentChatId).toBe(firstChatId);
+ expect(s(store).canSelectChat(secondChat.id)).toBe(false);
+ expect(s(store).canSelectChat(firstChatId)).toBe(true);
});
test("creates a new chat without switching while a chat is running", () => {
- const store = createStore();
- const firstChatId = store.currentChatId!;
+ const store = createAgentStore();
+ const firstChatId = s(store).currentChatId!;
- store.startChatRun(firstChatId, {
+ s(store).startChatRun(firstChatId, {
path: "/projects/demo",
title: "Demo",
});
- const secondChat = store.createChat({
+ const secondChat = s(store).createChat({
title: "Second",
});
- expect(store.currentChatId).toBe(firstChatId);
- expect(store.getChat(secondChat.id)?.title).toBe("Second");
+ expect(s(store).currentChatId).toBe(firstChatId);
+ expect(s(store).getChat(secondChat.id)?.title).toBe("Second");
});
- test("persists pending choose asks for awaiting-user chats", async () => {
- const store = createStore();
- const chatId = store.currentChatId!;
+ test("persists pending choose asks for awaiting-user chats", () => {
+ const store = createAgentStore();
+ const chatId = s(store).currentChatId!;
- store.awaitUser(chatId, {
+ s(store).awaitUser(chatId, {
toolCallId: "tool-1",
prompt: "Which database should I use?",
kind: "choose",
@@ -305,11 +304,9 @@ describe("useAgentStore", () => {
],
});
- await nextTick();
-
- const rehydratedStore = createStore();
- expect(rehydratedStore.getChat(chatId)?.status).toBe("awaiting_user");
- expect(rehydratedStore.getPendingAsk(chatId)).toEqual({
+ const rehydratedStore = createAgentStore();
+ expect(s(rehydratedStore).getChat(chatId)?.status).toBe("awaiting_user");
+ expect(s(rehydratedStore).getPendingAsk(chatId)).toEqual({
toolCallId: "tool-1",
prompt: "Which database should I use?",
kind: "choose",
@@ -358,9 +355,9 @@ describe("useAgentStore", () => {
})
);
- const store = createStore();
+ const store = createAgentStore();
- expect(store.getPendingAsk("thread-1")).toEqual({
+ expect(s(store).getPendingAsk("thread-1")).toEqual({
toolCallId: "tool-1",
prompt: "Choose a database",
kind: "input",
@@ -372,10 +369,10 @@ describe("useAgentStore", () => {
});
test("answerPendingAsk appends a synthetic tool result and clears pending state", () => {
- const store = createStore();
- const chatId = store.currentChatId!;
+ const store = createAgentStore();
+ const chatId = s(store).currentChatId!;
- store.awaitUser(chatId, {
+ s(store).awaitUser(chatId, {
toolCallId: "tool-1",
prompt: "Proceed?",
kind: "confirm",
@@ -383,13 +380,13 @@ describe("useAgentStore", () => {
cancelLabel: "Cancel",
});
- store.answerPendingAsk(chatId, {
+ s(store).answerPendingAsk(chatId, {
kind: "confirm",
answer: "Proceed",
confirmed: true,
});
- const messages = store.getMessages(chatId);
+ const messages = s(store).getMessages(chatId);
expect(messages).toHaveLength(1);
expect(messages[0].role).toBe("tool");
expect(messages[0].toolCallId).toBe("tool-1");
@@ -398,14 +395,14 @@ describe("useAgentStore", () => {
answer: "Proceed",
confirmed: true,
});
- expect(store.getPendingAsk(chatId)).toBeNull();
+ expect(s(store).getPendingAsk(chatId)).toBeNull();
});
test("answerPendingAsk stores choose labels and values", () => {
- const store = createStore();
- const chatId = store.currentChatId!;
+ const store = createAgentStore();
+ const chatId = s(store).currentChatId!;
- store.awaitUser(chatId, {
+ s(store).awaitUser(chatId, {
toolCallId: "tool-choose",
prompt: "Choose an environment",
kind: "choose",
@@ -415,13 +412,13 @@ describe("useAgentStore", () => {
],
});
- store.answerPendingAsk(chatId, {
+ s(store).answerPendingAsk(chatId, {
kind: "choose",
answer: "Production",
value: "prod",
});
- const messages = store.getMessages(chatId);
+ const messages = s(store).getMessages(chatId);
expect(messages).toHaveLength(1);
expect(messages[0].role).toBe("tool");
expect(messages[0].toolCallId).toBe("tool-choose");
@@ -430,7 +427,7 @@ describe("useAgentStore", () => {
answer: "Production",
value: "prod",
});
- expect(store.getPendingAsk(chatId)).toBeNull();
+ expect(s(store).getPendingAsk(chatId)).toBeNull();
});
test("migrates persisted chats without archived state", () => {
@@ -454,66 +451,72 @@ describe("useAgentStore", () => {
})
);
- const store = createStore();
+ const store = createAgentStore();
- expect(store.getChat("thread-1")?.archived).toBe(false);
+ expect(s(store).getChat("thread-1")?.archived).toBe(false);
});
test("does not update updatedTs when rename normalization keeps the same title", () => {
const dateNow = vi.spyOn(Date, "now");
dateNow.mockReturnValue(1000);
- const store = createStore();
- const chatId = store.currentChatId!;
+ const store = createAgentStore();
+ const chatId = s(store).currentChatId!;
- store.renameChat(chatId, "Renamed thread");
- const updatedTs = store.getChat(chatId)?.updatedTs;
+ s(store).renameChat(chatId, "Renamed thread");
+ const updatedTs = s(store).getChat(chatId)?.updatedTs;
dateNow.mockReturnValue(2000);
- store.renameChat(chatId, " Renamed thread ");
+ s(store).renameChat(chatId, " Renamed thread ");
- expect(store.getChat(chatId)?.title).toBe("Renamed thread");
- expect(store.getChat(chatId)?.updatedTs).toBe(updatedTs);
+ expect(s(store).getChat(chatId)?.title).toBe("Renamed thread");
+ expect(s(store).getChat(chatId)?.updatedTs).toBe(updatedTs);
dateNow.mockRestore();
});
test("supports renaming, archiving, unarchiving, and deleting chats", () => {
- const store = createStore();
- const firstChatId = store.currentChatId!;
- const secondChat = store.createChat({ title: "Second thread" });
+ const store = createAgentStore();
+ const firstChatId = s(store).currentChatId!;
+ const secondChat = s(store).createChat({ title: "Second thread" });
- store.renameChat(firstChatId, " Renamed thread ");
- store.archiveChat(firstChatId);
+ s(store).renameChat(firstChatId, " Renamed thread ");
+ s(store).archiveChat(firstChatId);
- expect(store.getChat(firstChatId)?.title).toBe("Renamed thread");
- expect(store.getChat(firstChatId)?.archived).toBe(true);
+ expect(s(store).getChat(firstChatId)?.title).toBe("Renamed thread");
+ expect(s(store).getChat(firstChatId)?.archived).toBe(true);
- store.unarchiveChat(firstChatId);
- expect(store.getChat(firstChatId)?.archived).toBe(false);
+ s(store).unarchiveChat(firstChatId);
+ expect(s(store).getChat(firstChatId)?.archived).toBe(false);
- store.deleteChat(secondChat.id);
- expect(store.getChat(secondChat.id)).toBeNull();
- expect(store.currentChatId).toBe(firstChatId);
+ s(store).deleteChat(secondChat.id);
+ expect(s(store).getChat(secondChat.id)).toBeNull();
+ expect(s(store).currentChatId).toBe(firstChatId);
});
test("tracks abort controllers per chat and cancels only the requested chat", () => {
- const store = createStore();
- const firstChatId = store.currentChatId!;
- const secondChat = store.createChat({ title: "Second thread" });
+ const store = createAgentStore();
+ const firstChatId = s(store).currentChatId!;
+ const secondChat = s(store).createChat({ title: "Second thread" });
const firstController = new AbortController();
const secondController = new AbortController();
- store.startChatRun(firstChatId, { path: "/projects/one", title: "One" });
- store.startChatRun(secondChat.id, { path: "/projects/two", title: "Two" });
- store.setAbortController(firstChatId, firstController);
- store.setAbortController(secondChat.id, secondController);
+ s(store).startChatRun(firstChatId, {
+ path: "/projects/one",
+ title: "One",
+ });
+ s(store).startChatRun(secondChat.id, {
+ path: "/projects/two",
+ title: "Two",
+ });
+ s(store).setAbortController(firstChatId, firstController);
+ s(store).setAbortController(secondChat.id, secondController);
- store.cancel(firstChatId);
+ s(store).cancel(firstChatId);
expect(firstController.signal.aborted).toBe(true);
expect(secondController.signal.aborted).toBe(false);
- expect(store.isChatRunning(firstChatId)).toBe(false);
- expect(store.isChatRunning(secondChat.id)).toBe(true);
+ expect(s(store).isChatRunning(firstChatId)).toBe(false);
+ expect(s(store).isChatRunning(secondChat.id)).toBe(true);
});
});
diff --git a/frontend/src/react/plugins/agent/store/agent.ts b/frontend/src/react/plugins/agent/store/agent.ts
new file mode 100644
index 0000000000..42e61a0726
--- /dev/null
+++ b/frontend/src/react/plugins/agent/store/agent.ts
@@ -0,0 +1,1100 @@
+import { v4 as uuidv4 } from "uuid";
+import { create } from "zustand";
+import { immer } from "zustand/middleware/immer";
+import type {
+ AgentAskUserResponse,
+ AgentChat,
+ AgentChatSnapshot,
+ AgentChatStatus,
+ AgentMessage,
+ AgentPendingAsk,
+ Message,
+ ToolCall,
+} from "../logic/types";
+
+export const AGENT_STATE_KEY = "bb-agent-state-v2";
+export const AGENT_WINDOW_KEY = "bb-agent-window";
+
+interface PersistedAgentState {
+ currentChatId: string | null;
+ chats: AgentChat[];
+ messagesByChatId: Record<string, AgentMessage[]>;
+ pendingAskByChatId: Record<string, AgentPendingAsk>;
+}
+
+interface CreateChatOptions {
+ page?: AgentChatSnapshot;
+ select?: boolean;
+ title?: string;
+ archived?: boolean;
+}
+
+interface AddMessageOptions extends Message {
+ chatId?: string;
+ metadata?: AgentMessage["metadata"];
+}
+
+const DEFAULT_CHAT_STATUS: AgentChatStatus = "idle";
+
+// --- Pure helper functions (copied verbatim from Pinia store) ---
+
+const createChatRecord = (options: CreateChatOptions = {}): AgentChat => {
+ const now = Date.now();
+ return {
+ id: uuidv4(),
+ title: options.title ?? "",
+ createdTs: now,
+ updatedTs: now,
+ status: DEFAULT_CHAT_STATUS,
+ totalTokensUsed: 0,
+ page: options.page,
+ archived: options.archived ?? false,
+ lastError: null,
+ requiresAIConfiguration: false,
+ interrupted: false,
+ runId: null,
+ };
+};
+
+const normalizeChatTitle = (title?: string) => {
+ return (title ?? "").trim();
+};
+
+const getChatTitleFromMessage = (content?: string) => {
+ const title = normalizeChatTitle(content).replace(/\s+/g, " ");
+ if (!title) {
+ return "";
+ }
+ return title.length <= 48 ? title : `${title.slice(0, 45)}...`;
+};
+
+const isRecord = (value: unknown): value is Record<string, unknown> => {
+ return typeof value === "object" && value !== null;
+};
+
+const normalizeMessage = (
+ raw: unknown,
+ chatId: string,
+ fallbackTs: number
+): AgentMessage => {
+ const message = isRecord(raw) ? raw : {};
+ return {
+ id: typeof message.id === "string" ? message.id : uuidv4(),
+ chatId:
+ typeof message.chatId === "string"
+ ? message.chatId
+ : typeof message.threadId === "string"
+ ? message.threadId
+ : chatId,
+ createdTs:
+ typeof message.createdTs === "number" ? message.createdTs : fallbackTs,
+ role:
+ message.role === "assistant" ||
+ message.role === "system" ||
+ message.role === "tool"
+ ? message.role
+ : "user",
+ content: typeof message.content === "string" ? message.content : undefined,
+ toolCalls: Array.isArray(message.toolCalls)
+ ? (message.toolCalls as ToolCall[])
+ : undefined,
+ toolCallId:
+ typeof message.toolCallId === "string" ? message.toolCallId : undefined,
+ metadata: isRecord(message.metadata)
+ ? { ...(message.metadata as AgentMessage["metadata"]) }
+ : undefined,
+ };
+};
+
+const normalizePendingAsk = (raw: unknown): AgentPendingAsk | null => {
+ const pendingAsk = isRecord(raw) ? raw : {};
+ if (
+ typeof pendingAsk.toolCallId !== "string" ||
+ typeof pendingAsk.prompt !== "string"
+ ) {
+ return null;
+ }
+
+ const options = Array.isArray(pendingAsk.options)
+ ? pendingAsk.options
+ .map((option) => {
+ const candidate = isRecord(option) ? option : {};
+ const label =
+ typeof candidate.label === "string"
+ ? candidate.label.trim()
+ : typeof candidate.value === "string"
+ ? candidate.value.trim()
+ : "";
+ const value =
+ typeof candidate.value === "string" ? candidate.value.trim() : "";
+ if (!label || !value) {
+ return null;
+ }
+ return {
+ label,
+ value,
+ description:
+ typeof candidate.description === "string" &&
+ candidate.description.trim()
+ ? candidate.description.trim()
+ : undefined,
+ };
+ })
+ .filter(
+ (option): option is NonNullable<typeof option> => option !== null
+ )
+ : [];
+
+ const kind =
+ pendingAsk.kind === "confirm"
+ ? "confirm"
+ : pendingAsk.kind === "choose" && options.length > 0
+ ? "choose"
+ : "input";
+
+ return {
+ toolCallId: pendingAsk.toolCallId,
+ prompt: pendingAsk.prompt,
+ kind,
+ defaultValue:
+ typeof pendingAsk.defaultValue === "string"
+ ? pendingAsk.defaultValue
+ : undefined,
+ confirmLabel:
+ typeof pendingAsk.confirmLabel === "string"
+ ? pendingAsk.confirmLabel
+ : undefined,
+ cancelLabel:
+ typeof pendingAsk.cancelLabel === "string"
+ ? pendingAsk.cancelLabel
+ : undefined,
+ options: kind === "choose" ? options : undefined,
+ };
+};
+
+const normalizeChat = (raw: unknown): AgentChat => {
+ const chat = isRecord(raw) ? raw : {};
+ const now = Date.now();
+ const status =
+ chat.status === "running" ||
+ chat.status === "awaiting_user" ||
+ chat.status === "error"
+ ? chat.status
+ : DEFAULT_CHAT_STATUS;
+ return {
+ id: typeof chat.id === "string" ? chat.id : uuidv4(),
+ title: typeof chat.title === "string" ? chat.title : "",
+ createdTs: typeof chat.createdTs === "number" ? chat.createdTs : now,
+ updatedTs: typeof chat.updatedTs === "number" ? chat.updatedTs : now,
+ status,
+ totalTokensUsed:
+ typeof chat.totalTokensUsed === "number" &&
+ Number.isFinite(chat.totalTokensUsed) &&
+ chat.totalTokensUsed >= 0
+ ? chat.totalTokensUsed
+ : 0,
+ page:
+ isRecord(chat.page) &&
+ typeof chat.page.path === "string" &&
+ typeof chat.page.title === "string"
+ ? {
+ path: chat.page.path,
+ title: chat.page.title,
+ }
+ : undefined,
+ archived: Boolean(chat.archived),
+ lastError:
+ typeof chat.lastError === "string"
+ ? chat.lastError
+ : chat.lastError === null
+ ? null
+ : null,
+ requiresAIConfiguration: Boolean(chat.requiresAIConfiguration),
+ interrupted: Boolean(chat.interrupted),
+ runId: typeof chat.runId === "string" ? chat.runId : null,
+ };
+};
+
+const sortMessages = (messages: AgentMessage[]) => {
+ messages.sort((a, b) => a.createdTs - b.createdTs);
+ return messages;
+};
+
+const createEmptyPersistedState = (): PersistedAgentState => ({
+ currentChatId: null,
+ chats: [],
+ messagesByChatId: {},
+ pendingAskByChatId: {},
+});
+
+const normalizePersistedState = (raw: unknown): PersistedAgentState => {
+ if (!isRecord(raw)) {
+ return createEmptyPersistedState();
+ }
+
+ const rawChats = Array.isArray(raw.chats)
+ ? raw.chats
+ : Array.isArray(raw.threads)
+ ? raw.threads
+ : [];
+ const rawMessagesByChatId = isRecord(raw.messagesByChatId)
+ ? raw.messagesByChatId
+ : isRecord(raw.messagesByThreadId)
+ ? raw.messagesByThreadId
+ : {};
+ const rawPendingAskByChatId = isRecord(raw.pendingAskByChatId)
+ ? raw.pendingAskByChatId
+ : isRecord(raw.pendingAskByThreadId)
+ ? raw.pendingAskByThreadId
+ : {};
+
+ const chats = rawChats.map((chat) => normalizeChat(chat));
+ const messagesByChatId: Record<string, AgentMessage[]> = {};
+ const pendingAskByChatId: Record<string, AgentPendingAsk> = {};
+
+ for (const chat of chats) {
+ const rawMessages: unknown[] = Array.isArray(rawMessagesByChatId[chat.id])
+ ? (rawMessagesByChatId[chat.id] as unknown[])
+ : [];
+ const messages = sortMessages(
+ rawMessages.map((message, index) =>
+ normalizeMessage(message, chat.id, chat.createdTs + index)
+ )
+ );
+
+ const firstUserMessage = messages.find(
+ (message) => message.role === "user"
+ );
+ const lastMessage = messages.at(-1);
+
+ if (!chat.title) {
+ chat.title = getChatTitleFromMessage(firstUserMessage?.content);
+ }
+ if (lastMessage) {
+ chat.updatedTs = Math.max(chat.updatedTs, lastMessage.createdTs);
+ }
+ if (chat.status === "running") {
+ chat.status = DEFAULT_CHAT_STATUS;
+ chat.interrupted = true;
+ chat.lastError = null;
+ chat.requiresAIConfiguration = false;
+ }
+
+ const pendingAsk = normalizePendingAsk(rawPendingAskByChatId[chat.id]);
+ if (chat.status === "awaiting_user") {
+ if (pendingAsk) {
+ pendingAskByChatId[chat.id] = pendingAsk;
+ } else {
+ chat.status = DEFAULT_CHAT_STATUS;
+ }
+ }
+
+ messagesByChatId[chat.id] = messages;
+ }
+
+ const savedCurrentChatId =
+ typeof raw.currentChatId === "string"
+ ? raw.currentChatId
+ : typeof raw.currentThreadId === "string"
+ ? raw.currentThreadId
+ : null;
+ const currentChatId =
+ savedCurrentChatId && chats.some((chat) => chat.id === savedCurrentChatId)
+ ? savedCurrentChatId
+ : (chats[0]?.id ?? null);
+
+ return {
+ currentChatId,
+ chats,
+ messagesByChatId,
+ pendingAskByChatId,
+ };
+};
+
+// --- Zustand store types ---
+
+export interface AgentState {
+ // Window state
+ visible: boolean;
+ position: { x: number; y: number };
+ size: { width: number; height: number };
+ sidebarWidth: number;
+ minimized: boolean;
+
+ // Chat state
+ chats: AgentChat[];
+ messagesByChatId: Record<string, AgentMessage[]>;
+ pendingAskByChatId: Record<string, AgentPendingAsk>;
+ currentChatId: string | null;
+ abortControllersByChatId: Record<string, AbortController>;
+
+ // UI actions
+ toggle: () => void;
+ minimize: () => void;
+ restore: () => void;
+ setPosition: (x: number, y: number) => void;
+ setSize: (width: number, height: number) => void;
+ setSidebarWidth: (width: number) => void;
+
+ // Chat CRUD
+ createChat: (options?: CreateChatOptions) => AgentChat;
+ ensureCurrentChat: (page?: AgentChatSnapshot) => AgentChat;
+ setCurrentChat: (chatId: string) => void;
+ updateChatPage: (chatId: string, page: AgentChatSnapshot) => AgentChat | null;
+ renameChat: (chatId: string, title: string) => AgentChat | null;
+ archiveChat: (chatId: string) => AgentChat | null;
+ unarchiveChat: (chatId: string) => AgentChat | null;
+ deleteChat: (chatId: string) => boolean;
+
+ // Messages
+ addMessage: (message: AddMessageOptions) => AgentMessage;
+ removeMessagesByRunId: (
+ chatId: string,
+ runId?: string | null
+ ) => AgentMessage[];
+ appendToolCall: (
+ chatId: string,
+ messageId: string,
+ toolCall: ToolCall
+ ) => AgentMessage | null;
+
+ // Status
+ setChatStatus: (
+ chatId: string,
+ status: AgentChatStatus,
+ options?: {
+ interrupted?: boolean;
+ lastError?: string | null;
+ requiresAIConfiguration?: boolean;
+ page?: AgentChatSnapshot;
+ }
+ ) => AgentChat | null;
+ startChatRun: (
+ chatId: string,
+ page?: AgentChatSnapshot,
+ options?: { runId?: string }
+ ) => void;
+ finishChatRun: (
+ chatId: string,
+ options?: {
+ status?: Extract<AgentChatStatus, "idle" | "error">;
+ lastError?: string | null;
+ requiresAIConfiguration?: boolean;
+ }
+ ) => void;
+ interruptChatRun: (chatId: string, page?: AgentChatSnapshot) => void;
+
+ // Pending ask
+ setPendingAsk: (
+ chatId: string,
+ pendingAsk: AgentPendingAsk
+ ) => AgentPendingAsk;
+ clearPendingAsk: (chatId?: string | null) => void;
+ awaitUser: (chatId: string, pendingAsk: AgentPendingAsk) => AgentPendingAsk;
+ answerPendingAsk: (
+ chatId: string,
+ response: AgentAskUserResponse,
+ metadata?: AgentMessage["metadata"]
+ ) => AgentMessage | null;
+
+ // Token
+ incrementChatTotalTokens: (
+ chatId: string,
+ totalTokensUsed: number
+ ) => AgentChat | null;
+
+ // Abort
+ setAbortController: (
+ chatId: string,
+ controller: AbortController | null
+ ) => AbortController | null;
+ getAbortController: (chatId?: string | null) => AbortController | null;
+ cancel: (chatId?: string | null) => void;
+
+ // Error
+ clearError: (chatId?: string | null) => void;
+
+ // Persistence
+ saveWindowState: () => void;
+ loadWindowState: () => void;
+ saveState: () => void;
+ loadState: () => void;
+
+ // Queries
+ getChat: (chatId?: string | null) => AgentChat | null;
+ getMessages: (chatId?: string | null) => AgentMessage[];
+ getPendingAsk: (chatId?: string | null) => AgentPendingAsk | null;
+ isChatRunning: (chatId?: string | null) => boolean;
+ canSelectChat: (chatId?: string | null) => boolean;
+ touchChat: (chatId: string) => AgentChat | null;
+}
+
+// --- Selector functions (derived values) ---
+
+// Stable empty references — avoids creating new objects on every selector call,
+// which would cause infinite re-render loops with useSyncExternalStore.
+const EMPTY_MESSAGES: AgentMessage[] = [];
+const EMPTY_CHATS: AgentChat[] = [];
+
+// Memoised selector: only re-sorts when the chats array reference changes.
+let _orderedChatsInput: AgentChat[] | null = null;
+let _orderedChatsResult: AgentChat[] = EMPTY_CHATS;
+
+export const selectOrderedChats = (state: AgentState): AgentChat[] => {
+ if (state.chats !== _orderedChatsInput) {
+ _orderedChatsInput = state.chats;
+ _orderedChatsResult = [...state.chats].sort((a, b) => {
+ if (b.updatedTs !== a.updatedTs) {
+ return b.updatedTs - a.updatedTs;
+ }
+ return b.createdTs - a.createdTs;
+ });
+ }
+ return _orderedChatsResult;
+};
+
+export const selectCurrentChat = (state: AgentState): AgentChat | null =>
+ state.chats.find((chat) => chat.id === state.currentChatId) ?? null;
+
+export const selectMessages = (state: AgentState): AgentMessage[] =>
+ (state.currentChatId
+ ? state.messagesByChatId[state.currentChatId]
+ : undefined) ?? EMPTY_MESSAGES;
+
+export const selectCurrentPendingAsk = (
+ state: AgentState
+): AgentPendingAsk | null =>
+ (state.currentChatId
+ ? state.pendingAskByChatId[state.currentChatId]
+ : undefined) ?? null;
+
+export const selectLoading = (state: AgentState): boolean =>
+ selectCurrentChat(state)?.status === "running";
+
+export const selectError = (state: AgentState): string | null =>
+ selectCurrentChat(state)?.lastError ?? null;
+
+export const selectCurrentChatRequiresAIConfiguration = (
+ state: AgentState
+): boolean => selectCurrentChat(state)?.requiresAIConfiguration ?? false;
+
+export const selectHasRunningChat = (state: AgentState): boolean =>
+ state.chats.some((chat) => chat.status === "running");
+
+// --- Store creation ---
+
+const loadInitialState = (): {
+ chats: AgentChat[];
+ messagesByChatId: Record<string, AgentMessage[]>;
+ pendingAskByChatId: Record<string, AgentPendingAsk>;
+ currentChatId: string | null;
+} => {
+ const saved = localStorage.getItem(AGENT_STATE_KEY);
+ let state: PersistedAgentState | null = null;
+
+ if (saved) {
+ try {
+ state = normalizePersistedState(JSON.parse(saved));
+ } catch {
+ localStorage.removeItem(AGENT_STATE_KEY);
+ }
+ }
+
+ if (
+ state &&
+ state.currentChatId &&
+ state.chats.some((c) => c.id === state!.currentChatId)
+ ) {
+ return state;
+ }
+
+ // Need a default chat
+ const chats = state?.chats ?? [];
+ const messagesByChatId = state?.messagesByChatId ?? {};
+ const pendingAskByChatId = state?.pendingAskByChatId ?? {};
+ const defaultChat = createChatRecord();
+ chats.push(defaultChat);
+ messagesByChatId[defaultChat.id] = [];
+
+ return {
+ chats,
+ messagesByChatId,
+ pendingAskByChatId,
+ currentChatId: defaultChat.id,
+ };
+};
+
+export const createAgentStore = () => {
+ const initial = loadInitialState();
+
+ const store = create<AgentState>()(
+ immer((set, get) => {
+ // Internal helpers that work on the plain (non-draft) state via get()
+ const _getChat = (chatId?: string | null): AgentChat | null => {
+ if (!chatId) return null;
+ return get().chats.find((chat) => chat.id === chatId) ?? null;
+ };
+
+ const _hasRunningChat = (): boolean =>
+ get().chats.some((chat) => chat.status === "running");
+
+ const _touchChatInDraft = (
+ chats: AgentChat[],
+ chatId: string
+ ): AgentChat | null => {
+ const chat = chats.find((c) => c.id === chatId);
+ if (!chat) return null;
+ chat.updatedTs = Date.now();
+ return chat;
+ };
+
+ return {
+ // Window state
+ visible: false,
+ position: {
+ x: typeof window !== "undefined" ? window.innerWidth - 420 : 0,
+ y: typeof window !== "undefined" ? window.innerHeight - 520 : 0,
+ },
+ size: { width: 400, height: 500 },
+ sidebarWidth: 256,
+ minimized: false,
+
+ // Chat state (from persisted/initial)
+ chats: initial.chats,
+ messagesByChatId: initial.messagesByChatId,
+ pendingAskByChatId: initial.pendingAskByChatId,
+ currentChatId: initial.currentChatId,
+ abortControllersByChatId: {},
+
+ // UI actions
+ toggle: () =>
+ set((state) => {
+ state.visible = !state.visible;
+ if (state.visible) {
+ state.minimized = false;
+ }
+ }),
+ minimize: () =>
+ set((state) => {
+ state.minimized = true;
+ }),
+ restore: () =>
+ set((state) => {
+ state.minimized = false;
+ }),
+ setPosition: (x, y) =>
+ set((state) => {
+ state.position = { x, y };
+ }),
+ setSize: (width, height) =>
+ set((state) => {
+ state.size = { width, height };
+ }),
+ setSidebarWidth: (width) =>
+ set((state) => {
+ state.sidebarWidth = width;
+ }),
+
+ // Queries
+ getChat: (chatId) => _getChat(chatId),
+
+ getMessages: (chatId) => {
+ if (!chatId) return [];
+ return get().messagesByChatId[chatId] ?? [];
+ },
+
+ getPendingAsk: (chatId) => {
+ const id = chatId ?? get().currentChatId;
+ if (!id) return null;
+ return get().pendingAskByChatId[id] ?? null;
+ },
+
+ getAbortController: (chatId) => {
+ if (!chatId) return null;
+ return get().abortControllersByChatId[chatId] ?? null;
+ },
+
+ isChatRunning: (chatId) => _getChat(chatId)?.status === "running",
+
+ canSelectChat: (chatId) => {
+ if (!chatId || !_getChat(chatId)) return false;
+ return !_hasRunningChat() || get().currentChatId === chatId;
+ },
+
+ touchChat: (chatId) => {
+ let result: AgentChat | null = null;
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === chatId);
+ if (chat) {
+ chat.updatedTs = Date.now();
+ result = { ...chat } as AgentChat;
+ }
+ });
+ return result;
+ },
+
+ setAbortController: (chatId, controller) => {
+ // AbortControllers are not serializable, store outside immer
+ const controllers = get().abortControllersByChatId;
+ if (controller) {
+ set((state) => {
+ state.abortControllersByChatId[chatId] = controller;
+ });
+ return controller;
+ }
+ if (controllers[chatId]) {
+ set((state) => {
+ delete state.abortControllersByChatId[chatId];
+ });
+ }
+ return null;
+ },
+
+ // Chat CRUD
+ createChat: (options = {}) => {
+ const chat = createChatRecord(options);
+ const shouldSelect =
+ (options.select ?? true) &&
+ (!_hasRunningChat() || get().currentChatId === null);
+ set((state) => {
+ state.chats.push(chat);
+ state.messagesByChatId[chat.id] = [];
+ if (shouldSelect) {
+ state.currentChatId = chat.id;
+ }
+ });
+ return chat;
+ },
+
+ ensureCurrentChat: (page) => {
+ const existing = _getChat(get().currentChatId);
+ if (existing) {
+ if (page && !existing.page) {
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === existing.id);
+ if (chat) {
+ chat.page = page;
+ _touchChatInDraft(state.chats, chat.id);
+ }
+ });
+ }
+ return _getChat(existing.id)!;
+ }
+ return get().createChat({ page });
+ },
+
+ setCurrentChat: (chatId) => {
+ if (get().canSelectChat(chatId)) {
+ set((state) => {
+ state.currentChatId = chatId;
+ });
+ }
+ },
+
+ updateChatPage: (chatId, page) => {
+ if (!_getChat(chatId)) return null;
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === chatId);
+ if (chat) {
+ chat.page = page;
+ _touchChatInDraft(state.chats, chatId);
+ }
+ });
+ return _getChat(chatId);
+ },
+
+ renameChat: (chatId, title) => {
+ const chat = _getChat(chatId);
+ if (!chat) return null;
+ const normalizedTitle = normalizeChatTitle(title);
+ if (chat.title === normalizedTitle) return chat;
+ set((state) => {
+ const c = state.chats.find((c) => c.id === chatId);
+ if (c) {
+ c.title = normalizedTitle;
+ _touchChatInDraft(state.chats, chatId);
+ }
+ });
+ return _getChat(chatId);
+ },
+
+ archiveChat: (chatId) => {
+ if (!_getChat(chatId)) return null;
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === chatId);
+ if (chat) {
+ chat.archived = true;
+ _touchChatInDraft(state.chats, chatId);
+ }
+ });
+ return _getChat(chatId);
+ },
+
+ unarchiveChat: (chatId) => {
+ if (!_getChat(chatId)) return null;
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === chatId);
+ if (chat) {
+ chat.archived = false;
+ _touchChatInDraft(state.chats, chatId);
+ }
+ });
+ return _getChat(chatId);
+ },
+
+ deleteChat: (chatId) => {
+ if (!_getChat(chatId)) return false;
+ get().cancel(chatId);
+ set((state) => {
+ state.chats = state.chats.filter((c) => c.id !== chatId);
+ delete state.messagesByChatId[chatId];
+ delete state.pendingAskByChatId[chatId];
+ delete state.abortControllersByChatId[chatId];
+ if (state.currentChatId === chatId) {
+ // Select next available chat
+ const ordered = [...state.chats].sort((a, b) => {
+ if (b.updatedTs !== a.updatedTs)
+ return b.updatedTs - a.updatedTs;
+ return b.createdTs - a.createdTs;
+ });
+ if (ordered.length > 0) {
+ state.currentChatId = ordered[0].id;
+ } else {
+ // Create a new default chat
+ const newChat = createChatRecord();
+ state.chats.push(newChat);
+ state.messagesByChatId[newChat.id] = [];
+ state.currentChatId = newChat.id;
+ }
+ }
+ });
+ return true;
+ },
+
+ // Messages
+ addMessage: (message) => {
+ const chatId =
+ message.chatId && _getChat(message.chatId)
+ ? message.chatId
+ : get().ensureCurrentChat().id;
+ const createdTs = Date.now();
+ const agentMessage: AgentMessage = {
+ ...message,
+ id: uuidv4(),
+ chatId,
+ createdTs,
+ };
+ set((state) => {
+ const chatMessages = state.messagesByChatId[chatId] ?? [];
+ if (!state.messagesByChatId[chatId]) {
+ state.messagesByChatId[chatId] = chatMessages;
+ }
+ chatMessages.push(agentMessage);
+ const chat = state.chats.find((c) => c.id === chatId);
+ if (chat) {
+ if (message.role === "user" && !chat.title) {
+ chat.title = getChatTitleFromMessage(message.content);
+ }
+ chat.lastError = null;
+ chat.requiresAIConfiguration = false;
+ chat.interrupted = false;
+ chat.updatedTs = createdTs;
+ }
+ });
+ return agentMessage;
+ },
+
+ removeMessagesByRunId: (chatId, runId) => {
+ if (!runId || !_getChat(chatId)) return [];
+ const existingMessages = get().messagesByChatId[chatId] ?? [];
+ const removedMessages = existingMessages.filter(
+ (m) => m.metadata?.runId === runId
+ );
+ if (removedMessages.length === 0) return [];
+ set((state) => {
+ state.messagesByChatId[chatId] = (
+ state.messagesByChatId[chatId] ?? []
+ ).filter((m) => m.metadata?.runId !== runId);
+ _touchChatInDraft(state.chats, chatId);
+ });
+ return removedMessages;
+ },
+
+ appendToolCall: (chatId, messageId, toolCall) => {
+ const messages = get().messagesByChatId[chatId] ?? [];
+ const message = messages.find((m) => m.id === messageId);
+ if (!message) return null;
+ set((state) => {
+ const msgs = state.messagesByChatId[chatId] ?? [];
+ const msg = msgs.find((m) => m.id === messageId);
+ if (msg) {
+ msg.toolCalls = [...(msg.toolCalls ?? []), toolCall];
+ _touchChatInDraft(state.chats, chatId);
+ }
+ });
+ return (
+ get()
+ .getMessages(chatId)
+ .find((m) => m.id === messageId) ?? null
+ );
+ },
+
+ // Status
+ setChatStatus: (chatId, status, options = {}) => {
+ if (!_getChat(chatId)) return null;
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === chatId);
+ if (chat) {
+ chat.status = status;
+ chat.interrupted = options.interrupted ?? false;
+ chat.lastError = options.lastError ?? null;
+ chat.requiresAIConfiguration =
+ options.requiresAIConfiguration ?? false;
+ if (options.page) {
+ chat.page = options.page;
+ }
+ if (status !== "awaiting_user") {
+ delete state.pendingAskByChatId[chatId];
+ }
+ _touchChatInDraft(state.chats, chatId);
+ }
+ });
+ return _getChat(chatId);
+ },
+
+ startChatRun: (chatId, page, options = {}) => {
+ get().setChatStatus(chatId, "running", { page });
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === chatId);
+ if (chat) {
+ chat.runId = options.runId ?? chat.runId ?? null;
+ }
+ });
+ },
+
+ finishChatRun: (chatId, options = {}) => {
+ get().setChatStatus(chatId, options.status ?? DEFAULT_CHAT_STATUS, {
+ lastError: options.lastError ?? null,
+ requiresAIConfiguration: options.requiresAIConfiguration ?? false,
+ interrupted: false,
+ });
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === chatId);
+ if (chat) {
+ chat.runId = null;
+ }
+ });
+ },
+
+ interruptChatRun: (chatId, page) => {
+ get().setChatStatus(chatId, DEFAULT_CHAT_STATUS, {
+ interrupted: true,
+ page,
+ });
+ },
+
+ // Pending ask
+ setPendingAsk: (chatId, pendingAsk) => {
+ set((state) => {
+ state.pendingAskByChatId[chatId] = pendingAsk;
+ _touchChatInDraft(state.chats, chatId);
+ });
+ return pendingAsk;
+ },
+
+ clearPendingAsk: (chatId) => {
+ const id = chatId ?? get().currentChatId;
+ if (!id || !get().pendingAskByChatId[id]) return;
+ set((state) => {
+ delete state.pendingAskByChatId[id];
+ _touchChatInDraft(state.chats, id);
+ });
+ },
+
+ awaitUser: (chatId, pendingAsk) => {
+ get().setChatStatus(chatId, "awaiting_user");
+ return get().setPendingAsk(chatId, pendingAsk);
+ },
+
+ answerPendingAsk: (chatId, response, metadata) => {
+ const pendingAsk = get().getPendingAsk(chatId);
+ if (!pendingAsk) return null;
+ const toolMessage = get().addMessage({
+ chatId,
+ role: "tool",
+ toolCallId: pendingAsk.toolCallId,
+ content: JSON.stringify(response),
+ metadata,
+ });
+ get().clearPendingAsk(chatId);
+ return toolMessage;
+ },
+
+ // Token
+ incrementChatTotalTokens: (chatId, totalTokensUsed) => {
+ if (!_getChat(chatId) || totalTokensUsed <= 0) return null;
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === chatId);
+ if (chat) {
+ chat.totalTokensUsed += totalTokensUsed;
+ _touchChatInDraft(state.chats, chatId);
+ }
+ });
+ return _getChat(chatId);
+ },
+
+ // Abort / cancel
+ cancel: (chatId) => {
+ const id = chatId ?? get().currentChatId;
+ if (!id) return;
+ get().getAbortController(id)?.abort();
+ get().setAbortController(id, null);
+ if (get().isChatRunning(id)) {
+ get().interruptChatRun(id);
+ }
+ },
+
+ // Error
+ clearError: (chatId) => {
+ const id = chatId ?? get().currentChatId;
+ const chat = _getChat(id);
+ if (!chat) return;
+ set((state) => {
+ const c = state.chats.find((c) => c.id === id);
+ if (c) {
+ c.lastError = null;
+ c.requiresAIConfiguration = false;
+ c.interrupted = false;
+ c.runId = null;
+ if (c.status === "error") {
+ c.status = DEFAULT_CHAT_STATUS;
+ }
+ _touchChatInDraft(state.chats, c.id);
+ }
+ });
+ },
+
+ // Persistence
+ saveWindowState: () => {
+ const state = get();
+ localStorage.setItem(
+ AGENT_WINDOW_KEY,
+ JSON.stringify({
+ position: state.position,
+ size: state.size,
+ sidebarWidth: state.sidebarWidth,
+ })
+ );
+ },
+
+ loadWindowState: () => {
+ const saved = localStorage.getItem(AGENT_WINDOW_KEY);
+ if (!saved) return;
+ try {
+ const state = JSON.parse(saved) as {
+ position?: { x?: number; y?: number };
+ size?: { width?: number; height?: number };
+ sidebarWidth?: number;
+ };
+ set((draft) => {
+ if (
+ typeof state.position?.x === "number" &&
+ typeof state.position?.y === "number"
+ ) {
+ draft.position = {
+ x: state.position.x,
+ y: state.position.y,
+ };
+ }
+ if (
+ typeof state.size?.width === "number" &&
+ typeof state.size?.height === "number"
+ ) {
+ draft.size = {
+ width: state.size.width,
+ height: state.size.height,
+ };
+ }
+ if (typeof state.sidebarWidth === "number") {
+ draft.sidebarWidth = state.sidebarWidth;
+ }
+ });
+ } catch {
+ localStorage.removeItem(AGENT_WINDOW_KEY);
+ }
+ },
+
+ saveState: () => {
+ const state = get();
+ const persistedState: PersistedAgentState = {
+ currentChatId: state.currentChatId,
+ chats: state.chats,
+ messagesByChatId: state.messagesByChatId,
+ pendingAskByChatId: state.pendingAskByChatId,
+ };
+ localStorage.setItem(AGENT_STATE_KEY, JSON.stringify(persistedState));
+ },
+
+ loadState: () => {
+ const saved = localStorage.getItem(AGENT_STATE_KEY);
+ if (saved) {
+ try {
+ const state = normalizePersistedState(JSON.parse(saved));
+ set((draft) => {
+ draft.chats = state.chats;
+ draft.messagesByChatId = state.messagesByChatId;
+ draft.pendingAskByChatId = state.pendingAskByChatId;
+ draft.currentChatId = state.currentChatId;
+ });
+ } catch {
+ localStorage.removeItem(AGENT_STATE_KEY);
+ }
+ }
+
+ const s = get();
+ if (
+ !s.currentChatId ||
+ !s.chats.some((c) => c.id === s.currentChatId)
+ ) {
+ const chat = createChatRecord();
+ set((draft) => {
+ draft.chats.push(chat);
+ draft.messagesByChatId[chat.id] = [];
+ draft.currentChatId = chat.id;
+ });
+ }
+ },
+ };
+ })
+ );
+
+ // Auto-persist on state changes
+ // Auto-persist only the chat state slice (not UI/window state).
+ // Uses a serialization check to avoid redundant writes during
+ // drag/resize operations that only change position/size.
+ let lastSerialized = "";
+ store.subscribe((state) => {
+ const persistedState: PersistedAgentState = {
+ currentChatId: state.currentChatId,
+ chats: state.chats,
+ messagesByChatId: state.messagesByChatId,
+ pendingAskByChatId: state.pendingAskByChatId,
+ };
+ const serialized = JSON.stringify(persistedState);
+ if (serialized !== lastSerialized) {
+ lastSerialized = serialized;
+ localStorage.setItem(AGENT_STATE_KEY, serialized);
+ }
+ });
+
+ // Load persisted window state (position, size, sidebar width) on creation.
+ store.getState().loadWindowState();
+
+ return store;
+};
+
+// Singleton for production use.
+// The return value of create() IS a React hook — callable as
+// useAgentStore(selector) to subscribe React components to state slices.
+// Also callable outside React via useAgentStore.getState().
+export const useAgentStore = createAgentStore();
diff --git a/frontend/src/views/DashboardHeader.vue b/frontend/src/views/DashboardHeader.vue
index 03621d2903..c9df78a524 100644
--- a/frontend/src/views/DashboardHeader.vue
+++ b/frontend/src/views/DashboardHeader.vue
@@ -82,7 +82,7 @@ import { v4 as uuidv4 } from "uuid";
import { computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import ProjectSwitchPopover from "@/components/Project/ProjectSwitch/ProjectSwitchPopover.vue";
-import { useAgentStore } from "@/plugins/agent";
+import { useAgentStore } from "@/react/plugins/agent/store/agent";
import {
WORKSPACE_ROUTE_LANDING,
WORKSPACE_ROUTE_MY_ISSUES,
@@ -124,7 +124,7 @@ defineEmits<{
"toggle-mobile-sidebar": [];
}>();
-const agentStore = useAgentStore();
+const agentStore = { toggle: () => useAgentStore.getState().toggle() };
const subscriptionStore = useSubscriptionV1Store();
const route = useRoute();
const router = useRouter();