Merge pull request #185 from shumaiOne/feat/chatbot-ui-layout

feat(chat): chatbot UI
This commit is contained in:
Yiling-J
2026-07-13 16:55:25 +08:00
committed by GitHub
82 changed files with 3477 additions and 202 deletions
+1
View File
@@ -114,6 +114,7 @@ async function run() {
const server = Bun.serve({
port,
idleTimeout: 120,
maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE
? parseInt(process.env.MAX_REQUEST_BODY_SIZE)
: 1024 * 1024 * 1024 * 10, // Default 10GB
+174
View File
@@ -15,6 +15,8 @@ import {
updateAssetMetadataActivity,
getAssetPathContextActivity,
executeAgentToolActivity,
generateSessionNameActivity,
type GenerateSessionNameParams,
} from './agent'
import * as piAgent from '../index'
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
@@ -741,4 +743,176 @@ describe('Agent Database Activities Integration', () => {
})
})
})
describe('generateSessionNameActivity', () => {
it('should generate and save session name for chat sessions', async () => {
await prisma.team.create({
data: { id: 't1', name: 'Test Team' },
})
const user = await prisma.user.create({
data: { id: 'u1', name: 'Test User', email: 'u1@test.com' },
})
const agentUser = await prisma.user.create({
data: {
id: 'agent-123',
name: 'Chat Agent User',
email: 'agent@shumai.ai',
type: 'agent',
},
})
const agent = await prisma.agent.create({
data: {
id: agentUser.id,
teamId: 't1',
type: 'chat',
config: { provider: 'openai', model: 'gpt-4' },
},
})
await prisma.agentSession.create({
data: {
id: 'session-123',
agentId: 'agent-123',
userId: user.id,
cwd: process.cwd(),
type: 'chat',
name: null,
},
})
const mockHarness = {
prompt: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: ' "Summarized Chat Title" ' }],
}),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: {} as unknown as Session<DatabaseSessionMetadata>,
harness: mockHarness as unknown as AgentHarness,
})
await generateSessionNameActivity({
teamId: 't1',
agentId: 'agent-123',
prompt: 'hello world prompt',
sessionId: 'session-123',
context: {
agent: {
...agent,
provider: { name: 'openai' },
modelRef: {
id: 'm1',
providerName: 'openai',
modelId: 'gpt-4',
name: 'GPT-4',
config: {},
createdAt: new Date(),
updatedAt: new Date(),
},
} as unknown as GenerateSessionNameParams['context']['agent'],
dbProviders: [
{
name: 'openai',
config: { api: 'openai-responses', apiKey: 'fake-key' },
models: [
{
modelId: 'gpt-4',
name: 'GPT-4',
config: {
reasoning: false,
input: ['text'],
contextWindow: 4096,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
],
},
],
},
})
const updatedSession = await prisma.agentSession.findUnique({
where: { id: 'session-123' },
})
expect(updatedSession?.name).toBe('Summarized Chat Title')
expect(mockHarness.prompt).toHaveBeenCalledWith('hello world prompt')
// Verify that transient naming session was cleaned up (deleted)
const namingSessions = await prisma.agentSession.findMany({
where: { type: 'naming' },
})
expect(namingSessions).toHaveLength(0)
})
it('should skip name generation for comment sessions or if name is already set', async () => {
await prisma.team.create({
data: { id: 't1', name: 'Test Team' },
})
const user = await prisma.user.create({
data: { id: 'u1', name: 'Test User', email: 'u1@test.com' },
})
const agentUser = await prisma.user.create({
data: {
id: 'agent-123',
name: 'Chat Agent User',
email: 'agent2@shumai.ai',
type: 'agent',
},
})
await prisma.agent.create({
data: {
id: agentUser.id,
teamId: 't1',
type: 'chat',
config: { provider: 'openai', model: 'gpt-4' },
},
})
await prisma.agentSession.create({
data: {
id: 'session-comment',
agentId: 'agent-123',
userId: user.id,
cwd: process.cwd(),
type: 'comment',
name: null,
},
})
await prisma.agentSession.create({
data: {
id: 'session-named',
agentId: 'agent-123',
userId: user.id,
cwd: process.cwd(),
type: 'chat',
name: 'Existing Name',
},
})
vi.mocked(piAgent.createAgentSession).mockClear()
await generateSessionNameActivity({
teamId: 't1',
agentId: 'agent-123',
prompt: 'hello comment',
sessionId: 'session-comment',
context: {
agent: {} as unknown as GenerateSessionNameParams['context']['agent'],
dbProviders: [],
},
})
await generateSessionNameActivity({
teamId: 't1',
agentId: 'agent-123',
prompt: 'hello named',
sessionId: 'session-named',
context: {
agent: {} as unknown as GenerateSessionNameParams['context']['agent'],
dbProviders: [],
},
})
expect(piAgent.createAgentSession).not.toHaveBeenCalled()
})
})
})
+149 -12
View File
@@ -1,23 +1,28 @@
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '../index'
import { DatabaseSessionStorage } from '../database-session-storage'
import { prisma, AssetType, Prisma, type Skill } from '@shumai/db'
import { logger } from '@shumai/core/src/logger'
import { s3Service } from '@shumai/core/src/s3/s3'
import {
type AgentTool,
type AgentMessage,
type AgentTool,
type SessionTreeEntry,
} from '@earendil-works/pi-agent-core'
import { type ImageContent } from '@earendil-works/pi-ai'
import { ApplicationFailure } from '@temporalio/activity'
import { assetService } from '@shumai/core/src/asset/asset'
import { VersionStackService } from '@shumai/core/src/versionStack/versionStack'
import { uploadService } from '@shumai/core/src/upload/upload'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { paginateQuery, encodeCursor } from '@shumai/core/src/pagination'
import { ulid } from 'ulid'
import { logger } from '@shumai/core/src/logger'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { encodeCursor, paginateQuery } from '@shumai/core/src/pagination'
import { s3Service } from '@shumai/core/src/s3/s3'
import { uploadService } from '@shumai/core/src/upload/upload'
import { VersionStackService } from '@shumai/core/src/versionStack/versionStack'
import { AssetType, prisma, Prisma, type Skill } from '@shumai/db'
import { ApplicationFailure } from '@temporalio/activity'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { ulid } from 'ulid'
import { DatabaseSessionStorage } from '../database-session-storage'
import {
createAgentSession,
fieldsToTypeBoxSchema,
type AutofillField,
type DbProviderInfo,
} from '../index'
import { UpdateAssetMetadataRequest } from '@shumai/dtos'
@@ -58,6 +63,7 @@ async function executeAgentPrompt(params: {
userCommentId?: string | null
tools?: AgentTool[]
context: AgentExecutionContext
attachedAssets?: Array<{ id: string; name: string; type: string }>
}): Promise<{ text: string; usage: Usage; sessionId: string }> {
const { agent, dbProviders, teamSkills, allowedDomains } = params.context
@@ -157,6 +163,21 @@ If you need to create files in the local filesystem (for example, a temporary fi
} as unknown as SessionTreeEntry)
}
if (params.attachedAssets && params.attachedAssets.length > 0) {
const storage = session.getStorage()
const parentId = await storage.getLeafId()
await storage.appendEntry({
id: ulid(),
type: 'custom',
parentId,
timestamp: new Date().toISOString(),
customType: 'context_display_info',
data: {
assets: params.attachedAssets,
},
} as unknown as SessionTreeEntry)
}
const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass })
const sessionEntries = await session.getEntries()
@@ -219,6 +240,7 @@ export interface AgentChatParams {
userCommentId?: string | null
explicitMention?: boolean
context: AgentExecutionContext
attachedAssets?: Array<{ id: string; name: string; type: string }>
}
export async function agentChatActivity(params: AgentChatParams) {
@@ -235,6 +257,7 @@ export async function agentChatActivity(params: AgentChatParams) {
userId: params.userId,
userCommentId: params.userCommentId,
context: params.context,
attachedAssets: params.attachedAssets,
})
}
@@ -1120,3 +1143,117 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
})
}
}
export interface GenerateSessionNameParams {
teamId: string
agentId: string
prompt: string
sessionId: string
context: {
agent: Prisma.AgentGetPayload<{ include: { modelRef: true; provider: true } }>
dbProviders: DbProviderInfo[]
}
}
export async function generateSessionNameActivity(
params: GenerateSessionNameParams,
): Promise<void> {
const { sessionId, prompt, teamId, agentId } = params
const { agent, dbProviders } = params.context
// 1. Fetch current session and verify it is a chatbot session and unnamed
const sessionRecord = await prisma.agentSession.findUnique({
where: { id: sessionId },
})
if (!sessionRecord || sessionRecord.type !== 'chat' || sessionRecord.name !== null) {
logger.info({ sessionId }, 'Skipping session name generation: not an unnamed chatbot session')
return
}
if (!agent || !agent.modelRef || !agent.provider) {
logger.warn(
{ sessionId },
'Skipping session name generation: Agent, model, or provider configuration not found',
)
return
}
const providerName = agent.provider.name
const modelId = agent.modelRef.modelId
let namingSessionId: string | undefined
try {
// 2. Create transient naming session in database
const namingSession = await prisma.agentSession.create({
data: {
agentId,
userId: sessionRecord.userId,
cwd: process.cwd(),
assetId: sessionRecord.assetId,
type: 'naming',
},
})
namingSessionId = namingSession.id
const systemInstruction =
"You are a helpful assistant. Generate a short 2 to 4 words title/name for a chat session based on the user's first message. " +
'Do NOT include quotation marks, markdown formatting, or any extra conversational text. Return only the title.'
// 3. Create agent session and harness using the naming session
const { harness } = await createAgentSession({
teamId,
agentId,
providerName,
modelId,
systemPrompt: systemInstruction,
teamSkills: [],
allowedDomains: [],
sessionId: namingSessionId,
userId: sessionRecord.userId || undefined,
providers: dbProviders,
})
const result = await harness.prompt(prompt)
const resultText = result.content
.filter((c) => c.type === 'text')
.map((c) => {
if ('text' in c && typeof c.text === 'string') {
return c.text
}
return ''
})
.join('\n')
let chatName = resultText.trim()
// Clean up quotes if returned
if (
(chatName.startsWith('"') && chatName.endsWith('"')) ||
(chatName.startsWith("'") && chatName.endsWith("'"))
) {
chatName = chatName.slice(1, -1).trim()
}
if (chatName) {
await prisma.agentSession.update({
where: { id: sessionId },
data: { name: chatName },
})
logger.info({ sessionId, chatName }, 'Session name generated successfully')
}
} catch (err) {
logger.error({ sessionId, err }, 'Failed to generate session name')
} finally {
if (namingSessionId) {
await prisma.agentSession
.delete({
where: { id: namingSessionId },
})
.catch((deleteErr) => {
logger.error({ namingSessionId, deleteErr }, 'Failed to delete naming session')
})
}
}
}
+74 -66
View File
@@ -23,6 +23,75 @@ import { createListAssetsTool } from './tools/list-assets'
import { createReadSkillTool } from './tools/read-skill'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
export interface DbModelInfo {
modelId: string
name: string | null
config: PrismaJson.ModelConfig
}
export interface DbProviderInfo {
name: string
config: PrismaJson.ProviderConfig
models: DbModelInfo[]
}
export function getModelFromDb(providers: DbProviderInfo[], providerName: string, modelId: string) {
const dbProvider = providers.find((p) => p.name === providerName)
const dbModel = dbProvider?.models.find((m) => m.modelId === modelId)
if (!dbProvider || !dbModel) return undefined
// Model contains complex internal types from pi-ai
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let m: any
try {
// Try to get built-in model as template
// eslint-disable-next-line @typescript-eslint/no-explicit-any
m = { ...(getModel as any)(providerName, modelId) }
} catch {
// Not a built-in model
m = {
id: modelId,
name: dbModel.name || modelId,
provider: providerName,
api: 'openai-responses',
baseUrl: '',
reasoning: false,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 4096,
maxTokens: 4096,
}
}
// Override with database config
if (dbProvider.config.baseUrl) {
m.baseUrl = dbProvider.config.baseUrl
}
if (dbProvider.config.api) {
m.api = dbProvider.config.api
}
Object.assign(m, dbModel.config)
if (dbModel.name) {
m.name = dbModel.name
}
return m
}
export function getApiKeyAndHeadersFromDb(providers: DbProviderInfo[], providerName: string) {
// Helper to resolve key from ENV if it matches an ENV var name
const resolveKey = (key: string | undefined) => (key ? process.env[key] || key : undefined)
// Look up the provider in our providers list
const dbProvider = providers.find((p) => p.name === providerName)
const providerApiKey = dbProvider?.config?.apiKey
if (providerApiKey) {
return { apiKey: resolveKey(providerApiKey)! }
}
return undefined
}
export interface CreateAgentSessionParams {
teamId: string
agentId: string
@@ -36,15 +105,7 @@ export interface CreateAgentSessionParams {
userCommentId?: string | null
customTools?: AgentTool[]
thinkingLevel?: string
providers: Array<{
name: string
config: PrismaJson.ProviderConfig
models: Array<{
modelId: string
name: string | null
config: PrismaJson.ModelConfig
}>
}>
providers: DbProviderInfo[]
}
export async function createAgentSession(params: CreateAgentSessionParams) {
@@ -74,52 +135,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId)
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
// Helper to construct a Model object from database providers list
const getModelFromDb = (pName: string, mId: string) => {
const dbProvider = params.providers.find((p) => p.name === pName)
const dbModel = dbProvider?.models.find((m) => m.modelId === mId)
if (!dbProvider || !dbModel) return undefined
// Model contains complex internal types from pi-ai
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let m: any
try {
// Try to get built-in model as template
// eslint-disable-next-line @typescript-eslint/no-explicit-any
m = { ...(getModel as any)(pName, mId) }
} catch {
// Not a built-in model
m = {
id: mId,
name: dbModel.name || mId,
provider: pName,
api: 'openai-responses',
baseUrl: '',
reasoning: false,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 4096,
maxTokens: 4096,
}
}
// Override with database config
if (dbProvider.config.baseUrl) {
m.baseUrl = dbProvider.config.baseUrl
}
if (dbProvider.config.api) {
m.api = dbProvider.config.api
}
Object.assign(m, dbModel.config)
if (dbModel.name) {
m.name = dbModel.name
}
return m
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const model = getModelFromDb(providerName, modelId) || (getModel as any)(providerName, modelId)
const model =
getModelFromDb(params.providers, providerName, modelId) ||
(getModel as unknown as (p: string, m: string) => unknown)(providerName, modelId)
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
@@ -269,17 +287,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
return prompt
},
getApiKeyAndHeaders: async (targetModel) => {
// Helper to resolve key from ENV if it matches an ENV var name
const resolveKey = (key: string | undefined) => (key ? process.env[key] || key : undefined)
// Look up the provider in our providers list
const dbProvider = params.providers.find((p) => p.name === targetModel.provider)
const providerApiKey = dbProvider?.config?.apiKey
if (providerApiKey) {
return { apiKey: resolveKey(providerApiKey)! }
}
return undefined
return getApiKeyAndHeadersFromDb(params.providers, targetModel.provider)
},
tools: [...mediaTools, readSkill, sandboxedBash, ...systemTools, ...customTools],
})
@@ -46,11 +46,15 @@ describe('Agent Chat Workflow', () => {
getAssetPathContextActivity: Object.assign(vi.fn(), {
_activityName: 'getAssetPathContextActivity',
}),
generateSessionNameActivity: Object.assign(vi.fn(), {
_activityName: 'generateSessionNameActivity',
}),
}
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.generateSessionNameActivity.mockResolvedValue(undefined)
mockActivities.getAssetActivity.mockResolvedValue({
id: 'a1',
project: { teamId: 't1' },
@@ -166,6 +170,15 @@ describe('Agent Chat Workflow', () => {
status: 'completed',
output: { sessionId: 'session-123' },
})
// Verify session name generation triggered
expect(mockActivities.generateSessionNameActivity).toHaveBeenCalledWith({
teamId: 't1',
agentId: 'b1',
prompt: 'hello agent',
sessionId: 'session-123',
context: expect.any(Object),
})
})
it('should skip session initialization if sessionId is already provided', async () => {
@@ -198,6 +211,9 @@ describe('Agent Chat Workflow', () => {
agentsInstruction: expectedInstruction2,
}),
)
// Verify session name generation is skipped
expect(mockActivities.generateSessionNameActivity).not.toHaveBeenCalled()
})
it('should delete placeholder comment and finish when AI responds with __NO_REPLY__', async () => {
@@ -488,6 +504,10 @@ describe('Agent Chat Workflow', () => {
userCommentId: undefined,
explicitMention: true,
context: { agent: { id: 'b1' } },
attachedAssets: [
{ id: 'file-attachment-1', name: 'attachment.png', type: 'file' },
{ id: 'referenced-asset-1', name: 'ref-folder', type: 'folder' },
],
})
})
})
+22 -1
View File
@@ -17,6 +17,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
deleteCommentActivity,
initializeAgentSessionActivity,
getAssetPathContextActivity,
generateSessionNameActivity,
} = getActivities()
let placeholderCommentId: string | undefined
@@ -91,7 +92,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
const teamId = asset.project.teamId
// 4. Initialize Session if missing
let isNewChat = !payload.agent?.sessionId
let isNewChat = !payload.agent?.sessionId || payload.agent?.isNewChat === true
if (!sessionId) {
if (!userCommentId) {
throw ApplicationFailure.create({
@@ -126,6 +127,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
// Resolve Attached Files Details
const attachedFileDetailsList: string[] = []
const attachedAssets: Array<{ id: string; name: string; type: string }> = []
if (payload.agent?.attachedFiles) {
for (const fileId of payload.agent.attachedFiles) {
const file = await executeActivity(agentWorkerQueue, getAssetActivity, fileId)
@@ -134,6 +136,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
attachedFileDetailsList.push(
`- Name: ${file.name} (ID: ${file.id}, Type: ${file.type}, Media Type: ${file.mediaType || 'unknown'}, Project ID: ${file.projectId || 'unknown'}, Path: ${path})`,
)
attachedAssets.push({ id: file.id, name: file.name, type: file.type })
}
}
}
@@ -148,6 +151,11 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
referencedAssetDetailsList.push(
`- Name: ${referencedAsset.name} (ID: ${referencedAsset.id}, Type: ${referencedAsset.type}, Media Type: ${referencedAsset.mediaType || 'unknown'}, Project ID: ${referencedAsset.projectId || 'unknown'}, Path: ${path})`,
)
attachedAssets.push({
id: referencedAsset.id,
name: referencedAsset.name,
type: referencedAsset.type,
})
}
}
}
@@ -183,8 +191,21 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
userCommentId: userCommentId || undefined,
explicitMention: payload.agent?.explicitMention,
context,
attachedAssets,
})
if (isNewChat) {
await executeActivity(agentWorkerQueue, generateSessionNameActivity, {
teamId,
agentId,
prompt,
sessionId,
context,
}).catch((err) => {
console.error('Failed to run generateSessionNameActivity:', err)
})
}
// 7. Update Placeholder Comment
if (placeholderCommentId) {
if (aiResult.text.trim() === '__NO_REPLY__') {
+53 -9
View File
@@ -43,7 +43,7 @@ describe('Chat API', () => {
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
})
describe('GET /chat/sessions', () => {
describe('GET /teams/:teamId/chat/sessions', () => {
it('returns list of sessions', async () => {
const mockSessions = {
data: [
@@ -62,15 +62,16 @@ describe('Chat API', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(chatService.listSessions).mockResolvedValue(mockSessions as any)
const res = await app.request('/chat/sessions?first=10')
const res = await app.request('/teams/team1/chat/sessions?first=10')
expect(res.status).toBe(200)
const data = await res.json()
expect(data.data).toHaveLength(1)
expect(data.data[0].id).toBe('session1')
expect(chatService.listSessions).toHaveBeenCalledWith('user1', 'team1', expect.any(Object))
})
})
describe('GET /chat/sessions/:sessionId/messages', () => {
describe('GET /teams/:teamId/chat/sessions/:sessionId/messages', () => {
it('returns list of messages', async () => {
const mockMessages = [
{
@@ -84,27 +85,28 @@ describe('Chat API', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(chatService.listMessages).mockResolvedValue(mockMessages as any)
const res = await app.request('/chat/sessions/session1/messages')
const res = await app.request('/teams/team1/chat/sessions/session1/messages')
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toHaveLength(1)
expect(data[0].content).toBe('hello')
expect(chatService.listMessages).toHaveBeenCalledWith('user1', 'team1', 'session1')
})
})
describe('DELETE /chat/sessions/:sessionId', () => {
describe('DELETE /teams/:teamId/chat/sessions/:sessionId', () => {
it('deletes a session', async () => {
vi.mocked(chatService.deleteSession).mockResolvedValue(undefined)
const res = await app.request('/chat/sessions/session1', {
const res = await app.request('/teams/team1/chat/sessions/session1', {
method: 'DELETE',
})
expect(res.status).toBe(204)
expect(chatService.deleteSession).toHaveBeenCalledWith('user1', 'session1')
expect(chatService.deleteSession).toHaveBeenCalledWith('user1', 'team1', 'session1')
})
})
describe('POST /chat', () => {
describe('POST /teams/:teamId/chat', () => {
it('starts or continues chat and returns stream', async () => {
vi.mocked(chatService.startOrContinueChat).mockResolvedValue({
sessionId: 'session1',
@@ -135,7 +137,7 @@ describe('Chat API', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.workflowTask.findUnique).mockResolvedValue(mockTask as any)
const res = await app.request('/chat', {
const res = await app.request('/teams/team1/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -150,6 +152,48 @@ describe('Chat API', () => {
const text = await res.text()
expect(text).toContain('data:')
expect(text).toContain('entry1')
expect(chatService.startOrContinueChat).toHaveBeenCalledWith(
expect.objectContaining({ id: 'user1' }),
'team1',
expect.any(Object),
)
})
it('sends ping keep-alive SSE events when there are no new messages', async () => {
vi.mocked(chatService.startOrContinueChat).mockResolvedValue({
sessionId: 'session1',
taskId: 'task1',
})
// No new entries initially
// Mock returns a simple array instead of full PrismaPromise, so we bypass type safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.agentSessionEntry.findMany).mockResolvedValue([] as any)
const mockTask = {
id: 'task1',
status: 'completed',
output: {},
}
// Mock returns a simple task object instead of PrismaPromise, so we bypass type safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.workflowTask.findUnique).mockResolvedValue(mockTask as any)
const res = await app.request('/teams/team1/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
agentId: 'agent1',
textPrompt: 'hi',
}),
})
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toContain('text/event-stream')
const text = await res.text()
expect(text).toContain('data:')
expect(text).toContain('{"type":"ping"}')
})
})
})
+59 -8
View File
@@ -3,40 +3,83 @@ import { zValidator } from '@hono/zod-validator'
import { streamSSE } from 'hono/streaming'
import { prisma } from '@shumai/db'
import { chatService, mapEntryToMessage } from '@shumai/core/src/chat/chat'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { chatRequestSchema, paginationParamsSchema } from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.get('/chat/sessions', zValidator('query', paginationParamsSchema), async (c) => {
.get('/teams/:teamId/chat/sessions', zValidator('query', paginationParamsSchema), async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const query = c.req.valid('query')
const res = await chatService.listSessions(user.id, query)
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
const res = await chatService.listSessions(user.id, teamId, query)
return c.json(res, 200)
})
.get('/chat/sessions/:sessionId/messages', async (c) => {
.get('/teams/:teamId/chat/sessions/:sessionId/messages', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const sessionId = c.req.param('sessionId')
const res = await chatService.listMessages(user.id, sessionId)
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
const res = await chatService.listMessages(user.id, teamId, sessionId)
return c.json(res, 200)
})
.delete('/chat/sessions/:sessionId', async (c) => {
.delete('/teams/:teamId/chat/sessions/:sessionId', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const sessionId = c.req.param('sessionId')
await chatService.deleteSession(user.id, sessionId)
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
await chatService.deleteSession(user.id, teamId, sessionId)
return new Response(null, { status: 204 })
})
.post('/chat', zValidator('json', chatRequestSchema), async (c) => {
.post('/teams/:teamId/chat', zValidator('json', chatRequestSchema), async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
const { sessionId, taskId } = await chatService.startOrContinueChat(user, req)
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
const { sessionId, taskId } = await chatService.startOrContinueChat(user, teamId, req)
c.header('x-session-id', sessionId)
return streamSSE(c, async (stream) => {
// Send session ID as the first event
await stream.writeSSE({
data: JSON.stringify({
type: 'session',
sessionId,
}),
})
let lastEntryId = ''
const timeoutMs = 5 * 60 * 1000 // 5 minutes timeout
const startTime = Date.now()
@@ -57,6 +100,7 @@ const route = new Hono<{ Variables: { user: User } }>()
if (newEntries.length > 0) {
for (const record of newEntries) {
const message = mapEntryToMessage(record)
if (!message) continue
await stream.writeSSE({
data: JSON.stringify({
type: 'entry',
@@ -65,6 +109,12 @@ const route = new Hono<{ Variables: { user: User } }>()
})
}
lastEntryId = newEntries[newEntries.length - 1].id
} else {
await stream.writeSSE({
data: JSON.stringify({
type: 'ping',
}),
})
}
// Check if workflow has finished
@@ -84,6 +134,7 @@ const route = new Hono<{ Variables: { user: User } }>()
})
for (const record of finalEntries) {
const message = mapEntryToMessage(record)
if (!message) continue
await stream.writeSSE({
data: JSON.stringify({
type: 'entry',
+140 -28
View File
@@ -1,6 +1,6 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { chatService, buildSessionMessages, type PathEntry } from './chat'
import { chatService, buildSessionMessages, mapEntryToMessage, type PathEntry } from './chat'
import { describe, expect, it } from 'vitest'
describe('ChatService', () => {
@@ -14,7 +14,7 @@ describe('ChatService', () => {
const team = await prisma.team.create({
data: {
name: 'Test Team',
settings: { transcode: { videoStrategy: 'best_match' } },
settings: { transcode: { videoStrategy: 'best_match' }, chatbotAgentId: 'test-agent-id' },
sandbox: { create: {} },
},
})
@@ -73,10 +73,10 @@ describe('ChatService', () => {
}
it('should start a new chat session and trigger workflow', async () => {
const { user, project, rootFolder, agent } = await setupBasicData()
const { user, team, project, rootFolder } = await setupBasicData()
const { sessionId, taskId } = await chatService.startOrContinueChat(user, {
agentId: agent.id,
const { sessionId, taskId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello world',
projectId: project.id,
})
@@ -117,11 +117,11 @@ describe('ChatService', () => {
})
it('should continue an existing chat session', async () => {
const { user, project, agent } = await setupBasicData()
const { user, team, project } = await setupBasicData()
// Start
const { sessionId } = await chatService.startOrContinueChat(user, {
agentId: agent.id,
const { sessionId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'first message',
projectId: project.id,
})
@@ -129,8 +129,9 @@ describe('ChatService', () => {
// Continue
const { sessionId: nextSessionId, taskId: nextTaskId } = await chatService.startOrContinueChat(
user,
team.id,
{
agentId: agent.id,
agentId: 'test-agent-id',
textPrompt: 'second message',
sessionId,
},
@@ -156,7 +157,7 @@ describe('ChatService', () => {
})
it('should inject context of referenced assets and attached files', async () => {
const { user, project, rootFolder, agent } = await setupBasicData()
const { user, team, project, rootFolder } = await setupBasicData()
const childFolder = await prisma.asset.create({
data: {
@@ -186,8 +187,8 @@ describe('ChatService', () => {
},
})
const { taskId } = await chatService.startOrContinueChat(user, {
agentId: agent.id,
const { taskId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'process file',
projectId: project.id,
assetIds: [childFolder.id],
@@ -206,30 +207,41 @@ describe('ChatService', () => {
expect(taskPayload?.agent?.imageUrls).toContain('doc_s3_key')
})
it('should list sessions of a user', async () => {
const { user, project, agent } = await setupBasicData()
it('should list sessions of a user and only return chat type sessions', async () => {
const { user, team, project } = await setupBasicData()
await chatService.startOrContinueChat(user, {
agentId: agent.id,
await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'chat 1',
projectId: project.id,
})
await chatService.startOrContinueChat(user, {
agentId: agent.id,
await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'chat 2',
projectId: project.id,
})
const list = await chatService.listSessions(user.id, { first: 10 })
// Create a comment type session (which should be ignored by listSessions)
const defaultAgent = await prisma.agent.findFirst()
await prisma.agentSession.create({
data: {
agentId: defaultAgent ? defaultAgent.id : 'default',
userId: user.id,
cwd: process.cwd(),
type: 'comment',
},
})
const list = await chatService.listSessions(user.id, team.id, { first: 10 })
expect(list.data).toHaveLength(2)
})
it('should list messages mapped correctly', async () => {
const { user, project, agent } = await setupBasicData()
const { user, team, project } = await setupBasicData()
const { sessionId } = await chatService.startOrContinueChat(user, {
agentId: agent.id,
const { sessionId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello',
projectId: project.id,
})
@@ -253,7 +265,7 @@ describe('ChatService', () => {
},
})
const messages = await chatService.listMessages(user.id, sessionId)
const messages = await chatService.listMessages(user.id, team.id, sessionId)
expect(messages).toHaveLength(1)
// Casting to any to access properties of union in test assertions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -262,16 +274,116 @@ describe('ChatService', () => {
expect(msg.content).toEqual([{ type: 'text', text: 'hello' }])
})
it('should delete session and cascade', async () => {
const { user, project, agent } = await setupBasicData()
it('should hide customType context messages', async () => {
const { user, team, project } = await setupBasicData()
const { sessionId } = await chatService.startOrContinueChat(user, {
agentId: agent.id,
const { sessionId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello',
projectId: project.id,
})
// 1. Manually insert a test entry representing user message
await prisma.agentSessionEntry.create({
data: {
id: 'test-entry-1-user',
sessionId,
entry: {
type: 'message',
id: 'test-entry-1-user',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: [{ type: 'text', text: 'hello' }],
timestamp: Date.now(),
},
} as unknown as PrismaJson.PiSessionEntry,
},
})
// 2. Manually insert a test entry representing a custom context message
await prisma.agentSessionEntry.create({
data: {
id: 'test-entry-2-context',
sessionId,
entry: {
type: 'custom_message',
id: 'test-entry-2-context',
parentId: 'test-entry-1-user',
timestamp: new Date().toISOString(),
customType: 'context',
content: 'some context',
display: 'chat',
} as unknown as PrismaJson.PiSessionEntry,
},
})
// 3. Manually insert a test entry representing a custom thinking level change
await prisma.agentSessionEntry.create({
data: {
id: 'test-entry-3-thinking',
sessionId,
entry: {
type: 'thinking_level_change',
id: 'test-entry-3-thinking',
parentId: 'test-entry-2-context',
timestamp: new Date().toISOString(),
thinkingLevel: 'deep',
} as unknown as PrismaJson.PiSessionEntry,
},
})
// 4. Manually insert a test entry representing custom context_display_info entry
await prisma.agentSessionEntry.create({
data: {
id: 'test-entry-4-display',
sessionId,
entry: {
type: 'custom',
id: 'test-entry-4-display',
parentId: 'test-entry-3-thinking',
timestamp: new Date().toISOString(),
customType: 'context_display_info',
data: {
assets: [{ id: 'a1', name: 'File A', type: 'file' }],
},
} as unknown as PrismaJson.PiSessionEntry,
},
})
// Verify listMessages returns only the user, thinking level change and custom display entry message
const messages = await chatService.listMessages(user.id, team.id, sessionId)
expect(messages).toHaveLength(3)
expect(messages[0].id).toBe('test-entry-1-user')
expect(messages[1].id).toBe('test-entry-3-thinking')
expect(messages[2].id).toBe('test-entry-4-display')
expect(messages[2].role).toBe('custom')
expect((messages[2] as { customType?: string }).customType).toBe('context_display_info')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((messages[2] as any).details).toEqual({
assets: [{ id: 'a1', name: 'File A', type: 'file' }],
})
// Verify mapEntryToMessage returns null for context message
const contextRecord = await prisma.agentSessionEntry.findUnique({
where: { id: 'test-entry-2-context' },
})
expect(contextRecord).not.toBeNull()
const mapped = mapEntryToMessage(contextRecord!)
expect(mapped).toBeNull()
})
it('should delete session and cascade', async () => {
const { user, team, project } = await setupBasicData()
const { sessionId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'to delete',
projectId: project.id,
})
await chatService.deleteSession(user.id, sessionId)
await chatService.deleteSession(user.id, team.id, sessionId)
const session = await prisma.agentSession.findUnique({
where: { id: sessionId },
+40 -6
View File
@@ -28,6 +28,7 @@ export function buildSessionMessages(pathEntries: PathEntry[]): ChatMessage[] {
timestamp: entry.message.timestamp || timestampMs,
} as unknown as ChatMessage)
} else if (entry.type === 'custom_message') {
if (entry.customType === 'context') return
messages.push({
id: entry.id,
role: 'custom',
@@ -37,6 +38,14 @@ export function buildSessionMessages(pathEntries: PathEntry[]): ChatMessage[] {
details: entry.details as Record<string, unknown> | undefined,
timestamp: timestampMs,
} as unknown as ChatMessage)
} else if (entry.type === 'custom') {
messages.push({
id: entry.id,
role: 'custom',
customType: entry.customType,
details: (entry as { data?: unknown }).data as Record<string, unknown> | undefined,
timestamp: timestampMs,
} as unknown as ChatMessage)
} else if (entry.type === 'branch_summary') {
messages.push({
id: entry.id,
@@ -89,8 +98,14 @@ export function buildSessionMessages(pathEntries: PathEntry[]): ChatMessage[] {
export function mapEntryToMessage(
entryRecord: Prisma.AgentSessionEntryGetPayload<Record<string, never>>,
): ChatMessage {
): ChatMessage | null {
const entryObj = entryRecord.entry as unknown as SessionTreeEntry
if (
entryObj.type === 'custom_message' &&
(entryObj as { customType?: string }).customType === 'context'
) {
return null
}
const pathEntries = [{ ...entryObj, id: entryRecord.id }]
const messages = buildSessionMessages(pathEntries)
if (messages.length > 0) {
@@ -126,6 +141,7 @@ export class ChatService {
async startOrContinueChat(
user: User,
teamId: string,
req: ChatRequest,
): Promise<{ sessionId: string; taskId: string }> {
const {
@@ -232,20 +248,30 @@ export class ChatService {
const teamId = asset.project.teamId
const projectId = asset.project.id
let activeSessionId = passedSessionId
// Ensure AI agent configuration exists
const agent = await tx.agent.findUnique({ where: { id: agentId } })
if (!agent) {
throw new Error(`Agent with ID "${agentId}" not found`)
}
let activeSessionId = passedSessionId
if (agent.teamId !== teamId) {
throw new Error(`Agent does not belong to the specified team`)
}
if (activeSessionId) {
const sessionExists = await tx.agentSession.findUnique({
where: { id: activeSessionId },
select: { id: true },
select: { id: true, userId: true },
})
if (!sessionExists) throw new Error('Session not found')
if (sessionExists.userId !== user.id) throw new Error('Unauthorized session access')
// Update the session's agentId to match the selected agent
await tx.agentSession.update({
where: { id: activeSessionId },
data: { agentId },
})
} else {
const newSession = await tx.agentSession.create({
data: {
@@ -253,6 +279,7 @@ export class ChatService {
userId: user.id,
cwd: process.cwd(),
assetId: asset.id,
type: 'chat',
},
})
activeSessionId = newSession.id
@@ -276,6 +303,7 @@ export class ChatService {
agentId,
sessionId: activeSessionId,
userId: user.id,
isNewChat: !passedSessionId,
},
},
},
@@ -290,10 +318,15 @@ export class ChatService {
async listSessions(
userId: string,
teamId: string,
params: { first?: number; after?: string },
): Promise<PaginatedData<ChatSessionInfo[]>> {
const where: Prisma.AgentSessionWhereInput = {
userId,
type: 'chat',
agent: {
teamId,
},
}
return await paginateQuery(
@@ -310,6 +343,7 @@ export class ChatService {
userId: s.userId,
assetId: s.assetId,
userCommentId: s.userCommentId,
name: s.name,
createdAt: s.createdAt.toISOString(),
updatedAt: s.updatedAt.toISOString(),
}))
@@ -319,7 +353,7 @@ export class ChatService {
)
}
async listMessages(userId: string, sessionId: string): Promise<ChatMessage[]> {
async listMessages(userId: string, teamId: string, sessionId: string): Promise<ChatMessage[]> {
const session = await this.prismaClient.agentSession.findUnique({
where: { id: sessionId },
})
@@ -346,7 +380,7 @@ export class ChatService {
return buildSessionMessages(pathEntries)
}
async deleteSession(userId: string, sessionId: string): Promise<void> {
async deleteSession(userId: string, teamId: string, sessionId: string): Promise<void> {
const session = await this.prismaClient.agentSession.findUnique({
where: { id: sessionId },
})
@@ -0,0 +1,8 @@
-- CreateEnum
CREATE TYPE "AgentSessionType" AS ENUM ('comment', 'chat');
-- AlterTable
ALTER TABLE "agent_sessions" ADD COLUMN "type" "AgentSessionType" NOT NULL DEFAULT 'comment';
-- CreateIndex
CREATE INDEX "agent_sessions_type_idx" ON "agent_sessions"("type");
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "agent_sessions" ADD COLUMN "name" TEXT;
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "AgentSessionType" ADD VALUE 'naming';
+9
View File
@@ -645,6 +645,12 @@ enum AgentType {
embedding
}
enum AgentSessionType {
comment
chat
naming
}
model Agent {
id String @id
user User @relation(fields: [id], references: [id], onDelete: Cascade)
@@ -693,11 +699,14 @@ model AgentSession {
assetId String? @map("asset_id")
asset Asset? @relation("AssetToAgentSession", fields: [assetId], references: [id], onDelete: Cascade)
userCommentId String? @map("user_comment_id")
type AgentSessionType @default(comment)
name String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
entries AgentSessionEntry[]
comments AssetComment[]
@@index([type])
@@map("agent_sessions")
}
+34
View File
@@ -626,6 +626,23 @@ export type JsonWithAggregatesFilterBase<$PrismaModel = never> = {
_max?: Prisma.NestedJsonFilter<$PrismaModel>
}
export type EnumAgentSessionTypeFilter<$PrismaModel = never> = {
equals?: $Enums.AgentSessionType | Prisma.EnumAgentSessionTypeFieldRefInput<$PrismaModel>
in?: $Enums.AgentSessionType[] | Prisma.ListEnumAgentSessionTypeFieldRefInput<$PrismaModel>
notIn?: $Enums.AgentSessionType[] | Prisma.ListEnumAgentSessionTypeFieldRefInput<$PrismaModel>
not?: Prisma.NestedEnumAgentSessionTypeFilter<$PrismaModel> | $Enums.AgentSessionType
}
export type EnumAgentSessionTypeWithAggregatesFilter<$PrismaModel = never> = {
equals?: $Enums.AgentSessionType | Prisma.EnumAgentSessionTypeFieldRefInput<$PrismaModel>
in?: $Enums.AgentSessionType[] | Prisma.ListEnumAgentSessionTypeFieldRefInput<$PrismaModel>
notIn?: $Enums.AgentSessionType[] | Prisma.ListEnumAgentSessionTypeFieldRefInput<$PrismaModel>
not?: Prisma.NestedEnumAgentSessionTypeWithAggregatesFilter<$PrismaModel> | $Enums.AgentSessionType
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedEnumAgentSessionTypeFilter<$PrismaModel>
_max?: Prisma.NestedEnumAgentSessionTypeFilter<$PrismaModel>
}
export type NestedStringFilter<$PrismaModel = never> = {
equals?: string | Prisma.StringFieldRefInput<$PrismaModel>
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
@@ -1184,4 +1201,21 @@ export type NestedJsonFilterBase<$PrismaModel = never> = {
not?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
}
export type NestedEnumAgentSessionTypeFilter<$PrismaModel = never> = {
equals?: $Enums.AgentSessionType | Prisma.EnumAgentSessionTypeFieldRefInput<$PrismaModel>
in?: $Enums.AgentSessionType[] | Prisma.ListEnumAgentSessionTypeFieldRefInput<$PrismaModel>
notIn?: $Enums.AgentSessionType[] | Prisma.ListEnumAgentSessionTypeFieldRefInput<$PrismaModel>
not?: Prisma.NestedEnumAgentSessionTypeFilter<$PrismaModel> | $Enums.AgentSessionType
}
export type NestedEnumAgentSessionTypeWithAggregatesFilter<$PrismaModel = never> = {
equals?: $Enums.AgentSessionType | Prisma.EnumAgentSessionTypeFieldRefInput<$PrismaModel>
in?: $Enums.AgentSessionType[] | Prisma.ListEnumAgentSessionTypeFieldRefInput<$PrismaModel>
notIn?: $Enums.AgentSessionType[] | Prisma.ListEnumAgentSessionTypeFieldRefInput<$PrismaModel>
not?: Prisma.NestedEnumAgentSessionTypeWithAggregatesFilter<$PrismaModel> | $Enums.AgentSessionType
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedEnumAgentSessionTypeFilter<$PrismaModel>
_max?: Prisma.NestedEnumAgentSessionTypeFilter<$PrismaModel>
}
+9
View File
@@ -153,3 +153,12 @@ export const AgentType = {
} as const
export type AgentType = (typeof AgentType)[keyof typeof AgentType]
export const AgentSessionType = {
comment: 'comment',
chat: 'chat',
naming: 'naming'
} as const
export type AgentSessionType = (typeof AgentSessionType)[keyof typeof AgentSessionType]
File diff suppressed because one or more lines are too long
@@ -3308,6 +3308,8 @@ export const AgentSessionScalarFieldEnum = {
leafId: 'leafId',
assetId: 'assetId',
userCommentId: 'userCommentId',
type: 'type',
name: 'name',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
@@ -3728,6 +3730,20 @@ export type EnumAgentTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$Prisma
export type ListEnumAgentTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AgentType[]'>
/**
* Reference to a field of type 'AgentSessionType'
*/
export type EnumAgentSessionTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AgentSessionType'>
/**
* Reference to a field of type 'AgentSessionType[]'
*/
export type ListEnumAgentSessionTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AgentSessionType[]'>
/**
* Batch Payload for updateMany & deleteMany & createMany
*/
@@ -493,6 +493,8 @@ export const AgentSessionScalarFieldEnum = {
leafId: 'leafId',
assetId: 'assetId',
userCommentId: 'userCommentId',
type: 'type',
name: 'name',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
+115 -1
View File
@@ -34,6 +34,8 @@ export type AgentSessionMinAggregateOutputType = {
leafId: string | null
assetId: string | null
userCommentId: string | null
type: $Enums.AgentSessionType | null
name: string | null
createdAt: Date | null
updatedAt: Date | null
}
@@ -46,6 +48,8 @@ export type AgentSessionMaxAggregateOutputType = {
leafId: string | null
assetId: string | null
userCommentId: string | null
type: $Enums.AgentSessionType | null
name: string | null
createdAt: Date | null
updatedAt: Date | null
}
@@ -58,6 +62,8 @@ export type AgentSessionCountAggregateOutputType = {
leafId: number
assetId: number
userCommentId: number
type: number
name: number
createdAt: number
updatedAt: number
_all: number
@@ -72,6 +78,8 @@ export type AgentSessionMinAggregateInputType = {
leafId?: true
assetId?: true
userCommentId?: true
type?: true
name?: true
createdAt?: true
updatedAt?: true
}
@@ -84,6 +92,8 @@ export type AgentSessionMaxAggregateInputType = {
leafId?: true
assetId?: true
userCommentId?: true
type?: true
name?: true
createdAt?: true
updatedAt?: true
}
@@ -96,6 +106,8 @@ export type AgentSessionCountAggregateInputType = {
leafId?: true
assetId?: true
userCommentId?: true
type?: true
name?: true
createdAt?: true
updatedAt?: true
_all?: true
@@ -181,6 +193,8 @@ export type AgentSessionGroupByOutputType = {
leafId: string | null
assetId: string | null
userCommentId: string | null
type: $Enums.AgentSessionType
name: string | null
createdAt: Date
updatedAt: Date
_count: AgentSessionCountAggregateOutputType | null
@@ -214,6 +228,8 @@ export type AgentSessionWhereInput = {
leafId?: Prisma.StringNullableFilter<"AgentSession"> | string | null
assetId?: Prisma.StringNullableFilter<"AgentSession"> | string | null
userCommentId?: Prisma.StringNullableFilter<"AgentSession"> | string | null
type?: Prisma.EnumAgentSessionTypeFilter<"AgentSession"> | $Enums.AgentSessionType
name?: Prisma.StringNullableFilter<"AgentSession"> | string | null
createdAt?: Prisma.DateTimeFilter<"AgentSession"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"AgentSession"> | Date | string
agent?: Prisma.XOR<Prisma.AgentScalarRelationFilter, Prisma.AgentWhereInput>
@@ -231,6 +247,8 @@ export type AgentSessionOrderByWithRelationInput = {
leafId?: Prisma.SortOrderInput | Prisma.SortOrder
assetId?: Prisma.SortOrderInput | Prisma.SortOrder
userCommentId?: Prisma.SortOrderInput | Prisma.SortOrder
type?: Prisma.SortOrder
name?: Prisma.SortOrderInput | Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
agent?: Prisma.AgentOrderByWithRelationInput
@@ -251,6 +269,8 @@ export type AgentSessionWhereUniqueInput = Prisma.AtLeast<{
leafId?: Prisma.StringNullableFilter<"AgentSession"> | string | null
assetId?: Prisma.StringNullableFilter<"AgentSession"> | string | null
userCommentId?: Prisma.StringNullableFilter<"AgentSession"> | string | null
type?: Prisma.EnumAgentSessionTypeFilter<"AgentSession"> | $Enums.AgentSessionType
name?: Prisma.StringNullableFilter<"AgentSession"> | string | null
createdAt?: Prisma.DateTimeFilter<"AgentSession"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"AgentSession"> | Date | string
agent?: Prisma.XOR<Prisma.AgentScalarRelationFilter, Prisma.AgentWhereInput>
@@ -268,6 +288,8 @@ export type AgentSessionOrderByWithAggregationInput = {
leafId?: Prisma.SortOrderInput | Prisma.SortOrder
assetId?: Prisma.SortOrderInput | Prisma.SortOrder
userCommentId?: Prisma.SortOrderInput | Prisma.SortOrder
type?: Prisma.SortOrder
name?: Prisma.SortOrderInput | Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
_count?: Prisma.AgentSessionCountOrderByAggregateInput
@@ -286,6 +308,8 @@ export type AgentSessionScalarWhereWithAggregatesInput = {
leafId?: Prisma.StringNullableWithAggregatesFilter<"AgentSession"> | string | null
assetId?: Prisma.StringNullableWithAggregatesFilter<"AgentSession"> | string | null
userCommentId?: Prisma.StringNullableWithAggregatesFilter<"AgentSession"> | string | null
type?: Prisma.EnumAgentSessionTypeWithAggregatesFilter<"AgentSession"> | $Enums.AgentSessionType
name?: Prisma.StringNullableWithAggregatesFilter<"AgentSession"> | string | null
createdAt?: Prisma.DateTimeWithAggregatesFilter<"AgentSession"> | Date | string
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"AgentSession"> | Date | string
}
@@ -295,6 +319,8 @@ export type AgentSessionCreateInput = {
cwd: string
leafId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
agent: Prisma.AgentCreateNestedOneWithoutAgentSessionsInput
@@ -312,6 +338,8 @@ export type AgentSessionUncheckedCreateInput = {
leafId?: string | null
assetId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
entries?: Prisma.AgentSessionEntryUncheckedCreateNestedManyWithoutSessionInput
@@ -323,6 +351,8 @@ export type AgentSessionUpdateInput = {
cwd?: Prisma.StringFieldUpdateOperationsInput | string
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
agent?: Prisma.AgentUpdateOneRequiredWithoutAgentSessionsNestedInput
@@ -340,6 +370,8 @@ export type AgentSessionUncheckedUpdateInput = {
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
entries?: Prisma.AgentSessionEntryUncheckedUpdateManyWithoutSessionNestedInput
@@ -354,6 +386,8 @@ export type AgentSessionCreateManyInput = {
leafId?: string | null
assetId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -363,6 +397,8 @@ export type AgentSessionUpdateManyMutationInput = {
cwd?: Prisma.StringFieldUpdateOperationsInput | string
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -375,6 +411,8 @@ export type AgentSessionUncheckedUpdateManyInput = {
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -402,6 +440,8 @@ export type AgentSessionCountOrderByAggregateInput = {
leafId?: Prisma.SortOrder
assetId?: Prisma.SortOrder
userCommentId?: Prisma.SortOrder
type?: Prisma.SortOrder
name?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
}
@@ -414,6 +454,8 @@ export type AgentSessionMaxOrderByAggregateInput = {
leafId?: Prisma.SortOrder
assetId?: Prisma.SortOrder
userCommentId?: Prisma.SortOrder
type?: Prisma.SortOrder
name?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
}
@@ -426,6 +468,8 @@ export type AgentSessionMinOrderByAggregateInput = {
leafId?: Prisma.SortOrder
assetId?: Prisma.SortOrder
userCommentId?: Prisma.SortOrder
type?: Prisma.SortOrder
name?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
}
@@ -577,6 +621,10 @@ export type AgentSessionUncheckedUpdateManyWithoutAgentNestedInput = {
deleteMany?: Prisma.AgentSessionScalarWhereInput | Prisma.AgentSessionScalarWhereInput[]
}
export type EnumAgentSessionTypeFieldUpdateOperationsInput = {
set?: $Enums.AgentSessionType
}
export type AgentSessionCreateNestedOneWithoutEntriesInput = {
create?: Prisma.XOR<Prisma.AgentSessionCreateWithoutEntriesInput, Prisma.AgentSessionUncheckedCreateWithoutEntriesInput>
connectOrCreate?: Prisma.AgentSessionCreateOrConnectWithoutEntriesInput
@@ -596,6 +644,8 @@ export type AgentSessionCreateWithoutUserInput = {
cwd: string
leafId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
agent: Prisma.AgentCreateNestedOneWithoutAgentSessionsInput
@@ -611,6 +661,8 @@ export type AgentSessionUncheckedCreateWithoutUserInput = {
leafId?: string | null
assetId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
entries?: Prisma.AgentSessionEntryUncheckedCreateNestedManyWithoutSessionInput
@@ -654,6 +706,8 @@ export type AgentSessionScalarWhereInput = {
leafId?: Prisma.StringNullableFilter<"AgentSession"> | string | null
assetId?: Prisma.StringNullableFilter<"AgentSession"> | string | null
userCommentId?: Prisma.StringNullableFilter<"AgentSession"> | string | null
type?: Prisma.EnumAgentSessionTypeFilter<"AgentSession"> | $Enums.AgentSessionType
name?: Prisma.StringNullableFilter<"AgentSession"> | string | null
createdAt?: Prisma.DateTimeFilter<"AgentSession"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"AgentSession"> | Date | string
}
@@ -663,6 +717,8 @@ export type AgentSessionCreateWithoutAssetInput = {
cwd: string
leafId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
agent: Prisma.AgentCreateNestedOneWithoutAgentSessionsInput
@@ -678,6 +734,8 @@ export type AgentSessionUncheckedCreateWithoutAssetInput = {
cwd: string
leafId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
entries?: Prisma.AgentSessionEntryUncheckedCreateNestedManyWithoutSessionInput
@@ -715,6 +773,8 @@ export type AgentSessionCreateWithoutCommentsInput = {
cwd: string
leafId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
agent: Prisma.AgentCreateNestedOneWithoutAgentSessionsInput
@@ -731,6 +791,8 @@ export type AgentSessionUncheckedCreateWithoutCommentsInput = {
leafId?: string | null
assetId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
entries?: Prisma.AgentSessionEntryUncheckedCreateNestedManyWithoutSessionInput
@@ -757,6 +819,8 @@ export type AgentSessionUpdateWithoutCommentsInput = {
cwd?: Prisma.StringFieldUpdateOperationsInput | string
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
agent?: Prisma.AgentUpdateOneRequiredWithoutAgentSessionsNestedInput
@@ -773,6 +837,8 @@ export type AgentSessionUncheckedUpdateWithoutCommentsInput = {
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
entries?: Prisma.AgentSessionEntryUncheckedUpdateManyWithoutSessionNestedInput
@@ -783,6 +849,8 @@ export type AgentSessionCreateWithoutAgentInput = {
cwd: string
leafId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
user?: Prisma.UserCreateNestedOneWithoutAgentSessionsInput
@@ -798,6 +866,8 @@ export type AgentSessionUncheckedCreateWithoutAgentInput = {
leafId?: string | null
assetId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
entries?: Prisma.AgentSessionEntryUncheckedCreateNestedManyWithoutSessionInput
@@ -835,6 +905,8 @@ export type AgentSessionCreateWithoutEntriesInput = {
cwd: string
leafId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
agent: Prisma.AgentCreateNestedOneWithoutAgentSessionsInput
@@ -851,6 +923,8 @@ export type AgentSessionUncheckedCreateWithoutEntriesInput = {
leafId?: string | null
assetId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
comments?: Prisma.AssetCommentUncheckedCreateNestedManyWithoutSessionInput
@@ -877,6 +951,8 @@ export type AgentSessionUpdateWithoutEntriesInput = {
cwd?: Prisma.StringFieldUpdateOperationsInput | string
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
agent?: Prisma.AgentUpdateOneRequiredWithoutAgentSessionsNestedInput
@@ -893,6 +969,8 @@ export type AgentSessionUncheckedUpdateWithoutEntriesInput = {
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
comments?: Prisma.AssetCommentUncheckedUpdateManyWithoutSessionNestedInput
@@ -905,6 +983,8 @@ export type AgentSessionCreateManyUserInput = {
leafId?: string | null
assetId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -914,6 +994,8 @@ export type AgentSessionUpdateWithoutUserInput = {
cwd?: Prisma.StringFieldUpdateOperationsInput | string
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
agent?: Prisma.AgentUpdateOneRequiredWithoutAgentSessionsNestedInput
@@ -929,6 +1011,8 @@ export type AgentSessionUncheckedUpdateWithoutUserInput = {
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
entries?: Prisma.AgentSessionEntryUncheckedUpdateManyWithoutSessionNestedInput
@@ -942,6 +1026,8 @@ export type AgentSessionUncheckedUpdateManyWithoutUserInput = {
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -953,6 +1039,8 @@ export type AgentSessionCreateManyAssetInput = {
cwd: string
leafId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -962,6 +1050,8 @@ export type AgentSessionUpdateWithoutAssetInput = {
cwd?: Prisma.StringFieldUpdateOperationsInput | string
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
agent?: Prisma.AgentUpdateOneRequiredWithoutAgentSessionsNestedInput
@@ -977,6 +1067,8 @@ export type AgentSessionUncheckedUpdateWithoutAssetInput = {
cwd?: Prisma.StringFieldUpdateOperationsInput | string
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
entries?: Prisma.AgentSessionEntryUncheckedUpdateManyWithoutSessionNestedInput
@@ -990,6 +1082,8 @@ export type AgentSessionUncheckedUpdateManyWithoutAssetInput = {
cwd?: Prisma.StringFieldUpdateOperationsInput | string
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -1001,6 +1095,8 @@ export type AgentSessionCreateManyAgentInput = {
leafId?: string | null
assetId?: string | null
userCommentId?: string | null
type?: $Enums.AgentSessionType
name?: string | null
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -1010,6 +1106,8 @@ export type AgentSessionUpdateWithoutAgentInput = {
cwd?: Prisma.StringFieldUpdateOperationsInput | string
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
user?: Prisma.UserUpdateOneWithoutAgentSessionsNestedInput
@@ -1025,6 +1123,8 @@ export type AgentSessionUncheckedUpdateWithoutAgentInput = {
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
entries?: Prisma.AgentSessionEntryUncheckedUpdateManyWithoutSessionNestedInput
@@ -1038,6 +1138,8 @@ export type AgentSessionUncheckedUpdateManyWithoutAgentInput = {
leafId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userCommentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
type?: Prisma.EnumAgentSessionTypeFieldUpdateOperationsInput | $Enums.AgentSessionType
name?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -1090,6 +1192,8 @@ export type AgentSessionSelect<ExtArgs extends runtime.Types.Extensions.Internal
leafId?: boolean
assetId?: boolean
userCommentId?: boolean
type?: boolean
name?: boolean
createdAt?: boolean
updatedAt?: boolean
agent?: boolean | Prisma.AgentDefaultArgs<ExtArgs>
@@ -1108,6 +1212,8 @@ export type AgentSessionSelectCreateManyAndReturn<ExtArgs extends runtime.Types.
leafId?: boolean
assetId?: boolean
userCommentId?: boolean
type?: boolean
name?: boolean
createdAt?: boolean
updatedAt?: boolean
agent?: boolean | Prisma.AgentDefaultArgs<ExtArgs>
@@ -1123,6 +1229,8 @@ export type AgentSessionSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.
leafId?: boolean
assetId?: boolean
userCommentId?: boolean
type?: boolean
name?: boolean
createdAt?: boolean
updatedAt?: boolean
agent?: boolean | Prisma.AgentDefaultArgs<ExtArgs>
@@ -1138,11 +1246,13 @@ export type AgentSessionSelectScalar = {
leafId?: boolean
assetId?: boolean
userCommentId?: boolean
type?: boolean
name?: boolean
createdAt?: boolean
updatedAt?: boolean
}
export type AgentSessionOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "agentId" | "userId" | "cwd" | "leafId" | "assetId" | "userCommentId" | "createdAt" | "updatedAt", ExtArgs["result"]["agentSession"]>
export type AgentSessionOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "agentId" | "userId" | "cwd" | "leafId" | "assetId" | "userCommentId" | "type" | "name" | "createdAt" | "updatedAt", ExtArgs["result"]["agentSession"]>
export type AgentSessionInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
agent?: boolean | Prisma.AgentDefaultArgs<ExtArgs>
user?: boolean | Prisma.AgentSession$userArgs<ExtArgs>
@@ -1179,6 +1289,8 @@ export type $AgentSessionPayload<ExtArgs extends runtime.Types.Extensions.Intern
leafId: string | null
assetId: string | null
userCommentId: string | null
type: $Enums.AgentSessionType
name: string | null
createdAt: Date
updatedAt: Date
}, ExtArgs["result"]["agentSession"]>
@@ -1616,6 +1728,8 @@ export interface AgentSessionFieldRefs {
readonly leafId: Prisma.FieldRef<"AgentSession", 'String'>
readonly assetId: Prisma.FieldRef<"AgentSession", 'String'>
readonly userCommentId: Prisma.FieldRef<"AgentSession", 'String'>
readonly type: Prisma.FieldRef<"AgentSession", 'AgentSessionType'>
readonly name: Prisma.FieldRef<"AgentSession", 'String'>
readonly createdAt: Prisma.FieldRef<"AgentSession", 'DateTime'>
readonly updatedAt: Prisma.FieldRef<"AgentSession", 'DateTime'>
}
+1
View File
@@ -292,6 +292,7 @@ declare global {
imageUrls?: string[]
attachedFiles?: string[]
assetIds?: string[]
isNewChat?: boolean
}
// ----------------------------------------------------------------------
+1
View File
@@ -32,6 +32,7 @@ export const chatSessionInfoSchema = z.object({
userId: z.string().nullable(),
assetId: z.string().nullable(),
userCommentId: z.string().nullable(),
name: z.string().nullable().optional(),
createdAt: z.string(),
updatedAt: z.string(),
})
+1 -1
View File
@@ -71,7 +71,7 @@ export const VideoTranscodeStrategy = {
export type VideoTranscodeStrategy =
(typeof VideoTranscodeStrategy)[keyof typeof VideoTranscodeStrategy]
export const updateTeamSettingsRequestSchema = z.discriminatedUnion('key', [
export const updateTeamSettingsRequestSchema = z.union([
z.object({
key: z.literal('transcode.videoStrategy'),
value: z.nativeEnum(VideoTranscodeStrategy),
+74 -10
View File
@@ -1,5 +1,5 @@
import { Badge } from '@/ui/components/ui/badge'
import { client } from '@/ui/api/client'
import { Badge } from '@/ui/components/ui/badge'
import {
DropdownMenu,
DropdownMenuContent,
@@ -13,17 +13,33 @@ import {
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import {
BotFilled,
DockToLeft,
DockToLeftFilled,
DockToRight,
DockToRightFilled,
} from '@/ui/components/ui/icons'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/ui/components/ui/tooltip'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import type { AncestorFolder } from '@shumai/dtos'
import { Link, useNavigate } from '@tanstack/react-router'
import { Check, ChevronDown, Columns2, FileIcon, History, LayoutGrid, List } from 'lucide-react'
import {
Bot,
Check,
ChevronDown,
Columns2,
FileIcon,
History,
LayoutGrid,
List,
} from 'lucide-react'
interface BreadcrumbNavProps {
teamId: string
@@ -43,6 +59,8 @@ interface BreadcrumbNavProps {
onLeftSidebarToggle?: () => void
isRightSidebarCollapsed: boolean
onRightSidebarToggle: () => void
isChatbotOpen?: boolean
onChatbotToggle?: () => void
isPublic?: boolean
shareId?: string
onFolderClick?: (folderId: string) => void
@@ -81,6 +99,8 @@ export function BreadcrumbNav({
onLeftSidebarToggle,
isRightSidebarCollapsed,
onRightSidebarToggle,
isChatbotOpen = false,
onChatbotToggle,
isPublic = false,
onFolderClick,
fileId,
@@ -94,6 +114,8 @@ export function BreadcrumbNav({
const navigate = useNavigate()
const { canEdit } = usePermissions(projectId)
const isChatbotDisabled = false
const handleVersionClick = (versionId: string) => {
if (!fileId) return
if (isPublic && shareId) {
@@ -364,10 +386,10 @@ export function BreadcrumbNav({
)}
</div>
{!fileId && (
<div className="flex items-center gap-2">
<div className="flex flex-shrink-0 items-center gap-1 rounded-md border border-border bg-background p-1">
{/* Left Sidebar Toggle */}
{!isPublic && onLeftSidebarToggle && (
{!fileId && !isPublic && onLeftSidebarToggle && (
<button
onClick={onLeftSidebarToggle}
className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
@@ -382,7 +404,7 @@ export function BreadcrumbNav({
)}
{/* Card View */}
{!isPublic && displayStyle && onDisplayStyleChange && (
{!fileId && !isPublic && displayStyle && onDisplayStyleChange && (
<>
<button
onClick={() => onDisplayStyleChange('card')}
@@ -414,17 +436,59 @@ export function BreadcrumbNav({
{/* Right Sidebar Toggle */}
<button
onClick={onRightSidebarToggle}
className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
className={`rounded p-1.5 transition-colors ${
!isRightSidebarCollapsed && !isChatbotOpen
? 'bg-accent text-accent-foreground'
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
}`}
title={isRightSidebarCollapsed ? 'Show Right Sidebar' : 'Hide Right Sidebar'}
>
{isRightSidebarCollapsed ? (
<DockToRight className="h-4 w-4" />
) : (
{!isRightSidebarCollapsed && !isChatbotOpen ? (
<DockToRightFilled className="h-4 w-4 fill-primary stroke-0" />
) : (
<DockToRight className="h-4 w-4" />
)}
</button>
</div>
)}
{/* Chatbot Toggle Button */}
{!isPublic && onChatbotToggle && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span>
<button
disabled={isChatbotDisabled}
onClick={onChatbotToggle}
className={cn(
'h-9 w-9 flex items-center justify-center rounded-full border border-border bg-background transition-colors',
isChatbotOpen
? 'bg-accent text-accent-foreground'
: 'text-muted-foreground hover:bg-accent hover:text-foreground',
isChatbotDisabled && 'opacity-50 cursor-not-allowed',
)}
>
{isChatbotOpen ? (
<BotFilled className="h-6 w-6 text-primary transition-colors" />
) : (
<Bot className="h-6 w-6 text-muted-foreground transition-colors" />
)}
</button>
</span>
</TooltipTrigger>
<TooltipContent>
<p>
{isChatbotDisabled
? m.configure_chatbot_agent_first()
: isChatbotOpen
? m.hide_chatbot()
: m.show_chatbot()}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
</div>
)
}
@@ -0,0 +1,659 @@
import { client } from '@/ui/api/client'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
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 { useDroppable } from '@dnd-kit/react'
import type { ChatMessage } from '@shumai/dtos'
import { useQuery } from '@tanstack/react-query'
import {
ArrowLeft,
ArrowUp,
Bot,
Brain,
ChevronDown,
History,
Loader2,
Plus,
Trash2,
Wrench,
} from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import Markdown from 'react-markdown'
import { formatTimeAgo } from '../lib/time'
interface ChatbotSidebarProps {
projectId: string
contextAssetId?: string
}
export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProps) {
const {
isHistoryMode,
setIsHistoryMode,
currentSessionId,
chatAssets,
removeAsset,
messages,
historySessions,
isStreaming,
fetchHistorySessions,
loadSession,
deleteSession,
startNewSession,
sendMessage,
selectedAgentId,
setSelectedAgentId,
} = useChatbotStore()
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
useEffect(() => {
if (projectId) {
ensureTeamIdForProject(projectId)
}
}, [projectId, ensureTeamIdForProject])
const { data: agents = [] } = useQuery({
queryKey: ['agents', teamId],
queryFn: async () => {
if (!teamId) return []
const res = await client.api.teams[':teamId'].agents.$get({
param: { teamId },
})
if (!res.ok) throw new Error('failed to fetch agents')
return res.json()
},
enabled: !!teamId,
})
const chatAgents = agents.filter((a) => a.type === 'chat' && a.enabled)
useEffect(() => {
if (chatAgents.length > 0) {
const exists = chatAgents.some((a) => a.id === selectedAgentId)
if (!exists) {
setSelectedAgentId(chatAgents[0].id)
}
}
}, [chatAgents, selectedAgentId, setSelectedAgentId])
const [inputText, setInputText] = useState('')
const messagesEndRef = useRef<HTMLDivElement>(null)
const scrollAreaRef = useRef<HTMLDivElement>(null)
const isFirstScrollRef = useRef(true)
const isRestoringRef = useRef(true)
useEffect(() => {
isRestoringRef.current = true
isFirstScrollRef.current = true
}, [projectId, contextAssetId, isHistoryMode])
// Restore scroll position on mount or when navigation changes the project/context
useEffect(() => {
const viewport = scrollAreaRef.current?.querySelector('[data-slot="scroll-area-viewport"]')
if (!viewport) return
const { scrollTop, isAtBottom } = useChatbotStore.getState()
// Use a timeout to ensure the DOM has settled and scrollHeight is fully calculated
const timer = setTimeout(() => {
if (isAtBottom) {
viewport.scrollTop = viewport.scrollHeight
} else {
viewport.scrollTop = scrollTop
}
// Allow scroll events triggered by this restoration to fire and be ignored before tracking
const enableTimer = setTimeout(() => {
isRestoringRef.current = false
}, 50)
return () => clearTimeout(enableTimer)
}, 0)
return () => clearTimeout(timer)
}, [projectId, contextAssetId, isHistoryMode])
// Listen to scroll events on the viewport to save scroll state
useEffect(() => {
const viewport = scrollAreaRef.current?.querySelector('[data-slot="scroll-area-viewport"]')
if (!viewport) return
const handleScroll = () => {
if (isRestoringRef.current) return
const scrollTop = viewport.scrollTop
// We consider the user at the bottom if they are within 10px of the bottom boundary
const isAtBottom = viewport.scrollHeight - scrollTop - viewport.clientHeight < 10
useChatbotStore.getState().setScrollState(scrollTop, isAtBottom)
}
viewport.addEventListener('scroll', handleScroll)
return () => {
viewport.removeEventListener('scroll', handleScroll)
}
}, [projectId, contextAssetId, isHistoryMode])
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
id: 'chatbot-sidebar',
data: {
type: 'chatbot-sidebar',
},
})
// Auto-scroll messages list to bottom
useEffect(() => {
if (!isHistoryMode) {
const { isAtBottom } = useChatbotStore.getState()
if (isAtBottom || isStreaming) {
const behavior = isFirstScrollRef.current ? 'auto' : 'smooth'
messagesEndRef.current?.scrollIntoView({ behavior })
}
isFirstScrollRef.current = false
}
}, [messages, isStreaming, isHistoryMode])
// Fetch history when entering history mode
useEffect(() => {
if (isHistoryMode && teamId) {
fetchHistorySessions(teamId)
}
}, [isHistoryMode, fetchHistorySessions, teamId])
const handleSend = () => {
if (!inputText.trim() || isStreaming || !teamId) return
sendMessage(teamId, inputText, projectId, contextAssetId)
setInputText('')
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.nativeEvent.isComposing) return
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
handleSend()
}
}
const getMessageText = (content: unknown): string => {
if (typeof content === 'string') return content
if (Array.isArray(content)) {
return content
.map((c) => {
if (typeof c === 'string') return c
if (c && typeof c === 'object' && 'type' in c && c.type === 'text' && 'text' in c) {
return String((c as { text: unknown }).text)
}
return ''
})
.join('')
}
return ''
}
const preprocessMarkdown = (text: string): string => {
return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:')
}
const renderMessage = (msg: ChatMessage) => {
switch (msg.role as string) {
case 'user': {
const msgObj = msg as unknown as Record<string, unknown>
return (
<div key={msg.id} className="flex justify-end w-full">
<div className="bg-primary text-primary-foreground rounded-lg px-3 py-2 max-w-[85%] text-sm whitespace-pre-wrap shadow-xs break-words">
{getMessageText(msgObj.content)}
</div>
</div>
)
}
case 'assistant': {
const msgObj = msg as unknown as Record<string, unknown>
const content = msgObj.content as unknown[]
if (!content) return null
const renderedBlocks: React.ReactNode[] = []
content.forEach((block: unknown, idx: number) => {
if (!block || typeof block !== 'object') return
const b = block as unknown as Record<string, unknown>
switch (b.type) {
case 'text': {
const text = b.text
if (typeof text !== 'string' || !text.trim()) return
renderedBlocks.push(
<div
key={`txt-${idx}`}
className="text-sm leading-[1.8] prose prose-sm dark:prose-invert max-w-none break-words"
>
<Markdown
components={{
// eslint-disable-next-line @typescript-eslint/no-unused-vars
pre: ({ node, ...props }) => (
<pre
className="whitespace-pre-wrap break-all break-words bg-muted text-foreground p-4 rounded-md border border-border/50 font-mono text-sm"
{...props}
/>
),
}}
>
{preprocessMarkdown(text)}
</Markdown>
</div>,
)
break
}
case 'thinking': {
const thinking = b.thinking
if (typeof thinking !== 'string' || !thinking.trim()) return
renderedBlocks.push(
<details
key={`think-${idx}`}
className="group border border-border/50 rounded-lg bg-muted/20 my-2 overflow-hidden"
>
<summary className="flex items-center gap-2 p-2.5 text-xs font-medium text-muted-foreground select-none cursor-pointer hover:bg-muted/40 transition-colors list-none [&::-webkit-details-marker]:hidden">
<Brain className="h-3.5 w-3.5 text-primary/70 animate-pulse" />
<span>{m.role_thinking() || 'Thinking'}</span>
<ChevronDown className="h-3 w-3 ml-auto transition-transform group-open:rotate-180" />
</summary>
<div className="p-3 pt-0 text-xs text-muted-foreground/90 border-t border-border/40 bg-muted/10 leading-relaxed prose prose-sm dark:prose-invert max-w-none whitespace-pre-wrap font-sans">
<Markdown>{preprocessMarkdown(thinking)}</Markdown>
</div>
</details>,
)
break
}
case 'toolCall': {
const toolName = String(b.name || b.toolName || m.unknown())
const toolArgs = b.arguments || b.args
renderedBlocks.push(
<details
key={`tool-${idx}`}
className="group border border-border/50 rounded-lg bg-violet-500/5 my-2 overflow-hidden"
>
<summary className="flex items-center gap-2 p-2.5 text-xs font-semibold text-violet-600 dark:text-violet-400 select-none cursor-pointer hover:bg-violet-500/10 transition-colors list-none [&::-webkit-details-marker]:hidden">
<Wrench className="h-3.5 w-3.5" />
<span>{m.calling_tool()}</span>
<span className="font-mono bg-violet-500/10 px-1.5 py-0.5 rounded text-[11px] text-violet-700 dark:text-violet-300">
{toolName}
</span>
<ChevronDown className="h-3 w-3 ml-auto transition-transform group-open:rotate-180" />
</summary>
{!!toolArgs && (
<div className="p-3 pt-0 text-[10px] text-muted-foreground/90 border-t border-border/40 bg-violet-500/5 font-sans">
<div className="text-[9px] text-muted-foreground/60 uppercase font-bold tracking-wider mb-1.5">
{m.tool_arguments() || 'Arguments'}
</div>
<pre className="font-mono bg-muted/30 p-2 rounded border border-border/30 overflow-x-auto max-h-32">
{JSON.stringify(toolArgs, null, 2)}
</pre>
</div>
)}
</details>,
)
break
}
case 'image': {
const mimeType = String(b.mimeType || 'image/png')
const data = String(b.data || '')
renderedBlocks.push(
<div key={`img-${idx}`} className="my-2 max-w-full">
{data ? (
<img
src={data.startsWith('data:') ? data : `data:${mimeType};base64,${data}`}
alt="Attached asset"
className="max-h-60 rounded border border-border/50 object-contain shadow-xs"
/>
) : (
<div className="text-xs text-muted-foreground italic flex items-center gap-1.5 py-1">
{m.image_object()}
</div>
)}
</div>,
)
break
}
default: {
const stringified = JSON.stringify(block, 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
let shouldShowFooter = false
if (content.length > 0) {
const lastBlock = content[content.length - 1]
if (typeof lastBlock === 'string' && lastBlock.trim().length > 0) {
shouldShowFooter = true
} else if (lastBlock && typeof lastBlock === 'object') {
const lb = lastBlock as Record<string, unknown>
if (lb.type === 'text' && typeof lb.text === 'string' && lb.text.trim().length > 0) {
shouldShowFooter = true
}
}
}
return (
<div key={msg.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">
{m.created_by_agent()}
</div>
)}
</div>
)
}
case 'toolResult': {
return (
<div
key={msg.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' })}
</span>
</div>
)
}
case 'thinking_level_change':
case 'custom': {
const msgObj = msg as unknown as Record<string, unknown>
if (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}
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>
<ul className="list-disc list-inside space-y-0.5">
{assets.map((asset) => (
<li key={asset.id} className="truncate">
{asset.name} <span className="text-muted-foreground/70">({asset.type})</span>
</li>
))}
</ul>
</div>
)
}
const systemContent = msgObj.content || ''
return (
<div
key={msg.id}
className="text-center text-xs text-muted-foreground italic bg-muted/20 py-1.5 rounded"
>
{getMessageText(systemContent)}
</div>
)
}
default:
return null
}
}
return (
<div
ref={setDroppableRef}
className={cn(
'relative flex flex-col h-full bg-background transition-colors duration-200 min-h-0',
)}
>
{isOver && (
<div className="absolute inset-0 bg-accent/30 border-2 border-primary z-50 pointer-events-none flex items-center justify-center p-6 text-center animate-in fade-in duration-150">
<div className="bg-background/95 text-foreground px-4 py-3 rounded-xl border border-border/80 flex flex-col items-center gap-2 shadow-lg max-w-[80%] animate-in zoom-in-95 duration-150">
<Bot className="h-6 w-6 text-primary animate-bounce" />
<span className="text-sm font-semibold text-foreground">
{m.chatbot_drag_drop_hint() || 'Drop assets here'}
</span>
</div>
</div>
)}
{/* Header section */}
<div className="flex items-center justify-between p-4 pt-[0.7rem] flex-shrink-0">
{isHistoryMode ? (
<>
<div className="flex items-center gap-2 font-semibold">
<span>{m.history()}</span>
</div>
<button
onClick={() => setIsHistoryMode(false)}
className="p-1.5 hover:bg-accent rounded-md text-muted-foreground hover:text-foreground transition-colors"
title="Close History"
>
<ArrowLeft className="h-4 w-4" />
</button>
</>
) : (
<>
<div className="flex items-center gap-2 font-semibold">
<span>{m.shumai_agent()}</span>
</div>
<div className="flex items-center gap-1">
<button
onClick={startNewSession}
className="p-1.5 hover:bg-accent rounded-md text-muted-foreground hover:text-foreground transition-colors"
title={m.new_chat()}
>
<Plus className="h-4 w-4" />
</button>
<button
onClick={() => setIsHistoryMode(true)}
className="p-1.5 hover:bg-accent rounded-md text-muted-foreground hover:text-foreground transition-colors"
title={m.history()}
>
<History className="h-4 w-4" />
</button>
</div>
</>
)}
</div>
{/* Main body view */}
{isHistoryMode ? (
<ScrollArea className="flex-1 p-4 min-h-0">
{historySessions.length === 0 ? (
<div className="flex flex-col items-center justify-center h-48 text-muted-foreground p-4 text-center">
<History className="h-8 w-8 mb-2 opacity-50 text-muted-foreground" />
<p className="text-sm">{m.no_history_sessions()}</p>
</div>
) : (
<div className="space-y-2 pb-4">
{historySessions.map((sess) => {
const isActive = sess.id === currentSessionId
return (
<div
key={sess.id}
className={cn(
'group relative flex items-center justify-between p-3 border rounded-lg transition-all cursor-pointer bg-card',
isActive ? 'border-primary' : 'border-border hover:bg-accent/30',
)}
>
<div
onClick={() => teamId && loadSession(teamId, sess.id)}
className="flex-1 min-w-0 pr-6"
>
<div className="text-sm font-semibold text-foreground truncate">
{sess.name || m.new_chat()}
</div>
<div className="text-xs text-muted-foreground mt-0.5">
{formatTimeAgo(sess.createdAt)}
</div>
</div>
<button
onClick={(e) => {
e.stopPropagation()
if (teamId && confirm(m.delete_session_confirm())) {
deleteSession(teamId, sess.id)
}
}}
className="absolute right-3 opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity text-muted-foreground hover:text-destructive p-1 rounded hover:bg-muted"
title="Delete Session"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
)
})}
</div>
)}
</ScrollArea>
) : (
<>
{/* Active Chat view */}
<ScrollArea ref={scrollAreaRef} className="flex-1 p-4 min-h-0 [&>div>div]:!block">
{messages.length === 0 ? (
<div className="flex flex-col items-center justify-center h-48 border-2 border-dashed border-border rounded-lg text-muted-foreground p-4 text-center">
<Bot className="h-8 w-8 mb-2 opacity-50 text-muted-foreground" />
<p className="text-sm">{m.chatbot_drag_drop_hint()}</p>
</div>
) : (
<div className="space-y-4 pb-4">
{messages.map(renderMessage)}
{isStreaming &&
messages.length > 0 &&
messages[messages.length - 1].role === 'user' && (
<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>Thinking...</span>
</div>
)}
<div ref={messagesEndRef} />
</div>
)}
</ScrollArea>
{/* Input Area (nested inside the border exactly like comment input) */}
<div className="p-2 flex-shrink-0 bg-background">
<div className="relative flex flex-col w-full border border-foreground/20 rounded-2xl shadow-xs transition-all duration-200 focus-within:ring-2 focus-within:ring-primary focus-within:border-transparent bg-background overflow-hidden">
{/* Context assets list at the top inside the border */}
{chatAssets.length > 0 && (
<div className="flex flex-col gap-1.5 min-h-0 max-h-[160px] overflow-y-auto border-b border-border bg-muted/5 p-3 divide-y divide-border/50">
{chatAssets.map((asset) => (
<div
key={asset.id}
className="flex items-center justify-between py-1.5 text-xs group"
>
<div className="flex items-baseline gap-1.5 min-w-0 pr-2">
<span className="truncate font-medium text-foreground">{asset.name}</span>
<span className="text-[9px] text-muted-foreground uppercase flex-shrink-0">
{asset.type}
</span>
</div>
<button
onClick={() => removeAsset(asset.id)}
className="text-muted-foreground hover:text-destructive transition-colors p-0.5"
title={m.remove_from_context()}
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
))}
</div>
)}
{/* Textarea inside the border */}
<textarea
value={inputText}
onChange={(e) => setInputText(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type a message..."
rows={2}
className="w-full bg-transparent border-none focus:ring-0 focus:outline-hidden resize-none min-h-[44px] max-h-[120px] px-3 py-2 text-sm focus-visible:outline-hidden focus:ring-transparent focus:border-transparent focus-visible:ring-0"
disabled={isStreaming}
/>
{/* Bottom row inside the border containing the agent selector and send button */}
<div className="flex justify-between items-center px-3 pb-2 pt-1">
{/* Agent selector */}
<div className="flex items-center gap-1.5 min-w-0 max-w-[70%]">
{chatAgents.length > 0 ? (
<Select
value={selectedAgentId || ''}
onValueChange={(val) => setSelectedAgentId(val)}
disabled={isStreaming}
>
<SelectTrigger className="h-8 border-none bg-transparent hover:bg-muted text-muted-foreground hover:text-foreground focus:ring-0 focus:ring-offset-0 px-2 py-0 gap-1.5 text-xs shrink-0 select-none shadow-none max-w-full">
<SelectValue placeholder={m.select_agent()} />
</SelectTrigger>
<SelectContent>
{chatAgents.map((agent) => (
<SelectItem key={agent.id} value={agent.id}>
<div className="flex items-center gap-2">
{agent.avatar ? (
<img
src={agent.avatar}
alt={agent.name}
className="w-4 h-4 rounded-full object-cover"
/>
) : (
<Bot className="w-4 h-4 text-muted-foreground" />
)}
<span className="text-xs">{agent.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<div className="flex items-center gap-1.5 px-2 py-1 text-[11px] text-muted-foreground/60 italic select-none">
<Bot className="h-3.5 w-3.5" />
<span>
{m.no_chat_agents_warning ? m.no_chat_agents_warning() : 'No agents'}
</span>
</div>
)}
</div>
<button
onClick={handleSend}
disabled={isStreaming || !inputText.trim() || !selectedAgentId}
className={cn(
'p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm',
inputText.trim() && !isStreaming && selectedAgentId
? 'bg-primary text-primary-foreground hover:bg-primary/95 transform hover:-translate-y-0.5'
: 'bg-muted text-muted-foreground cursor-not-allowed opacity-50',
)}
>
<ArrowUp className="h-4 w-4" />
</button>
</div>
</div>
</div>
</>
)}
</div>
)
}
@@ -1,13 +1,18 @@
import type { AssetInfo, AssetInfoPaginatedList } from '@shumai/dtos'
import type { CollectionInfo } from '@shumai/dtos'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import type { SearchCondition, SearchSort } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { m } from '@/ui/paraglide/messages.js'
import type {
AssetInfo,
AssetInfoPaginatedList,
CollectionInfo,
SearchCondition,
SearchSort,
} from '@shumai/dtos'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import { useMutation } from '@tanstack/react-query'
import { InferRequestType, InferResponseType } from 'hono/client'
import { m } from '@/ui/paraglide/messages.js'
import { useChatbotStore } from '@/ui/stores/chatbot'
import { useFieldStore } from '@/ui/stores/fields'
import { useMemberStore } from '@/ui/stores/members'
import { useTopNavStore } from '@/ui/stores/top-nav'
@@ -19,6 +24,7 @@ import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-quer
import { useNavigate } from '@tanstack/react-router'
import { useEffect, useMemo, useRef, useState } from 'react'
import { cn } from '../lib/utils'
import { ChatbotSidebar } from './chatbot-sidebar'
import { SnapToPointer } from './dnd-modifiers'
import { FileBrowser } from './file-browser/file-browser'
import { FileViewerRightSidebar } from './file-viewer-right-sidebar'
@@ -87,6 +93,7 @@ export default function FileSystemManager({
const [lastSelectedId, setLastSelectedId] = useState<string | null>(null)
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const { isChatbotOpen } = useChatbotStore()
const { members, fetchMembers } = useMemberStore()
const { metadata, fetchMetadata, setMetadata: setUserMetadata } = useUserMetadataStore()
@@ -433,10 +440,13 @@ export default function FileSystemManager({
onClick={() => setIsLeftSidebarCollapsed(true)}
/>
)}
{!isRightSidebarCollapsed && (
{(!isRightSidebarCollapsed || isChatbotOpen) && (
<div
className="md:hidden fixed inset-0 bg-black/50 z-40"
onClick={() => setIsRightSidebarCollapsed(true)}
onClick={() => {
setIsRightSidebarCollapsed(true)
useChatbotStore.getState().setIsChatbotOpen(false)
}}
/>
)}
@@ -495,7 +505,7 @@ export default function FileSystemManager({
rootFolderId={rootFolderId}
/>
{!isRightSidebarCollapsed && (
{(!isRightSidebarCollapsed || isChatbotOpen) && (
<>
<ResizeHandle
onResize={(delta) => {
@@ -505,9 +515,11 @@ export default function FileSystemManager({
/>
<div
style={{ width: rightSidebarWidth }}
className="bg-background border-l border-border flex flex-col flex-shrink-0"
className="bg-background flex flex-col flex-shrink-0"
>
{singleSelectedFile ? (
{isChatbotOpen ? (
<ChatbotSidebar projectId={projectId} contextAssetId={assetId} />
) : singleSelectedFile ? (
<FileViewerRightSidebar
teamId={teamId}
projectId={projectId}
@@ -213,6 +213,7 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
</div>
)}
{AGENT_TYPES.map((section) => {
const typeAgents = agents.filter((a) => a.type === section.type)
const Icon = section.icon
+30 -8
View File
@@ -2,10 +2,12 @@ import { useTopNavStore } from '@/ui/stores/top-nav'
import { BreadcrumbNav } from './breadcrumb-nav'
import { ShumaiLogo } from '@/ui/components/ui/icons'
import { useUiStore } from '@/ui/stores/ui'
import { useChatbotStore } from '@/ui/stores/chatbot'
export function TopNav() {
const { projectState } = useTopNavStore()
const uiStore = useUiStore()
const { isChatbotOpen, setIsChatbotOpen } = useChatbotStore()
if (!projectState) {
return <TeamHeader />
@@ -58,14 +60,32 @@ export function TopNav() {
const onRightSidebarToggle =
isPublic && projectState.onRightSidebarToggle
? projectState.onRightSidebarToggle
: () =>
isFileView
? uiStore.setFileViewRightSidebarCollapsed(!uiStore.fileViewRightSidebarCollapsed)
: isShareConfig
? uiStore.setShareConfigRightSidebarCollapsed(
!uiStore.shareConfigRightSidebarCollapsed,
)
: uiStore.setFileListRightSidebarCollapsed(!uiStore.fileListRightSidebarCollapsed)
: () => {
if (!isPublic && isChatbotOpen) {
setIsChatbotOpen(false)
if (isFileView) {
uiStore.setFileViewRightSidebarCollapsed(false)
} else if (isShareConfig) {
uiStore.setShareConfigRightSidebarCollapsed(false)
} else {
uiStore.setFileListRightSidebarCollapsed(false)
}
} else {
if (isFileView) {
uiStore.setFileViewRightSidebarCollapsed(!uiStore.fileViewRightSidebarCollapsed)
} else if (isShareConfig) {
uiStore.setShareConfigRightSidebarCollapsed(!uiStore.shareConfigRightSidebarCollapsed)
} else {
uiStore.setFileListRightSidebarCollapsed(!uiStore.fileListRightSidebarCollapsed)
}
}
}
const onChatbotToggle = isPublic
? undefined
: () => {
setIsChatbotOpen(!isChatbotOpen)
}
const displayStyle = projectId ? (uiStore.viewModes[projectId] ?? 'card') : 'card'
const onDisplayStyleChange = isPublic
@@ -88,6 +108,8 @@ export function TopNav() {
onLeftSidebarToggle={onLeftSidebarToggle}
isRightSidebarCollapsed={isRightSidebarCollapsed}
onRightSidebarToggle={onRightSidebarToggle}
isChatbotOpen={!isPublic && isChatbotOpen}
onChatbotToggle={onChatbotToggle}
isPublic={isPublic}
shareId={shareId}
fileId={fileId}
+28
View File
@@ -55,6 +55,34 @@ export const DockToRightFilled: React.FC<IconProps> = (props) => (
</svg>
)
/**
* Icon: Bot (Filled)
* A filled version of the Bot icon, useful when the chatbot sidebar is active.
*/
export const BotFilled: React.FC<IconProps> = (props) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
{...props}
>
<path d="M12 8V4H8" />
<path
d="M6 7H18A3 3 0 0 1 21 10V18A3 3 0 0 1 18 21H6A3 3 0 0 1 3 18V10A3 3 0 0 1 6 7ZM8 13V15A1 1 0 0 0 10 15V13A1 1 0 0 0 8 13ZM14 13V15A1 1 0 0 0 16 15V13A1 1 0 0 0 14 13Z"
fill="currentColor"
stroke="none"
/>
<path d="M2 14h2" />
<path d="M20 14h2" />
</svg>
)
export const NotificationFillIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -9,6 +9,7 @@ import { useState } from 'react'
import { toast } from 'sonner'
import type { DragEndEvent, DragStartEvent } from '@dnd-kit/react'
import type { DragState } from './dnd-types'
import { useChatbotStore } from '@/ui/stores/chatbot'
interface UseFileSystemDndProps {
teamId: string
@@ -188,6 +189,23 @@ export function useFileSystemDnd({
const targetId = (target.id as string).split(':').pop()!
const targetData = target.data as { type: string; item: AssetInfo } | undefined
if (targetData?.type === 'chatbot-sidebar') {
const draggedItems = [...folders, ...files].filter((item) =>
dragState.draggedIds.has(item.id!),
)
const chatAssets = draggedItems.map((item) => ({
id: item.id!,
name: item.name || 'Unnamed',
type: item.type as 'file' | 'folder',
}))
useChatbotStore.getState().addAssets(chatAssets)
onClearSelection()
setDragState(undefined)
return
}
if (targetData?.type === 'share-link') {
const shareId = targetId
const assetIds = Array.from(dragState.draggedIds)
+25
View File
@@ -167,3 +167,28 @@
.no-scrollbar::-webkit-scrollbar {
display: none; /* Chrome, Safari and Opera */
}
/* Style code blocks and inline code inside .prose (rendered markdown) */
.prose pre {
background-color: var(--muted);
color: var(--foreground);
padding: 1rem;
border-radius: var(--radius-md);
border: 1px solid var(--border);
font-family: var(--font-mono);
font-size: 0.875em;
overflow-x: auto;
}
.prose code {
font-family: var(--font-mono);
}
/* Style inline code (code not inside pre) */
.prose :not(pre) > code {
background-color: var(--muted);
color: var(--foreground);
padding: 0.15rem 0.3rem;
border-radius: var(--radius-sm);
font-size: 0.875em;
}
+23 -1
View File
@@ -6,6 +6,7 @@
"language": "Language",
"personal_info": "Personal Info",
"language_settings": "Language Settings",
"assets_added_to_context": "Assets added to context:",
"select_preferred_language": "Select your preferred display language.",
"settings": "Settings",
"welcome_back": "Welcome Back",
@@ -819,5 +820,26 @@
"created_by_at": "{time} by {author}",
"date_format_long": "MMMM d, yyyy",
"tool_result_with_name": "Tool Result: {name}",
"reply_to_message": "reply to: {message}"
"reply_to_message": "reply to: {message}",
"chatbot_context": "Chatbot Context",
"clear": "Clear",
"chatbot_drag_drop_hint": "Drag and drop files or folders here to add them to chatbot context",
"context_assets_count": "Context Assets ({count})",
"remove_from_context": "Remove from context",
"hide_chatbot": "Hide Chatbot",
"show_chatbot": "Show Chatbot",
"created_by_agent": "Created by Agent",
"new_chat": "New Chat",
"shumai_agent": "Shumai Agent",
"history": "History",
"send": "Send",
"no_history_sessions": "No chat history found.",
"delete_session_confirm": "Are you sure you want to delete this chat session?",
"configure_chatbot_agent_first": "Please configure a chatbot agent in team settings first.",
"global_chatbot": "Global Chatbot",
"global_chatbot_description": "Select the agent that handles conversation inside the global chatbot sidebar.",
"select_chatbot_agent": "Select chatbot agent",
"no_chat_agents_warning": "No chat agents found. Please create a Chat Agent below first.",
"settings_saved": "Settings saved successfully",
"select_agent": "Select Agent"
}
+23 -1
View File
@@ -6,6 +6,7 @@
"language": "语言",
"personal_info": "个人信息",
"language_settings": "语言设置",
"assets_added_to_context": "已添加至上下文的资源:",
"select_preferred_language": "选择您首选的显示语言。",
"settings": "设置",
"welcome_back": "欢迎回来",
@@ -819,5 +820,26 @@
"created_by_at": "{time} 由 {author} 创建",
"date_format_long": "yyyy年M月d日",
"tool_result_with_name": "工具结果:{name}",
"reply_to_message": "回复:{message}"
"reply_to_message": "回复:{message}",
"chatbot_context": "聊天机器人上下文",
"clear": "清空",
"chatbot_drag_drop_hint": "拖拽文件或文件夹到此处以添加到聊天机器人上下文",
"context_assets_count": "上下文资源 ({count})",
"remove_from_context": "从上下文中移除",
"hide_chatbot": "隐藏聊天机器人",
"show_chatbot": "显示聊天机器人",
"created_by_agent": "由智能体创建",
"new_chat": "开启新会话",
"shumai_agent": "数脉智能体",
"history": "历史记录",
"send": "发送",
"no_history_sessions": "暂无历史会话记录",
"delete_session_confirm": "您确定要删除此会话记录吗?",
"configure_chatbot_agent_first": "请先在团队设置中配置聊天机器人智能体。",
"global_chatbot": "全局聊天机器人",
"global_chatbot_description": "选择在全局聊天机器人边栏中进行对话的智能体。",
"select_chatbot_agent": "选择聊天机器人智能体",
"no_chat_agents_warning": "未找到聊天智能体。请先在下方创建聊天智能体。",
"settings_saved": "设置保存成功",
"select_agent": "选择智能体"
}
+21
View File
@@ -4,6 +4,7 @@ export * from "./uploads.js";
export * from "./language.js";
export * from "./personal_info.js";
export * from "./language_settings.js";
export * from "./assets_added_to_context.js";
export * from "./select_preferred_language.js";
export * from "./settings.js";
export * from "./welcome_back.js";
@@ -767,4 +768,24 @@ export * from "./created_by_at.js";
export * from "./date_format_long.js";
export * from "./tool_result_with_name.js";
export * from "./reply_to_message.js";
export * from "./chatbot_context.js";
export * from "./clear.js";
export * from "./chatbot_drag_drop_hint.js";
export * from "./context_assets_count.js";
export * from "./remove_from_context.js";
export * from "./hide_chatbot.js";
export * from "./show_chatbot.js";
export * from "./new_chat.js";
export * from "./shumai_agent.js";
export * from "./history.js";
export * from "./send.js";
export * from "./no_history_sessions.js";
export * from "./delete_session_confirm.js";
export * from "./configure_chatbot_agent_first.js";
export * from "./global_chatbot.js";
export * from "./global_chatbot_description.js";
export * from "./select_chatbot_agent.js";
export * from "./no_chat_agents_warning.js";
export * from "./settings_saved.js";
export * from "./select_agent.js";
export type LocalizedString = import("../runtime.js").LocalizedString;
+22 -1
View File
@@ -6,6 +6,7 @@ export * from './uploads.js'
export * from './language.js'
export * from './personal_info.js'
export * from './language_settings.js'
export * from './assets_added_to_context.js'
export * from './select_preferred_language.js'
export * from './settings.js'
export * from './welcome_back.js'
@@ -768,4 +769,24 @@ export * from './fullscreen.js'
export * from './created_by_at.js'
export * from './date_format_long.js'
export * from './tool_result_with_name.js'
export * from './reply_to_message.js'
export * from './reply_to_message.js'
export * from './chatbot_context.js'
export * from './clear.js'
export * from './chatbot_drag_drop_hint.js'
export * from './context_assets_count.js'
export * from './remove_from_context.js'
export * from './hide_chatbot.js'
export * from './show_chatbot.js'
export * from './new_chat.js'
export * from './shumai_agent.js'
export * from './history.js'
export * from './send.js'
export * from './no_history_sessions.js'
export * from './delete_session_confirm.js'
export * from './configure_chatbot_agent_first.js'
export * from './global_chatbot.js'
export * from './global_chatbot_description.js'
export * from './select_chatbot_agent.js'
export * from './no_chat_agents_warning.js'
export * from './settings_saved.js'
export * from './select_agent.js'
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Assets added to context:" |
*
* @param {Assets_Added_To_ContextInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const assets_added_to_context: ((inputs?: Assets_Added_To_ContextInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Assets_Added_To_ContextInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Assets_Added_To_ContextInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Assets_Added_To_ContextInputs */
const en_assets_added_to_context = /** @type {(inputs: Assets_Added_To_ContextInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Assets added to context:`)
};
const zh_assets_added_to_context = /** @type {(inputs: Assets_Added_To_ContextInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`已添加至上下文的资源:`)
};
/**
* | output |
* | --- |
* | "Assets added to context:" |
*
* @param {Assets_Added_To_ContextInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const assets_added_to_context = /** @type {((inputs?: Assets_Added_To_ContextInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Assets_Added_To_ContextInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_assets_added_to_context(inputs)
return zh_assets_added_to_context(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Chatbot Context" |
*
* @param {Chatbot_ContextInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const chatbot_context: ((inputs?: Chatbot_ContextInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Chatbot_ContextInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Chatbot_ContextInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Chatbot_ContextInputs */
const en_chatbot_context = /** @type {(inputs: Chatbot_ContextInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Chatbot Context`)
};
const zh_chatbot_context = /** @type {(inputs: Chatbot_ContextInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`聊天机器人上下文`)
};
/**
* | output |
* | --- |
* | "Chatbot Context" |
*
* @param {Chatbot_ContextInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const chatbot_context = /** @type {((inputs?: Chatbot_ContextInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Chatbot_ContextInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_chatbot_context(inputs)
return zh_chatbot_context(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Drag and drop files or folders here to add them to chatbot context" |
*
* @param {Chatbot_Drag_Drop_HintInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const chatbot_drag_drop_hint: ((inputs?: Chatbot_Drag_Drop_HintInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Chatbot_Drag_Drop_HintInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Chatbot_Drag_Drop_HintInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Chatbot_Drag_Drop_HintInputs */
const en_chatbot_drag_drop_hint = /** @type {(inputs: Chatbot_Drag_Drop_HintInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Drag and drop files or folders here to add them to chatbot context`)
};
const zh_chatbot_drag_drop_hint = /** @type {(inputs: Chatbot_Drag_Drop_HintInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`拖拽文件或文件夹到此处以添加到聊天机器人上下文`)
};
/**
* | output |
* | --- |
* | "Drag and drop files or folders here to add them to chatbot context" |
*
* @param {Chatbot_Drag_Drop_HintInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const chatbot_drag_drop_hint = /** @type {((inputs?: Chatbot_Drag_Drop_HintInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Chatbot_Drag_Drop_HintInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_chatbot_drag_drop_hint(inputs)
return zh_chatbot_drag_drop_hint(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Clear" |
*
* @param {ClearInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const clear: ((inputs?: ClearInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<ClearInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type ClearInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} ClearInputs */
const en_clear = /** @type {(inputs: ClearInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Clear`)
};
const zh_clear = /** @type {(inputs: ClearInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`清空`)
};
/**
* | output |
* | --- |
* | "Clear" |
*
* @param {ClearInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const clear = /** @type {((inputs?: ClearInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<ClearInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_clear(inputs)
return zh_clear(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Please configure a chatbot agent in team settings first." |
*
* @param {Configure_Chatbot_Agent_FirstInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const configure_chatbot_agent_first: ((inputs?: Configure_Chatbot_Agent_FirstInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Configure_Chatbot_Agent_FirstInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Configure_Chatbot_Agent_FirstInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Configure_Chatbot_Agent_FirstInputs */
const en_configure_chatbot_agent_first = /** @type {(inputs: Configure_Chatbot_Agent_FirstInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Please configure a chatbot agent in team settings first.`)
};
const zh_configure_chatbot_agent_first = /** @type {(inputs: Configure_Chatbot_Agent_FirstInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`请先在团队设置中配置聊天机器人智能体。`)
};
/**
* | output |
* | --- |
* | "Please configure a chatbot agent in team settings first." |
*
* @param {Configure_Chatbot_Agent_FirstInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const configure_chatbot_agent_first = /** @type {((inputs?: Configure_Chatbot_Agent_FirstInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Configure_Chatbot_Agent_FirstInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_configure_chatbot_agent_first(inputs)
return zh_configure_chatbot_agent_first(inputs)
});
+18
View File
@@ -0,0 +1,18 @@
/**
* | output |
* | --- |
* | "Context Assets ({count})" |
*
* @param {Context_Assets_CountInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const context_assets_count: ((inputs: Context_Assets_CountInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Context_Assets_CountInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Context_Assets_CountInputs = {
count: NonNullable<unknown>;
};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{ count: NonNullable<unknown> }} Context_Assets_CountInputs */
const en_context_assets_count = /** @type {(inputs: Context_Assets_CountInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`Context Assets (${i?.count})`)
};
const zh_context_assets_count = /** @type {(inputs: Context_Assets_CountInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`上下文资源 (${i?.count})`)
};
/**
* | output |
* | --- |
* | "Context Assets ({count})" |
*
* @param {Context_Assets_CountInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const context_assets_count = /** @type {((inputs: Context_Assets_CountInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Context_Assets_CountInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_context_assets_count(inputs)
return zh_context_assets_count(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Are you sure you want to delete this chat session?" |
*
* @param {Delete_Session_ConfirmInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const delete_session_confirm: ((inputs?: Delete_Session_ConfirmInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Delete_Session_ConfirmInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Delete_Session_ConfirmInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Delete_Session_ConfirmInputs */
const en_delete_session_confirm = /** @type {(inputs: Delete_Session_ConfirmInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Are you sure you want to delete this chat session?`)
};
const zh_delete_session_confirm = /** @type {(inputs: Delete_Session_ConfirmInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`您确定要删除此会话记录吗?`)
};
/**
* | output |
* | --- |
* | "Are you sure you want to delete this chat session?" |
*
* @param {Delete_Session_ConfirmInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const delete_session_confirm = /** @type {((inputs?: Delete_Session_ConfirmInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Delete_Session_ConfirmInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_delete_session_confirm(inputs)
return zh_delete_session_confirm(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Global Chatbot" |
*
* @param {Global_ChatbotInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const global_chatbot: ((inputs?: Global_ChatbotInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Global_ChatbotInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Global_ChatbotInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Global_ChatbotInputs */
const en_global_chatbot = /** @type {(inputs: Global_ChatbotInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Global Chatbot`)
};
const zh_global_chatbot = /** @type {(inputs: Global_ChatbotInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`全局聊天机器人`)
};
/**
* | output |
* | --- |
* | "Global Chatbot" |
*
* @param {Global_ChatbotInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const global_chatbot = /** @type {((inputs?: Global_ChatbotInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Global_ChatbotInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_global_chatbot(inputs)
return zh_global_chatbot(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Select the agent that handles conversation inside the global chatbot sidebar." |
*
* @param {Global_Chatbot_DescriptionInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const global_chatbot_description: ((inputs?: Global_Chatbot_DescriptionInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Global_Chatbot_DescriptionInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Global_Chatbot_DescriptionInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Global_Chatbot_DescriptionInputs */
const en_global_chatbot_description = /** @type {(inputs: Global_Chatbot_DescriptionInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Select the agent that handles conversation inside the global chatbot sidebar.`)
};
const zh_global_chatbot_description = /** @type {(inputs: Global_Chatbot_DescriptionInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`选择在全局聊天机器人边栏中进行对话的智能体。`)
};
/**
* | output |
* | --- |
* | "Select the agent that handles conversation inside the global chatbot sidebar." |
*
* @param {Global_Chatbot_DescriptionInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const global_chatbot_description = /** @type {((inputs?: Global_Chatbot_DescriptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Global_Chatbot_DescriptionInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_global_chatbot_description(inputs)
return zh_global_chatbot_description(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Hide Chatbot" |
*
* @param {Hide_ChatbotInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const hide_chatbot: ((inputs?: Hide_ChatbotInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Hide_ChatbotInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Hide_ChatbotInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Hide_ChatbotInputs */
const en_hide_chatbot = /** @type {(inputs: Hide_ChatbotInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Hide Chatbot`)
};
const zh_hide_chatbot = /** @type {(inputs: Hide_ChatbotInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`隐藏聊天机器人`)
};
/**
* | output |
* | --- |
* | "Hide Chatbot" |
*
* @param {Hide_ChatbotInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const hide_chatbot = /** @type {((inputs?: Hide_ChatbotInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Hide_ChatbotInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_hide_chatbot(inputs)
return zh_hide_chatbot(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "History" |
*
* @param {HistoryInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const history: ((inputs?: HistoryInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<HistoryInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type HistoryInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} HistoryInputs */
const en_history = /** @type {(inputs: HistoryInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`History`)
};
const zh_history = /** @type {(inputs: HistoryInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`历史记录`)
};
/**
* | output |
* | --- |
* | "History" |
*
* @param {HistoryInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const history = /** @type {((inputs?: HistoryInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<HistoryInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_history(inputs)
return zh_history(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "New Chat" |
*
* @param {New_ChatInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const new_chat: ((inputs?: New_ChatInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<New_ChatInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type New_ChatInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} New_ChatInputs */
const en_new_chat = /** @type {(inputs: New_ChatInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`New Chat`)
};
const zh_new_chat = /** @type {(inputs: New_ChatInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`开启新会话`)
};
/**
* | output |
* | --- |
* | "New Chat" |
*
* @param {New_ChatInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const new_chat = /** @type {((inputs?: New_ChatInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<New_ChatInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_new_chat(inputs)
return zh_new_chat(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "No chat agents found. Please create a Chat Agent below first." |
*
* @param {No_Chat_Agents_WarningInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const no_chat_agents_warning: ((inputs?: No_Chat_Agents_WarningInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<No_Chat_Agents_WarningInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type No_Chat_Agents_WarningInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} No_Chat_Agents_WarningInputs */
const en_no_chat_agents_warning = /** @type {(inputs: No_Chat_Agents_WarningInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`No chat agents found. Please create a Chat Agent below first.`)
};
const zh_no_chat_agents_warning = /** @type {(inputs: No_Chat_Agents_WarningInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`未找到聊天智能体。请先在下方创建聊天智能体。`)
};
/**
* | output |
* | --- |
* | "No chat agents found. Please create a Chat Agent below first." |
*
* @param {No_Chat_Agents_WarningInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const no_chat_agents_warning = /** @type {((inputs?: No_Chat_Agents_WarningInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<No_Chat_Agents_WarningInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_no_chat_agents_warning(inputs)
return zh_no_chat_agents_warning(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "No chat history found." |
*
* @param {No_History_SessionsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const no_history_sessions: ((inputs?: No_History_SessionsInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<No_History_SessionsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type No_History_SessionsInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} No_History_SessionsInputs */
const en_no_history_sessions = /** @type {(inputs: No_History_SessionsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`No chat history found.`)
};
const zh_no_history_sessions = /** @type {(inputs: No_History_SessionsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`暂无历史会话记录`)
};
/**
* | output |
* | --- |
* | "No chat history found." |
*
* @param {No_History_SessionsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const no_history_sessions = /** @type {((inputs?: No_History_SessionsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<No_History_SessionsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_no_history_sessions(inputs)
return zh_no_history_sessions(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Remove from context" |
*
* @param {Remove_From_ContextInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const remove_from_context: ((inputs?: Remove_From_ContextInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Remove_From_ContextInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Remove_From_ContextInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Remove_From_ContextInputs */
const en_remove_from_context = /** @type {(inputs: Remove_From_ContextInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Remove from context`)
};
const zh_remove_from_context = /** @type {(inputs: Remove_From_ContextInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`从上下文中移除`)
};
/**
* | output |
* | --- |
* | "Remove from context" |
*
* @param {Remove_From_ContextInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const remove_from_context = /** @type {((inputs?: Remove_From_ContextInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Remove_From_ContextInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_remove_from_context(inputs)
return zh_remove_from_context(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Select Agent" |
*
* @param {Select_AgentInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const select_agent: ((inputs?: Select_AgentInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Select_AgentInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Select_AgentInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Select_AgentInputs */
const en_select_agent = /** @type {(inputs: Select_AgentInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Select Agent`)
};
const zh_select_agent = /** @type {(inputs: Select_AgentInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`选择智能体`)
};
/**
* | output |
* | --- |
* | "Select Agent" |
*
* @param {Select_AgentInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const select_agent = /** @type {((inputs?: Select_AgentInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Select_AgentInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_select_agent(inputs)
return zh_select_agent(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Select chatbot agent" |
*
* @param {Select_Chatbot_AgentInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const select_chatbot_agent: ((inputs?: Select_Chatbot_AgentInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Select_Chatbot_AgentInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Select_Chatbot_AgentInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Select_Chatbot_AgentInputs */
const en_select_chatbot_agent = /** @type {(inputs: Select_Chatbot_AgentInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Select chatbot agent`)
};
const zh_select_chatbot_agent = /** @type {(inputs: Select_Chatbot_AgentInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`选择聊天机器人智能体`)
};
/**
* | output |
* | --- |
* | "Select chatbot agent" |
*
* @param {Select_Chatbot_AgentInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const select_chatbot_agent = /** @type {((inputs?: Select_Chatbot_AgentInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Select_Chatbot_AgentInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_select_chatbot_agent(inputs)
return zh_select_chatbot_agent(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Send" |
*
* @param {SendInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const send: ((inputs?: SendInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<SendInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type SendInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} SendInputs */
const en_send = /** @type {(inputs: SendInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Send`)
};
const zh_send = /** @type {(inputs: SendInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`发送`)
};
/**
* | output |
* | --- |
* | "Send" |
*
* @param {SendInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const send = /** @type {((inputs?: SendInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<SendInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_send(inputs)
return zh_send(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Settings saved successfully" |
*
* @param {Settings_SavedInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const settings_saved: ((inputs?: Settings_SavedInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Settings_SavedInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Settings_SavedInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Settings_SavedInputs */
const en_settings_saved = /** @type {(inputs: Settings_SavedInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Settings saved successfully`)
};
const zh_settings_saved = /** @type {(inputs: Settings_SavedInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`设置保存成功`)
};
/**
* | output |
* | --- |
* | "Settings saved successfully" |
*
* @param {Settings_SavedInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const settings_saved = /** @type {((inputs?: Settings_SavedInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Settings_SavedInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_settings_saved(inputs)
return zh_settings_saved(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Show Chatbot" |
*
* @param {Show_ChatbotInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const show_chatbot: ((inputs?: Show_ChatbotInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Show_ChatbotInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Show_ChatbotInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Show_ChatbotInputs */
const en_show_chatbot = /** @type {(inputs: Show_ChatbotInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Show Chatbot`)
};
const zh_show_chatbot = /** @type {(inputs: Show_ChatbotInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`显示聊天机器人`)
};
/**
* | output |
* | --- |
* | "Show Chatbot" |
*
* @param {Show_ChatbotInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const show_chatbot = /** @type {((inputs?: Show_ChatbotInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Show_ChatbotInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_show_chatbot(inputs)
return zh_show_chatbot(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Shumai Agent" |
*
* @param {Shumai_AgentInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const shumai_agent: ((inputs?: Shumai_AgentInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Shumai_AgentInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Shumai_AgentInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Shumai_AgentInputs */
const en_shumai_agent = /** @type {(inputs: Shumai_AgentInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Shumai Agent`)
};
const zh_shumai_agent = /** @type {(inputs: Shumai_AgentInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`数脉智能体`)
};
/**
* | output |
* | --- |
* | "Shumai Agent" |
*
* @param {Shumai_AgentInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const shumai_agent = /** @type {((inputs?: Shumai_AgentInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Shumai_AgentInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_shumai_agent(inputs)
return zh_shumai_agent(inputs)
});
@@ -1,26 +1,29 @@
import { createLazyFileRoute } from '@tanstack/react-router'
import { client } from '@/ui/api/client'
import { FileViewer } from '@/ui/components/file-viewer'
import { CompareViewer } from '@/ui/components/compare/compare-viewer'
import { ChatbotSidebar } from '@/ui/components/chatbot-sidebar'
import { pickDefaultCompareVersions } from '@/ui/components/compare/compare-utils'
import { CompareViewer } from '@/ui/components/compare/compare-viewer'
import { FileViewer } from '@/ui/components/file-viewer'
import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
import { m } from '@/ui/paraglide/messages.js'
import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
import { ResizeHandle } from '@/ui/components/resize-handle'
import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
import { ResizeHandle } from '@/ui/components/resize-handle'
import { m } from '@/ui/paraglide/messages.js'
import { useChatbotStore } from '@/ui/stores/chatbot'
import { useMemberStore } from '@/ui/stores/members'
import { useTeamContextStore } from '@/ui/stores/team-context'
import { useTopNavStore } from '@/ui/stores/top-nav'
import { useUiStore } from '@/ui/stores/ui'
import { type Annotation } from '@/ui/types'
import { useMutation } from '@tanstack/react-query'
import { createLazyFileRoute } from '@tanstack/react-router'
import { InferRequestType, InferResponseType } from 'hono/client'
import type { MediaController } from '@/ui/components/viewers/types'
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 type { MediaController } from '@/ui/components/viewers/types'
function FileViewPage() {
const { projectId, fileId } = Route.useParams()
@@ -37,6 +40,8 @@ function FileViewPage() {
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const [annotations, setAnnotations] = useState<Annotation[]>([])
const { fileViewRightSidebarCollapsed } = useUiStore()
const { isChatbotOpen } = useChatbotStore()
const [currentTime, setCurrentTime] = useState(0)
const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null)
const [compareActiveAsset, setCompareActiveAsset] = useState<AssetInfo | null>(null)
@@ -431,29 +436,40 @@ function FileViewPage() {
</FileViewer>
)}
</div>
<ResizeHandle
onResize={(delta) => {
setRightSidebarWidth((prev) => Math.max(300, Math.min(600, prev - delta)))
}}
className="hidden md:block"
/>
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0">
<FileViewerRightSidebar
teamId={teamId}
projectId={projectId}
file={sidebarFile}
onSaveField={handleSaveField}
members={members}
onCommentSelect={handleCommentSelect}
currentTime={currentTime}
onTyping={() => {
if (isCompareMode) return
mediaControllerRef.current?.pause()
}}
selectedCommentId={selectedCommentId}
hideAnnotationControl={sidebarFile?.mediaType?.startsWith('audio/')}
/>
</div>
{(!fileViewRightSidebarCollapsed || isChatbotOpen) && (
<>
<ResizeHandle
onResize={(delta) => {
setRightSidebarWidth((prev) => Math.max(300, Math.min(600, prev - delta)))
}}
className="hidden md:block"
/>
<div
style={{ width: rightSidebarWidth }}
className="flex-shrink-0 bg-background flex flex-col"
>
{isChatbotOpen ? (
<ChatbotSidebar projectId={projectId} contextAssetId={activeFileId} />
) : (
<FileViewerRightSidebar
teamId={teamId}
projectId={projectId}
file={sidebarFile}
onSaveField={handleSaveField}
members={members}
onCommentSelect={handleCommentSelect}
currentTime={currentTime}
onTyping={() => {
if (isCompareMode) return
mediaControllerRef.current?.pause()
}}
selectedCommentId={selectedCommentId}
hideAnnotationControl={sidebarFile?.mediaType?.startsWith('audio/')}
/>
)}
</div>
</>
)}
</div>
</div>
)
+262
View File
@@ -0,0 +1,262 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { useChatbotStore } from './chatbot'
import { client } from '@/ui/api/client'
import type { ChatMessage } from '@shumai/dtos'
vi.mock('@/ui/api/client', () => {
const chatMock = {
$post: vi.fn(),
sessions: {
$get: vi.fn(() => Promise.resolve({ ok: true, json: async () => ({ data: [] }) } as unknown)),
$delete: vi.fn(),
messages: {
$get: vi.fn(),
},
},
}
return {
client: {
api: {
teams: {
':teamId': {
chat: chatMock,
},
},
},
},
}
})
describe('useChatbotStore', () => {
beforeEach(() => {
vi.resetAllMocks()
useChatbotStore.setState({
isHistoryMode: false,
isChatbotOpen: false,
currentSessionId: null,
chatAssets: [],
messages: [],
historySessions: [],
isStreaming: false,
selectedAgentId: 'agent-1',
})
})
it('should add, remove and clear assets in context', () => {
const store = useChatbotStore.getState()
expect(store.chatAssets).toHaveLength(0)
store.addAssets([
{ id: '1', name: 'File A', type: 'file' },
{ id: '2', name: 'Folder B', type: 'folder' },
])
expect(useChatbotStore.getState().chatAssets).toHaveLength(2)
useChatbotStore.getState().removeAsset('1')
expect(useChatbotStore.getState().chatAssets).toHaveLength(1)
expect(useChatbotStore.getState().chatAssets[0].id).toBe('2')
useChatbotStore.getState().clearAssets()
expect(useChatbotStore.getState().chatAssets).toHaveLength(0)
})
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],
chatAssets: [{ id: 'asset-1', name: 'Asset', type: 'file' }],
})
useChatbotStore.getState().startNewSession()
const state = useChatbotStore.getState()
expect(state.currentSessionId).toBeNull()
expect(state.messages).toHaveLength(0)
expect(state.chatAssets).toHaveLength(0)
})
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":"done","status":"completed"}\n\n',
]
let eventIdx = 0
const mockReader = {
read: vi.fn(async () => {
if (eventIdx < mockEvents.length) {
const value = new TextEncoder().encode(mockEvents[eventIdx++])
return { done: false, value }
}
return { done: true, value: undefined }
}),
}
const mockResponse = {
ok: true,
headers: {
get: vi.fn(() => 'sess-123'),
},
body: {
getReader: () => mockReader,
},
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(client.api.teams[':teamId'].chat.$post).mockResolvedValue(mockResponse as any)
const sendPromise = useChatbotStore.getState().sendMessage('team-123', 'hello', 'proj-123')
// 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).toEqual([
{ type: 'text', text: 'hello' },
])
expect(stateWithOptimistic.isStreaming).toBe(true)
await sendPromise
// Final state assertions
const finalState = useChatbotStore.getState()
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')
})
it('should not remove optimistic message when historical user message streams back', async () => {
useChatbotStore.setState({
currentSessionId: 'sess-123',
messages: [
{
id: 'user-msg-ulid-old',
role: 'user',
content: [{ type: 'text', text: 'old message' }],
timestamp: 100,
} as unknown as ChatMessage,
],
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":"done","status":"completed"}\n\n',
]
let eventIdx = 0
const mockReader = {
read: vi.fn(async () => {
if (eventIdx < mockEvents.length) {
const value = new TextEncoder().encode(mockEvents[eventIdx++])
return { done: false, value }
}
return { done: true, value: undefined }
}),
}
const mockResponse = {
ok: true,
headers: {
get: vi.fn(() => 'sess-123'),
},
body: {
getReader: () => mockReader,
},
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(client.api.teams[':teamId'].chat.$post).mockResolvedValue(mockResponse as any)
const sendPromise = useChatbotStore
.getState()
.sendMessage('team-123', 'new message', 'proj-123')
// 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-')
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')
})
it('should create optimistic context display message when sending with assets', async () => {
// 1. Setup chatAssets in store
useChatbotStore.setState({
chatAssets: [{ id: 'asset-1', name: 'File 1.txt', type: 'file' }],
})
// 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":"done","status":"completed"}\n\n',
]
let eventIdx = 0
const mockReader = {
read: vi.fn(async () => {
if (eventIdx < mockEvents.length) {
const value = new TextEncoder().encode(mockEvents[eventIdx++])
return { done: false, value }
}
return { done: true, value: undefined }
}),
}
const mockResponse = {
ok: true,
headers: {
get: vi.fn(() => 'sess-123'),
},
body: {
getReader: () => mockReader,
},
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(client.api.teams[':teamId'].chat.$post).mockResolvedValue(mockResponse as any)
const sendPromise = useChatbotStore.getState().sendMessage('team-123', 'hello', 'proj-123')
// 3. Verify that both the optimistic context message and user message are present immediately
const stateWithOptimistic = useChatbotStore.getState()
expect(stateWithOptimistic.messages).toHaveLength(2)
// First message should be the optimistic context_display_info
expect(stateWithOptimistic.messages[0].id).toContain('temp-context-')
expect(stateWithOptimistic.messages[0].role).toBe('custom')
expect((stateWithOptimistic.messages[0] as { customType?: string }).customType).toBe(
'context_display_info',
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((stateWithOptimistic.messages[0] as any).details).toEqual({
assets: [{ id: 'asset-1', name: 'File 1.txt', type: 'file' }],
})
// Second message should be the optimistic user message
expect(stateWithOptimistic.messages[1].id).toContain('temp-')
expect(stateWithOptimistic.messages[1].role).toBe('user')
await sendPromise
// 4. Verify they are replaced correctly by the real backend entries
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')
})
})
+306
View File
@@ -0,0 +1,306 @@
import { create } from 'zustand'
import { client } from '@/ui/api/client'
import type { ChatMessage, ChatSessionInfo } from '@shumai/dtos'
import { toast } from 'sonner'
export interface ChatAsset {
id: string
name: string
type: 'file' | 'folder'
}
interface ChatbotState {
isChatbotOpen: boolean
setIsChatbotOpen: (open: boolean) => void
isHistoryMode: boolean
setIsHistoryMode: (history: boolean) => void
currentSessionId: string | null
setCurrentSessionId: (id: string | null) => void
chatAssets: ChatAsset[]
addAssets: (assets: ChatAsset[]) => void
removeAsset: (id: string) => void
clearAssets: () => void
messages: ChatMessage[]
setMessages: (messages: ChatMessage[]) => void
historySessions: ChatSessionInfo[]
setHistorySessions: (sessions: ChatSessionInfo[]) => void
isStreaming: boolean
setIsStreaming: (streaming: boolean) => void
selectedAgentId: string | null
setSelectedAgentId: (id: string | null) => void
scrollTop: number
isAtBottom: boolean
setScrollState: (scrollTop: number, isAtBottom: boolean) => void
fetchHistorySessions: (teamId: string) => Promise<void>
loadSession: (teamId: string, sessionId: string) => Promise<void>
deleteSession: (teamId: string, sessionId: string) => Promise<void>
startNewSession: () => void
sendMessage: (
teamId: string,
text: string,
projectId: string,
contextAssetId?: string,
) => Promise<void>
}
export const useChatbotStore = create<ChatbotState>((set) => ({
isChatbotOpen: false,
setIsChatbotOpen: (open) => set({ isChatbotOpen: open }),
isHistoryMode: false,
setIsHistoryMode: (history) => set({ isHistoryMode: history }),
currentSessionId: null,
setCurrentSessionId: (id) => set({ currentSessionId: id }),
chatAssets: [],
addAssets: (assets) =>
set((state) => {
const existingIds = new Set(state.chatAssets.map((a) => a.id))
const uniqueNewAssets = assets.filter((a) => !existingIds.has(a.id))
return { chatAssets: [...state.chatAssets, ...uniqueNewAssets] }
}),
removeAsset: (id) =>
set((state) => ({
chatAssets: state.chatAssets.filter((a) => a.id !== id),
})),
clearAssets: () => set({ chatAssets: [] }),
messages: [],
setMessages: (messages) => set({ messages }),
historySessions: [],
setHistorySessions: (sessions) => set({ historySessions: sessions }),
isStreaming: false,
setIsStreaming: (streaming) => set({ isStreaming: streaming }),
selectedAgentId: null,
setSelectedAgentId: (id) => set({ selectedAgentId: id }),
scrollTop: 0,
isAtBottom: true,
setScrollState: (scrollTop, isAtBottom) => set({ scrollTop, isAtBottom }),
fetchHistorySessions: async (teamId) => {
try {
const res = await client.api.teams[':teamId'].chat.sessions.$get({
param: { teamId },
query: { first: '50' },
})
if (res.ok) {
const data = await res.json()
set({ historySessions: data.data || [] })
}
} catch (err) {
console.error('Failed to fetch history sessions:', err)
}
},
loadSession: async (teamId, sessionId) => {
try {
const res = await client.api.teams[':teamId'].chat.sessions[':sessionId'].messages.$get({
param: { teamId, sessionId },
})
if (res.ok) {
const messages = await res.json()
const sessionInfo = useChatbotStore
.getState()
.historySessions.find((s) => s.id === sessionId)
const agentId = sessionInfo?.agentId || null
set({
currentSessionId: sessionId,
messages: messages as ChatMessage[],
isHistoryMode: false,
scrollTop: 0,
isAtBottom: true,
...(agentId ? { selectedAgentId: agentId } : {}),
})
} else {
throw new Error('Failed to load session messages')
}
} catch (err) {
const errMsg = err instanceof Error ? err.message : 'Failed to load session'
toast.error(errMsg)
}
},
deleteSession: async (teamId, sessionId) => {
try {
const res = await client.api.teams[':teamId'].chat.sessions[':sessionId'].$delete({
param: { teamId, sessionId },
})
if (res.ok) {
toast.success('Session deleted successfully')
set((s) => ({
historySessions: s.historySessions.filter((sess) => sess.id !== sessionId),
currentSessionId: s.currentSessionId === sessionId ? null : s.currentSessionId,
messages: s.currentSessionId === sessionId ? [] : s.messages,
}))
} else {
throw new Error('Failed to delete session')
}
} catch (err) {
const errMsg = err instanceof Error ? err.message : 'Failed to delete session'
toast.error(errMsg)
}
},
startNewSession: () => {
set({
currentSessionId: null,
messages: [],
chatAssets: [],
scrollTop: 0,
isAtBottom: true,
})
},
sendMessage: async (teamId, text, projectId, contextAssetId) => {
const state = useChatbotStore.getState()
if (state.isStreaming) return
const tempId = `temp-${Date.now()}`
const optimisticMsg = {
id: tempId,
role: 'user' as const,
content: [{ type: 'text', text }],
timestamp: Date.now(),
} as unknown as ChatMessage
const newMessages = [...state.messages]
if (state.chatAssets.length > 0) {
const tempContextId = `temp-context-${Date.now()}`
const optimisticContextMsg = {
id: tempContextId,
role: 'custom' as const,
customType: 'context_display_info',
details: {
assets: state.chatAssets.map((a) => ({
id: a.id,
name: a.name,
type: a.type,
})),
},
timestamp: Date.now() - 1,
} as unknown as ChatMessage
newMessages.push(optimisticContextMsg)
}
newMessages.push(optimisticMsg)
set({
messages: newMessages,
isStreaming: true,
chatAssets: [],
isAtBottom: true,
})
const assetIds = state.chatAssets.map((a) => a.id)
const agentId = state.selectedAgentId
if (!agentId) {
toast.error('No agent selected')
return
}
try {
const res = await client.api.teams[':teamId'].chat.$post({
param: { teamId },
json: {
agentId,
textPrompt: text,
assetIds,
sessionId: state.currentSessionId || undefined,
contextAssetId,
projectId,
},
})
if (!res.ok) {
throw new Error('Failed to start chat')
}
// Try reading custom header first
const headerSessionId = res.headers.get('x-session-id')
if (headerSessionId && !state.currentSessionId) {
set({ currentSessionId: headerSessionId })
}
const reader = res.body?.getReader()
if (!reader) {
throw new Error('No stream body')
}
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed) continue
if (trimmed.startsWith('data: ')) {
const dataStr = trimmed.slice(6)
try {
const data = JSON.parse(dataStr)
if (data.type === 'session') {
if (!useChatbotStore.getState().currentSessionId) {
set({ currentSessionId: data.sessionId })
}
} else if (data.type === 'entry') {
const entry = data.entry as ChatMessage
set((s) => {
const isExisting = s.messages.some((m) => m.id === entry.id)
// Replace temp/optimistic message when the real counterpart streams back
const filtered = s.messages.filter((m) => {
if (entry.role === 'user' && !isExisting) {
return !(m.id.startsWith('temp-') && !m.id.startsWith('temp-context-'))
}
if (
entry.role === 'custom' &&
entry.customType === 'context_display_info' &&
!isExisting
) {
return !m.id.startsWith('temp-context-')
}
return true
})
// Prevent duplicates by ID
const existingIdx = filtered.findIndex((m) => m.id === entry.id)
if (existingIdx !== -1) {
const copy = [...filtered]
copy[existingIdx] = entry
return { messages: copy }
} else {
return { messages: [...filtered, entry] }
}
})
} else if (data.type === 'done') {
if (data.status === 'failed') {
toast.error(data.error || 'Workflow failed')
}
}
} catch (err) {
console.error('Error parsing SSE line:', err)
}
}
}
}
// If we finished successfully, trigger a history list refresh
const finalState = useChatbotStore.getState()
finalState.fetchHistorySessions(teamId)
} catch (err) {
const errMsg = err instanceof Error ? err.message : 'Failed to send message'
toast.error(errMsg)
// Remove optimistic message on failure
set((s) => ({
messages: s.messages.filter((m) => m.id !== tempId),
}))
} finally {
set({ isStreaming: false })
}
},
}))
+25
View File
@@ -123,3 +123,28 @@
@apply bg-background text-foreground;
}
}
/* Style code blocks and inline code inside .prose (rendered markdown) */
.prose pre {
background-color: var(--muted);
color: var(--foreground);
padding: 1rem;
border-radius: var(--radius-md);
border: 1px solid var(--border);
font-family: var(--font-mono);
font-size: 0.875em;
overflow-x: auto;
}
.prose code {
font-family: var(--font-mono);
}
/* Style inline code (code not inside pre) */
.prose :not(pre) > code {
background-color: var(--muted);
color: var(--foreground);
padding: 0.15rem 0.3rem;
border-radius: var(--radius-sm);
font-size: 0.875em;
}
+10 -6
View File
@@ -97,11 +97,15 @@ export default defineConfig({
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
...(process.env.E2E_SKIP_APP_SERVER === 'true' ? [] : [{
command: 'bun run apps/web/e2e/serve.ts',
url: 'http://localhost:5200',
reuseExistingServer: !process.env.CI,
timeout: 120_000,
}]),
...(process.env.E2E_SKIP_APP_SERVER === 'true'
? []
: [
{
command: 'bun run apps/web/e2e/serve.ts',
url: 'http://localhost:5200',
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
]),
],
})