Compare commits

...
50 Commits
Author SHA1 Message Date
yiling 8efc9c1865 Release v0.1.9 2026-07-14 20:21:21 +08:00
Yiling-J 0eeb2f18f3 Merge pull request #187 from shumaiOne/fix/chat-api-db-queries
refactor(api/chat): remove direct Prisma query from API layer
2026-07-14 16:47:44 +08:00
yiling 6643d63e81 refactor(api/chat): remove direct Prisma query from API layer
API layer routes in packages/api/src/chat.ts accessed the database directly via prisma, violating communication layer boundaries.

This refactoring migrates these queries to packages/core/src/chat/chat.ts:
- Added getNewSessionMessages to fetch mapped SSE entries.
- Added getChatWorkflowStatus to check task completions.
- Added abortSession to handle workflow cancellation and task updates in core.
- Updated both core and API tests to match refactored signatures and mock boundaries.
2026-07-14 16:40:55 +08:00
Yiling-J b53b76bc6e Merge pull request #186 from shumaiOne/feat/agent-abort
feat(agent): support aborting agent execution
2026-07-14 16:35:19 +08:00
yiling 636e92af4c fix(agent): unregister temporal cancellation listener on completion 2026-07-14 16:08:43 +08:00
yiling a7dc7bbff2 perf(agent): optimize active task lookup using indexed sessionId column 2026-07-14 15:44:10 +08:00
yiling cd48d2d389 fix(agent): resolve lint, typecheck, and stop button UI issues 2026-07-14 10:35:25 +08:00
yiling 8a942d4f4e feat(agent): support aborting agent execution in local and temporal modes 2026-07-14 10:25:06 +08:00
Yiling-J e772581542 Merge pull request #185 from shumaiOne/feat/chatbot-ui-layout
feat(chat): chatbot UI
2026-07-13 16:55:25 +08:00
yiling 7baf95e48c fix(webui): preserve chatbot sidebar scroll position across navigations 2026-07-13 16:49:04 +08:00
yiling 15cbf12162 fix(webui): render theme-aware markdown code blocks in dark/light mode 2026-07-13 14:52:38 +08:00
yiling d560032013 feat(chat): send SSE keep-alive ping heartbeats during polling 2026-07-13 12:17:00 +08:00
yiling 02f2fde8ac fix(chat): remove explicit any in test mock to fix CI lint 2026-07-13 11:52:44 +08:00
yiling e080167ac5 feat(chat): enforce team-scoped authorization and session creator check
- Update chat API routes and service methods to include and verify teamId context
- Validate that the requesting user is the creator of the chat session during continuation
- Update frontend chatbot store and components to pass teamId parameter
- Update backend API/core and frontend store tests to verify team scoping and creator checks
2026-07-13 11:35:55 +08:00
yiling 61c49b4d7f feat(chat): allow user to choose chatbot in sidebar
- Remove chatbotAgentId from team settings and schema definition
- Make agentId a required parameter in ChatRequest DTO and chatService
- Fetch chatbot agents on chatbot sidebar mount and default to first enabled chat agent
- Render an agent selector dropdown inside the message input area
- Update existing chat sessions to follow the selected agent when continuing a conversation
2026-07-13 10:10:56 +08:00
yiling bad93466ae feat(webui): use filled bot icon when chatbot sidebar is open 2026-07-13 09:37:37 +08:00
yiling 1f8b0bac21 update ui 2026-07-13 09:34:51 +08:00
yiling c55380c0fd feat(webui): make toolCall block collapsible and render footer conditionally 2026-07-12 15:40:21 +08:00
yiling 3de57fd176 feat(webui): refactor chatbot message rendering to type-safe nested switch 2026-07-12 15:18:31 +08:00
yiling 0a4622ed8a syle minor fix 2026-07-12 10:29:29 +08:00
yiling bcb17acaf7 chore(serve): set idleTimeout to 120 seconds in Bun.serve 2026-07-11 21:11:18 +08:00
yiling b57a3e0239 chore(chat): support isNewChat payload flag and fix any casts 2026-07-11 21:05:47 +08:00
yiling c5ce4d07e9 feat(chat): add chatbot session name generation 2026-07-11 20:54:09 +08:00
yiling b5d52a4e56 feat(chat): add AgentSessionType enum and filter chatbot history sessions 2026-07-11 20:14:40 +08:00
yiling 94a3ec0b9b feat(chat): support optimistic context display entry locally during message sending 2026-07-11 17:02:58 +08:00
yiling bd897b951a chore: format codebase 2026-07-11 16:58:37 +08:00
yiling 482df3315c feat(chat): append and display context_display_info custom entry for attached assets 2026-07-11 16:58:09 +08:00
yiling cc9b32716d feat(chat): filter out context messages from API list and SSE stream 2026-07-11 15:47:48 +08:00
yiling 35db3fc49e fix(chatbot): preserve historical message order during SSE playback 2026-07-11 15:12:59 +08:00
yiling 6a5f8db0d6 fix(chatbot): preserve optimistic message during history playback of active sessions 2026-07-11 15:08:07 +08:00
yiling b13c47f207 feat(chatbot): highlight entire sidebar area with semi-transparent cover on dragover 2026-07-11 14:56:21 +08:00
yiling 2f68043e17 fix(chatbot): clear attached assets on message send and remove drag-drop toast 2026-07-11 14:41:23 +08:00
yiling 3d266a5606 feat(chatbot): remove agentId from request and resolve it via team settings, toggle chatbot icon with tooltip guard 2026-07-11 11:49:38 +08:00
yiling 87d811dad6 style(chatbot): move send button inside input border area to match comment input design 2026-07-11 10:59:56 +08:00
yiling 4a7da10ca8 fix(chatbot): prevent Enter from sending message during IME composition 2026-07-11 10:55:01 +08:00
yiling d19200e9ef feat(chatbot): implement chatbot sidebar, message view, history mode and sse stream 2026-07-11 10:49:40 +08:00
yiling 77718a3e1a refactor(webui): render chatbot button as standalone Bot icon outside the toggle group 2026-07-11 10:19:41 +08:00
yiling 8d2d915f36 feat(webui): add chatbot layout and drag-drop context store 2026-07-11 10:16:46 +08:00
Yiling-J 6ede64495f Merge pull request #184 from shumaiOne/feat/app-e2e-tests
feat(e2e): set up fullstack app-level e2e test framework and signup test case
2026-07-10 23:06:16 +08:00
yiling 13f220ef0f refactor(e2e): replace S3 bucket name check with explicit SHUMAI_E2E env flag 2026-07-10 20:11:54 +08:00
yiling 4e9fae96b1 fix(ci): split E2E jobs and support skipping app server via E2E_SKIP_APP_SERVER 2026-07-10 19:41:31 +08:00
yiling 8d23d8b1c3 fix(ci): split E2E tests into harness and app jobs 2026-07-10 19:28:14 +08:00
yiling 1e1ddd1a3d fix(e2e): declare types dependencies and adjust CI projects execution using --no-deps 2026-07-10 19:10:30 +08:00
yiling 55457fcd36 fix(webui): snap playhead to last frame upon ended event in useFramePlayer 2026-07-10 16:35:41 +08:00
yiling 9414ebaefd feat(e2e): run harness tests in parallel and app E2E tests sequentially using project dependencies 2026-07-10 16:27:51 +08:00
yiling 515c491d5d fix(e2e): restore Playwright empty object destructuring for fixture parameters 2026-07-10 16:21:09 +08:00
yiling 0aba2ee557 refactor(e2e): migrate database reset logic to standard Playwright custom fixture 2026-07-10 16:18:45 +08:00
yiling cd96015b9d feat(e2e): add browser selection support for app-level E2E tests 2026-07-10 15:35:59 +08:00
yiling 26982ee494 feat(e2e): set up fullstack app-level e2e test framework and signup test case 2026-07-10 15:21:01 +08:00
Yiling-J af5c85a87b Add installation command for ffmpeg using Chocolatey 2026-07-10 09:57:21 +08:00
117 changed files with 4557 additions and 345 deletions
+46 -4
View File
@@ -57,7 +57,7 @@ jobs:
bun run /tmp/shumai-local-release/node/node_modules/@shumai-one/shumai-transcode/bin/shumai-transcode-app.js --check
e2e_video_player:
name: E2E (${{ matrix.project }})
name: Harness E2E (${{ matrix.project }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
@@ -86,13 +86,55 @@ jobs:
- name: Install Playwright browser (${{ matrix.project }})
run: bunx playwright install --with-deps ${{ matrix.project }}
- name: Run video player e2e tests
run: bun run test:e2e --project=${{ matrix.project }}
- name: Run video player harness tests
env:
E2E_SKIP_APP_SERVER: true
run: bun run test:e2e --project=harness-${{ matrix.project }}
- name: Upload Playwright report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
with:
name: playwright-report-${{ matrix.project }}
name: playwright-report-harness-${{ matrix.project }}
path: playwright-report/
retention-days: 7
e2e_app:
name: App E2E (${{ matrix.project }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
project: chromium
- os: ubuntu-latest
project: firefox
# App E2E needs Docker for testcontainers, run webkit on Ubuntu
- os: ubuntu-latest
project: webkit
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- name: Install dependencies
run: bun install
- name: Install Playwright browser (${{ matrix.project }})
run: bunx playwright install --with-deps ${{ matrix.project }}
- name: Run app E2E tests
run: bun run test:e2e --project=app-${{ matrix.project }} --no-deps
- name: Upload Playwright report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
with:
name: playwright-report-app-${{ matrix.project }}
path: playwright-report/
retention-days: 7
+1
View File
@@ -305,6 +305,7 @@ We use `prisma-json-types-generator` to enforce strict type-safety for Prisma `J
- Development: Use `bun --bun run prisma migrate dev` to create and apply migrations during development.
- Production: Use `bun --bun run prisma migrate deploy` to apply pending migrations in production environments.
- **No Automatic Dev DB Reset**: Do not run `prisma migrate reset --force` or commands that force-reset the database automatically. If migrations become out of sync or a reset is required, stop executing, report the situation to the user, and present suggested manual cleanup/reset steps for the user to execute.
### Commands
+1
View File
@@ -199,6 +199,7 @@ winget install Gyan.FFmpeg
**Chocolatey**
```powershell
choco install ffmpeg
```
#### Step 4: Install Shumai globally
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent-app",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/cli",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode-app",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"bin": {
+56
View File
@@ -0,0 +1,56 @@
import { test as base } from '@playwright/test'
import { PrismaClient } from '../../../packages/db/src/generated/prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'
import { Pool } from 'pg'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
const currentDir = path.dirname(fileURLToPath(import.meta.url))
const envPath = path.resolve(currentDir, '.env.e2e')
// Load E2E environment variables if present
if (fs.existsSync(envPath)) {
const content = fs.readFileSync(envPath, 'utf8')
content.split('\n').forEach((line) => {
const parts = line.split('=')
if (parts.length >= 2) {
const key = parts[0].trim()
const value = parts.slice(1).join('=').trim()
process.env[key] = value
}
})
}
export const test = base.extend<{ prisma: PrismaClient }>({
prisma: [
// eslint-disable-next-line no-empty-pattern
async ({}, use) => {
const connectionString = process.env.DATABASE_URL
const pool = new Pool({ connectionString })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
// Reset database state before the test runs
await prisma.$executeRawUnsafe(`
DO $$ DECLARE
r RECORD;
BEGIN
FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename <> '_prisma_migrations') LOOP
EXECUTE 'TRUNCATE TABLE ' || quote_ident(r.tablename) || ' CASCADE;';
END LOOP;
END $$;
`)
// Provide the clean prisma instance to the test
await use(prisma)
// Disconnect and clean up resources after the test finishes
await prisma.$disconnect()
await pool.end()
},
{ auto: true },
],
})
export { expect } from '@playwright/test'
+36
View File
@@ -0,0 +1,36 @@
import { teardown as dbTeardown } from '../../../packages/db/src/test-global-setup'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
const currentDir = path.dirname(fileURLToPath(import.meta.url))
export default async function globalTeardown() {
const envPath = path.resolve(currentDir, '.env.e2e')
if (fs.existsSync(envPath)) {
const content = fs.readFileSync(envPath, 'utf8')
let bucketName: string | undefined
content.split('\n').forEach((line) => {
const parts = line.split('=')
if (parts.length >= 2 && parts[0].trim() === 'S3_BUCKET') {
bucketName = parts.slice(1).join('=').trim()
}
})
if (bucketName) {
const bucketDir = path.resolve('data', bucketName)
if (fs.existsSync(bucketDir)) {
console.log(`Cleaning up E2E local storage bucket: ${bucketDir}`)
fs.rmSync(bucketDir, { recursive: true, force: true })
}
}
// Delete the temp .env.e2e file
fs.unlinkSync(envPath)
}
// Stop pgvector container
await dbTeardown()
console.log('Global teardown complete.')
}
+35
View File
@@ -0,0 +1,35 @@
import { globalTestSetup } from '../../../packages/db/src/test-global-setup'
import { randomBytes } from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
const currentDir = path.dirname(fileURLToPath(import.meta.url))
async function start() {
console.log('Starting E2E test database container...')
await globalTestSetup()
// Generate a random S3 bucket name
const randomSuffix = randomBytes(4).toString('hex')
const bucketName = `shumai-e2e-${randomSuffix}`
process.env.S3_BUCKET = bucketName
process.env.SHUMAI_SERVER_PORT = '5200'
process.env.BETTER_AUTH_URL = 'http://localhost:5200'
process.env.NODE_ENV = 'development'
process.env.SHUMAI_E2E = 'true'
// Write variables to .env.e2e file so the teardown can load them
const envContent = [`DATABASE_URL=${process.env.DATABASE_URL}`, `S3_BUCKET=${bucketName}`].join(
'\n',
)
fs.writeFileSync(path.resolve(currentDir, '.env.e2e'), envContent)
console.log(`E2E env file written. Starting Web App...`)
// Now run the web app
await import('../src/index.ts')
}
start().catch(console.error)
+75
View File
@@ -0,0 +1,75 @@
import { expect, test } from './fixtures'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
const currentDir = path.dirname(fileURLToPath(import.meta.url))
const tempImgPath = path.resolve(currentDir, 'temp-cover.png')
test.beforeAll(async () => {
// Create a 1x1 transparent PNG file
const pngBase64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='
fs.writeFileSync(tempImgPath, Buffer.from(pngBase64, 'base64'))
})
test.afterAll(async () => {
if (fs.existsSync(tempImgPath)) {
fs.unlinkSync(tempImgPath)
}
})
test('should sign up and create a project with a cover image', async ({ page }) => {
const email = `test-${Date.now()}@shumai.local`
const password = 'Password123!'
// 1. Sign Up Flow
await page.goto('/signup')
await expect(page).toHaveURL(/\/signup/)
// Fill credentials
await page.fill('#email', email)
await page.fill('#password', password)
// Submit sign up
await page.click('button[type="submit"]')
// Wait for the automatic redirect to the team page (since only one team exists)
await expect(page).toHaveURL(/\/teams\/[^/]+/)
// 2. Create Project Flow
// Click the "Create Project" button on the dashboard
await page.click('button:has-text("Create Project")')
const dialog = page.locator('[role="dialog"]')
await expect(dialog).toBeVisible()
// Fill project name
const projectName = `My Project ${Date.now()}`
await dialog.locator('#name').fill(projectName)
// Set cover image
await dialog.locator('input[type="file"]').setInputFiles(tempImgPath)
// Wait for image upload completion and preview
await expect(dialog.locator('img[alt="Cover Preview"]')).toBeVisible({ timeout: 15_000 })
// Click submit in dialog
await dialog.locator('button[type="submit"]').click()
// Wait for navigation to the project page
await expect(page).toHaveURL(/\/projects\/[^/]+/)
// Verify project name appears in the project view
await expect(page.locator(`text=${projectName}`).first()).toBeVisible()
// 3. Verification on Dashboard
// Navigate back to the dashboard via sidebar
await page.click('button[aria-label="Dashboard"]')
// Wait for dashboard URL
await expect(page).toHaveURL(/\/teams\/[^/]+/)
// Verify the project card is visible and displays the cover image with project name alt text
await expect(page.locator(`img[alt="${projectName}"]`)).toBeVisible()
})
+6 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/web-app",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"dependencies": {
@@ -13,5 +13,10 @@
"@shumai/transcode": "workspace:*",
"@shumai/webui": "workspace:*",
"hono": "4.12.23"
},
"devDependencies": {
"@prisma/adapter-pg": "7.8.0",
"pg": "8.21.0",
"@types/pg": "8.20.0"
}
}
+12 -5
View File
@@ -96,7 +96,6 @@ async function run() {
.replaceAll('content="./', 'content="/')
const serveMainHtml = () => new Response(mainHtmlText, { headers: mainHtmlHeaders })
routes['/'] = serveMainHtml
routes['/*'] = serveMainHtml
} else {
@@ -115,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
@@ -136,7 +136,14 @@ async function run() {
process.on('SIGTERM', shutdown)
}
handleDaemonCommands('shumai', run).catch((err) => {
console.error(err)
process.exit(1)
})
if (process.env.SHUMAI_E2E === 'true') {
run().catch((err) => {
console.error(err)
process.exit(1)
})
} else {
handleDaemonCommands('shumai', run).catch((err) => {
console.error(err)
process.exit(1)
})
}
+18 -13
View File
@@ -37,7 +37,7 @@
},
"apps/agent": {
"name": "@shumai/agent-app",
"version": "0.1.7",
"version": "0.1.8",
"bin": {
"shumai-agent": "./src/index.ts",
},
@@ -49,7 +49,7 @@
},
"apps/cli": {
"name": "@shumai/cli",
"version": "0.1.7",
"version": "0.1.8",
"bin": {
"shumai-cli": "./src/index.ts",
},
@@ -64,7 +64,7 @@
},
"apps/transcode": {
"name": "@shumai/transcode-app",
"version": "0.1.7",
"version": "0.1.8",
"bin": {
"shumai-transcode": "./src/index.ts",
},
@@ -76,7 +76,7 @@
},
"apps/web": {
"name": "@shumai/web-app",
"version": "0.1.7",
"version": "0.1.8",
"dependencies": {
"@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*",
@@ -88,10 +88,15 @@
"@shumai/workflow-core": "workspace:*",
"hono": "4.12.23",
},
"devDependencies": {
"@prisma/adapter-pg": "7.8.0",
"@types/pg": "8.20.0",
"pg": "8.21.0",
},
},
"packages/agent": {
"name": "@shumai/agent",
"version": "0.1.7",
"version": "0.1.8",
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.52",
"@earendil-works/pi-agent-core": "0.78.0",
@@ -115,7 +120,7 @@
},
"packages/api": {
"name": "@shumai/api",
"version": "0.1.7",
"version": "0.1.8",
"dependencies": {
"@hono/zod-validator": "0.7.6",
"@shumai/core": "workspace:*",
@@ -129,7 +134,7 @@
},
"packages/core": {
"name": "@shumai/core",
"version": "0.1.7",
"version": "0.1.8",
"dependencies": {
"@earendil-works/pi-agent-core": "0.78.0",
"@shumai/db": "workspace:*",
@@ -157,7 +162,7 @@
},
"packages/db": {
"name": "@shumai/db",
"version": "0.1.7",
"version": "0.1.8",
"dependencies": {
"@earendil-works/pi-agent-core": "0.78.0",
"@prisma/adapter-pg": "7.8.0",
@@ -173,7 +178,7 @@
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.1.7",
"version": "0.1.8",
"dependencies": {
"@earendil-works/pi-agent-core": "0.78.0",
"zod": "4.4.3",
@@ -181,11 +186,11 @@
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.1.7",
"version": "0.1.8",
},
"packages/transcode": {
"name": "@shumai/transcode",
"version": "0.1.7",
"version": "0.1.8",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -199,7 +204,7 @@
},
"packages/webui": {
"name": "@shumai/webui",
"version": "0.1.7",
"version": "0.1.8",
"dependencies": {
"@base-ui/react": "1.5.0",
"@dnd-kit/abstract": "0.4.0",
@@ -296,7 +301,7 @@
},
"packages/workflow-core": {
"name": "@shumai/workflow-core",
"version": "0.1.7",
"version": "0.1.8",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "shumai",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"repository": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"main": "./src/index.ts",
+317
View File
@@ -15,10 +15,15 @@ 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'
import { type DatabaseSessionMetadata } from '../database-session-storage'
import { triggerLocalCancel } from '@shumai/workflow-core'
import { Context } from '@temporalio/activity'
import {
prisma,
AssetType,
@@ -44,6 +49,9 @@ vi.mock('../index', async () => {
describe('Agent Activities', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.spyOn(Context, 'current').mockImplementation(() => {
throw new Error('Not in Temporal')
})
})
it('should call agentChatActivity and prompt the harness', async () => {
@@ -87,6 +95,143 @@ describe('Agent Activities', () => {
expect(piAgent.createAgentSession).toHaveBeenCalled()
})
it('should register local cancellation handler and call harness.abort when cancelled in local mode', async () => {
let resolvePrompt!: (value: {
content: Array<{ type: string; text: string } | { type: string }>
usage: { input: number; output: number }
stopReason?: string
errorMessage?: string
}) => void
const promptPromise = new Promise<Parameters<typeof resolvePrompt>[0]>((resolve) => {
resolvePrompt = resolve
})
const mockHarness = {
prompt: vi.fn().mockReturnValue(promptPromise),
abort: vi.fn(),
}
const mockSession = {
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
harness: mockHarness as unknown as AgentHarness,
})
const context = {
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
const executionPromise = agentChatActivity({
taskId: 'task-123',
teamId: 't1',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
context,
})
// Yield to let the asynchronous setup register the cancel handler
await new Promise((resolve) => setTimeout(resolve, 50))
// Simulate user cancellation
const cancelled = triggerLocalCancel('task-123')
expect(cancelled).toBe(true)
expect(mockHarness.abort).toHaveBeenCalled()
// Resolve the prompt promise to allow the activity to finish clean
resolvePrompt({
content: [{ type: 'text', text: 'AI response' }],
usage: { input: 10, output: 20 },
})
await executionPromise
})
it('should listen to Temporal cancellation signal and call harness.abort when cancelled in Temporal mode', async () => {
const mockTemporalContext = {
cancellationSignal: new EventTarget(),
heartbeat: vi.fn(),
} as unknown as Context
vi.spyOn(Context, 'current').mockReturnValue(mockTemporalContext)
let resolvePrompt!: (value: {
content: Array<{ type: string; text: string } | { type: string }>
usage: { input: number; output: number }
stopReason?: string
errorMessage?: string
}) => void
const promptPromise = new Promise<Parameters<typeof resolvePrompt>[0]>((resolve) => {
resolvePrompt = resolve
})
const mockHarness = {
prompt: vi.fn().mockReturnValue(promptPromise),
abort: vi.fn(),
}
const mockSession = {
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
harness: mockHarness as unknown as AgentHarness,
})
const context = {
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
const addEventListenerSpy = vi.spyOn(mockTemporalContext.cancellationSignal, 'addEventListener')
const removeEventListenerSpy = vi.spyOn(
mockTemporalContext.cancellationSignal,
'removeEventListener',
)
const executionPromise = agentChatActivity({
teamId: 't1',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
context,
})
// Yield to let the asynchronous setup add the abort event listener
await new Promise((resolve) => setTimeout(resolve, 50))
expect(addEventListenerSpy).toHaveBeenCalledWith('abort', expect.any(Function), { once: true })
// Simulate Temporal cancellation event
mockTemporalContext.cancellationSignal.dispatchEvent(new Event('abort'))
expect(mockHarness.abort).toHaveBeenCalled()
// Resolve the prompt promise to allow the activity to finish clean
resolvePrompt({
content: [{ type: 'text', text: 'AI response' }],
usage: { input: 10, output: 20 },
})
await executionPromise
expect(removeEventListenerSpy).toHaveBeenCalledWith('abort', expect.any(Function))
addEventListenerSpy.mockRestore()
removeEventListenerSpy.mockRestore()
})
it('should include error message in text when stopReason is error', async () => {
const mockHarness = {
prompt: vi.fn().mockResolvedValue({
@@ -741,4 +886,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()
})
})
})
+191 -13
View File
@@ -1,23 +1,29 @@
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, Context } from '@temporalio/activity'
import { registerLocalCancelHandler, unregisterLocalCancelHandler } from '@shumai/workflow-core'
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'
@@ -48,6 +54,7 @@ export interface AgentExecutionContext {
}
async function executeAgentPrompt(params: {
taskId?: string
teamId: string
agentId: string
prompt: string
@@ -58,6 +65,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
@@ -143,6 +151,35 @@ If you need to create files in the local filesystem (for example, a temporary fi
}
}
let heartbeatInterval: ReturnType<typeof setInterval> | null = null
const onAbort = () => {
harness.abort()
}
let temporalSignal: EventTarget | undefined
try {
temporalSignal = Context.current().cancellationSignal
} catch {
// Ignore
}
if (temporalSignal) {
temporalSignal.addEventListener('abort', onAbort, { once: true })
heartbeatInterval = setInterval(() => {
try {
Context.current().heartbeat()
} catch (err) {
logger.debug({ err }, 'Failed to send activity heartbeat')
}
}, 2000)
} else if (params.taskId) {
registerLocalCancelHandler(params.taskId, () => {
harness.abort()
})
}
try {
if (params.agentsInstruction && params.agentsInstruction.trim()) {
const storage = session.getStorage()
@@ -157,6 +194,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()
@@ -202,11 +254,20 @@ If you need to create files in the local filesystem (for example, a temporary fi
}
return { text, usage, sessionId }
} finally {
// Cleanup handled by agent session if needed
if (heartbeatInterval) {
clearInterval(heartbeatInterval)
}
if (temporalSignal) {
temporalSignal.removeEventListener('abort', onAbort)
}
if (params.taskId) {
unregisterLocalCancelHandler(params.taskId)
}
}
}
export interface AgentChatParams {
taskId?: string
teamId: string
agentId: string
message: string
@@ -219,6 +280,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) {
@@ -226,6 +288,7 @@ export async function agentChatActivity(params: AgentChatParams) {
const sessionId = params.sessionId
return executeAgentPrompt({
taskId: params.taskId,
teamId: params.teamId,
agentId: params.agentId,
prompt: cleanMessage,
@@ -235,6 +298,7 @@ export async function agentChatActivity(params: AgentChatParams) {
userId: params.userId,
userCommentId: params.userCommentId,
context: params.context,
attachedAssets: params.attachedAssets,
})
}
@@ -1120,3 +1184,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],
})
+36 -14
View File
@@ -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 () => {
@@ -475,19 +491,25 @@ describe('Agent Chat Workflow', () => {
])
.build()
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith({
teamId: 't1',
agentId: 'b1',
message: 'chatbot prompt',
imageUrls: [],
projectId: 'p1',
folderId: '',
agentsInstruction: expectedInstruction,
sessionId: 'session-direct-123',
userId: undefined,
userCommentId: undefined,
explicitMention: true,
context: { agent: { id: 'b1' } },
})
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
expect.objectContaining({
teamId: 't1',
agentId: 'b1',
message: 'chatbot prompt',
imageUrls: [],
projectId: 'p1',
folderId: '',
agentsInstruction: expectedInstruction,
sessionId: 'session-direct-123',
userId: undefined,
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' },
],
}),
)
})
})
+42 -5
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,
})
}
}
}
@@ -171,6 +179,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
}
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
taskId: task.id,
teamId,
agentId: agentId,
message: prompt,
@@ -183,8 +192,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__') {
@@ -220,10 +242,25 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
// Update placeholder comment with error message
if (placeholderCommentId && agentWorkerQueue) {
try {
const errorMessage =
err instanceof Error && err.message.startsWith('AI error:')
? `AI error: ${err.message.substring(9)}`
: 'Sorry, I encountered an error while processing your request.'
let errorMessage = 'Sorry, I encountered an error while processing your request.'
if (err instanceof Error) {
if (err.message.startsWith('AI error:')) {
errorMessage = `AI error: ${err.message.substring(9)}`
} else if (
err.message.includes('aborted') ||
err.message.includes('abort') ||
err.name === 'AbortError' ||
err.message.includes('cancel')
) {
errorMessage = 'Agent execution stopped.'
}
} else if (
String(err).includes('aborted') ||
String(err).includes('abort') ||
String(err).includes('cancel')
) {
errorMessage = 'Agent execution stopped.'
}
await executeActivity(agentWorkerQueue, updateCommentActivity, {
commentId: placeholderCommentId,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/api",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"main": "./src/index.ts",
+99 -40
View File
@@ -3,6 +3,7 @@ import { Hono } from 'hono'
import chatRoute from './chat'
import { chatService } from '@shumai/core/src/chat/chat'
import { authzService } from '@shumai/core/src/authz/authz'
import type { ChatMessage } from '@shumai/dtos'
vi.mock('@shumai/core/src/chat/chat', async (importOriginal) => {
const original = await importOriginal<typeof import('@shumai/core/src/chat/chat')>()
@@ -13,22 +14,13 @@ vi.mock('@shumai/core/src/chat/chat', async (importOriginal) => {
listMessages: vi.fn(),
deleteSession: vi.fn(),
startOrContinueChat: vi.fn(),
getNewSessionMessages: vi.fn(),
getChatWorkflowStatus: vi.fn(),
abortSession: vi.fn(),
},
}
})
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/db', () => ({
prisma: {
agentSessionEntry: {
findMany: vi.fn(),
},
workflowTask: {
findUnique: vi.fn(),
},
},
}))
import { prisma } from '@shumai/db'
describe('Chat API', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
@@ -43,7 +35,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 +54,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,58 +77,56 @@ 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',
taskId: 'task1',
})
const mockEntries = [
{
id: 'entry1',
sessionId: 'session1',
entry: {
type: 'message',
message: {
vi.mocked(chatService.getNewSessionMessages)
.mockResolvedValueOnce({
messages: [
{
id: 'entry1',
role: 'user',
content: [{ type: 'text', text: 'hi' }],
},
},
},
]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.agentSessionEntry.findMany).mockResolvedValue(mockEntries as any)
content: 'hi',
} as unknown as ChatMessage,
],
lastEntryId: 'entry1',
})
.mockResolvedValue({
messages: [],
lastEntryId: 'entry1',
})
const mockTask = {
id: 'task1',
vi.mocked(chatService.getChatWorkflowStatus).mockResolvedValue({
status: 'completed',
output: {},
}
// 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 +141,74 @@ 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',
})
vi.mocked(chatService.getNewSessionMessages).mockResolvedValue({
messages: [],
lastEntryId: null,
})
vi.mocked(chatService.getChatWorkflowStatus).mockResolvedValue({
status: 'completed',
output: {},
})
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"}')
})
})
describe('POST /teams/:teamId/chat/sessions/:sessionId/abort', () => {
it('aborts an active chat session and updates task status', async () => {
vi.mocked(chatService.abortSession).mockResolvedValue(undefined)
const res = await app.request('/teams/team1/chat/sessions/session1/abort', {
method: 'POST',
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toEqual({ success: true })
expect(chatService.abortSession).toHaveBeenCalledWith('user1', 'session1')
})
it('returns 404 if no active task is found for the session', async () => {
vi.mocked(chatService.abortSession).mockRejectedValue(
new Error('No active execution found for this session'),
)
const res = await app.request('/teams/team1/chat/sessions/session1/abort', {
method: 'POST',
})
expect(res.status).toBe(404)
const data = await res.json()
expect(data.error).toBe('No active execution found for this session')
})
})
})
+104 -37
View File
@@ -1,42 +1,84 @@
import { Hono } from 'hono'
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 { chatService } 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()
@@ -45,18 +87,14 @@ const route = new Hono<{ Variables: { user: User } }>()
if (stream.aborted) {
break
}
// Query new entries from the DB
const newEntries = await prisma.agentSessionEntry.findMany({
where: {
sessionId,
...(lastEntryId ? { id: { gt: lastEntryId } } : {}),
},
orderBy: { id: 'asc' },
})
// Query new entries from the DB via chatService
const { messages, lastEntryId: newLastId } = await chatService.getNewSessionMessages(
sessionId,
lastEntryId || undefined,
)
if (newEntries.length > 0) {
for (const record of newEntries) {
const message = mapEntryToMessage(record)
if (messages.length > 0) {
for (const message of messages) {
await stream.writeSSE({
data: JSON.stringify({
type: 'entry',
@@ -64,26 +102,28 @@ 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
const task = await prisma.workflowTask.findUnique({
where: { id: taskId },
select: { status: true, output: true },
})
if (newLastId) {
lastEntryId = newLastId
}
// Check if workflow has finished via chatService
const task = await chatService.getChatWorkflowStatus(taskId)
if (task && (task.status === 'completed' || task.status === 'failed')) {
// Fetch any remaining entries one last time
const finalEntries = await prisma.agentSessionEntry.findMany({
where: {
sessionId,
...(lastEntryId ? { id: { gt: lastEntryId } } : {}),
},
orderBy: { id: 'asc' },
})
for (const record of finalEntries) {
const message = mapEntryToMessage(record)
const { messages: finalMessages } = await chatService.getNewSessionMessages(
sessionId,
lastEntryId || undefined,
)
for (const message of finalMessages) {
await stream.writeSSE({
data: JSON.stringify({
type: 'entry',
@@ -93,7 +133,7 @@ const route = new Hono<{ Variables: { user: User } }>()
}
// Send done status
const output = task.output as Record<string, unknown> | null
const output = task.output
await stream.writeSSE({
data: JSON.stringify({
type: 'done',
@@ -122,5 +162,32 @@ const route = new Hono<{ Variables: { user: User } }>()
}
})
})
.post('/teams/:teamId/chat/sessions/:sessionId/abort', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const sessionId = c.req.param('sessionId')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
try {
await chatService.abortSession(user.id, sessionId)
return c.json({ success: true }, 200)
} catch (error: unknown) {
const err = error as Error
if (
err.message === 'Session not found' ||
err.message === 'Unauthorized session access' ||
err.message === 'No active execution found for this session'
) {
return c.json({ error: err.message }, 404)
}
throw error
}
})
export default route
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/core",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"main": "./src/index.ts",
+308 -30
View File
@@ -1,7 +1,8 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { chatService, buildSessionMessages, type PathEntry } from './chat'
import { describe, expect, it } from 'vitest'
import { chatService, buildSessionMessages, mapEntryToMessage, type PathEntry } from './chat'
import { describe, expect, it, vi } from 'vitest'
import { workflowService } from '@shumai/workflow-core'
describe('ChatService', () => {
setupTestDbHooks()
@@ -14,7 +15,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 +74,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,
})
@@ -110,18 +111,18 @@ describe('ChatService', () => {
})
expect(task).toBeDefined()
expect(task?.type).toBe('chat')
expect(task?.status).toBe('pending')
expect(['pending', 'processing']).toContain(task?.status)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const taskPayload = task?.payload as any
expect(taskPayload?.agent?.prompt).toBe('hello world')
})
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 +130,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 +158,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 +188,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 +208,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 +266,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 +275,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 },
@@ -364,4 +477,169 @@ describe('ChatService', () => {
expect(msg3.content).toBe('Branch summary details')
expect((msg3.details as Record<string, unknown>).fromId).toBe('entry-old')
})
describe('getNewSessionMessages', () => {
it('returns new messages and lastEntryId', async () => {
const { user, team, project } = await setupBasicData()
const { sessionId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello',
projectId: project.id,
})
// Insert two entries
const entry1 = await prisma.agentSessionEntry.create({
data: {
id: 'entry-id-1',
sessionId,
entry: {
type: 'message',
id: 'entry-id-1',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: [{ type: 'text', text: 'msg 1' }],
},
} as unknown as PrismaJson.PiSessionEntry,
},
})
const entry2 = await prisma.agentSessionEntry.create({
data: {
id: 'entry-id-2',
sessionId,
entry: {
type: 'message',
id: 'entry-id-2',
parentId: 'entry-id-1',
timestamp: new Date().toISOString(),
message: {
role: 'assistant',
content: [{ type: 'text', text: 'msg 2' }],
},
} as unknown as PrismaJson.PiSessionEntry,
},
})
// 1. Get all messages
const res1 = await chatService.getNewSessionMessages(sessionId)
expect(res1.messages).toHaveLength(2)
expect(res1.lastEntryId).toBe(entry2.id)
expect(res1.messages[0].id).toBe(entry1.id)
// 2. Get with lastEntryId
const res2 = await chatService.getNewSessionMessages(sessionId, entry1.id)
expect(res2.messages).toHaveLength(1)
expect(res2.lastEntryId).toBe(entry2.id)
expect(res2.messages[0].id).toBe(entry2.id)
// 3. Get with latest lastEntryId
const res3 = await chatService.getNewSessionMessages(sessionId, entry2.id)
expect(res3.messages).toHaveLength(0)
expect(res3.lastEntryId).toBe(entry2.id)
})
})
describe('getChatWorkflowStatus', () => {
it('returns task status and output', async () => {
const { team, project } = await setupBasicData()
const rootFolder = await prisma.asset.findFirst({
where: { projectId: project.id, type: 'root' },
})
const task = await prisma.workflowTask.create({
data: {
assetId: rootFolder!.id,
type: 'chat',
status: 'completed',
teamId: team.id,
projectId: project.id,
payload: { projectId: project.id },
output: { success: true },
},
})
const statusRes = await chatService.getChatWorkflowStatus(task.id)
expect(statusRes).not.toBeNull()
expect(statusRes?.status).toBe('completed')
expect(statusRes?.output).toEqual({ success: true })
})
it('returns null if task not found', async () => {
const statusRes = await chatService.getChatWorkflowStatus('non-existent-task')
expect(statusRes).toBeNull()
})
})
describe('abortSession', () => {
it('cancels active task and marks failed/aborted', async () => {
const { user, team, project } = await setupBasicData()
const { sessionId, taskId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'long execution',
projectId: project.id,
})
// Mark the task as processing
await prisma.workflowTask.update({
where: { id: taskId },
data: { status: 'processing' },
})
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
await chatService.abortSession(user.id, sessionId)
expect(cancelSpy).toHaveBeenCalledWith(taskId)
const updatedTask = await prisma.workflowTask.findUnique({
where: { id: taskId },
})
expect(updatedTask?.status).toBe('failed')
expect(updatedTask?.output).toEqual({ error: 'aborted' })
cancelSpy.mockRestore()
})
it('throws error if session not found', async () => {
await expect(chatService.abortSession('user-1', 'non-existent-session')).rejects.toThrow(
'Session not found',
)
})
it('throws error if unauthorized', async () => {
const { team, project } = await setupBasicData()
const otherUser = await prisma.user.create({
data: { name: 'Other User', email: `other-${Date.now()}@example.com`, password: 'pw' },
})
const { sessionId } = await chatService.startOrContinueChat(otherUser, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello',
projectId: project.id,
})
await expect(chatService.abortSession('different-user-id', sessionId)).rejects.toThrow(
'Unauthorized session access',
)
})
it('throws error if no active task', async () => {
const { user, team, project } = await setupBasicData()
const { sessionId, taskId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello',
projectId: project.id,
})
// Complete the task
await prisma.workflowTask.update({
where: { id: taskId },
data: { status: 'completed' },
})
await expect(chatService.abortSession(user.id, sessionId)).rejects.toThrow(
'No active execution found for this session',
)
})
})
})
+120 -6
View File
@@ -4,6 +4,7 @@ import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/a
import { paginateQuery, type PaginatedData } from '@shumai/core/src/pagination'
import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos'
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { workflowService } from '@shumai/workflow-core'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -28,6 +29,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 +39,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 +99,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 +142,7 @@ export class ChatService {
async startOrContinueChat(
user: User,
teamId: string,
req: ChatRequest,
): Promise<{ sessionId: string; taskId: string }> {
const {
@@ -232,20 +249,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 +280,7 @@ export class ChatService {
userId: user.id,
cwd: process.cwd(),
assetId: asset.id,
type: 'chat',
},
})
activeSessionId = newSession.id
@@ -265,6 +293,7 @@ export class ChatService {
status: 'pending',
teamId,
projectId,
sessionId: activeSessionId,
payload: {
projectId,
agent: {
@@ -276,6 +305,7 @@ export class ChatService {
agentId,
sessionId: activeSessionId,
userId: user.id,
isNewChat: !passedSessionId,
},
},
},
@@ -290,10 +320,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 +345,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 +355,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 +382,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 },
})
@@ -360,6 +396,84 @@ export class ChatService {
where: { id: sessionId },
})
}
async getNewSessionMessages(
sessionId: string,
lastEntryId?: string,
): Promise<{ messages: ChatMessage[]; lastEntryId: string | null }> {
const entries = await this.prismaClient.agentSessionEntry.findMany({
where: {
sessionId,
...(lastEntryId ? { id: { gt: lastEntryId } } : {}),
},
orderBy: { id: 'asc' },
})
if (entries.length === 0) {
return { messages: [], lastEntryId: lastEntryId ?? null }
}
const messages: ChatMessage[] = []
for (const entry of entries) {
const message = mapEntryToMessage(entry)
if (message) {
messages.push(message)
}
}
return {
messages,
lastEntryId: entries[entries.length - 1].id,
}
}
async getChatWorkflowStatus(
taskId: string,
): Promise<{ status: string | null; output: Record<string, unknown> | null } | null> {
const task = await this.prismaClient.workflowTask.findUnique({
where: { id: taskId },
select: { status: true, output: true },
})
if (!task) return null
return {
status: task.status,
output: task.output as Record<string, unknown> | null,
}
}
async abortSession(userId: string, sessionId: string): Promise<void> {
const session = await this.prismaClient.agentSession.findUnique({
where: { id: sessionId },
})
if (!session) {
throw new Error('Session not found')
}
if (session.userId !== userId) {
throw new Error('Unauthorized session access')
}
const taskToAbort = await this.prismaClient.workflowTask.findFirst({
where: {
status: { in: ['pending', 'processing'] },
type: 'chat',
sessionId,
},
})
if (!taskToAbort) {
throw new Error('No active execution found for this session')
}
await workflowService.cancel(taskToAbort.id)
await this.prismaClient.workflowTask.update({
where: { id: taskToAbort.id },
data: {
status: 'failed',
output: { error: 'aborted' },
},
})
}
}
export const chatService = new ChatService()
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/db",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -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';
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "workflow_tasks" ADD COLUMN "session_id" TEXT;
-- CreateIndex
CREATE INDEX "workflow_tasks_session_id_idx" ON "workflow_tasks"("session_id");
@@ -0,0 +1,4 @@
-- Backfill session_id from existing task payloads
UPDATE "workflow_tasks"
SET "session_id" = (payload->'agent'->>'sessionId')
WHERE "session_id" IS NULL AND (payload->'agent'->>'sessionId') IS NOT NULL;
+11
View File
@@ -629,6 +629,7 @@ model WorkflowTask {
inputTokens Int @default(0) @map("input_tokens")
outputTokens Int @default(0) @map("output_tokens")
model String?
sessionId String? @map("session_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@ -638,6 +639,7 @@ model WorkflowTask {
@@index([teamId])
@@index([projectId])
@@index([type])
@@index([sessionId])
}
enum AgentType {
chat
@@ -645,6 +647,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 +701,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
@@ -3266,6 +3266,7 @@ export const WorkflowTaskScalarFieldEnum = {
inputTokens: 'inputTokens',
outputTokens: 'outputTokens',
model: 'model',
sessionId: 'sessionId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
@@ -3308,6 +3309,8 @@ export const AgentSessionScalarFieldEnum = {
leafId: 'leafId',
assetId: 'assetId',
userCommentId: 'userCommentId',
type: 'type',
name: 'name',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
@@ -3728,6 +3731,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
*/
@@ -451,6 +451,7 @@ export const WorkflowTaskScalarFieldEnum = {
inputTokens: 'inputTokens',
outputTokens: 'outputTokens',
model: 'model',
sessionId: 'sessionId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
@@ -493,6 +494,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'>
}
+29 -1
View File
@@ -50,6 +50,7 @@ export type WorkflowTaskMinAggregateOutputType = {
inputTokens: number | null
outputTokens: number | null
model: string | null
sessionId: string | null
createdAt: Date | null
updatedAt: Date | null
}
@@ -66,6 +67,7 @@ export type WorkflowTaskMaxAggregateOutputType = {
inputTokens: number | null
outputTokens: number | null
model: string | null
sessionId: string | null
createdAt: Date | null
updatedAt: Date | null
}
@@ -84,6 +86,7 @@ export type WorkflowTaskCountAggregateOutputType = {
inputTokens: number
outputTokens: number
model: number
sessionId: number
createdAt: number
updatedAt: number
_all: number
@@ -112,6 +115,7 @@ export type WorkflowTaskMinAggregateInputType = {
inputTokens?: true
outputTokens?: true
model?: true
sessionId?: true
createdAt?: true
updatedAt?: true
}
@@ -128,6 +132,7 @@ export type WorkflowTaskMaxAggregateInputType = {
inputTokens?: true
outputTokens?: true
model?: true
sessionId?: true
createdAt?: true
updatedAt?: true
}
@@ -146,6 +151,7 @@ export type WorkflowTaskCountAggregateInputType = {
inputTokens?: true
outputTokens?: true
model?: true
sessionId?: true
createdAt?: true
updatedAt?: true
_all?: true
@@ -251,6 +257,7 @@ export type WorkflowTaskGroupByOutputType = {
inputTokens: number
outputTokens: number
model: string | null
sessionId: string | null
createdAt: Date
updatedAt: Date
_count: WorkflowTaskCountAggregateOutputType | null
@@ -292,6 +299,7 @@ export type WorkflowTaskWhereInput = {
inputTokens?: Prisma.IntFilter<"WorkflowTask"> | number
outputTokens?: Prisma.IntFilter<"WorkflowTask"> | number
model?: Prisma.StringNullableFilter<"WorkflowTask"> | string | null
sessionId?: Prisma.StringNullableFilter<"WorkflowTask"> | string | null
createdAt?: Prisma.DateTimeFilter<"WorkflowTask"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"WorkflowTask"> | Date | string
}
@@ -310,6 +318,7 @@ export type WorkflowTaskOrderByWithRelationInput = {
inputTokens?: Prisma.SortOrder
outputTokens?: Prisma.SortOrder
model?: Prisma.SortOrderInput | Prisma.SortOrder
sessionId?: Prisma.SortOrderInput | Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
}
@@ -331,6 +340,7 @@ export type WorkflowTaskWhereUniqueInput = Prisma.AtLeast<{
inputTokens?: Prisma.IntFilter<"WorkflowTask"> | number
outputTokens?: Prisma.IntFilter<"WorkflowTask"> | number
model?: Prisma.StringNullableFilter<"WorkflowTask"> | string | null
sessionId?: Prisma.StringNullableFilter<"WorkflowTask"> | string | null
createdAt?: Prisma.DateTimeFilter<"WorkflowTask"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"WorkflowTask"> | Date | string
}, "id">
@@ -349,6 +359,7 @@ export type WorkflowTaskOrderByWithAggregationInput = {
inputTokens?: Prisma.SortOrder
outputTokens?: Prisma.SortOrder
model?: Prisma.SortOrderInput | Prisma.SortOrder
sessionId?: Prisma.SortOrderInput | Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
_count?: Prisma.WorkflowTaskCountOrderByAggregateInput
@@ -375,6 +386,7 @@ export type WorkflowTaskScalarWhereWithAggregatesInput = {
inputTokens?: Prisma.IntWithAggregatesFilter<"WorkflowTask"> | number
outputTokens?: Prisma.IntWithAggregatesFilter<"WorkflowTask"> | number
model?: Prisma.StringNullableWithAggregatesFilter<"WorkflowTask"> | string | null
sessionId?: Prisma.StringNullableWithAggregatesFilter<"WorkflowTask"> | string | null
createdAt?: Prisma.DateTimeWithAggregatesFilter<"WorkflowTask"> | Date | string
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"WorkflowTask"> | Date | string
}
@@ -393,6 +405,7 @@ export type WorkflowTaskCreateInput = {
inputTokens?: number
outputTokens?: number
model?: string | null
sessionId?: string | null
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -411,6 +424,7 @@ export type WorkflowTaskUncheckedCreateInput = {
inputTokens?: number
outputTokens?: number
model?: string | null
sessionId?: string | null
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -429,6 +443,7 @@ export type WorkflowTaskUpdateInput = {
inputTokens?: Prisma.IntFieldUpdateOperationsInput | number
outputTokens?: Prisma.IntFieldUpdateOperationsInput | number
model?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
sessionId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -447,6 +462,7 @@ export type WorkflowTaskUncheckedUpdateInput = {
inputTokens?: Prisma.IntFieldUpdateOperationsInput | number
outputTokens?: Prisma.IntFieldUpdateOperationsInput | number
model?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
sessionId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -465,6 +481,7 @@ export type WorkflowTaskCreateManyInput = {
inputTokens?: number
outputTokens?: number
model?: string | null
sessionId?: string | null
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -483,6 +500,7 @@ export type WorkflowTaskUpdateManyMutationInput = {
inputTokens?: Prisma.IntFieldUpdateOperationsInput | number
outputTokens?: Prisma.IntFieldUpdateOperationsInput | number
model?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
sessionId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -501,6 +519,7 @@ export type WorkflowTaskUncheckedUpdateManyInput = {
inputTokens?: Prisma.IntFieldUpdateOperationsInput | number
outputTokens?: Prisma.IntFieldUpdateOperationsInput | number
model?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
sessionId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -519,6 +538,7 @@ export type WorkflowTaskCountOrderByAggregateInput = {
inputTokens?: Prisma.SortOrder
outputTokens?: Prisma.SortOrder
model?: Prisma.SortOrder
sessionId?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
}
@@ -540,6 +560,7 @@ export type WorkflowTaskMaxOrderByAggregateInput = {
inputTokens?: Prisma.SortOrder
outputTokens?: Prisma.SortOrder
model?: Prisma.SortOrder
sessionId?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
}
@@ -556,6 +577,7 @@ export type WorkflowTaskMinOrderByAggregateInput = {
inputTokens?: Prisma.SortOrder
outputTokens?: Prisma.SortOrder
model?: Prisma.SortOrder
sessionId?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
}
@@ -589,6 +611,7 @@ export type WorkflowTaskSelect<ExtArgs extends runtime.Types.Extensions.Internal
inputTokens?: boolean
outputTokens?: boolean
model?: boolean
sessionId?: boolean
createdAt?: boolean
updatedAt?: boolean
}, ExtArgs["result"]["workflowTask"]>
@@ -607,6 +630,7 @@ export type WorkflowTaskSelectCreateManyAndReturn<ExtArgs extends runtime.Types.
inputTokens?: boolean
outputTokens?: boolean
model?: boolean
sessionId?: boolean
createdAt?: boolean
updatedAt?: boolean
}, ExtArgs["result"]["workflowTask"]>
@@ -625,6 +649,7 @@ export type WorkflowTaskSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.
inputTokens?: boolean
outputTokens?: boolean
model?: boolean
sessionId?: boolean
createdAt?: boolean
updatedAt?: boolean
}, ExtArgs["result"]["workflowTask"]>
@@ -643,11 +668,12 @@ export type WorkflowTaskSelectScalar = {
inputTokens?: boolean
outputTokens?: boolean
model?: boolean
sessionId?: boolean
createdAt?: boolean
updatedAt?: boolean
}
export type WorkflowTaskOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "uid" | "teamId" | "projectId" | "assetId" | "type" | "status" | "payload" | "output" | "heartbeat" | "inputTokens" | "outputTokens" | "model" | "createdAt" | "updatedAt", ExtArgs["result"]["workflowTask"]>
export type WorkflowTaskOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "uid" | "teamId" | "projectId" | "assetId" | "type" | "status" | "payload" | "output" | "heartbeat" | "inputTokens" | "outputTokens" | "model" | "sessionId" | "createdAt" | "updatedAt", ExtArgs["result"]["workflowTask"]>
export type $WorkflowTaskPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
name: "WorkflowTask"
@@ -672,6 +698,7 @@ export type $WorkflowTaskPayload<ExtArgs extends runtime.Types.Extensions.Intern
inputTokens: number
outputTokens: number
model: string | null
sessionId: string | null
createdAt: Date
updatedAt: Date
}, ExtArgs["result"]["workflowTask"]>
@@ -1110,6 +1137,7 @@ export interface WorkflowTaskFieldRefs {
readonly inputTokens: Prisma.FieldRef<"WorkflowTask", 'Int'>
readonly outputTokens: Prisma.FieldRef<"WorkflowTask", 'Int'>
readonly model: Prisma.FieldRef<"WorkflowTask", 'String'>
readonly sessionId: Prisma.FieldRef<"WorkflowTask", 'String'>
readonly createdAt: Prisma.FieldRef<"WorkflowTask", 'DateTime'>
readonly updatedAt: Prisma.FieldRef<"WorkflowTask", 'DateTime'>
}
+1
View File
@@ -292,6 +292,7 @@ declare global {
imageUrls?: string[]
attachedFiles?: string[]
assetIds?: string[]
isNewChat?: boolean
}
// ----------------------------------------------------------------------
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/dtos",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"main": "./src/index.ts",
+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),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/tableprinter",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -75,6 +75,7 @@ describe('Transcode Workflow', () => {
assetId: 'asset-1',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
@@ -166,6 +167,7 @@ describe('Transcode Workflow', () => {
assetId: 'asset-image',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
@@ -249,6 +251,7 @@ describe('Transcode Workflow', () => {
assetId: 'asset-1',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
@@ -281,6 +284,7 @@ describe('Transcode Workflow', () => {
assetId: 'asset-video',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
@@ -344,6 +348,7 @@ describe('Transcode Workflow', () => {
assetId: 'asset-image',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
@@ -396,6 +401,7 @@ describe('Transcode Workflow', () => {
assetId: 'asset-audio',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
+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,673 @@
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,
abortActiveSession,
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">
<span>{m.no_chat_agents_warning()}</span>
</div>
)}
</div>
{isStreaming ? (
<button
onClick={() => {
if (teamId) {
abortActiveSession(teamId)
}
}}
className="p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm bg-destructive text-destructive-foreground hover:bg-destructive/90 transform hover:-translate-y-0.5"
title="Stop generation"
>
<div className="h-4 w-4 flex items-center justify-center">
<div className="h-3 w-3 bg-current rounded-[2px] bg-white" />
</div>
</button>
) : (
<button
onClick={handleSend}
disabled={!inputText.trim() || !selectedAgentId}
className={cn(
'p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm',
inputText.trim() && 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)
@@ -186,8 +186,13 @@ export function useFramePlayer(
}
}
const handleEnded = () => {
setCurrentFrame(totalFrames - 1)
}
video.addEventListener('play', handlePlay)
video.addEventListener('pause', handlePause)
video.addEventListener('ended', handleEnded)
// If it's already playing when this effect runs
if (!video.paused) {
@@ -199,6 +204,7 @@ export function useFramePlayer(
active = false
video.removeEventListener('play', handlePlay)
video.removeEventListener('pause', handlePause)
video.removeEventListener('ended', handleEnded)
if (rVfcId !== null) {
const videoWithCallback = video as unknown as HtmlVideoElementWithCallback
if (videoWithCallback.cancelVideoFrameCallback) {
+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": "选择智能体"
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/webui",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"type": "module",
"main": "./index.html",
+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 = {};

Some files were not shown because too many files have changed in this diff Show More