mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 03:14:11 +00:00
refactor(agent)!: migrate to Pi Durable and embed the agent queue (#525)
* refactor(agent)!: migrate sessions to Pi Durable Replace patched AgentHarness storage with per-session SQLite and PostgreSQL commit mirroring. Migrate legacy history automatically and run agent queues with the main server. BREAKING CHANGE: Remove standalone agent workers and return native Pi entry records from chat history APIs. * fix(agent): constrain session log dialog scrolling Keep the header visible and wrap long output while log entries and expanded records scroll within the dialog. Cover desktop and narrow viewports through the dashboard Sessions flow. * fix(agent): hide entry IDs from session log card headers Retain internal entry IDs in expanded raw records for debugging. Verify that card headers omit the IDs while raw JSON preserves them. * test(e2e): handle browser wheel limits in session log checks Verify that a normal wheel event moves the viewport before explicitly scrolling to the final record. Keep the dialog bounds, fixed header, wrapping, and expanded-record assertions. * fix(agent): select model providers without inheriting unrelated auth * fix(webui): prevent resize feedback when toggling agent panel * test(agent): reproduce concurrent comment session races * fix(agent): serialize comment sessions and deduplicate history * docs(changelog): consolidate Pi Durable changes into one entry
This commit is contained in:
@@ -1,5 +1,3 @@
|
||||
import React from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import {
|
||||
Dialog,
|
||||
@@ -8,13 +6,15 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Separator } from '@/ui/components/ui/separator'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { Skeleton } from '@/ui/components/ui/skeleton'
|
||||
import { formatTimeAgo } from '@/ui/lib/time'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { EntryRecord } from '@earendil-works/pi-durable'
|
||||
import { getShumaiMessage, serializeContextToXml } from '@shumai/dtos'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Terminal } from 'lucide-react'
|
||||
import Markdown from 'react-markdown'
|
||||
import { serializeContextToXml, type ShumaiMessageContext } from '@shumai/dtos'
|
||||
|
||||
interface AgentSessionLogsDialogProps {
|
||||
sessionId?: string | null
|
||||
@@ -22,8 +22,43 @@ interface AgentSessionLogsDialogProps {
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
const preprocessMarkdown = (text: string): string => {
|
||||
return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:')
|
||||
function EntryLog({ entry }: { entry: EntryRecord }) {
|
||||
const application = getShumaiMessage(entry)
|
||||
const message = entry.model?.[0]
|
||||
const timestamp = application?.timestamp ?? message?.timestamp
|
||||
const content = application
|
||||
? `${application.displayText}\n\n${serializeContextToXml(application.context)}`
|
||||
: message && typeof message.content === 'string'
|
||||
? message.content
|
||||
: (Array.isArray(message?.content) ? message.content : [])
|
||||
.filter((block) => block.type === 'text')
|
||||
.map((block) => block.text)
|
||||
.join('\n')
|
||||
const role =
|
||||
application || message?.role === 'user'
|
||||
? m.role_user()
|
||||
: message?.role === 'assistant'
|
||||
? m.role_agent()
|
||||
: message?.role === 'toolResult'
|
||||
? m.tool_result_with_name({ name: message.toolName })
|
||||
: entry.kind
|
||||
return (
|
||||
<div className="min-w-0 rounded-lg border border-border bg-muted/30 p-3 space-y-2 [overflow-wrap:anywhere]">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<span className="font-semibold text-foreground">{role}</span>
|
||||
{timestamp !== undefined && <span>{formatTimeAgo(new Date(timestamp).toISOString())}</span>}
|
||||
</div>
|
||||
{content && (
|
||||
<div className="text-xs whitespace-pre-wrap break-words [&_pre]:whitespace-pre-wrap [&_pre]:break-all">
|
||||
<Markdown>{content}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
<details className="text-xs text-muted-foreground">
|
||||
<summary className="cursor-pointer font-mono">{entry.kind}</summary>
|
||||
<pre className="mt-2 whitespace-pre-wrap break-all">{JSON.stringify(entry, null, 2)}</pre>
|
||||
</details>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function AgentSessionLogsDialog({
|
||||
@@ -31,373 +66,37 @@ export function AgentSessionLogsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: AgentSessionLogsDialogProps) {
|
||||
const { data: logs, isLoading: isLogsLoading } = useQuery({
|
||||
const { data: entries, isLoading } = useQuery({
|
||||
queryKey: ['agent-sessions', sessionId, 'entries'],
|
||||
queryFn: async () => {
|
||||
if (!sessionId) return []
|
||||
const res = await client.api['agent-sessions'][':sessionId'].entries.$get({
|
||||
const response = await client.api['agent-sessions'][':sessionId'].entries.$get({
|
||||
param: { sessionId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch session logs')
|
||||
return await res.json()
|
||||
if (!response.ok) throw new Error('Failed to fetch session logs')
|
||||
return (await response.json()) as EntryRecord[]
|
||||
},
|
||||
enabled: open && !!sessionId,
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[80vh] flex flex-col p-6 overflow-hidden bg-background/95 backdrop-blur-md border border-foreground/15 shadow-2xl">
|
||||
<DialogHeader className="pb-4 border-b border-foreground/15">
|
||||
<DialogTitle className="flex items-center gap-2 text-xl font-bold">
|
||||
<Terminal className="w-5 h-5 text-violet-500" />
|
||||
<DialogContent className="sm:max-w-2xl h-[80dvh] max-h-[80dvh] flex flex-col overflow-hidden">
|
||||
<DialogHeader className="shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Terminal className="h-5 w-5" />
|
||||
{m.agent_session_logs()}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{m.agent_logs_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto pr-1 py-4 space-y-4 min-h-0 select-text">
|
||||
{isLogsLoading ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-4">
|
||||
<Skeleton className="h-5 w-5 rounded-full shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-1/4" />
|
||||
<Skeleton className="h-20 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<Skeleton className="h-5 w-5 rounded-full shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-1/4" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : logs && logs.length > 0 ? (
|
||||
<div className="flex flex-col">
|
||||
{logs.map((entry) => {
|
||||
const piEntry = entry.entry as Record<string, unknown> | null
|
||||
const timestampStr =
|
||||
piEntry?.timestamp || (entry as Record<string, unknown>).timestamp
|
||||
let timestamp = ''
|
||||
if (typeof timestampStr === 'string' || typeof timestampStr === 'number') {
|
||||
const dateObj = new Date(timestampStr)
|
||||
if (!isNaN(dateObj.getTime())) {
|
||||
timestamp = formatTimeAgo(dateObj.toISOString())
|
||||
}
|
||||
}
|
||||
|
||||
if (piEntry && typeof piEntry === 'object') {
|
||||
if (piEntry.type === 'custom_message') {
|
||||
if (piEntry.customType === 'context') return null
|
||||
if (piEntry.customType === 'shumai_message') {
|
||||
const xml = serializeContextToXml(piEntry.details as ShumaiMessageContext)
|
||||
const text = typeof piEntry.content === 'string' ? piEntry.content : ''
|
||||
const fullText = xml ? `${text}\n\n${xml}`.trim() : text
|
||||
const badgeColor = 'bg-primary/10 text-primary'
|
||||
const roleName = m.role_user()
|
||||
|
||||
return (
|
||||
<div key={entry.id} className="relative pl-6 pb-6 last:pb-0">
|
||||
{/* Timeline Line */}
|
||||
<div className="absolute left-[9px] top-2 bottom-0 w-0.5 bg-foreground/10 last:hidden" />
|
||||
|
||||
{/* Timeline Node */}
|
||||
<div className="absolute left-0 top-1.5 h-5 w-5 rounded-full border-4 border-background flex items-center justify-center bg-primary" />
|
||||
|
||||
<div className="flex flex-col gap-1.5 bg-muted/30 dark:bg-muted/10 p-3 rounded-lg border border-foreground/5 backdrop-blur-xs w-full">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span
|
||||
className={`text-[10px] px-2 py-0.5 rounded-full font-semibold uppercase tracking-wider ${badgeColor}`}
|
||||
>
|
||||
{roleName}
|
||||
</span>
|
||||
<span
|
||||
className="text-[10px] font-mono text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded border border-foreground/10 select-all"
|
||||
title={m.entry_id()}
|
||||
>
|
||||
{m.entry_id()}: {entry.id}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground/60 shrink-0">
|
||||
{timestamp}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-foreground/90 whitespace-pre-wrap leading-relaxed font-sans">
|
||||
{fullText}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (piEntry.type === 'message' && piEntry.message) {
|
||||
const msg = piEntry.message as Record<string, unknown>
|
||||
let badgeColor = 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200'
|
||||
let roleName: string = String(msg.role || '')
|
||||
|
||||
if (msg.role === 'user') {
|
||||
badgeColor = 'bg-primary/10 text-primary'
|
||||
roleName = m.role_user()
|
||||
} else if (msg.role === 'assistant') {
|
||||
badgeColor =
|
||||
'bg-violet-100 text-violet-800 dark:bg-violet-900/30 dark:text-violet-300'
|
||||
roleName = m.role_agent()
|
||||
} else if (msg.role === 'toolResult') {
|
||||
badgeColor = msg.isError
|
||||
? 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300'
|
||||
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300'
|
||||
roleName = m.tool_result_with_name({
|
||||
name: String(msg.toolName || m.unknown()),
|
||||
})
|
||||
} else if (msg.role === 'thought') {
|
||||
badgeColor =
|
||||
'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300'
|
||||
roleName = m.role_thinking()
|
||||
}
|
||||
|
||||
const renderToolCallArguments = (args: unknown) => {
|
||||
let parsedArgs: unknown = args
|
||||
if (typeof args === 'string') {
|
||||
try {
|
||||
parsedArgs = JSON.parse(args)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
parsedArgs &&
|
||||
typeof parsedArgs === 'object' &&
|
||||
!Array.isArray(parsedArgs)
|
||||
) {
|
||||
const obj = parsedArgs as Record<string, unknown>
|
||||
return (
|
||||
<div className="mt-1 space-y-1.5 pt-3">
|
||||
{Object.entries(obj).map(([key, value]) => {
|
||||
const valueStr =
|
||||
value && typeof value === 'object'
|
||||
? JSON.stringify(value, null, 2)
|
||||
: String(value)
|
||||
return (
|
||||
<div key={key} className="text-xs leading-relaxed break-words">
|
||||
<span className="font-semibold text-violet-600 dark:text-violet-400">
|
||||
{key}:
|
||||
</span>{' '}
|
||||
<span className="text-foreground/90 font-mono whitespace-pre-wrap">
|
||||
{valueStr}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-xs font-mono whitespace-pre-wrap">{String(args)}</div>
|
||||
)
|
||||
}
|
||||
|
||||
const renderMessageContent = () => {
|
||||
const content = msg.content
|
||||
if (!content) return null
|
||||
|
||||
if (typeof content === 'string') {
|
||||
if (!content.trim()) return null
|
||||
return (
|
||||
<div className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words">
|
||||
<Markdown>{preprocessMarkdown(content)}</Markdown>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
const renderedBlocks: React.ReactNode[] = []
|
||||
|
||||
content.forEach((item, idx) => {
|
||||
if (!item) return
|
||||
|
||||
if (typeof item === 'string') {
|
||||
if (!item.trim()) return
|
||||
renderedBlocks.push(
|
||||
<div
|
||||
key={`str-${idx}`}
|
||||
className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words"
|
||||
>
|
||||
<Markdown>{preprocessMarkdown(item)}</Markdown>
|
||||
</div>,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof item === 'object') {
|
||||
const itemObj = item as Record<string, unknown>
|
||||
const type = itemObj.type
|
||||
if (type === 'text') {
|
||||
const text = itemObj.text
|
||||
if (typeof text !== 'string' || !text.trim()) return
|
||||
renderedBlocks.push(
|
||||
<div
|
||||
key={`txt-${idx}`}
|
||||
className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words"
|
||||
>
|
||||
<Markdown>{preprocessMarkdown(text)}</Markdown>
|
||||
</div>,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (type === 'toolCall') {
|
||||
const toolName = String(
|
||||
itemObj.name || itemObj.toolName || m.unknown(),
|
||||
)
|
||||
const toolArgs = itemObj.arguments || itemObj.args
|
||||
renderedBlocks.push(
|
||||
<div key={`tool-${idx}`} className="text-xs space-y-2 py-1">
|
||||
<div className="font-semibold text-violet-600 dark:text-violet-400 flex items-center gap-1.5">
|
||||
{m.calling_tool()}{' '}
|
||||
<span className="font-mono bg-violet-500/10 px-1 py-0.5 rounded text-[11px]">
|
||||
{toolName}
|
||||
</span>
|
||||
</div>
|
||||
{!!toolArgs && (
|
||||
<div className="space-y-1 pt-3">
|
||||
<div className="text-[10px] text-muted-foreground/60 uppercase font-bold tracking-wider">
|
||||
{m.tool_arguments()}
|
||||
</div>
|
||||
{renderToolCallArguments(toolArgs)}
|
||||
</div>
|
||||
)}
|
||||
</div>,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (type === 'image') {
|
||||
renderedBlocks.push(
|
||||
<div
|
||||
key={`img-${idx}`}
|
||||
className="text-xs text-muted-foreground italic flex items-center gap-1.5 py-1"
|
||||
>
|
||||
{m.image_object()}
|
||||
</div>,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Fallback for other object types
|
||||
const stringified = JSON.stringify(item, null, 2)
|
||||
if (stringified === '{}') return
|
||||
renderedBlocks.push(
|
||||
<pre
|
||||
key={`other-${idx}`}
|
||||
className="text-xs text-foreground/80 font-mono whitespace-pre-wrap break-words bg-muted/20 p-2 rounded"
|
||||
>
|
||||
{stringified}
|
||||
</pre>,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
if (renderedBlocks.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className="space-y-3 w-full">
|
||||
{renderedBlocks.map((block, index) => (
|
||||
<React.Fragment key={index}>
|
||||
{index > 0 && <Separator className="my-3 opacity-50" />}
|
||||
{block}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={entry.id} className="relative pl-6 pb-6 last:pb-0">
|
||||
{/* Timeline Line */}
|
||||
<div className="absolute left-[9px] top-2 bottom-0 w-0.5 bg-foreground/10 last:hidden" />
|
||||
|
||||
{/* Timeline Node */}
|
||||
<div
|
||||
className={`absolute left-0 top-1.5 h-5 w-5 rounded-full border-4 border-background flex items-center justify-center ${
|
||||
msg.role === 'user'
|
||||
? 'bg-primary'
|
||||
: msg.role === 'assistant'
|
||||
? 'bg-violet-500'
|
||||
: msg.role === 'toolResult'
|
||||
? msg.isError
|
||||
? 'bg-red-500'
|
||||
: 'bg-emerald-500'
|
||||
: 'bg-amber-500'
|
||||
}`}
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-1.5 bg-muted/30 dark:bg-muted/10 p-3 rounded-lg border border-foreground/5 backdrop-blur-xs w-full">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span
|
||||
className={`text-[10px] px-2 py-0.5 rounded-full font-semibold uppercase tracking-wider ${badgeColor}`}
|
||||
>
|
||||
{roleName}
|
||||
</span>
|
||||
<span
|
||||
className="text-[10px] font-mono text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded border border-foreground/10 select-all"
|
||||
title={m.entry_id()}
|
||||
>
|
||||
{m.entry_id()}: {entry.id}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground/60 shrink-0">
|
||||
{timestamp}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{renderMessageContent()}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for non-message entries or arbitrary entries
|
||||
return (
|
||||
<div key={entry.id} className="relative pl-6 pb-6 last:pb-0">
|
||||
<div className="absolute left-[9px] top-2 bottom-0 w-0.5 bg-foreground/10 last:hidden" />
|
||||
<div className="absolute left-0 top-1.5 h-5 w-5 rounded-full border-4 border-background bg-gray-400" />
|
||||
<div className="bg-muted/30 p-3 rounded-lg border border-foreground/5">
|
||||
<div className="flex items-center justify-between gap-2 mb-1.5 flex-wrap">
|
||||
<span
|
||||
className="text-[10px] font-mono text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded border border-foreground/10 select-all"
|
||||
title="Entry ID"
|
||||
>
|
||||
ID: {entry.id}
|
||||
</span>
|
||||
<div className="text-[10px] text-muted-foreground/60">{timestamp}</div>
|
||||
</div>
|
||||
<pre className="text-xs text-foreground/80 font-mono whitespace-pre-wrap break-words">
|
||||
{JSON.stringify(entry.entry, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center text-muted-foreground">
|
||||
<Terminal className="w-8 h-8 text-muted-foreground/40 mb-2 animate-pulse" />
|
||||
<p className="text-sm font-medium">{m.no_logs_found()}</p>
|
||||
<p className="text-xs text-muted-foreground/60 mt-1">{m.session_no_entries_yet()}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<ScrollArea className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
||||
<div className="space-y-3 pr-3 py-2">
|
||||
{isLoading ? (
|
||||
<Skeleton className="h-32 w-full" />
|
||||
) : (
|
||||
entries?.map((entry) => <EntryLog key={entry.id} entry={entry} />)
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render, waitFor } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { ChatbotSidebar } from './chatbot-sidebar'
|
||||
import { useChatbotStore, AGENT_PREFERENCE_STORAGE_KEY } from '@/ui/stores/chatbot'
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { ChatMessage } from '@shumai/dtos'
|
||||
import { AGENT_PREFERENCE_STORAGE_KEY, useChatbotStore } from '@/ui/stores/chatbot'
|
||||
import { type EntryRecord } from '@shumai/dtos'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { cleanup, render, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ChatbotSidebar } from './chatbot-sidebar'
|
||||
|
||||
const localStorageMock = (() => {
|
||||
let store: Record<string, string> = {}
|
||||
@@ -203,20 +202,24 @@ describe('ChatbotSidebar - Agent Selection & Preference Persistence', () => {
|
||||
const mockSelectMessage = vi.fn()
|
||||
|
||||
const mockMessage = {
|
||||
id: 'msg-1',
|
||||
role: 'custom',
|
||||
customType: 'shumai_message',
|
||||
content: 'Fix the color in this scene',
|
||||
details: {
|
||||
annotation: true,
|
||||
annotations: [{ type: 'rectangle', x: 5, y: 10 }],
|
||||
position: { type: 'time', seconds: 15 },
|
||||
currentAsset: { id: 'file-123', name: 'video.mp4', type: 'file' },
|
||||
attachedFiles: [
|
||||
{ id: 'att-1', name: 'color-ref.png', type: 'image', mediaType: 'image/png' },
|
||||
],
|
||||
id: 10,
|
||||
conversationId: 1,
|
||||
kind: 'shumai.message',
|
||||
model: [{ role: 'user', content: 'Fix the color in this scene', timestamp: 0 }],
|
||||
data: {
|
||||
displayText: 'Fix the color in this scene',
|
||||
timestamp: 0,
|
||||
context: {
|
||||
annotation: true,
|
||||
annotations: [{ type: 'rectangle', x: 5, y: 10 }],
|
||||
position: { type: 'time', seconds: 15 },
|
||||
currentAsset: { id: 'file-123', name: 'video.mp4', type: 'file' },
|
||||
attachedFiles: [
|
||||
{ id: 'att-1', name: 'color-ref.png', type: 'image', mediaType: 'image' },
|
||||
],
|
||||
},
|
||||
},
|
||||
} as unknown as ChatMessage
|
||||
} as unknown as EntryRecord
|
||||
|
||||
useChatbotStore.setState({
|
||||
messages: [mockMessage],
|
||||
@@ -247,15 +250,19 @@ describe('ChatbotSidebar - Agent Selection & Preference Persistence', () => {
|
||||
|
||||
it('renders selected message card with border-blue-500 instead of ring when selectedMessageId matches', async () => {
|
||||
const mockMessage = {
|
||||
id: 'msg-selected',
|
||||
role: 'custom',
|
||||
customType: 'shumai_message',
|
||||
content: 'Selected message content',
|
||||
details: {
|
||||
position: { type: 'time', seconds: 10 },
|
||||
currentAsset: { id: 'file-123', name: 'video.mp4', type: 'file' },
|
||||
id: 11,
|
||||
conversationId: 1,
|
||||
kind: 'shumai.message',
|
||||
model: [{ role: 'user', content: 'Selected message content', timestamp: 0 }],
|
||||
data: {
|
||||
displayText: 'Selected message content',
|
||||
timestamp: 0,
|
||||
context: {
|
||||
position: { type: 'time', seconds: 10 },
|
||||
currentAsset: { id: 'file-123', name: 'video.mp4', type: 'file' },
|
||||
},
|
||||
},
|
||||
} as unknown as ChatMessage
|
||||
} as unknown as EntryRecord
|
||||
|
||||
useChatbotStore.setState({
|
||||
messages: [mockMessage],
|
||||
@@ -263,11 +270,7 @@ describe('ChatbotSidebar - Agent Selection & Preference Persistence', () => {
|
||||
|
||||
const { getByText } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ChatbotSidebar
|
||||
projectId="proj-1"
|
||||
contextAssetId="file-123"
|
||||
selectedMessageId="msg-selected"
|
||||
/>
|
||||
<ChatbotSidebar projectId="proj-1" contextAssetId="file-123" selectedMessageId="11" />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
@@ -287,17 +290,21 @@ describe('ChatbotSidebar - Agent Selection & Preference Persistence', () => {
|
||||
const mockSelectMessage = vi.fn()
|
||||
|
||||
const mockMessage = {
|
||||
id: 'msg-2',
|
||||
role: 'custom',
|
||||
customType: 'shumai_message',
|
||||
content: 'Other file comment',
|
||||
details: {
|
||||
annotation: true,
|
||||
annotations: [{ type: 'rectangle', x: 5, y: 10 }],
|
||||
position: { type: 'time', seconds: 20 },
|
||||
currentAsset: { id: 'other-file-456', name: 'other.mp4', type: 'file' },
|
||||
id: 12,
|
||||
conversationId: 1,
|
||||
kind: 'shumai.message',
|
||||
model: [{ role: 'user', content: 'Other file comment', timestamp: 0 }],
|
||||
data: {
|
||||
displayText: 'Other file comment',
|
||||
timestamp: 0,
|
||||
context: {
|
||||
annotation: true,
|
||||
annotations: [{ type: 'rectangle', x: 5, y: 10 }],
|
||||
position: { type: 'time', seconds: 20 },
|
||||
currentAsset: { id: 'other-file-456', name: 'other.mp4', type: 'file' },
|
||||
},
|
||||
},
|
||||
} as unknown as ChatMessage
|
||||
} as unknown as EntryRecord
|
||||
|
||||
useChatbotStore.setState({
|
||||
messages: [mockMessage],
|
||||
@@ -328,33 +335,37 @@ describe('ChatbotSidebar - Agent Selection & Preference Persistence', () => {
|
||||
>)
|
||||
|
||||
const mockMessage = {
|
||||
id: 'msg-full',
|
||||
role: 'custom',
|
||||
customType: 'shumai_message',
|
||||
content: 'Review this scene carefully',
|
||||
details: {
|
||||
annotation: true,
|
||||
annotations: [
|
||||
{
|
||||
type: 'box',
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[0, 0],
|
||||
[10, 10],
|
||||
],
|
||||
},
|
||||
],
|
||||
position: { type: 'time', seconds: 45 },
|
||||
currentAsset: { id: 'file-123', name: 'clip.mp4', type: 'file' },
|
||||
attachedFiles: [
|
||||
{ id: 'att-1', name: 'reference-mood.jpg', type: 'image', mediaType: 'image/jpeg' },
|
||||
],
|
||||
referencedAssets: [
|
||||
{ id: 'asset-ref-1', name: 'Storyboard.pdf', type: 'file' },
|
||||
{ id: 'asset-ref-2', name: 'Audio Stems', type: 'folder' },
|
||||
],
|
||||
id: 13,
|
||||
conversationId: 1,
|
||||
kind: 'shumai.message',
|
||||
model: [{ role: 'user', content: 'Review this scene carefully', timestamp: 0 }],
|
||||
data: {
|
||||
displayText: 'Review this scene carefully',
|
||||
timestamp: 0,
|
||||
context: {
|
||||
annotation: true,
|
||||
annotations: [
|
||||
{
|
||||
type: 'box',
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[0, 0],
|
||||
[10, 10],
|
||||
],
|
||||
},
|
||||
],
|
||||
position: { type: 'time', seconds: 45 },
|
||||
currentAsset: { id: 'file-123', name: 'clip.mp4', type: 'file' },
|
||||
attachedFiles: [
|
||||
{ id: 'att-1', name: 'reference-mood.jpg', type: 'image', mediaType: 'image' },
|
||||
],
|
||||
referencedAssets: [
|
||||
{ id: 'asset-ref-1', name: 'Storyboard.pdf', type: 'file' },
|
||||
{ id: 'asset-ref-2', name: 'Audio Stems', type: 'folder' },
|
||||
],
|
||||
},
|
||||
},
|
||||
} as unknown as ChatMessage
|
||||
} as unknown as EntryRecord
|
||||
|
||||
useChatbotStore.setState({
|
||||
messages: [mockMessage],
|
||||
@@ -434,11 +445,11 @@ describe('ChatbotSidebar - Agent Selection & Preference Persistence', () => {
|
||||
|
||||
it('renders thinking_level_change messages properly in the chat log', () => {
|
||||
const mockThinkingChangeMsg = {
|
||||
id: 'think-1',
|
||||
role: 'thinking_level_change',
|
||||
content: 'Thinking level changed to high',
|
||||
timestamp: Date.now(),
|
||||
} as unknown as ChatMessage
|
||||
id: 14,
|
||||
conversationId: 1,
|
||||
kind: 'shumai.thinking_level_change',
|
||||
data: { thinkingLevel: 'high' },
|
||||
} as unknown as EntryRecord
|
||||
|
||||
useChatbotStore.setState({
|
||||
messages: [mockThinkingChangeMsg],
|
||||
@@ -450,7 +461,7 @@ describe('ChatbotSidebar - Agent Selection & Preference Persistence', () => {
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(getByText('Thinking level changed to high')).toBeTruthy()
|
||||
expect(getByText('Thinking Level: high')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('disables message input when teamId is not available', async () => {
|
||||
|
||||
@@ -7,13 +7,16 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { isImageFileName } from '@/ui/lib/media'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useChatbotStore } from '@/ui/stores/chatbot'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { useDroppable } from '@dnd-kit/react'
|
||||
import type { AssetInfo, ChatMessage, ShumaiMessageContext } from '@shumai/dtos'
|
||||
import type { EntryRecord } from '@earendil-works/pi-durable'
|
||||
import type { AssetInfo, ShumaiMessageContext } from '@shumai/dtos'
|
||||
import { getShumaiMessage } from '@shumai/dtos'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
ArrowLeft,
|
||||
@@ -36,7 +39,6 @@ import { formatTimeAgo } from '../lib/time'
|
||||
import { ChatInput } from './chat/message-input'
|
||||
import { DrawAnnotation } from './ui/icons'
|
||||
import { formatTimecode } from './viewers/video/utils'
|
||||
import { isImageFileName } from '@/ui/lib/media'
|
||||
|
||||
interface ChatbotSidebarProps {
|
||||
projectId: string
|
||||
@@ -47,7 +49,7 @@ interface ChatbotSidebarProps {
|
||||
startTimecode?: string
|
||||
formatTimestamp?: (second: number) => string
|
||||
onTyping?: () => void
|
||||
onSelectMessage?: (message: ChatMessage) => void
|
||||
onSelectMessage?: (message: EntryRecord) => void
|
||||
selectedMessageId?: string | null
|
||||
}
|
||||
|
||||
@@ -236,19 +238,31 @@ export function ChatbotSidebar({
|
||||
return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:')
|
||||
}
|
||||
|
||||
const renderMessage = (msg: ChatMessage) => {
|
||||
switch (msg.role as string) {
|
||||
const renderMessage = (entry: EntryRecord) => {
|
||||
const applicationMessage = getShumaiMessage(entry)
|
||||
const msg = entry.model?.[0]
|
||||
const role: string | undefined = applicationMessage
|
||||
? 'user'
|
||||
: entry.kind === 'shumai.thinking_level_change'
|
||||
? 'thinking_level_change'
|
||||
: entry.kind === 'pi.compaction'
|
||||
? 'system'
|
||||
: msg?.role
|
||||
const payload = applicationMessage
|
||||
? { content: applicationMessage.displayText, details: applicationMessage.context }
|
||||
: (msg ?? entry.data ?? {})
|
||||
switch (role) {
|
||||
case 'user':
|
||||
case 'custom': {
|
||||
const msgObj = msg as unknown as Record<string, unknown>
|
||||
if (msg.role === 'custom' && msgObj.customType === 'context_display_info') {
|
||||
const msgObj = payload as unknown as Record<string, unknown>
|
||||
if (role === 'custom' && msgObj.customType === 'context_display_info') {
|
||||
const details = msgObj.details as
|
||||
{ assets?: Array<{ id: string; name: string; type: string }> } | undefined
|
||||
const assets = details?.assets || []
|
||||
if (assets.length === 0) return null
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
key={entry.id}
|
||||
className="text-xs text-muted-foreground bg-muted/40 p-2.5 rounded-lg border border-border/50 space-y-1 my-1"
|
||||
>
|
||||
<div className="font-semibold">{m.assets_added_to_context()}</div>
|
||||
@@ -262,7 +276,7 @@ export function ChatbotSidebar({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (msg.role === 'user' || msgObj.customType === 'shumai_message') {
|
||||
if (role === 'user' || msgObj.customType === 'shumai_message') {
|
||||
const details = msgObj.details as ShumaiMessageContext | undefined
|
||||
const referencedAssets = details?.referencedAssets || []
|
||||
const attachedFiles = details?.attachedFiles || []
|
||||
@@ -273,7 +287,7 @@ export function ChatbotSidebar({
|
||||
!details?.currentAsset?.id ||
|
||||
(contextAssetId && details.currentAsset.id === contextAssetId) ||
|
||||
(file?.id && details.currentAsset.id === file.id)
|
||||
const isSelected = selectedMessageId === msg.id
|
||||
const isSelected = selectedMessageId === String(entry.id)
|
||||
let timeStr = ''
|
||||
if (position?.type === 'time') {
|
||||
if (formatTimestamp) {
|
||||
@@ -293,12 +307,12 @@ export function ChatbotSidebar({
|
||||
const hasAttachmentsOrAssets = attachedFiles.length > 0 || referencedAssets.length > 0
|
||||
const handleCardClick = () => {
|
||||
if (isCurrentAssetMatch && onSelectMessage) {
|
||||
onSelectMessage(msg)
|
||||
onSelectMessage(entry)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
key={entry.id}
|
||||
onClick={handleCardClick}
|
||||
className={cn(
|
||||
'flex flex-col items-end w-full group transition-all duration-150',
|
||||
@@ -434,10 +448,14 @@ export function ChatbotSidebar({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const systemContent = msgObj.content || ''
|
||||
const systemContent =
|
||||
msgObj.content ||
|
||||
(typeof msgObj.thinkingLevel === 'string'
|
||||
? `${m.thinking_level()}: ${msgObj.thinkingLevel}`
|
||||
: '')
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
key={entry.id}
|
||||
className="text-center text-xs text-muted-foreground italic bg-muted/20 py-1.5 rounded"
|
||||
>
|
||||
{getMessageText(systemContent)}
|
||||
@@ -445,7 +463,7 @@ export function ChatbotSidebar({
|
||||
)
|
||||
}
|
||||
case 'assistant': {
|
||||
const msgObj = msg as unknown as Record<string, unknown>
|
||||
const msgObj = payload as unknown as Record<string, unknown>
|
||||
const content = msgObj.content as unknown[]
|
||||
if (!content) return null
|
||||
const renderedBlocks: React.ReactNode[] = []
|
||||
@@ -576,7 +594,7 @@ export function ChatbotSidebar({
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div key={msg.id} className="flex flex-col w-full space-y-1">
|
||||
<div key={entry.id} className="flex flex-col w-full space-y-1">
|
||||
<div className="space-y-2 w-full">{renderedBlocks}</div>
|
||||
{shouldShowFooter && (
|
||||
<div className="text-[10px] text-muted-foreground self-start italic pt-1">
|
||||
@@ -589,21 +607,27 @@ export function ChatbotSidebar({
|
||||
case 'toolResult': {
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
key={entry.id}
|
||||
className="flex items-center gap-2 text-xs text-muted-foreground bg-muted/40 p-2 rounded-md border border-border/50"
|
||||
>
|
||||
<span className="font-semibold">
|
||||
{m.tool_result_with_name({ name: (msg as { toolName?: string }).toolName || 'tool' })}
|
||||
{m.tool_result_with_name({
|
||||
name: (msg as { toolName?: string } | undefined)?.toolName || 'tool',
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
case 'thinking_level_change': {
|
||||
const msgObj = msg as unknown as Record<string, unknown>
|
||||
const systemContent = msgObj.content || ''
|
||||
const msgObj = payload as unknown as Record<string, unknown>
|
||||
const systemContent =
|
||||
msgObj.content ||
|
||||
(typeof msgObj.thinkingLevel === 'string'
|
||||
? `${m.thinking_level()}: ${msgObj.thinkingLevel}`
|
||||
: '')
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
key={entry.id}
|
||||
className="text-center text-xs text-muted-foreground italic bg-muted/20 py-1.5 rounded"
|
||||
>
|
||||
{getMessageText(systemContent)}
|
||||
@@ -749,12 +773,9 @@ export function ChatbotSidebar({
|
||||
{messages.map(renderMessage)}
|
||||
{isStreaming &&
|
||||
messages.length > 0 &&
|
||||
(messages[messages.length - 1].role === 'user' ||
|
||||
(
|
||||
messages[messages.length - 1] as unknown as {
|
||||
customType?: string
|
||||
}
|
||||
).customType === 'shumai_message') && (
|
||||
['pi.user', 'shumai.message', 'shumai.optimistic'].includes(
|
||||
messages[messages.length - 1].kind,
|
||||
) && (
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted-foreground italic">
|
||||
<Loader2 className="h-3 w-3 animate-spin text-primary" />
|
||||
<span>{m.thinking_status()}</span>
|
||||
|
||||
@@ -117,6 +117,7 @@ export function FileBrowserGridView({
|
||||
const [cols, setCols] = useState(5)
|
||||
|
||||
useEffect(() => {
|
||||
let resizeFrame = 0
|
||||
const updateCols = () => {
|
||||
if (!containerRef.current) return
|
||||
const width = containerRef.current.offsetWidth
|
||||
@@ -128,9 +129,16 @@ export function FileBrowserGridView({
|
||||
}
|
||||
|
||||
updateCols()
|
||||
const observer = new ResizeObserver(updateCols)
|
||||
const observer = new ResizeObserver(() => {
|
||||
// Defer column changes so row measurements do not feed back into resize delivery.
|
||||
cancelAnimationFrame(resizeFrame)
|
||||
resizeFrame = requestAnimationFrame(updateCols)
|
||||
})
|
||||
if (containerRef.current) observer.observe(containerRef.current)
|
||||
return () => observer.disconnect()
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
cancelAnimationFrame(resizeFrame)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const rows = useMemo(() => {
|
||||
|
||||
@@ -10,11 +10,16 @@ if (typeof window !== 'undefined') {
|
||||
'ResizeObserver loop limit exceeded',
|
||||
'ResizeObserver loop completed with undelivered notifications.',
|
||||
]
|
||||
window.addEventListener('error', (e) => {
|
||||
if (resizeObserverErrorNames.includes(e.message)) {
|
||||
e.stopImmediatePropagation()
|
||||
}
|
||||
})
|
||||
// Capture these warnings before Bun's development overlay handles them.
|
||||
window.addEventListener(
|
||||
'error',
|
||||
(e) => {
|
||||
if (resizeObserverErrorNames.includes(e.message)) {
|
||||
e.stopImmediatePropagation()
|
||||
}
|
||||
},
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
const queryClient = new QueryClient()
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
"@dnd-kit/abstract": "0.5.0",
|
||||
"@dnd-kit/dom": "0.5.0",
|
||||
"@dnd-kit/react": "0.5.0",
|
||||
"@earendil-works/pi-ai": "1.5.0",
|
||||
"@earendil-works/pi-durable": "1.5.0",
|
||||
"@ferrucc-io/emoji-picker": "0.1.2",
|
||||
"@hookform/resolvers": "5.9.1",
|
||||
"@lexical/code": "0.49.0",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { ArchiveConfirmDialog } from '@/ui/components/archive-confirm-dialog'
|
||||
import { ChatbotSidebar } from '@/ui/components/chatbot-sidebar'
|
||||
import { pickDefaultCompareVersions } from '@/ui/components/compare/compare-utils'
|
||||
import { CompareViewer } from '@/ui/components/compare/compare-viewer'
|
||||
@@ -6,11 +7,10 @@ import { FileViewer } from '@/ui/components/file-viewer'
|
||||
import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
|
||||
import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
|
||||
import { MobileFileDetail } from '@/ui/components/file-viewer/mobile-file-detail'
|
||||
import { ArchiveConfirmDialog } from '@/ui/components/archive-confirm-dialog'
|
||||
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
|
||||
import { useIsMobile } from '@/ui/hooks/use-mobile'
|
||||
import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { ResizeHandle } from '@/ui/components/resize-handle'
|
||||
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
|
||||
import { useIsMobile } from '@/ui/hooks/use-mobile'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import { useChatbotStore } from '@/ui/stores/chatbot'
|
||||
@@ -20,6 +20,8 @@ import { useTopNavStore } from '@/ui/stores/top-nav'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
|
||||
import { type Annotation } from '@/ui/types'
|
||||
import type { EntryRecord } from '@earendil-works/pi-durable'
|
||||
import { getShumaiMessage } from '@shumai/dtos'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { InferRequestType, InferResponseType } from 'hono/client'
|
||||
@@ -43,20 +45,14 @@ import {
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
|
||||
import { toast } from 'sonner'
|
||||
import type { MediaController } from '@/ui/components/viewers/types'
|
||||
import type {
|
||||
AssetInfo,
|
||||
AssetInfoPaginatedList,
|
||||
ChatMessage,
|
||||
CommentInfo,
|
||||
ShumaiMessageContext,
|
||||
} from '@shumai/dtos'
|
||||
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
|
||||
import type { AssetInfo, AssetInfoPaginatedList, CommentInfo } from '@shumai/dtos'
|
||||
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
function FileViewPage() {
|
||||
const { projectId, fileId } = Route.useParams()
|
||||
@@ -644,10 +640,9 @@ function FileViewPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleChatMessageSelect = (msg: ChatMessage) => {
|
||||
setSelectedCommentId(msg.id || null)
|
||||
const msgObj = msg as unknown as Record<string, unknown>
|
||||
const details = msgObj.details as ShumaiMessageContext | undefined
|
||||
const handleChatMessageSelect = (msg: EntryRecord) => {
|
||||
setSelectedCommentId(String(msg.id))
|
||||
const details = getShumaiMessage(msg)?.context
|
||||
const rawAnnotations = details?.annotations as Annotation[] | undefined
|
||||
if (rawAnnotations && rawAnnotations.length > 0) {
|
||||
setAnnotations(rawAnnotations)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { useChatbotStore, AGENT_PREFERENCE_STORAGE_KEY } from './chatbot'
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { ChatMessage } from '@shumai/dtos'
|
||||
import { type EntryRecord, getShumaiMessage } from '@shumai/dtos'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AGENT_PREFERENCE_STORAGE_KEY, useChatbotStore } from './chatbot'
|
||||
|
||||
const localStorageMock = (() => {
|
||||
let store: Record<string, string> = {}
|
||||
@@ -86,7 +86,14 @@ describe('useChatbotStore', () => {
|
||||
useChatbotStore.setState({
|
||||
selectedAgentId: 'agent-temporary-historical',
|
||||
currentSessionId: 'sess-historical',
|
||||
messages: [{ id: 'msg-1', role: 'user', content: 'test' } as unknown as ChatMessage],
|
||||
messages: [
|
||||
{
|
||||
id: 10,
|
||||
conversationId: 1,
|
||||
kind: 'pi.user',
|
||||
model: [{ role: 'user', content: 'test', timestamp: 0 }],
|
||||
} as unknown as EntryRecord,
|
||||
],
|
||||
})
|
||||
|
||||
useChatbotStore.getState().startNewSession()
|
||||
@@ -102,7 +109,14 @@ describe('useChatbotStore', () => {
|
||||
|
||||
useChatbotStore.setState({
|
||||
currentSessionId: 'sess-abc',
|
||||
messages: [{ id: 'msg-1', role: 'user', content: 'test' } as unknown as ChatMessage],
|
||||
messages: [
|
||||
{
|
||||
id: 10,
|
||||
conversationId: 1,
|
||||
kind: 'pi.user',
|
||||
model: [{ role: 'user', content: 'test', timestamp: 0 }],
|
||||
} as unknown as EntryRecord,
|
||||
],
|
||||
})
|
||||
// Navigating or changing other state does not wipe inputText
|
||||
expect(useChatbotStore.getState().inputText).toBe('Draft text in progress')
|
||||
@@ -132,7 +146,14 @@ describe('useChatbotStore', () => {
|
||||
it('should reset currentSessionId and messages on startNewSession', () => {
|
||||
useChatbotStore.setState({
|
||||
currentSessionId: 'sess-abc',
|
||||
messages: [{ id: 'msg-1', role: 'user', content: 'test' } as unknown as ChatMessage],
|
||||
messages: [
|
||||
{
|
||||
id: 10,
|
||||
conversationId: 1,
|
||||
kind: 'pi.user',
|
||||
model: [{ role: 'user', content: 'test', timestamp: 0 }],
|
||||
} as unknown as EntryRecord,
|
||||
],
|
||||
chatAssets: [{ id: 'asset-1', name: 'Asset', type: 'file' }],
|
||||
})
|
||||
|
||||
@@ -146,8 +167,8 @@ describe('useChatbotStore', () => {
|
||||
it('should handle incoming SSE stream and replace optimistic message in a new session', async () => {
|
||||
const mockEvents = [
|
||||
'data: {"type":"session","sessionId":"sess-123"}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"user-msg-ulid","role":"user","content":[{"type":"text","text":"hello"}],"timestamp":123}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"assistant-msg-ulid","role":"assistant","content":[{"type":"text","text":"hi user"}],"timestamp":124}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":12,"conversationId":1,"kind":"pi.user","model":[{"role":"user","content":[{"type":"text","text":"hello"}],"timestamp":123}]}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":13,"conversationId":1,"kind":"pi.assistant","model":[{"role":"assistant","content":[{"type":"text","text":"hi user"}],"timestamp":124}]}}\n\n',
|
||||
'data: {"type":"done","status":"completed"}\n\n',
|
||||
]
|
||||
|
||||
@@ -180,8 +201,8 @@ describe('useChatbotStore', () => {
|
||||
// Optimistic message should be present immediately
|
||||
const stateWithOptimistic = useChatbotStore.getState()
|
||||
expect(stateWithOptimistic.messages).toHaveLength(1)
|
||||
expect(stateWithOptimistic.messages[0].id).toContain('temp-')
|
||||
expect((stateWithOptimistic.messages[0] as { content: unknown }).content).toBe('hello')
|
||||
expect(stateWithOptimistic.messages[0].id).toBeLessThan(0)
|
||||
expect(getShumaiMessage(stateWithOptimistic.messages[0])?.displayText).toBe('hello')
|
||||
expect(stateWithOptimistic.isStreaming).toBe(true)
|
||||
|
||||
await sendPromise
|
||||
@@ -191,8 +212,8 @@ describe('useChatbotStore', () => {
|
||||
expect(finalState.isStreaming).toBe(false)
|
||||
expect(finalState.currentSessionId).toBe('sess-123')
|
||||
expect(finalState.messages).toHaveLength(2)
|
||||
expect(finalState.messages[0].id).toBe('user-msg-ulid')
|
||||
expect(finalState.messages[1].id).toBe('assistant-msg-ulid')
|
||||
expect(finalState.messages[0].id).toBe(12)
|
||||
expect(finalState.messages[1].id).toBe(13)
|
||||
})
|
||||
|
||||
it('should not remove optimistic message when historical user message streams back', async () => {
|
||||
@@ -200,19 +221,21 @@ describe('useChatbotStore', () => {
|
||||
currentSessionId: 'sess-123',
|
||||
messages: [
|
||||
{
|
||||
id: 'user-msg-ulid-old',
|
||||
role: 'user',
|
||||
content: [{ type: 'text', text: 'old message' }],
|
||||
timestamp: 100,
|
||||
} as unknown as ChatMessage,
|
||||
id: 11,
|
||||
conversationId: 1,
|
||||
kind: 'pi.user',
|
||||
model: [
|
||||
{ role: 'user', content: [{ type: 'text', text: 'old message' }], timestamp: 100 },
|
||||
],
|
||||
} as unknown as EntryRecord,
|
||||
],
|
||||
chatAssets: [],
|
||||
})
|
||||
|
||||
const mockEvents = [
|
||||
'data: {"type":"session","sessionId":"sess-123"}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"user-msg-ulid-old","role":"user","content":[{"type":"text","text":"old message"}],"timestamp":100}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"user-msg-ulid-new","role":"user","content":[{"type":"text","text":"new message"}],"timestamp":150}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":11,"conversationId":1,"kind":"pi.user","model":[{"role":"user","content":[{"type":"text","text":"old message"}],"timestamp":100}]}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":14,"conversationId":1,"kind":"pi.user","model":[{"role":"user","content":[{"type":"text","text":"new message"}],"timestamp":150}]}}\n\n',
|
||||
'data: {"type":"done","status":"completed"}\n\n',
|
||||
]
|
||||
|
||||
@@ -247,16 +270,16 @@ describe('useChatbotStore', () => {
|
||||
// Optimistic message should be appended immediately
|
||||
const stateWithOptimistic = useChatbotStore.getState()
|
||||
expect(stateWithOptimistic.messages).toHaveLength(2)
|
||||
expect(stateWithOptimistic.messages[0].id).toBe('user-msg-ulid-old')
|
||||
expect(stateWithOptimistic.messages[1].id).toContain('temp-')
|
||||
expect(stateWithOptimistic.messages[0].id).toBe(11)
|
||||
expect(stateWithOptimistic.messages[1].id).toBeLessThan(0)
|
||||
|
||||
await sendPromise
|
||||
|
||||
// Final state assertions
|
||||
const finalState = useChatbotStore.getState()
|
||||
expect(finalState.messages).toHaveLength(2)
|
||||
expect(finalState.messages[0].id).toBe('user-msg-ulid-old')
|
||||
expect(finalState.messages[1].id).toBe('user-msg-ulid-new')
|
||||
expect(finalState.messages[0].id).toBe(11)
|
||||
expect(finalState.messages[1].id).toBe(14)
|
||||
})
|
||||
|
||||
it('should create optimistic context display message when sending with assets', async () => {
|
||||
@@ -268,8 +291,8 @@ describe('useChatbotStore', () => {
|
||||
// 2. Mock POST response with context_display_info entry streaming back
|
||||
const mockEvents = [
|
||||
'data: {"type":"session","sessionId":"sess-123"}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"context-display-ulid","role":"custom","customType":"context_display_info","details":{"assets":[{"id":"asset-1","name":"File 1.txt","type":"file"}]},"timestamp":120}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"user-msg-ulid","role":"user","content":[{"type":"text","text":"hello"}],"timestamp":123}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":15,"conversationId":1,"kind":"shumai.custom","data":{"customType":"context_display_info","details":{"assets":[{"id":"asset-1","name":"File 1.txt","type":"file"}]}}}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":12,"conversationId":1,"kind":"pi.user","model":[{"role":"user","content":[{"type":"text","text":"hello"}],"timestamp":123}]}}\n\n',
|
||||
'data: {"type":"done","status":"completed"}\n\n',
|
||||
]
|
||||
|
||||
@@ -304,13 +327,10 @@ describe('useChatbotStore', () => {
|
||||
expect(stateWithOptimistic.messages).toHaveLength(1)
|
||||
|
||||
// Message should be the optimistic shumai_message with referencedAssets in details
|
||||
expect(stateWithOptimistic.messages[0].id).toContain('temp-')
|
||||
expect(stateWithOptimistic.messages[0].role).toBe('custom')
|
||||
expect((stateWithOptimistic.messages[0] as { customType?: string }).customType).toBe(
|
||||
'shumai_message',
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((stateWithOptimistic.messages[0] as any).details.referencedAssets).toEqual([
|
||||
expect(stateWithOptimistic.messages[0].id).toBeLessThan(0)
|
||||
expect(stateWithOptimistic.messages[0].kind).toBe('shumai.optimistic')
|
||||
|
||||
expect(getShumaiMessage(stateWithOptimistic.messages[0])?.context?.referencedAssets).toEqual([
|
||||
{ id: 'asset-1', name: 'File 1.txt', type: 'file' },
|
||||
])
|
||||
|
||||
@@ -319,15 +339,15 @@ describe('useChatbotStore', () => {
|
||||
// 4. Verify message list after streaming completes
|
||||
const finalState = useChatbotStore.getState()
|
||||
expect(finalState.messages).toHaveLength(2)
|
||||
expect(finalState.messages[0].id).toBe('context-display-ulid')
|
||||
expect(finalState.messages[1].id).toBe('user-msg-ulid')
|
||||
expect(finalState.messages[0].id).toBe(15)
|
||||
expect(finalState.messages[1].id).toBe(12)
|
||||
})
|
||||
|
||||
it('should invoke onAssetMutation callback when asset creation tool result arrives', async () => {
|
||||
const mockEvents = [
|
||||
'data: {"type":"session","sessionId":"sess-123"}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"user-msg-ulid","role":"user","content":[{"type":"text","text":"create a file"}],"timestamp":123}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"tool-res-ulid","role":"toolResult","toolName":"create_file","isError":false,"content":"File created","timestamp":124}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":12,"conversationId":1,"kind":"pi.user","model":[{"role":"user","content":[{"type":"text","text":"create a file"}],"timestamp":123}]}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":16,"conversationId":1,"kind":"pi.tool-result","model":[{"role":"toolResult","content":"File created","timestamp":124,"toolName":"create_file","isError":false}]}}\n\n',
|
||||
'data: {"type":"done","status":"completed"}\n\n',
|
||||
]
|
||||
|
||||
@@ -366,8 +386,8 @@ describe('useChatbotStore', () => {
|
||||
it('should replace optimistic message when shumai_message entry streams back', async () => {
|
||||
const mockEvents = [
|
||||
'data: {"type":"session","sessionId":"sess-123"}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"user-msg-ulid","role":"custom","customType":"shumai_message","content":"hello","details":{"user":{"id":"u1","name":"User 1"}},"timestamp":123}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"assistant-msg-ulid","role":"assistant","content":[{"type":"text","text":"Hi!"}],"timestamp":124}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":12,"conversationId":1,"kind":"shumai.message","data":{"displayText":"hello","timestamp":123,"context":{"user":{"id":"u1","name":"User 1"}}}}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":13,"conversationId":1,"kind":"pi.assistant","model":[{"role":"assistant","content":[{"type":"text","text":"Hi!"}],"timestamp":124}]}}\n\n',
|
||||
'data: {"type":"done","status":"completed"}\n\n',
|
||||
]
|
||||
|
||||
@@ -400,17 +420,16 @@ describe('useChatbotStore', () => {
|
||||
// Optimistic message should be present immediately
|
||||
const stateWithOptimistic = useChatbotStore.getState()
|
||||
expect(stateWithOptimistic.messages).toHaveLength(1)
|
||||
expect(stateWithOptimistic.messages[0].id).toContain('temp-')
|
||||
expect(stateWithOptimistic.messages[0].id).toBeLessThan(0)
|
||||
|
||||
await sendPromise
|
||||
|
||||
// Final state assertions: optimistic message must be replaced
|
||||
const finalState = useChatbotStore.getState()
|
||||
expect(finalState.messages).toHaveLength(2)
|
||||
expect(finalState.messages[0].id).toBe('user-msg-ulid')
|
||||
expect(finalState.messages[0].role).toBe('custom')
|
||||
expect((finalState.messages[0] as { customType?: string }).customType).toBe('shumai_message')
|
||||
expect(finalState.messages[1].id).toBe('assistant-msg-ulid')
|
||||
expect(finalState.messages[0].id).toBe(12)
|
||||
expect(finalState.messages[0].kind).toBe('shumai.message')
|
||||
expect(finalState.messages[1].id).toBe(13)
|
||||
})
|
||||
|
||||
it('should include attachments, annotations, and second in optimistic message and API call', async () => {
|
||||
@@ -459,20 +478,20 @@ describe('useChatbotStore', () => {
|
||||
},
|
||||
],
|
||||
12.5,
|
||||
[{ id: 'att-1', name: 'screenshot.png', type: 'image', mediaType: 'image/png' }],
|
||||
[{ id: 'att-1', name: 'screenshot.png', type: 'image', mediaType: 'image' }],
|
||||
)
|
||||
|
||||
// Check optimistic message has annotations, second position, and attachedFiles
|
||||
const optimisticState = useChatbotStore.getState()
|
||||
expect(optimisticState.messages).toHaveLength(1)
|
||||
const optMsg = optimisticState.messages[0] as unknown as Record<string, unknown>
|
||||
expect(optMsg.customType).toBe('shumai_message')
|
||||
const details = optMsg.details as Record<string, unknown>
|
||||
expect(optMsg.kind).toBe('shumai.optimistic')
|
||||
const details = getShumaiMessage(optimisticState.messages[0])!.context
|
||||
expect(details.annotation).toBe(true)
|
||||
expect(details.annotations).toHaveLength(1)
|
||||
expect(details.position).toEqual({ type: 'time', seconds: 12.5 })
|
||||
expect(details.attachedFiles).toEqual([
|
||||
{ id: 'att-1', name: 'screenshot.png', type: 'image', mediaType: 'image/png' },
|
||||
{ id: 'att-1', name: 'screenshot.png', type: 'image', mediaType: 'image' },
|
||||
])
|
||||
|
||||
await sendPromise
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { create } from 'zustand'
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { ChatMessage, ChatSessionInfo } from '@shumai/dtos'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import type { EntryId, EntryRecord, JsonObject } from '@earendil-works/pi-durable'
|
||||
import { ROOT_CONVERSATION_ID } from '@earendil-works/pi-durable'
|
||||
import type { ChatSessionInfo } from '@shumai/dtos'
|
||||
import { toast } from 'sonner'
|
||||
import { create } from 'zustand'
|
||||
|
||||
export const AGENT_PREFERENCE_STORAGE_KEY = 'shumai_selected_agent_id'
|
||||
|
||||
@@ -39,8 +41,8 @@ interface ChatbotState {
|
||||
addAssets: (assets: ChatAsset[]) => void
|
||||
removeAsset: (id: string) => void
|
||||
clearAssets: () => void
|
||||
messages: ChatMessage[]
|
||||
setMessages: (messages: ChatMessage[]) => void
|
||||
messages: EntryRecord[]
|
||||
setMessages: (messages: EntryRecord[]) => void
|
||||
historySessions: ChatSessionInfo[]
|
||||
setHistorySessions: (sessions: ChatSessionInfo[]) => void
|
||||
isStreaming: boolean
|
||||
@@ -142,7 +144,7 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
const agentId = sessionInfo?.agentId || null
|
||||
set({
|
||||
currentSessionId: sessionId,
|
||||
messages: messages as ChatMessage[],
|
||||
messages: messages as EntryRecord[],
|
||||
isHistoryMode: false,
|
||||
scrollTop: 0,
|
||||
isAtBottom: true,
|
||||
@@ -205,27 +207,34 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
const state = useChatbotStore.getState()
|
||||
if (state.isStreaming) return
|
||||
|
||||
const tempId = `temp-${Date.now()}`
|
||||
const optimisticMsg = {
|
||||
const tempId = -Date.now() as EntryId
|
||||
const optimisticMsg: EntryRecord = {
|
||||
id: tempId,
|
||||
role: 'custom' as const,
|
||||
customType: 'shumai_message',
|
||||
content: text,
|
||||
display: true,
|
||||
details: {
|
||||
currentAsset: contextAssetId ? { id: contextAssetId, name: '', type: 'file' } : undefined,
|
||||
position:
|
||||
second !== undefined && second !== null ? { type: 'time', seconds: second } : undefined,
|
||||
annotation: !!(annotations && annotations.length > 0),
|
||||
annotations: annotations || undefined,
|
||||
attachedFiles: attachedFilesMeta || undefined,
|
||||
referencedAssets:
|
||||
state.chatAssets.length > 0
|
||||
? state.chatAssets.map((a) => ({ id: a.id, name: a.name, type: a.type }))
|
||||
: undefined,
|
||||
},
|
||||
timestamp: Date.now(),
|
||||
} as unknown as ChatMessage
|
||||
conversationId: ROOT_CONVERSATION_ID,
|
||||
kind: 'shumai.optimistic',
|
||||
data: JSON.parse(
|
||||
JSON.stringify({
|
||||
displayText: text,
|
||||
timestamp: Date.now(),
|
||||
context: {
|
||||
currentAsset: contextAssetId
|
||||
? { id: contextAssetId, name: '', type: 'file' }
|
||||
: undefined,
|
||||
position:
|
||||
second !== undefined && second !== null
|
||||
? { type: 'time', seconds: second }
|
||||
: undefined,
|
||||
annotation: !!(annotations && annotations.length > 0),
|
||||
annotations: annotations || undefined,
|
||||
attachedFiles: attachedFilesMeta || undefined,
|
||||
referencedAssets:
|
||||
state.chatAssets.length > 0
|
||||
? state.chatAssets.map((a) => ({ id: a.id, name: a.name, type: a.type }))
|
||||
: undefined,
|
||||
},
|
||||
}),
|
||||
) as JsonObject,
|
||||
}
|
||||
|
||||
const newMessages = [...state.messages, optimisticMsg]
|
||||
|
||||
@@ -302,10 +311,10 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
set({ currentSessionId: data.sessionId })
|
||||
}
|
||||
} else if (data.type === 'entry') {
|
||||
const entry = data.entry as ChatMessage
|
||||
const entryObj = entry as unknown as Record<string, unknown>
|
||||
const entry = data.entry as EntryRecord
|
||||
const entryObj = entry.model?.[0]
|
||||
if (
|
||||
entryObj.role === 'toolResult' &&
|
||||
entryObj?.role === 'toolResult' &&
|
||||
typeof entryObj.toolName === 'string' &&
|
||||
[
|
||||
'create_file',
|
||||
@@ -323,23 +332,8 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
set((s) => {
|
||||
const isExisting = s.messages.some((m) => m.id === entry.id)
|
||||
const isUserMessage =
|
||||
(entry.role === 'user' ||
|
||||
(entry.role === 'custom' && entry.customType === 'shumai_message')) &&
|
||||
!isExisting
|
||||
// Replace temp/optimistic message when the real counterpart streams back
|
||||
const filtered = s.messages.filter((m) => {
|
||||
if (isUserMessage) {
|
||||
return !m.id.startsWith('temp-')
|
||||
}
|
||||
if (
|
||||
entry.role === 'custom' &&
|
||||
entry.customType === 'context_display_info' &&
|
||||
!isExisting
|
||||
) {
|
||||
return !m.id.startsWith('temp-context-')
|
||||
}
|
||||
return true
|
||||
})
|
||||
['pi.user', 'shumai.message'].includes(entry.kind) && !isExisting
|
||||
const filtered = s.messages.filter((m) => !isUserMessage || m.id >= 0)
|
||||
|
||||
// Prevent duplicates by ID
|
||||
const existingIdx = filtered.findIndex((m) => m.id === entry.id)
|
||||
|
||||
Reference in New Issue
Block a user