Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(studio): avoid invalid requests on playground initialization (#5049)

yufeng733622422122
diff --git a/web-studio/src/routes/playground/-components/agent-panel-initialization.test.tsx b/web-studio/src/routes/playground/-components/agent-panel-initialization.test.tsx
new file mode 100644
index 000000000..5f1573b64
--- /dev/null
+++ b/web-studio/src/routes/playground/-components/agent-panel-initialization.test.tsx
@@ -0,0 +1,128 @@
+// @vitest-environment jsdom
+import { act, cleanup, render } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { AgentPanel } from './agent-panel'
+
+const mocks = vi.hoisted(() => ({
+ history: vi.fn(),
+ create: vi.fn(),
+ send: vi.fn(),
+ onSend: undefined as undefined | ((message: string) => Promise<void>),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({ identityScopeKey: 'test' }),
+}))
+vi.mock('#/lib/sessions/use-session-titles', () => ({
+ useSessionTitles: () => ({ getTitle: () => '', setTitle: vi.fn() }),
+}))
+vi.mock('#/lib/sessions/use-sessions', () => ({
+ useBotHealth: () => ({ isLoading: true }),
+ useCreateSession: () => ({ mutateAsync: mocks.create }),
+ useSessionListByRecency: () => ({ data: [], isLoading: false }),
+ useSessionMessages: mocks.history,
+}))
+vi.mock('#/lib/sessions/use-chat', () => ({
+ useChat: () => ({
+ messages: [],
+ status: 'idle',
+ abort: vi.fn(),
+ setMessages: vi.fn(),
+ send: mocks.send,
+ }),
+}))
+
+vi.mock('#/routes/sessions/-components/composer', () => ({
+ Composer: ({ onSend }: { onSend: (message: string) => Promise<void> }) => {
+ mocks.onSend = onSend
+ return null
+ },
+}))
+
+beforeEach(() => {
+ Element.prototype.scrollIntoView = vi.fn()
+ mocks.history.mockReset().mockReturnValue({ data: undefined })
+ mocks.create.mockReset()
+ mocks.send.mockReset()
+ window.localStorage.clear()
+})
+afterEach(cleanup)
+
+it('keeps a new draft out of history requests and the URL', () => {
+ const onSessionChange = vi.fn()
+ render(
+ <AgentPanel
+ onOpenResource={vi.fn()}
+ onSessionChange={onSessionChange}
+ toolbarContainer={null}
+ />,
+ )
+ expect(mocks.history).toHaveBeenCalledWith(undefined)
+ expect(onSessionChange).not.toHaveBeenCalled()
+ expect(mocks.create).not.toHaveBeenCalled()
+})
+
+it('loads history for an existing session', () => {
+ render(
+ <AgentPanel
+ initialSessionId="existing"
+ onOpenResource={vi.fn()}
+ onSessionChange={vi.fn()}
+ toolbarContainer={null}
+ />,
+ )
+ expect(mocks.history).toHaveBeenCalledWith('existing')
+})
+
+it('creates the draft before sending and publishes only the persisted ID', async () => {
+ const onSessionChange = vi.fn()
+ let resolveCreation!: (value: { session_id: string }) => void
+ mocks.create.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveCreation = resolve
+ }),
+ )
+ render(
+ <AgentPanel
+ onOpenResource={vi.fn()}
+ onSessionChange={onSessionChange}
+ toolbarContainer={null}
+ />,
+ )
+ let sending!: Promise<void>
+ act(() => {
+ sending = mocks.onSend!('hello')
+ })
+ expect(mocks.send).not.toHaveBeenCalled()
+ expect(onSessionChange).not.toHaveBeenCalled()
+ const id = mocks.create.mock.calls[0][0]
+ await act(async () => {
+ resolveCreation({ session_id: id })
+ await sending
+ })
+ expect(onSessionChange).toHaveBeenCalledWith(id)
+ expect(mocks.send).toHaveBeenCalledWith('hello')
+ expect(
+ mocks.history.mock.calls.every(([historyId]) => historyId === undefined),
+ ).toBe(true)
+})
+
+it('does not send or publish the draft when creation fails', async () => {
+ const onSessionChange = vi.fn()
+ mocks.create.mockRejectedValue(new Error('unavailable'))
+ render(
+ <AgentPanel
+ onOpenResource={vi.fn()}
+ onSessionChange={onSessionChange}
+ toolbarContainer={null}
+ />,
+ )
+ await act(async () => {
+ await mocks.onSend!('hello')
+ })
+ expect(mocks.send).not.toHaveBeenCalled()
+ expect(onSessionChange).not.toHaveBeenCalled()
+})
diff --git a/web-studio/src/routes/playground/-components/agent-panel-submission.test.tsx b/web-studio/src/routes/playground/-components/agent-panel-submission.test.tsx
new file mode 100644
index 000000000..ed9cf7428
--- /dev/null
+++ b/web-studio/src/routes/playground/-components/agent-panel-submission.test.tsx
@@ -0,0 +1,141 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { AgentPanel } from './agent-panel'
+import { registerPlaygroundAgentSessionId } from '../-lib/utils'
+
+const m = vi.hoisted(() => ({
+ create: vi.fn(),
+ stream: vi.fn(),
+ history: vi.fn(),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({ identityScopeKey: 'test' }),
+}))
+vi.mock('#/lib/sessions/use-session-titles', () => ({
+ useSessionTitles: () => ({ getTitle: (id: string) => id, setTitle: vi.fn() }),
+ setSessionTitle: vi.fn(),
+}))
+vi.mock('#/lib/sessions/use-sessions', () => ({
+ useBotHealth: () => ({ isLoading: true }),
+ useCreateSession: () => ({ mutateAsync: m.create }),
+ useSessionListByRecency: () => ({
+ data: [{ session_id: 'B' }],
+ isLoading: false,
+ }),
+ useSessionMessages: m.history,
+}))
+vi.mock('#/lib/sessions/api', () => ({
+ sendChatStream: m.stream,
+ addMessage: vi.fn(),
+ serializeParts: vi.fn(),
+}))
+beforeEach(() => {
+ Element.prototype.scrollIntoView = vi.fn()
+ window.localStorage.clear()
+ m.create.mockReset()
+ m.history.mockReset().mockReturnValue({ data: undefined })
+ m.stream.mockReset().mockImplementation(() => new Promise(() => {}))
+})
+afterEach(() => {
+ cleanup()
+ document.body.innerHTML = ''
+})
+function submit(text: string) {
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: text } })
+ fireEvent.click(screen.getByRole('button', { name: 'chat.send' }))
+}
+function setup() {
+ let resolve!: (value: { session_id: string }) => void
+ let reject!: (error: Error) => void
+ m.create.mockImplementation(
+ () =>
+ new Promise((res, rej) => {
+ resolve = res
+ reject = rej
+ }),
+ )
+ registerPlaygroundAgentSessionId('B', 'test')
+ const toolbar = document.createElement('div')
+ document.body.append(toolbar)
+ const url = vi.fn()
+ render(
+ <AgentPanel
+ toolbarContainer={toolbar}
+ onSessionChange={url}
+ onOpenResource={vi.fn()}
+ />,
+ )
+ return {
+ url,
+ resolve: (id: string) => resolve({ session_id: id }),
+ reject: (error: Error) => reject(error),
+ }
+}
+it('preserves edits and blocks duplicate submission while creation waits', async () => {
+ const pending = setup()
+ submit('first')
+ const id = m.create.mock.calls[0][0]
+ submit('second')
+ expect(screen.getByRole('textbox').value).toBe('second')
+ expect(m.stream).not.toHaveBeenCalled()
+ await act(async () => {
+ pending.resolve(id)
+ })
+ expect(m.stream).toHaveBeenCalledTimes(1)
+ expect(m.stream.mock.calls[0][0]).toEqual({
+ message: 'first',
+ session_id: id,
+ })
+})
+it('ignores a late creation after switching to another session', async () => {
+ const pending = setup()
+ submit('message for A')
+ const id = m.create.mock.calls[0][0]
+ fireEvent.click(screen.getByTitle('agent.history'))
+ fireEvent.click(screen.getAllByText('B')[0].closest('button')!)
+ expect(pending.url).toHaveBeenLastCalledWith('B')
+ expect(m.history).toHaveBeenLastCalledWith('B')
+ await act(async () => {
+ pending.resolve(id)
+ })
+ expect(pending.url).toHaveBeenLastCalledWith('B')
+ expect(m.history).toHaveBeenLastCalledWith('B')
+ expect(m.stream).not.toHaveBeenCalled()
+})
+it('preserves the first input when creation fails', async () => {
+ const pending = setup()
+ submit('important input')
+ await act(async () => {
+ pending.reject(new Error('offline'))
+ })
+ expect(screen.getByRole('textbox').value).toBe('important input')
+ expect(m.stream).not.toHaveBeenCalled()
+})
+
+it('clears accepted input once creation succeeds', async () => {
+ const pending = setup()
+ submit('first')
+ expect(screen.getByRole('textbox').value).toBe('first')
+ const id = m.create.mock.calls[0][0]
+ await act(async () => {
+ pending.resolve(id)
+ })
+ expect(screen.getByRole('textbox').value).toBe('')
+ expect(m.stream).toHaveBeenCalledTimes(1)
+})
+
+it('does not send or publish after the panel unmounts', async () => {
+ const pending = setup()
+ submit('first')
+ const id = m.create.mock.calls[0][0]
+ cleanup()
+ await act(async () => {
+ pending.resolve(id)
+ })
+ expect(pending.url).not.toHaveBeenCalled()
+ expect(m.stream).not.toHaveBeenCalled()
+})
diff --git a/web-studio/src/routes/playground/-components/agent-panel.tsx b/web-studio/src/routes/playground/-components/agent-panel.tsx
index a9e3d8016..6b494d038 100644
--- a/web-studio/src/routes/playground/-components/agent-panel.tsx
+++ b/web-studio/src/routes/playground/-components/agent-panel.tsx
@@ -59,7 +59,16 @@ export function AgentPanel({
const [historyOpen, setHistoryOpen] = useState(false)
const [sessionError, setSessionError] = useState<string | null>(null)
const [isCreatingSession, setIsCreatingSession] = useState(false)
+ const [historySessionId, setHistorySessionId] = useState(initialSessionId)
+ const [persistedSessionId, setPersistedSessionId] = useState(initialSessionId)
const creationStartedRef = useRef(false)
+ const creationGenerationRef = useRef(0)
+ useEffect(
+ () => () => {
+ creationGenerationRef.current += 1
+ },
+ [],
+ )
const botHealth = useBotHealth()
const createSession = useCreateSession()
const { data: sessions, isLoading: isLoadingSessions } =
@@ -68,7 +77,7 @@ export function AgentPanel({
const [playgroundSessionIds, setPlaygroundSessionIds] = useState<string[]>(
() => readPlaygroundAgentSessionIds(identityScopeKey),
)
- const { data: historyMessages } = useSessionMessages(sessionId)
+ const { data: historyMessages } = useSessionMessages(historySessionId)
const chat = useChat({
identityScopeKey,
initialMessages: historyMessages,
@@ -81,6 +90,7 @@ export function AgentPanel({
const handleNewSession = useCallback(async () => {
if (isCreatingSession) return
+ const generation = ++creationGenerationRef.current
chat.abort()
chat.setMessages([])
creationStartedRef.current = true
@@ -93,18 +103,25 @@ export function AgentPanel({
12_000,
t('agent.createTimeout'),
)
+ if (generation !== creationGenerationRef.current) return
setPlaygroundSessionIds(
registerPlaygroundAgentSessionId(result.session_id, identityScopeKey),
)
setTitle(result.session_id, t('agent.newSessionTitle'))
+ setHistorySessionId(undefined)
+ setPersistedSessionId(result.session_id)
setSessionId(result.session_id)
onSessionChange(result.session_id)
setHistoryOpen(false)
} catch (error) {
+ if (generation !== creationGenerationRef.current) return
creationStartedRef.current = false
setSessionError(error instanceof Error ? error.message : String(error))
} finally {
- setIsCreatingSession(false)
+ if (generation === creationGenerationRef.current) {
+ creationStartedRef.current = false
+ setIsCreatingSession(false)
+ }
}
}, [
chat,
@@ -118,13 +135,16 @@ export function AgentPanel({
const handleSwitchSession = useCallback(
(nextSessionId: string) => {
+ creationGenerationRef.current += 1
chat.abort()
- creationStartedRef.current = true
+ creationStartedRef.current = false
setSessionError(null)
setIsCreatingSession(false)
setPlaygroundSessionIds(
registerPlaygroundAgentSessionId(nextSessionId, identityScopeKey),
)
+ setHistorySessionId(nextSessionId)
+ setPersistedSessionId(nextSessionId)
setSessionId(nextSessionId)
onSessionChange(nextSessionId)
setHistoryOpen(false)
@@ -132,21 +152,14 @@ export function AgentPanel({
[chat, identityScopeKey, onSessionChange],
)
- // Notify parent of the initial sessionId so the URL stays in sync.
- // The session is lazily created on the backend by the first addMessage call.
- useEffect(() => {
- if (sessionId) {
- onSessionChange(sessionId)
- }
- }, [])
-
+ // Only publish IDs that exist on the server; drafts must not survive in the URL.
useEffect(() => {
- if (sessionId) {
+ if (persistedSessionId) {
setPlaygroundSessionIds(
- registerPlaygroundAgentSessionId(sessionId, identityScopeKey),
+ registerPlaygroundAgentSessionId(persistedSessionId, identityScopeKey),
)
}
- }, [identityScopeKey, sessionId])
+ }, [identityScopeKey, persistedSessionId])
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
@@ -158,10 +171,34 @@ export function AgentPanel({
])
const send = useCallback(
- (message: string) => {
+ async (message: string) => {
+ if (creationStartedRef.current) return false
+ if (!persistedSessionId) {
+ const generation = ++creationGenerationRef.current
+ creationStartedRef.current = true
+ setIsCreatingSession(true)
+ setSessionError(null)
+ try {
+ const result = await createSession.mutateAsync(sessionId)
+ if (generation !== creationGenerationRef.current) return false
+ setPersistedSessionId(result.session_id)
+ onSessionChange(result.session_id)
+ } catch (error) {
+ if (generation === creationGenerationRef.current) {
+ setSessionError(getErrorMessage(error))
+ }
+ return false
+ } finally {
+ if (generation === creationGenerationRef.current) {
+ creationStartedRef.current = false
+ setIsCreatingSession(false)
+ }
+ }
+ }
void chat.send(message)
+ return true
},
- [chat],
+ [chat, createSession, onSessionChange, persistedSessionId, sessionId],
)
const isStreaming = chat.status === 'streaming'
@@ -252,6 +289,7 @@ export function AgentPanel({
) : (
<div className="border-t bg-background/80">
<Composer
+ key={sessionId}
variant="compact"
isStreaming={isStreaming}
onCancel={chat.abort}
diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsx
index b16780fca..6f1216279 100644
--- a/web-studio/src/routes/resources/-components/file-preview.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.tsx
@@ -228,7 +228,9 @@ function directoryLevelPreview(
}
function useDirectoryPreview(file: VikingFsEntry | null) {
- const enabled = Boolean(file?.isDir)
+ const enabled = Boolean(
+ file?.isDir && normalizeDirUri(file.uri) !== 'viking://',
+ )
const abstractQuery = useQuery({
enabled,
queryKey: ['viking-directory-sidecar', file?.uri, 'abstract'],
diff --git a/web-studio/src/routes/resources/-lib/api.test.ts b/web-studio/src/routes/resources/-lib/api.test.ts
index fb525c5c5..fff8379cb 100644
--- a/web-studio/src/routes/resources/-lib/api.test.ts
+++ b/web-studio/src/routes/resources/-lib/api.test.ts
@@ -27,6 +27,16 @@ beforeEach(() => {
})
describe('fetchDirectorySidecarContent', () => {
+ it.each(['abstract', 'overview'] as const)(
+ 'does not read a %s sidecar for the virtual root',
+ async (level) => {
+ await expect(
+ fetchDirectorySidecarContent('viking://', level),
+ ).resolves.toBe('')
+ expect(getContentReadMock).not.toHaveBeenCalled()
+ },
+ )
+
it('reads raw L0/L1 sidecars instead of the body-only semantic accessors', async () => {
getContentReadMock.mockResolvedValue({
data: {
diff --git a/web-studio/src/routes/resources/-lib/api.ts b/web-studio/src/routes/resources/-lib/api.ts
index 52b1b6101..c9d6f7696 100644
--- a/web-studio/src/routes/resources/-lib/api.ts
+++ b/web-studio/src/routes/resources/-lib/api.ts
@@ -164,7 +164,9 @@ export async function fetchDirectorySidecarContent(
uri: string,
level: 'abstract' | 'overview',
): Promise<string> {
- const sidecarUri = `${normalizeDirUri(uri)}.${level}.md`
+ const directoryUri = normalizeDirUri(uri)
+ if (directoryUri === 'viking://') return ''
+ const sidecarUri = `${directoryUri}.${level}.md`
const result = await fetchFileContent(sidecarUri, {
limit: -1,
raw: true,
diff --git a/web-studio/src/routes/sessions/-components/composer.tsx b/web-studio/src/routes/sessions/-components/composer.tsx
index 9d9f3b5c3..8e56c8257 100644
--- a/web-studio/src/routes/sessions/-components/composer.tsx
+++ b/web-studio/src/routes/sessions/-components/composer.tsx
@@ -5,7 +5,7 @@ import { ArrowUpIcon, SquareIcon } from 'lucide-react'
import { cn } from '#/lib/utils'
interface ComposerProps {
- onSend: (message: string) => void
+ onSend: (message: string) => void | boolean | Promise<void | boolean>
onCancel: () => void
isStreaming: boolean
variant?: 'default' | 'compact'
@@ -19,6 +19,8 @@ export function Composer({
}: ComposerProps) {
const { t } = useTranslation('sessions')
const [value, setValue] = useState('')
+ const [isSubmitting, setIsSubmitting] = useState(false)
+ const submittingRef = useRef(false)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const isCompact = variant === 'compact'
@@ -29,16 +31,23 @@ export function Composer({
el.style.height = `${Math.min(el.scrollHeight, 200)}px`
}, [])
- const handleSend = useCallback(() => {
+ const handleSend = useCallback(async () => {
const trimmed = value.trim()
- if (!trimmed) return
- onSend(trimmed)
- setValue('')
- requestAnimationFrame(() => {
- const el = textareaRef.current
- if (el) el.style.height = 'auto'
- })
- }, [value, onSend])
+ if (!trimmed || submittingRef.current || isStreaming) return
+ submittingRef.current = true
+ setIsSubmitting(true)
+ try {
+ const accepted = await onSend(trimmed)
+ if (accepted === false) return
+ // Do not erase text edited while the submission was pending.
+ setValue((current) => (current === value ? '' : current))
+ } catch {
+ // The caller owns error reporting; keep the input available for retry.
+ } finally {
+ submittingRef.current = false
+ setIsSubmitting(false)
+ }
+ }, [value, onSend, isStreaming])
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
@@ -109,7 +118,7 @@ export function Composer({
type="button"
aria-label={t('chat.send')}
onClick={handleSend}
- disabled={!value.trim()}
+ disabled={!value.trim() || isSubmitting}
className={cn(
'inline-flex size-8 items-center justify-center rounded-lg',
'bg-primary text-primary-foreground',