mirror of
https://github.com/simstudioai/sim.git
synced 2026-01-24 14:27:56 -05:00
Compare commits
35 Commits
fix/copilo
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9c4251c1c | ||
|
|
cc2be33d6b | ||
|
|
45371e521e | ||
|
|
0ce0f98aa5 | ||
|
|
dff1c9d083 | ||
|
|
b09f683072 | ||
|
|
a8bb0db660 | ||
|
|
af82820a28 | ||
|
|
4372841797 | ||
|
|
5e8c843241 | ||
|
|
7bf3d73ee6 | ||
|
|
7ffc11a738 | ||
|
|
be578e2ed7 | ||
|
|
f415e5edc4 | ||
|
|
13a6e6c3fa | ||
|
|
f5ab7f21ae | ||
|
|
bfb6fffe38 | ||
|
|
4fbec0a43f | ||
|
|
585f5e365b | ||
|
|
3792bdd252 | ||
|
|
eb5d1f3e5b | ||
|
|
54ab82c8dd | ||
|
|
f895bf469b | ||
|
|
dd3209af06 | ||
|
|
b6ba3b50a7 | ||
|
|
b304233062 | ||
|
|
57e4b49bd6 | ||
|
|
e12dd204ed | ||
|
|
3d9d9cbc54 | ||
|
|
0f4ec962ad | ||
|
|
4827866f9a | ||
|
|
3e697d9ed9 | ||
|
|
4431a1a484 | ||
|
|
4d1a9a3f22 | ||
|
|
eb07a080fb |
@@ -59,7 +59,7 @@ export default function StatusIndicator() {
|
|||||||
href={statusUrl}
|
href={statusUrl}
|
||||||
target='_blank'
|
target='_blank'
|
||||||
rel='noopener noreferrer'
|
rel='noopener noreferrer'
|
||||||
className={`flex min-w-[165px] items-center gap-[6px] whitespace-nowrap text-[12px] transition-colors ${STATUS_COLORS[status]}`}
|
className={`flex items-center gap-[6px] whitespace-nowrap text-[12px] transition-colors ${STATUS_COLORS[status]}`}
|
||||||
aria-label={`System status: ${message}`}
|
aria-label={`System status: ${message}`}
|
||||||
>
|
>
|
||||||
<StatusDotIcon status={status} className='h-[6px] w-[6px]' aria-hidden='true' />
|
<StatusDotIcon status={status} className='h-[6px] w-[6px]' aria-hidden='true' />
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
'use client'
|
|
||||||
|
|
||||||
import { useState } from 'react'
|
|
||||||
import { ArrowLeft, ChevronLeft } from 'lucide-react'
|
|
||||||
import Link from 'next/link'
|
|
||||||
|
|
||||||
export function BackLink() {
|
|
||||||
const [isHovered, setIsHovered] = useState(false)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link
|
|
||||||
href='/studio'
|
|
||||||
className='group flex items-center gap-1 text-gray-600 text-sm hover:text-gray-900'
|
|
||||||
onMouseEnter={() => setIsHovered(true)}
|
|
||||||
onMouseLeave={() => setIsHovered(false)}
|
|
||||||
>
|
|
||||||
<span className='group-hover:-translate-x-0.5 inline-flex transition-transform duration-200'>
|
|
||||||
{isHovered ? (
|
|
||||||
<ArrowLeft className='h-4 w-4' aria-hidden='true' />
|
|
||||||
) : (
|
|
||||||
<ChevronLeft className='h-4 w-4' aria-hidden='true' />
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
Back to Sim Studio
|
|
||||||
</Link>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -5,10 +5,7 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/emcn'
|
|||||||
import { FAQ } from '@/lib/blog/faq'
|
import { FAQ } from '@/lib/blog/faq'
|
||||||
import { getAllPostMeta, getPostBySlug, getRelatedPosts } from '@/lib/blog/registry'
|
import { getAllPostMeta, getPostBySlug, getRelatedPosts } from '@/lib/blog/registry'
|
||||||
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildPostMetadata } from '@/lib/blog/seo'
|
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildPostMetadata } from '@/lib/blog/seo'
|
||||||
import { getBaseUrl } from '@/lib/core/utils/urls'
|
|
||||||
import { soehne } from '@/app/_styles/fonts/soehne/soehne'
|
import { soehne } from '@/app/_styles/fonts/soehne/soehne'
|
||||||
import { BackLink } from '@/app/(landing)/studio/[slug]/back-link'
|
|
||||||
import { ShareButton } from '@/app/(landing)/studio/[slug]/share-button'
|
|
||||||
|
|
||||||
export async function generateStaticParams() {
|
export async function generateStaticParams() {
|
||||||
const posts = await getAllPostMeta()
|
const posts = await getAllPostMeta()
|
||||||
@@ -51,7 +48,9 @@ export default async function Page({ params }: { params: Promise<{ slug: string
|
|||||||
/>
|
/>
|
||||||
<header className='mx-auto max-w-[1450px] px-6 pt-8 sm:px-8 sm:pt-12 md:px-12 md:pt-16'>
|
<header className='mx-auto max-w-[1450px] px-6 pt-8 sm:px-8 sm:pt-12 md:px-12 md:pt-16'>
|
||||||
<div className='mb-6'>
|
<div className='mb-6'>
|
||||||
<BackLink />
|
<Link href='/studio' className='text-gray-600 text-sm hover:text-gray-900'>
|
||||||
|
← Back to Sim Studio
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
<div className='flex flex-col gap-8 md:flex-row md:gap-12'>
|
<div className='flex flex-col gap-8 md:flex-row md:gap-12'>
|
||||||
<div className='w-full flex-shrink-0 md:w-[450px]'>
|
<div className='w-full flex-shrink-0 md:w-[450px]'>
|
||||||
@@ -76,31 +75,28 @@ export default async function Page({ params }: { params: Promise<{ slug: string
|
|||||||
>
|
>
|
||||||
{post.title}
|
{post.title}
|
||||||
</h1>
|
</h1>
|
||||||
<div className='mt-4 flex items-center justify-between'>
|
<div className='mt-4 flex items-center gap-3'>
|
||||||
<div className='flex items-center gap-3'>
|
{(post.authors || [post.author]).map((a, idx) => (
|
||||||
{(post.authors || [post.author]).map((a, idx) => (
|
<div key={idx} className='flex items-center gap-2'>
|
||||||
<div key={idx} className='flex items-center gap-2'>
|
{a?.avatarUrl ? (
|
||||||
{a?.avatarUrl ? (
|
<Avatar className='size-6'>
|
||||||
<Avatar className='size-6'>
|
<AvatarImage src={a.avatarUrl} alt={a.name} />
|
||||||
<AvatarImage src={a.avatarUrl} alt={a.name} />
|
<AvatarFallback>{a.name.slice(0, 2)}</AvatarFallback>
|
||||||
<AvatarFallback>{a.name.slice(0, 2)}</AvatarFallback>
|
</Avatar>
|
||||||
</Avatar>
|
) : null}
|
||||||
) : null}
|
<Link
|
||||||
<Link
|
href={a?.url || '#'}
|
||||||
href={a?.url || '#'}
|
target='_blank'
|
||||||
target='_blank'
|
rel='noopener noreferrer author'
|
||||||
rel='noopener noreferrer author'
|
className='text-[14px] text-gray-600 leading-[1.5] hover:text-gray-900 sm:text-[16px]'
|
||||||
className='text-[14px] text-gray-600 leading-[1.5] hover:text-gray-900 sm:text-[16px]'
|
itemProp='author'
|
||||||
itemProp='author'
|
itemScope
|
||||||
itemScope
|
itemType='https://schema.org/Person'
|
||||||
itemType='https://schema.org/Person'
|
>
|
||||||
>
|
<span itemProp='name'>{a?.name}</span>
|
||||||
<span itemProp='name'>{a?.name}</span>
|
</Link>
|
||||||
</Link>
|
</div>
|
||||||
</div>
|
))}
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<ShareButton url={`${getBaseUrl()}/studio/${slug}`} title={post.title} />
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
'use client'
|
|
||||||
|
|
||||||
import { useState } from 'react'
|
|
||||||
import { Share2 } from 'lucide-react'
|
|
||||||
import { Popover, PopoverContent, PopoverItem, PopoverTrigger } from '@/components/emcn'
|
|
||||||
|
|
||||||
interface ShareButtonProps {
|
|
||||||
url: string
|
|
||||||
title: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ShareButton({ url, title }: ShareButtonProps) {
|
|
||||||
const [open, setOpen] = useState(false)
|
|
||||||
const [copied, setCopied] = useState(false)
|
|
||||||
|
|
||||||
const handleCopyLink = async () => {
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(url)
|
|
||||||
setCopied(true)
|
|
||||||
setTimeout(() => {
|
|
||||||
setCopied(false)
|
|
||||||
setOpen(false)
|
|
||||||
}, 1000)
|
|
||||||
} catch {
|
|
||||||
setOpen(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleShareTwitter = () => {
|
|
||||||
const tweetUrl = `https://twitter.com/intent/tweet?url=${encodeURIComponent(url)}&text=${encodeURIComponent(title)}`
|
|
||||||
window.open(tweetUrl, '_blank', 'noopener,noreferrer')
|
|
||||||
setOpen(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleShareLinkedIn = () => {
|
|
||||||
const linkedInUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`
|
|
||||||
window.open(linkedInUrl, '_blank', 'noopener,noreferrer')
|
|
||||||
setOpen(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Popover
|
|
||||||
open={open}
|
|
||||||
onOpenChange={setOpen}
|
|
||||||
variant='secondary'
|
|
||||||
size='sm'
|
|
||||||
colorScheme='inverted'
|
|
||||||
>
|
|
||||||
<PopoverTrigger asChild>
|
|
||||||
<button
|
|
||||||
className='flex items-center gap-1.5 text-gray-600 text-sm hover:text-gray-900'
|
|
||||||
aria-label='Share this post'
|
|
||||||
>
|
|
||||||
<Share2 className='h-4 w-4' />
|
|
||||||
<span>Share</span>
|
|
||||||
</button>
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverContent align='end' minWidth={140}>
|
|
||||||
<PopoverItem onClick={handleCopyLink}>{copied ? 'Copied!' : 'Copy link'}</PopoverItem>
|
|
||||||
<PopoverItem onClick={handleShareTwitter}>Share on X</PopoverItem>
|
|
||||||
<PopoverItem onClick={handleShareLinkedIn}>Share on LinkedIn</PopoverItem>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -22,7 +22,7 @@ export default async function StudioIndex({
|
|||||||
? filtered.sort((a, b) => {
|
? filtered.sort((a, b) => {
|
||||||
if (a.featured && !b.featured) return -1
|
if (a.featured && !b.featured) return -1
|
||||||
if (!a.featured && b.featured) return 1
|
if (!a.featured && b.featured) return 1
|
||||||
return new Date(b.date).getTime() - new Date(a.date).getTime()
|
return 0
|
||||||
})
|
})
|
||||||
: filtered
|
: filtered
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import type { AgentCapabilities, AgentSkill } from '@/lib/a2a/types'
|
|||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
||||||
import { getRedisClient } from '@/lib/core/config/redis'
|
import { getRedisClient } from '@/lib/core/config/redis'
|
||||||
import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils'
|
import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils'
|
||||||
import { checkWorkspaceAccess } from '@/lib/workspaces/permissions/utils'
|
|
||||||
|
|
||||||
const logger = createLogger('A2AAgentCardAPI')
|
const logger = createLogger('A2AAgentCardAPI')
|
||||||
|
|
||||||
@@ -96,11 +95,6 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<Ro
|
|||||||
return NextResponse.json({ error: 'Agent not found' }, { status: 404 })
|
return NextResponse.json({ error: 'Agent not found' }, { status: 404 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const workspaceAccess = await checkWorkspaceAccess(existingAgent.workspaceId, auth.userId)
|
|
||||||
if (!workspaceAccess.canWrite) {
|
|
||||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
|
|
||||||
if (
|
if (
|
||||||
@@ -166,11 +160,6 @@ export async function DELETE(request: NextRequest, { params }: { params: Promise
|
|||||||
return NextResponse.json({ error: 'Agent not found' }, { status: 404 })
|
return NextResponse.json({ error: 'Agent not found' }, { status: 404 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const workspaceAccess = await checkWorkspaceAccess(existingAgent.workspaceId, auth.userId)
|
|
||||||
if (!workspaceAccess.canWrite) {
|
|
||||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.delete(a2aAgent).where(eq(a2aAgent.id, agentId))
|
await db.delete(a2aAgent).where(eq(a2aAgent.id, agentId))
|
||||||
|
|
||||||
logger.info(`Deleted A2A agent: ${agentId}`)
|
logger.info(`Deleted A2A agent: ${agentId}`)
|
||||||
@@ -205,11 +194,6 @@ export async function POST(request: NextRequest, { params }: { params: Promise<R
|
|||||||
return NextResponse.json({ error: 'Agent not found' }, { status: 404 })
|
return NextResponse.json({ error: 'Agent not found' }, { status: 404 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const workspaceAccess = await checkWorkspaceAccess(existingAgent.workspaceId, auth.userId)
|
|
||||||
if (!workspaceAccess.canWrite) {
|
|
||||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const action = body.action as 'publish' | 'unpublish' | 'refresh'
|
const action = body.action as 'publish' | 'unpublish' | 'refresh'
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import {
|
|||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
||||||
import { getBrandConfig } from '@/lib/branding/branding'
|
import { getBrandConfig } from '@/lib/branding/branding'
|
||||||
import { acquireLock, getRedisClient, releaseLock } from '@/lib/core/config/redis'
|
import { acquireLock, getRedisClient, releaseLock } from '@/lib/core/config/redis'
|
||||||
import { validateExternalUrl } from '@/lib/core/security/input-validation'
|
|
||||||
import { SSE_HEADERS } from '@/lib/core/utils/sse'
|
import { SSE_HEADERS } from '@/lib/core/utils/sse'
|
||||||
import { getBaseUrl } from '@/lib/core/utils/urls'
|
import { getBaseUrl } from '@/lib/core/utils/urls'
|
||||||
import { markExecutionCancelled } from '@/lib/execution/cancellation'
|
import { markExecutionCancelled } from '@/lib/execution/cancellation'
|
||||||
@@ -1119,13 +1118,17 @@ async function handlePushNotificationSet(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const urlValidation = validateExternalUrl(
|
try {
|
||||||
params.pushNotificationConfig.url,
|
const url = new URL(params.pushNotificationConfig.url)
|
||||||
'Push notification URL'
|
if (url.protocol !== 'https:') {
|
||||||
)
|
return NextResponse.json(
|
||||||
if (!urlValidation.isValid) {
|
createError(id, A2A_ERROR_CODES.INVALID_PARAMS, 'Push notification URL must use HTTPS'),
|
||||||
|
{ status: 400 }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
createError(id, A2A_ERROR_CODES.INVALID_PARAMS, urlValidation.error || 'Invalid URL'),
|
createError(id, A2A_ERROR_CODES.INVALID_PARAMS, 'Invalid push notification URL'),
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -104,11 +104,17 @@ export async function POST(req: NextRequest) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// Build execution params starting with LLM-provided arguments
|
// Build execution params starting with LLM-provided arguments
|
||||||
// Resolve all {{ENV_VAR}} references in the arguments (deep for nested objects)
|
// Resolve all {{ENV_VAR}} references in the arguments
|
||||||
const executionParams: Record<string, any> = resolveEnvVarReferences(
|
const executionParams: Record<string, any> = resolveEnvVarReferences(
|
||||||
toolArgs,
|
toolArgs,
|
||||||
decryptedEnvVars,
|
decryptedEnvVars,
|
||||||
{ deep: true }
|
{
|
||||||
|
resolveExactMatch: true,
|
||||||
|
allowEmbedded: true,
|
||||||
|
trimKeys: true,
|
||||||
|
onMissing: 'keep',
|
||||||
|
deep: true,
|
||||||
|
}
|
||||||
) as Record<string, any>
|
) as Record<string, any>
|
||||||
|
|
||||||
logger.info(`[${tracker.requestId}] Resolved env var references in arguments`, {
|
logger.info(`[${tracker.requestId}] Resolved env var references in arguments`, {
|
||||||
|
|||||||
@@ -84,14 +84,6 @@ vi.mock('@/lib/execution/isolated-vm', () => ({
|
|||||||
|
|
||||||
vi.mock('@sim/logger', () => loggerMock)
|
vi.mock('@sim/logger', () => loggerMock)
|
||||||
|
|
||||||
vi.mock('@/lib/auth/hybrid', () => ({
|
|
||||||
checkHybridAuth: vi.fn().mockResolvedValue({
|
|
||||||
success: true,
|
|
||||||
userId: 'user-123',
|
|
||||||
authType: 'session',
|
|
||||||
}),
|
|
||||||
}))
|
|
||||||
|
|
||||||
vi.mock('@/lib/execution/e2b', () => ({
|
vi.mock('@/lib/execution/e2b', () => ({
|
||||||
executeInE2B: vi.fn(),
|
executeInE2B: vi.fn(),
|
||||||
}))
|
}))
|
||||||
@@ -118,24 +110,6 @@ describe('Function Execute API Route', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('Security Tests', () => {
|
describe('Security Tests', () => {
|
||||||
it('should reject unauthorized requests', async () => {
|
|
||||||
const { checkHybridAuth } = await import('@/lib/auth/hybrid')
|
|
||||||
vi.mocked(checkHybridAuth).mockResolvedValueOnce({
|
|
||||||
success: false,
|
|
||||||
error: 'Unauthorized',
|
|
||||||
})
|
|
||||||
|
|
||||||
const req = createMockRequest('POST', {
|
|
||||||
code: 'return "test"',
|
|
||||||
})
|
|
||||||
|
|
||||||
const response = await POST(req)
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
expect(response.status).toBe(401)
|
|
||||||
expect(data).toHaveProperty('error', 'Unauthorized')
|
|
||||||
})
|
|
||||||
|
|
||||||
it.concurrent('should use isolated-vm for secure sandboxed execution', async () => {
|
it.concurrent('should use isolated-vm for secure sandboxed execution', async () => {
|
||||||
const req = createMockRequest('POST', {
|
const req = createMockRequest('POST', {
|
||||||
code: 'return "test"',
|
code: 'return "test"',
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { isE2bEnabled } from '@/lib/core/config/feature-flags'
|
import { isE2bEnabled } from '@/lib/core/config/feature-flags'
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { executeInE2B } from '@/lib/execution/e2b'
|
import { executeInE2B } from '@/lib/execution/e2b'
|
||||||
@@ -582,12 +581,6 @@ export async function POST(req: NextRequest) {
|
|||||||
let resolvedCode = '' // Store resolved code for error reporting
|
let resolvedCode = '' // Store resolved code for error reporting
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(req)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized function execution attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await req.json()
|
const body = await req.json()
|
||||||
|
|
||||||
const { DEFAULT_EXECUTION_TIMEOUT_MS } = await import('@/lib/execution/constants')
|
const { DEFAULT_EXECUTION_TIMEOUT_MS } = await import('@/lib/execution/constants')
|
||||||
|
|||||||
@@ -157,7 +157,7 @@ describe('Knowledge Base Documents API Route', () => {
|
|||||||
expect(vi.mocked(getDocuments)).toHaveBeenCalledWith(
|
expect(vi.mocked(getDocuments)).toHaveBeenCalledWith(
|
||||||
'kb-123',
|
'kb-123',
|
||||||
{
|
{
|
||||||
enabledFilter: undefined,
|
includeDisabled: false,
|
||||||
search: undefined,
|
search: undefined,
|
||||||
limit: 50,
|
limit: 50,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
@@ -166,7 +166,7 @@ describe('Knowledge Base Documents API Route', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should return documents with default filter', async () => {
|
it('should filter disabled documents by default', async () => {
|
||||||
const { checkKnowledgeBaseAccess } = await import('@/app/api/knowledge/utils')
|
const { checkKnowledgeBaseAccess } = await import('@/app/api/knowledge/utils')
|
||||||
const { getDocuments } = await import('@/lib/knowledge/documents/service')
|
const { getDocuments } = await import('@/lib/knowledge/documents/service')
|
||||||
|
|
||||||
@@ -194,7 +194,7 @@ describe('Knowledge Base Documents API Route', () => {
|
|||||||
expect(vi.mocked(getDocuments)).toHaveBeenCalledWith(
|
expect(vi.mocked(getDocuments)).toHaveBeenCalledWith(
|
||||||
'kb-123',
|
'kb-123',
|
||||||
{
|
{
|
||||||
enabledFilter: undefined,
|
includeDisabled: false,
|
||||||
search: undefined,
|
search: undefined,
|
||||||
limit: 50,
|
limit: 50,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
@@ -203,7 +203,7 @@ describe('Knowledge Base Documents API Route', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should filter documents by enabled status when requested', async () => {
|
it('should include disabled documents when requested', async () => {
|
||||||
const { checkKnowledgeBaseAccess } = await import('@/app/api/knowledge/utils')
|
const { checkKnowledgeBaseAccess } = await import('@/app/api/knowledge/utils')
|
||||||
const { getDocuments } = await import('@/lib/knowledge/documents/service')
|
const { getDocuments } = await import('@/lib/knowledge/documents/service')
|
||||||
|
|
||||||
@@ -223,7 +223,7 @@ describe('Knowledge Base Documents API Route', () => {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const url = 'http://localhost:3000/api/knowledge/kb-123/documents?enabledFilter=disabled'
|
const url = 'http://localhost:3000/api/knowledge/kb-123/documents?includeDisabled=true'
|
||||||
const req = new Request(url, { method: 'GET' }) as any
|
const req = new Request(url, { method: 'GET' }) as any
|
||||||
|
|
||||||
const { GET } = await import('@/app/api/knowledge/[id]/documents/route')
|
const { GET } = await import('@/app/api/knowledge/[id]/documents/route')
|
||||||
@@ -233,7 +233,7 @@ describe('Knowledge Base Documents API Route', () => {
|
|||||||
expect(vi.mocked(getDocuments)).toHaveBeenCalledWith(
|
expect(vi.mocked(getDocuments)).toHaveBeenCalledWith(
|
||||||
'kb-123',
|
'kb-123',
|
||||||
{
|
{
|
||||||
enabledFilter: 'disabled',
|
includeDisabled: true,
|
||||||
search: undefined,
|
search: undefined,
|
||||||
limit: 50,
|
limit: 50,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
@@ -361,7 +361,8 @@ describe('Knowledge Base Documents API Route', () => {
|
|||||||
expect(vi.mocked(createSingleDocument)).toHaveBeenCalledWith(
|
expect(vi.mocked(createSingleDocument)).toHaveBeenCalledWith(
|
||||||
validDocumentData,
|
validDocumentData,
|
||||||
'kb-123',
|
'kb-123',
|
||||||
expect.any(String)
|
expect.any(String),
|
||||||
|
'user-123'
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -469,7 +470,8 @@ describe('Knowledge Base Documents API Route', () => {
|
|||||||
expect(vi.mocked(createDocumentRecords)).toHaveBeenCalledWith(
|
expect(vi.mocked(createDocumentRecords)).toHaveBeenCalledWith(
|
||||||
validBulkData.documents,
|
validBulkData.documents,
|
||||||
'kb-123',
|
'kb-123',
|
||||||
expect.any(String)
|
expect.any(String),
|
||||||
|
'user-123'
|
||||||
)
|
)
|
||||||
expect(vi.mocked(processDocumentsWithQueue)).toHaveBeenCalled()
|
expect(vi.mocked(processDocumentsWithQueue)).toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { z } from 'zod'
|
|||||||
import { getSession } from '@/lib/auth'
|
import { getSession } from '@/lib/auth'
|
||||||
import {
|
import {
|
||||||
bulkDocumentOperation,
|
bulkDocumentOperation,
|
||||||
bulkDocumentOperationByFilter,
|
|
||||||
createDocumentRecords,
|
createDocumentRecords,
|
||||||
createSingleDocument,
|
createSingleDocument,
|
||||||
getDocuments,
|
getDocuments,
|
||||||
@@ -58,20 +57,13 @@ const BulkCreateDocumentsSchema = z.object({
|
|||||||
bulk: z.literal(true),
|
bulk: z.literal(true),
|
||||||
})
|
})
|
||||||
|
|
||||||
const BulkUpdateDocumentsSchema = z
|
const BulkUpdateDocumentsSchema = z.object({
|
||||||
.object({
|
operation: z.enum(['enable', 'disable', 'delete']),
|
||||||
operation: z.enum(['enable', 'disable', 'delete']),
|
documentIds: z
|
||||||
documentIds: z
|
.array(z.string())
|
||||||
.array(z.string())
|
.min(1, 'At least one document ID is required')
|
||||||
.min(1, 'At least one document ID is required')
|
.max(100, 'Cannot operate on more than 100 documents at once'),
|
||||||
.max(100, 'Cannot operate on more than 100 documents at once')
|
})
|
||||||
.optional(),
|
|
||||||
selectAll: z.boolean().optional(),
|
|
||||||
enabledFilter: z.enum(['all', 'enabled', 'disabled']).optional(),
|
|
||||||
})
|
|
||||||
.refine((data) => data.selectAll || (data.documentIds && data.documentIds.length > 0), {
|
|
||||||
message: 'Either selectAll must be true or documentIds must be provided',
|
|
||||||
})
|
|
||||||
|
|
||||||
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
@@ -98,17 +90,14 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
}
|
}
|
||||||
|
|
||||||
const url = new URL(req.url)
|
const url = new URL(req.url)
|
||||||
const enabledFilter = url.searchParams.get('enabledFilter') as
|
const includeDisabled = url.searchParams.get('includeDisabled') === 'true'
|
||||||
| 'all'
|
|
||||||
| 'enabled'
|
|
||||||
| 'disabled'
|
|
||||||
| null
|
|
||||||
const search = url.searchParams.get('search') || undefined
|
const search = url.searchParams.get('search') || undefined
|
||||||
const limit = Number.parseInt(url.searchParams.get('limit') || '50')
|
const limit = Number.parseInt(url.searchParams.get('limit') || '50')
|
||||||
const offset = Number.parseInt(url.searchParams.get('offset') || '0')
|
const offset = Number.parseInt(url.searchParams.get('offset') || '0')
|
||||||
const sortByParam = url.searchParams.get('sortBy')
|
const sortByParam = url.searchParams.get('sortBy')
|
||||||
const sortOrderParam = url.searchParams.get('sortOrder')
|
const sortOrderParam = url.searchParams.get('sortOrder')
|
||||||
|
|
||||||
|
// Validate sort parameters
|
||||||
const validSortFields: DocumentSortField[] = [
|
const validSortFields: DocumentSortField[] = [
|
||||||
'filename',
|
'filename',
|
||||||
'fileSize',
|
'fileSize',
|
||||||
@@ -116,7 +105,6 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
'chunkCount',
|
'chunkCount',
|
||||||
'uploadedAt',
|
'uploadedAt',
|
||||||
'processingStatus',
|
'processingStatus',
|
||||||
'enabled',
|
|
||||||
]
|
]
|
||||||
const validSortOrders: SortOrder[] = ['asc', 'desc']
|
const validSortOrders: SortOrder[] = ['asc', 'desc']
|
||||||
|
|
||||||
@@ -132,7 +120,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
const result = await getDocuments(
|
const result = await getDocuments(
|
||||||
knowledgeBaseId,
|
knowledgeBaseId,
|
||||||
{
|
{
|
||||||
enabledFilter: enabledFilter || undefined,
|
includeDisabled,
|
||||||
search,
|
search,
|
||||||
limit,
|
limit,
|
||||||
offset,
|
offset,
|
||||||
@@ -202,7 +190,8 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
const createdDocuments = await createDocumentRecords(
|
const createdDocuments = await createDocumentRecords(
|
||||||
validatedData.documents,
|
validatedData.documents,
|
||||||
knowledgeBaseId,
|
knowledgeBaseId,
|
||||||
requestId
|
requestId,
|
||||||
|
userId
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
@@ -261,10 +250,16 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
throw validationError
|
throw validationError
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
// Handle single document creation
|
||||||
try {
|
try {
|
||||||
const validatedData = CreateDocumentSchema.parse(body)
|
const validatedData = CreateDocumentSchema.parse(body)
|
||||||
|
|
||||||
const newDocument = await createSingleDocument(validatedData, knowledgeBaseId, requestId)
|
const newDocument = await createSingleDocument(
|
||||||
|
validatedData,
|
||||||
|
knowledgeBaseId,
|
||||||
|
requestId,
|
||||||
|
userId
|
||||||
|
)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { PlatformEvents } = await import('@/lib/core/telemetry')
|
const { PlatformEvents } = await import('@/lib/core/telemetry')
|
||||||
@@ -299,6 +294,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(`[${requestId}] Error creating document`, error)
|
logger.error(`[${requestId}] Error creating document`, error)
|
||||||
|
|
||||||
|
// Check if it's a storage limit error
|
||||||
const errorMessage = error instanceof Error ? error.message : 'Failed to create document'
|
const errorMessage = error instanceof Error ? error.message : 'Failed to create document'
|
||||||
const isStorageLimitError =
|
const isStorageLimitError =
|
||||||
errorMessage.includes('Storage limit exceeded') || errorMessage.includes('storage limit')
|
errorMessage.includes('Storage limit exceeded') || errorMessage.includes('storage limit')
|
||||||
@@ -335,22 +331,16 @@ export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const validatedData = BulkUpdateDocumentsSchema.parse(body)
|
const validatedData = BulkUpdateDocumentsSchema.parse(body)
|
||||||
const { operation, documentIds, selectAll, enabledFilter } = validatedData
|
const { operation, documentIds } = validatedData
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let result
|
const result = await bulkDocumentOperation(
|
||||||
if (selectAll) {
|
knowledgeBaseId,
|
||||||
result = await bulkDocumentOperationByFilter(
|
operation,
|
||||||
knowledgeBaseId,
|
documentIds,
|
||||||
operation,
|
requestId,
|
||||||
enabledFilter,
|
session.user.id
|
||||||
requestId
|
)
|
||||||
)
|
|
||||||
} else if (documentIds && documentIds.length > 0) {
|
|
||||||
result = await bulkDocumentOperation(knowledgeBaseId, operation, documentIds, requestId)
|
|
||||||
} else {
|
|
||||||
return NextResponse.json({ error: 'No documents specified' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import type { NextRequest } from 'next/server'
|
import type { NextRequest } from 'next/server'
|
||||||
|
import { getEffectiveDecryptedEnv } from '@/lib/environment/utils'
|
||||||
import { McpClient } from '@/lib/mcp/client'
|
import { McpClient } from '@/lib/mcp/client'
|
||||||
import { getParsedBody, withMcpAuth } from '@/lib/mcp/middleware'
|
import { getParsedBody, withMcpAuth } from '@/lib/mcp/middleware'
|
||||||
import { resolveMcpConfigEnvVars } from '@/lib/mcp/resolve-config'
|
import type { McpServerConfig, McpTransport } from '@/lib/mcp/types'
|
||||||
import type { McpTransport } from '@/lib/mcp/types'
|
|
||||||
import { createMcpErrorResponse, createMcpSuccessResponse } from '@/lib/mcp/utils'
|
import { createMcpErrorResponse, createMcpSuccessResponse } from '@/lib/mcp/utils'
|
||||||
|
import { resolveEnvVarReferences } from '@/executor/utils/reference-validation'
|
||||||
|
|
||||||
const logger = createLogger('McpServerTestAPI')
|
const logger = createLogger('McpServerTestAPI')
|
||||||
|
|
||||||
@@ -18,6 +19,30 @@ function isUrlBasedTransport(transport: McpTransport): boolean {
|
|||||||
return transport === 'streamable-http'
|
return transport === 'streamable-http'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve environment variables in strings
|
||||||
|
*/
|
||||||
|
function resolveEnvVars(value: string, envVars: Record<string, string>): string {
|
||||||
|
const missingVars: string[] = []
|
||||||
|
const resolvedValue = resolveEnvVarReferences(value, envVars, {
|
||||||
|
allowEmbedded: true,
|
||||||
|
resolveExactMatch: true,
|
||||||
|
trimKeys: true,
|
||||||
|
onMissing: 'keep',
|
||||||
|
deep: false,
|
||||||
|
missingKeys: missingVars,
|
||||||
|
}) as string
|
||||||
|
|
||||||
|
if (missingVars.length > 0) {
|
||||||
|
const uniqueMissing = Array.from(new Set(missingVars))
|
||||||
|
uniqueMissing.forEach((envKey) => {
|
||||||
|
logger.warn(`Environment variable "${envKey}" not found in MCP server test`)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolvedValue
|
||||||
|
}
|
||||||
|
|
||||||
interface TestConnectionRequest {
|
interface TestConnectionRequest {
|
||||||
name: string
|
name: string
|
||||||
transport: McpTransport
|
transport: McpTransport
|
||||||
@@ -71,30 +96,39 @@ export const POST = withMcpAuth('write')(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build initial config for resolution
|
let resolvedUrl = body.url
|
||||||
const initialConfig = {
|
let resolvedHeaders = body.headers || {}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const envVars = await getEffectiveDecryptedEnv(userId, workspaceId)
|
||||||
|
|
||||||
|
if (resolvedUrl) {
|
||||||
|
resolvedUrl = resolveEnvVars(resolvedUrl, envVars)
|
||||||
|
}
|
||||||
|
|
||||||
|
const resolvedHeadersObj: Record<string, string> = {}
|
||||||
|
for (const [key, value] of Object.entries(resolvedHeaders)) {
|
||||||
|
resolvedHeadersObj[key] = resolveEnvVars(value, envVars)
|
||||||
|
}
|
||||||
|
resolvedHeaders = resolvedHeadersObj
|
||||||
|
} catch (envError) {
|
||||||
|
logger.warn(
|
||||||
|
`[${requestId}] Failed to resolve environment variables, using raw values:`,
|
||||||
|
envError
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const testConfig: McpServerConfig = {
|
||||||
id: `test-${requestId}`,
|
id: `test-${requestId}`,
|
||||||
name: body.name,
|
name: body.name,
|
||||||
transport: body.transport,
|
transport: body.transport,
|
||||||
url: body.url,
|
url: resolvedUrl,
|
||||||
headers: body.headers || {},
|
headers: resolvedHeaders,
|
||||||
timeout: body.timeout || 10000,
|
timeout: body.timeout || 10000,
|
||||||
retries: 1, // Only one retry for tests
|
retries: 1, // Only one retry for tests
|
||||||
enabled: true,
|
enabled: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolve env vars using shared utility (non-strict mode for testing)
|
|
||||||
const { config: testConfig, missingVars } = await resolveMcpConfigEnvVars(
|
|
||||||
initialConfig,
|
|
||||||
userId,
|
|
||||||
workspaceId,
|
|
||||||
{ strict: false }
|
|
||||||
)
|
|
||||||
|
|
||||||
if (missingVars.length > 0) {
|
|
||||||
logger.warn(`[${requestId}] Some environment variables not found:`, { missingVars })
|
|
||||||
}
|
|
||||||
|
|
||||||
const testSecurityPolicy = {
|
const testSecurityPolicy = {
|
||||||
requireConsent: false,
|
requireConsent: false,
|
||||||
auditLevel: 'none' as const,
|
auditLevel: 'none' as const,
|
||||||
|
|||||||
@@ -3,9 +3,7 @@ import { account } from '@sim/db/schema'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { eq } from 'drizzle-orm'
|
import { eq } from 'drizzle-orm'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { checkWorkspaceAccess } from '@/lib/workspaces/permissions/utils'
|
|
||||||
import { refreshTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
import { refreshTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||||
import type { StreamingExecution } from '@/executor/types'
|
import type { StreamingExecution } from '@/executor/types'
|
||||||
import { executeProviderRequest } from '@/providers'
|
import { executeProviderRequest } from '@/providers'
|
||||||
@@ -22,11 +20,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const startTime = Date.now()
|
const startTime = Date.now()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request, { requireWorkflowId: false })
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] Provider API request started`, {
|
logger.info(`[${requestId}] Provider API request started`, {
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
userAgent: request.headers.get('User-Agent'),
|
userAgent: request.headers.get('User-Agent'),
|
||||||
@@ -92,13 +85,6 @@ export async function POST(request: NextRequest) {
|
|||||||
verbosity,
|
verbosity,
|
||||||
})
|
})
|
||||||
|
|
||||||
if (workspaceId) {
|
|
||||||
const workspaceAccess = await checkWorkspaceAccess(workspaceId, auth.userId)
|
|
||||||
if (!workspaceAccess.hasAccess) {
|
|
||||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let finalApiKey: string | undefined = apiKey
|
let finalApiKey: string | undefined = apiKey
|
||||||
try {
|
try {
|
||||||
if (provider === 'vertex' && vertexCredential) {
|
if (provider === 'vertex' && vertexCredential) {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { type NextRequest, NextResponse } from 'next/server'
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { createA2AClient } from '@/lib/a2a/utils'
|
import { createA2AClient } from '@/lib/a2a/utils'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
||||||
import { validateExternalUrl } from '@/lib/core/security/input-validation'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
export const dynamic = 'force-dynamic'
|
||||||
@@ -40,18 +39,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const validatedData = A2ASetPushNotificationSchema.parse(body)
|
const validatedData = A2ASetPushNotificationSchema.parse(body)
|
||||||
|
|
||||||
const urlValidation = validateExternalUrl(validatedData.webhookUrl, 'Webhook URL')
|
|
||||||
if (!urlValidation.isValid) {
|
|
||||||
logger.warn(`[${requestId}] Invalid webhook URL`, { error: urlValidation.error })
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: urlValidation.error,
|
|
||||||
},
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] A2A set push notification request`, {
|
logger.info(`[${requestId}] A2A set push notification request`, {
|
||||||
agentUrl: validatedData.agentUrl,
|
agentUrl: validatedData.agentUrl,
|
||||||
taskId: validatedData.taskId,
|
taskId: validatedData.taskId,
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { buildDeleteQuery, createMySQLConnection, executeQuery } from '@/app/api/tools/mysql/utils'
|
import { buildDeleteQuery, createMySQLConnection, executeQuery } from '@/app/api/tools/mysql/utils'
|
||||||
|
|
||||||
const logger = createLogger('MySQLDeleteAPI')
|
const logger = createLogger('MySQLDeleteAPI')
|
||||||
@@ -22,12 +21,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized MySQL delete attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = DeleteSchema.parse(body)
|
const params = DeleteSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createMySQLConnection, executeQuery, validateQuery } from '@/app/api/tools/mysql/utils'
|
import { createMySQLConnection, executeQuery, validateQuery } from '@/app/api/tools/mysql/utils'
|
||||||
|
|
||||||
const logger = createLogger('MySQLExecuteAPI')
|
const logger = createLogger('MySQLExecuteAPI')
|
||||||
@@ -21,12 +20,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized MySQL execute attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = ExecuteSchema.parse(body)
|
const params = ExecuteSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { buildInsertQuery, createMySQLConnection, executeQuery } from '@/app/api/tools/mysql/utils'
|
import { buildInsertQuery, createMySQLConnection, executeQuery } from '@/app/api/tools/mysql/utils'
|
||||||
|
|
||||||
const logger = createLogger('MySQLInsertAPI')
|
const logger = createLogger('MySQLInsertAPI')
|
||||||
@@ -43,12 +42,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized MySQL insert attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = InsertSchema.parse(body)
|
const params = InsertSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createMySQLConnection, executeIntrospect } from '@/app/api/tools/mysql/utils'
|
import { createMySQLConnection, executeIntrospect } from '@/app/api/tools/mysql/utils'
|
||||||
|
|
||||||
const logger = createLogger('MySQLIntrospectAPI')
|
const logger = createLogger('MySQLIntrospectAPI')
|
||||||
@@ -20,12 +19,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized MySQL introspect attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = IntrospectSchema.parse(body)
|
const params = IntrospectSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createMySQLConnection, executeQuery, validateQuery } from '@/app/api/tools/mysql/utils'
|
import { createMySQLConnection, executeQuery, validateQuery } from '@/app/api/tools/mysql/utils'
|
||||||
|
|
||||||
const logger = createLogger('MySQLQueryAPI')
|
const logger = createLogger('MySQLQueryAPI')
|
||||||
@@ -21,12 +20,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized MySQL query attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = QuerySchema.parse(body)
|
const params = QuerySchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { buildUpdateQuery, createMySQLConnection, executeQuery } from '@/app/api/tools/mysql/utils'
|
import { buildUpdateQuery, createMySQLConnection, executeQuery } from '@/app/api/tools/mysql/utils'
|
||||||
|
|
||||||
const logger = createLogger('MySQLUpdateAPI')
|
const logger = createLogger('MySQLUpdateAPI')
|
||||||
@@ -41,12 +40,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized MySQL update attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = UpdateSchema.parse(body)
|
const params = UpdateSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createPostgresConnection, executeDelete } from '@/app/api/tools/postgresql/utils'
|
import { createPostgresConnection, executeDelete } from '@/app/api/tools/postgresql/utils'
|
||||||
|
|
||||||
const logger = createLogger('PostgreSQLDeleteAPI')
|
const logger = createLogger('PostgreSQLDeleteAPI')
|
||||||
@@ -22,12 +21,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized PostgreSQL delete attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = DeleteSchema.parse(body)
|
const params = DeleteSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import {
|
import {
|
||||||
createPostgresConnection,
|
createPostgresConnection,
|
||||||
executeQuery,
|
executeQuery,
|
||||||
@@ -25,12 +24,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized PostgreSQL execute attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = ExecuteSchema.parse(body)
|
const params = ExecuteSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createPostgresConnection, executeInsert } from '@/app/api/tools/postgresql/utils'
|
import { createPostgresConnection, executeInsert } from '@/app/api/tools/postgresql/utils'
|
||||||
|
|
||||||
const logger = createLogger('PostgreSQLInsertAPI')
|
const logger = createLogger('PostgreSQLInsertAPI')
|
||||||
@@ -43,12 +42,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized PostgreSQL insert attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
|
|
||||||
const params = InsertSchema.parse(body)
|
const params = InsertSchema.parse(body)
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createPostgresConnection, executeIntrospect } from '@/app/api/tools/postgresql/utils'
|
import { createPostgresConnection, executeIntrospect } from '@/app/api/tools/postgresql/utils'
|
||||||
|
|
||||||
const logger = createLogger('PostgreSQLIntrospectAPI')
|
const logger = createLogger('PostgreSQLIntrospectAPI')
|
||||||
@@ -21,12 +20,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized PostgreSQL introspect attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = IntrospectSchema.parse(body)
|
const params = IntrospectSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createPostgresConnection, executeQuery } from '@/app/api/tools/postgresql/utils'
|
import { createPostgresConnection, executeQuery } from '@/app/api/tools/postgresql/utils'
|
||||||
|
|
||||||
const logger = createLogger('PostgreSQLQueryAPI')
|
const logger = createLogger('PostgreSQLQueryAPI')
|
||||||
@@ -21,12 +20,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized PostgreSQL query attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = QuerySchema.parse(body)
|
const params = QuerySchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createPostgresConnection, executeUpdate } from '@/app/api/tools/postgresql/utils'
|
import { createPostgresConnection, executeUpdate } from '@/app/api/tools/postgresql/utils'
|
||||||
|
|
||||||
const logger = createLogger('PostgreSQLUpdateAPI')
|
const logger = createLogger('PostgreSQLUpdateAPI')
|
||||||
@@ -41,12 +40,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized PostgreSQL update attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = UpdateSchema.parse(body)
|
const params = UpdateSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createSSHConnection, escapeShellArg, executeSSHCommand } from '@/app/api/tools/ssh/utils'
|
import { createSSHConnection, escapeShellArg, executeSSHCommand } from '@/app/api/tools/ssh/utils'
|
||||||
|
|
||||||
const logger = createLogger('SSHCheckCommandExistsAPI')
|
const logger = createLogger('SSHCheckCommandExistsAPI')
|
||||||
@@ -21,12 +20,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH check command exists attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = CheckCommandExistsSchema.parse(body)
|
const params = CheckCommandExistsSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { createLogger } from '@sim/logger'
|
|||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import type { Client, SFTPWrapper, Stats } from 'ssh2'
|
import type { Client, SFTPWrapper, Stats } from 'ssh2'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import {
|
import {
|
||||||
createSSHConnection,
|
createSSHConnection,
|
||||||
getFileType,
|
getFileType,
|
||||||
@@ -40,15 +39,10 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH check file exists attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = CheckFileExistsSchema.parse(body)
|
const params = CheckFileExistsSchema.parse(body)
|
||||||
|
|
||||||
|
// Validate authentication
|
||||||
if (!params.password && !params.privateKey) {
|
if (!params.password && !params.privateKey) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Either password or privateKey must be provided' },
|
{ error: 'Either password or privateKey must be provided' },
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import {
|
import {
|
||||||
createSSHConnection,
|
createSSHConnection,
|
||||||
escapeShellArg,
|
escapeShellArg,
|
||||||
@@ -28,15 +27,10 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH create directory attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = CreateDirectorySchema.parse(body)
|
const params = CreateDirectorySchema.parse(body)
|
||||||
|
|
||||||
|
// Validate authentication
|
||||||
if (!params.password && !params.privateKey) {
|
if (!params.password && !params.privateKey) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Either password or privateKey must be provided' },
|
{ error: 'Either password or privateKey must be provided' },
|
||||||
@@ -59,6 +53,7 @@ export async function POST(request: NextRequest) {
|
|||||||
const dirPath = sanitizePath(params.path)
|
const dirPath = sanitizePath(params.path)
|
||||||
const escapedPath = escapeShellArg(dirPath)
|
const escapedPath = escapeShellArg(dirPath)
|
||||||
|
|
||||||
|
// Check if directory already exists
|
||||||
const checkResult = await executeSSHCommand(
|
const checkResult = await executeSSHCommand(
|
||||||
client,
|
client,
|
||||||
`test -d '${escapedPath}' && echo "exists"`
|
`test -d '${escapedPath}' && echo "exists"`
|
||||||
@@ -75,6 +70,7 @@ export async function POST(request: NextRequest) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create directory
|
||||||
const mkdirFlag = params.recursive ? '-p' : ''
|
const mkdirFlag = params.recursive ? '-p' : ''
|
||||||
const command = `mkdir ${mkdirFlag} -m ${params.permissions} '${escapedPath}'`
|
const command = `mkdir ${mkdirFlag} -m ${params.permissions} '${escapedPath}'`
|
||||||
const result = await executeSSHCommand(client, command)
|
const result = await executeSSHCommand(client, command)
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import {
|
import {
|
||||||
createSSHConnection,
|
createSSHConnection,
|
||||||
escapeShellArg,
|
escapeShellArg,
|
||||||
@@ -28,15 +27,10 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH delete file attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = DeleteFileSchema.parse(body)
|
const params = DeleteFileSchema.parse(body)
|
||||||
|
|
||||||
|
// Validate authentication
|
||||||
if (!params.password && !params.privateKey) {
|
if (!params.password && !params.privateKey) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Either password or privateKey must be provided' },
|
{ error: 'Either password or privateKey must be provided' },
|
||||||
@@ -59,6 +53,7 @@ export async function POST(request: NextRequest) {
|
|||||||
const filePath = sanitizePath(params.path)
|
const filePath = sanitizePath(params.path)
|
||||||
const escapedPath = escapeShellArg(filePath)
|
const escapedPath = escapeShellArg(filePath)
|
||||||
|
|
||||||
|
// Check if path exists
|
||||||
const checkResult = await executeSSHCommand(
|
const checkResult = await executeSSHCommand(
|
||||||
client,
|
client,
|
||||||
`test -e '${escapedPath}' && echo "exists"`
|
`test -e '${escapedPath}' && echo "exists"`
|
||||||
@@ -67,6 +62,7 @@ export async function POST(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: `Path does not exist: ${filePath}` }, { status: 404 })
|
return NextResponse.json({ error: `Path does not exist: ${filePath}` }, { status: 404 })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Build delete command
|
||||||
let command: string
|
let command: string
|
||||||
if (params.recursive) {
|
if (params.recursive) {
|
||||||
command = params.force ? `rm -rf '${escapedPath}'` : `rm -r '${escapedPath}'`
|
command = params.force ? `rm -rf '${escapedPath}'` : `rm -r '${escapedPath}'`
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { createLogger } from '@sim/logger'
|
|||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import type { Client, SFTPWrapper } from 'ssh2'
|
import type { Client, SFTPWrapper } from 'ssh2'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
|
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
|
||||||
|
|
||||||
const logger = createLogger('SSHDownloadFileAPI')
|
const logger = createLogger('SSHDownloadFileAPI')
|
||||||
@@ -35,15 +34,10 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH download file attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = DownloadFileSchema.parse(body)
|
const params = DownloadFileSchema.parse(body)
|
||||||
|
|
||||||
|
// Validate authentication
|
||||||
if (!params.password && !params.privateKey) {
|
if (!params.password && !params.privateKey) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Either password or privateKey must be provided' },
|
{ error: 'Either password or privateKey must be provided' },
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createSSHConnection, executeSSHCommand, sanitizeCommand } from '@/app/api/tools/ssh/utils'
|
import { createSSHConnection, executeSSHCommand, sanitizeCommand } from '@/app/api/tools/ssh/utils'
|
||||||
|
|
||||||
const logger = createLogger('SSHExecuteCommandAPI')
|
const logger = createLogger('SSHExecuteCommandAPI')
|
||||||
@@ -22,15 +21,10 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH execute command attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = ExecuteCommandSchema.parse(body)
|
const params = ExecuteCommandSchema.parse(body)
|
||||||
|
|
||||||
|
// Validate authentication
|
||||||
if (!params.password && !params.privateKey) {
|
if (!params.password && !params.privateKey) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Either password or privateKey must be provided' },
|
{ error: 'Either password or privateKey must be provided' },
|
||||||
@@ -50,6 +44,7 @@ export async function POST(request: NextRequest) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Build command with optional working directory
|
||||||
let command = sanitizeCommand(params.command)
|
let command = sanitizeCommand(params.command)
|
||||||
if (params.workingDirectory) {
|
if (params.workingDirectory) {
|
||||||
command = `cd "${params.workingDirectory}" && ${command}`
|
command = `cd "${params.workingDirectory}" && ${command}`
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createSSHConnection, escapeShellArg, executeSSHCommand } from '@/app/api/tools/ssh/utils'
|
import { createSSHConnection, escapeShellArg, executeSSHCommand } from '@/app/api/tools/ssh/utils'
|
||||||
|
|
||||||
const logger = createLogger('SSHExecuteScriptAPI')
|
const logger = createLogger('SSHExecuteScriptAPI')
|
||||||
@@ -23,15 +22,10 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH execute script attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = ExecuteScriptSchema.parse(body)
|
const params = ExecuteScriptSchema.parse(body)
|
||||||
|
|
||||||
|
// Validate authentication
|
||||||
if (!params.password && !params.privateKey) {
|
if (!params.password && !params.privateKey) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Either password or privateKey must be provided' },
|
{ error: 'Either password or privateKey must be provided' },
|
||||||
@@ -51,10 +45,13 @@ export async function POST(request: NextRequest) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Create a temporary script file, execute it, and clean up
|
||||||
const scriptPath = `/tmp/sim_script_${requestId}.sh`
|
const scriptPath = `/tmp/sim_script_${requestId}.sh`
|
||||||
const escapedScriptPath = escapeShellArg(scriptPath)
|
const escapedScriptPath = escapeShellArg(scriptPath)
|
||||||
const escapedInterpreter = escapeShellArg(params.interpreter)
|
const escapedInterpreter = escapeShellArg(params.interpreter)
|
||||||
|
|
||||||
|
// Build the command to create, execute, and clean up the script
|
||||||
|
// Note: heredoc with quoted delimiter ('SIMEOF') prevents variable expansion
|
||||||
let command = `cat > '${escapedScriptPath}' << 'SIMEOF'
|
let command = `cat > '${escapedScriptPath}' << 'SIMEOF'
|
||||||
${params.script}
|
${params.script}
|
||||||
SIMEOF
|
SIMEOF
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createSSHConnection, executeSSHCommand } from '@/app/api/tools/ssh/utils'
|
import { createSSHConnection, executeSSHCommand } from '@/app/api/tools/ssh/utils'
|
||||||
|
|
||||||
const logger = createLogger('SSHGetSystemInfoAPI')
|
const logger = createLogger('SSHGetSystemInfoAPI')
|
||||||
@@ -20,15 +19,10 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH get system info attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = GetSystemInfoSchema.parse(body)
|
const params = GetSystemInfoSchema.parse(body)
|
||||||
|
|
||||||
|
// Validate authentication
|
||||||
if (!params.password && !params.privateKey) {
|
if (!params.password && !params.privateKey) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Either password or privateKey must be provided' },
|
{ error: 'Either password or privateKey must be provided' },
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { createLogger } from '@sim/logger'
|
|||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import type { Client, FileEntry, SFTPWrapper } from 'ssh2'
|
import type { Client, FileEntry, SFTPWrapper } from 'ssh2'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import {
|
import {
|
||||||
createSSHConnection,
|
createSSHConnection,
|
||||||
getFileType,
|
getFileType,
|
||||||
@@ -61,15 +60,10 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH list directory attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = ListDirectorySchema.parse(body)
|
const params = ListDirectorySchema.parse(body)
|
||||||
|
|
||||||
|
// Validate authentication
|
||||||
if (!params.password && !params.privateKey) {
|
if (!params.password && !params.privateKey) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Either password or privateKey must be provided' },
|
{ error: 'Either password or privateKey must be provided' },
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { randomUUID } from 'crypto'
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import {
|
import {
|
||||||
createSSHConnection,
|
createSSHConnection,
|
||||||
escapeShellArg,
|
escapeShellArg,
|
||||||
@@ -28,16 +27,9 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH move/rename attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = MoveRenameSchema.parse(body)
|
const params = MoveRenameSchema.parse(body)
|
||||||
|
|
||||||
// Validate SSH authentication
|
|
||||||
if (!params.password && !params.privateKey) {
|
if (!params.password && !params.privateKey) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Either password or privateKey must be provided' },
|
{ error: 'Either password or privateKey must be provided' },
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { createLogger } from '@sim/logger'
|
|||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import type { Client, SFTPWrapper } from 'ssh2'
|
import type { Client, SFTPWrapper } from 'ssh2'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
|
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
|
||||||
|
|
||||||
const logger = createLogger('SSHReadFileContentAPI')
|
const logger = createLogger('SSHReadFileContentAPI')
|
||||||
@@ -36,12 +35,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH read file content attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = ReadFileContentSchema.parse(body)
|
const params = ReadFileContentSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { createLogger } from '@sim/logger'
|
|||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import type { Client, SFTPWrapper } from 'ssh2'
|
import type { Client, SFTPWrapper } from 'ssh2'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
|
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
|
||||||
|
|
||||||
const logger = createLogger('SSHUploadFileAPI')
|
const logger = createLogger('SSHUploadFileAPI')
|
||||||
@@ -38,12 +37,6 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH upload file attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = UploadFileSchema.parse(body)
|
const params = UploadFileSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { createLogger } from '@sim/logger'
|
|||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import type { Client, SFTPWrapper } from 'ssh2'
|
import type { Client, SFTPWrapper } from 'ssh2'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
|
import { createSSHConnection, sanitizePath } from '@/app/api/tools/ssh/utils'
|
||||||
|
|
||||||
const logger = createLogger('SSHWriteFileContentAPI')
|
const logger = createLogger('SSHWriteFileContentAPI')
|
||||||
@@ -37,15 +36,10 @@ export async function POST(request: NextRequest) {
|
|||||||
const requestId = randomUUID().slice(0, 8)
|
const requestId = randomUUID().slice(0, 8)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const auth = await checkHybridAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized SSH write file content attempt`)
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const params = WriteFileContentSchema.parse(body)
|
const params = WriteFileContentSchema.parse(body)
|
||||||
|
|
||||||
|
// Validate authentication
|
||||||
if (!params.password && !params.privateKey) {
|
if (!params.password && !params.privateKey) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Either password or privateKey must be provided' },
|
{ error: 'Either password or privateKey must be provided' },
|
||||||
|
|||||||
@@ -1,211 +0,0 @@
|
|||||||
/**
|
|
||||||
* POST /api/v1/admin/credits
|
|
||||||
*
|
|
||||||
* Issue credits to a user by user ID or email.
|
|
||||||
*
|
|
||||||
* Body:
|
|
||||||
* - userId?: string - The user ID to issue credits to
|
|
||||||
* - email?: string - The user email to issue credits to (alternative to userId)
|
|
||||||
* - amount: number - The amount of credits to issue (in dollars)
|
|
||||||
* - reason?: string - Reason for issuing credits (for audit logging)
|
|
||||||
*
|
|
||||||
* Response: AdminSingleResponse<{
|
|
||||||
* success: true,
|
|
||||||
* entityType: 'user' | 'organization',
|
|
||||||
* entityId: string,
|
|
||||||
* amount: number,
|
|
||||||
* newCreditBalance: number,
|
|
||||||
* newUsageLimit: number,
|
|
||||||
* }>
|
|
||||||
*
|
|
||||||
* For Pro users: credits are added to user_stats.credit_balance
|
|
||||||
* For Team users: credits are added to organization.credit_balance
|
|
||||||
* Usage limits are updated accordingly to allow spending the credits.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { db } from '@sim/db'
|
|
||||||
import { organization, subscription, user, userStats } from '@sim/db/schema'
|
|
||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { and, eq } from 'drizzle-orm'
|
|
||||||
import { nanoid } from 'nanoid'
|
|
||||||
import { getHighestPrioritySubscription } from '@/lib/billing/core/subscription'
|
|
||||||
import { addCredits } from '@/lib/billing/credits/balance'
|
|
||||||
import { setUsageLimitForCredits } from '@/lib/billing/credits/purchase'
|
|
||||||
import { getEffectiveSeats } from '@/lib/billing/subscriptions/utils'
|
|
||||||
import { withAdminAuth } from '@/app/api/v1/admin/middleware'
|
|
||||||
import {
|
|
||||||
badRequestResponse,
|
|
||||||
internalErrorResponse,
|
|
||||||
notFoundResponse,
|
|
||||||
singleResponse,
|
|
||||||
} from '@/app/api/v1/admin/responses'
|
|
||||||
|
|
||||||
const logger = createLogger('AdminCreditsAPI')
|
|
||||||
|
|
||||||
export const POST = withAdminAuth(async (request) => {
|
|
||||||
try {
|
|
||||||
const body = await request.json()
|
|
||||||
const { userId, email, amount, reason } = body
|
|
||||||
|
|
||||||
if (!userId && !email) {
|
|
||||||
return badRequestResponse('Either userId or email is required')
|
|
||||||
}
|
|
||||||
|
|
||||||
if (userId && typeof userId !== 'string') {
|
|
||||||
return badRequestResponse('userId must be a string')
|
|
||||||
}
|
|
||||||
|
|
||||||
if (email && typeof email !== 'string') {
|
|
||||||
return badRequestResponse('email must be a string')
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) {
|
|
||||||
return badRequestResponse('amount must be a positive number')
|
|
||||||
}
|
|
||||||
|
|
||||||
let resolvedUserId: string
|
|
||||||
let userEmail: string | null = null
|
|
||||||
|
|
||||||
if (userId) {
|
|
||||||
const [userData] = await db
|
|
||||||
.select({ id: user.id, email: user.email })
|
|
||||||
.from(user)
|
|
||||||
.where(eq(user.id, userId))
|
|
||||||
.limit(1)
|
|
||||||
|
|
||||||
if (!userData) {
|
|
||||||
return notFoundResponse('User')
|
|
||||||
}
|
|
||||||
resolvedUserId = userData.id
|
|
||||||
userEmail = userData.email
|
|
||||||
} else {
|
|
||||||
const normalizedEmail = email.toLowerCase().trim()
|
|
||||||
const [userData] = await db
|
|
||||||
.select({ id: user.id, email: user.email })
|
|
||||||
.from(user)
|
|
||||||
.where(eq(user.email, normalizedEmail))
|
|
||||||
.limit(1)
|
|
||||||
|
|
||||||
if (!userData) {
|
|
||||||
return notFoundResponse('User with email')
|
|
||||||
}
|
|
||||||
resolvedUserId = userData.id
|
|
||||||
userEmail = userData.email
|
|
||||||
}
|
|
||||||
|
|
||||||
const userSubscription = await getHighestPrioritySubscription(resolvedUserId)
|
|
||||||
|
|
||||||
if (!userSubscription || !['pro', 'team', 'enterprise'].includes(userSubscription.plan)) {
|
|
||||||
return badRequestResponse(
|
|
||||||
'User must have an active Pro, Team, or Enterprise subscription to receive credits'
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
let entityType: 'user' | 'organization'
|
|
||||||
let entityId: string
|
|
||||||
const plan = userSubscription.plan
|
|
||||||
let seats: number | null = null
|
|
||||||
|
|
||||||
if (plan === 'team' || plan === 'enterprise') {
|
|
||||||
entityType = 'organization'
|
|
||||||
entityId = userSubscription.referenceId
|
|
||||||
|
|
||||||
const [orgExists] = await db
|
|
||||||
.select({ id: organization.id })
|
|
||||||
.from(organization)
|
|
||||||
.where(eq(organization.id, entityId))
|
|
||||||
.limit(1)
|
|
||||||
|
|
||||||
if (!orgExists) {
|
|
||||||
return notFoundResponse('Organization')
|
|
||||||
}
|
|
||||||
|
|
||||||
const [subData] = await db
|
|
||||||
.select()
|
|
||||||
.from(subscription)
|
|
||||||
.where(and(eq(subscription.referenceId, entityId), eq(subscription.status, 'active')))
|
|
||||||
.limit(1)
|
|
||||||
|
|
||||||
seats = getEffectiveSeats(subData)
|
|
||||||
} else {
|
|
||||||
entityType = 'user'
|
|
||||||
entityId = resolvedUserId
|
|
||||||
|
|
||||||
const [existingStats] = await db
|
|
||||||
.select({ id: userStats.id })
|
|
||||||
.from(userStats)
|
|
||||||
.where(eq(userStats.userId, entityId))
|
|
||||||
.limit(1)
|
|
||||||
|
|
||||||
if (!existingStats) {
|
|
||||||
await db.insert(userStats).values({
|
|
||||||
id: nanoid(),
|
|
||||||
userId: entityId,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await addCredits(entityType, entityId, amount)
|
|
||||||
|
|
||||||
let newCreditBalance: number
|
|
||||||
if (entityType === 'organization') {
|
|
||||||
const [orgData] = await db
|
|
||||||
.select({ creditBalance: organization.creditBalance })
|
|
||||||
.from(organization)
|
|
||||||
.where(eq(organization.id, entityId))
|
|
||||||
.limit(1)
|
|
||||||
newCreditBalance = Number.parseFloat(orgData?.creditBalance || '0')
|
|
||||||
} else {
|
|
||||||
const [stats] = await db
|
|
||||||
.select({ creditBalance: userStats.creditBalance })
|
|
||||||
.from(userStats)
|
|
||||||
.where(eq(userStats.userId, entityId))
|
|
||||||
.limit(1)
|
|
||||||
newCreditBalance = Number.parseFloat(stats?.creditBalance || '0')
|
|
||||||
}
|
|
||||||
|
|
||||||
await setUsageLimitForCredits(entityType, entityId, plan, seats, newCreditBalance)
|
|
||||||
|
|
||||||
let newUsageLimit: number
|
|
||||||
if (entityType === 'organization') {
|
|
||||||
const [orgData] = await db
|
|
||||||
.select({ orgUsageLimit: organization.orgUsageLimit })
|
|
||||||
.from(organization)
|
|
||||||
.where(eq(organization.id, entityId))
|
|
||||||
.limit(1)
|
|
||||||
newUsageLimit = Number.parseFloat(orgData?.orgUsageLimit || '0')
|
|
||||||
} else {
|
|
||||||
const [stats] = await db
|
|
||||||
.select({ currentUsageLimit: userStats.currentUsageLimit })
|
|
||||||
.from(userStats)
|
|
||||||
.where(eq(userStats.userId, entityId))
|
|
||||||
.limit(1)
|
|
||||||
newUsageLimit = Number.parseFloat(stats?.currentUsageLimit || '0')
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info('Admin API: Issued credits', {
|
|
||||||
resolvedUserId,
|
|
||||||
userEmail,
|
|
||||||
entityType,
|
|
||||||
entityId,
|
|
||||||
amount,
|
|
||||||
newCreditBalance,
|
|
||||||
newUsageLimit,
|
|
||||||
reason: reason || 'No reason provided',
|
|
||||||
})
|
|
||||||
|
|
||||||
return singleResponse({
|
|
||||||
success: true,
|
|
||||||
userId: resolvedUserId,
|
|
||||||
userEmail,
|
|
||||||
entityType,
|
|
||||||
entityId,
|
|
||||||
amount,
|
|
||||||
newCreditBalance,
|
|
||||||
newUsageLimit,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Admin API: Failed to issue credits', { error })
|
|
||||||
return internalErrorResponse('Failed to issue credits')
|
|
||||||
}
|
|
||||||
})
|
|
||||||
@@ -63,9 +63,6 @@
|
|||||||
* GET /api/v1/admin/subscriptions/:id - Get subscription details
|
* GET /api/v1/admin/subscriptions/:id - Get subscription details
|
||||||
* DELETE /api/v1/admin/subscriptions/:id - Cancel subscription (?atPeriodEnd=true for scheduled)
|
* DELETE /api/v1/admin/subscriptions/:id - Cancel subscription (?atPeriodEnd=true for scheduled)
|
||||||
*
|
*
|
||||||
* Credits:
|
|
||||||
* POST /api/v1/admin/credits - Issue credits to user (by userId or email)
|
|
||||||
*
|
|
||||||
* Access Control (Permission Groups):
|
* Access Control (Permission Groups):
|
||||||
* GET /api/v1/admin/access-control - List permission groups (?organizationId=X)
|
* GET /api/v1/admin/access-control - List permission groups (?organizationId=X)
|
||||||
* DELETE /api/v1/admin/access-control - Delete permission groups for org (?organizationId=X)
|
* DELETE /api/v1/admin/access-control - Delete permission groups for org (?organizationId=X)
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { validateInteger } from '@/lib/core/security/input-validation'
|
import { validateInteger } from '@/lib/core/security/input-validation'
|
||||||
import { PlatformEvents } from '@/lib/core/telemetry'
|
import { PlatformEvents } from '@/lib/core/telemetry'
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { resolveEnvVarsInObject } from '@/lib/webhooks/env-resolver'
|
|
||||||
import {
|
import {
|
||||||
cleanupExternalWebhook,
|
cleanupExternalWebhook,
|
||||||
createExternalWebhookSubscription,
|
createExternalWebhookSubscription,
|
||||||
@@ -113,9 +112,9 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const originalProviderConfig = providerConfig
|
|
||||||
let resolvedProviderConfig = providerConfig
|
let resolvedProviderConfig = providerConfig
|
||||||
if (providerConfig) {
|
if (providerConfig) {
|
||||||
|
const { resolveEnvVarsInObject } = await import('@/lib/webhooks/env-resolver')
|
||||||
const webhookDataForResolve = await db
|
const webhookDataForResolve = await db
|
||||||
.select({
|
.select({
|
||||||
workspaceId: workflow.workspaceId,
|
workspaceId: workflow.workspaceId,
|
||||||
@@ -231,23 +230,19 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
|
|||||||
hasFailedCountUpdate: failedCount !== undefined,
|
hasFailedCountUpdate: failedCount !== undefined,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Merge providerConfig to preserve credential-related fields
|
||||||
let finalProviderConfig = webhooks[0].webhook.providerConfig
|
let finalProviderConfig = webhooks[0].webhook.providerConfig
|
||||||
if (providerConfig !== undefined && originalProviderConfig) {
|
if (providerConfig !== undefined) {
|
||||||
const existingConfig = existingProviderConfig
|
const existingConfig = existingProviderConfig
|
||||||
finalProviderConfig = {
|
finalProviderConfig = {
|
||||||
...originalProviderConfig,
|
...nextProviderConfig,
|
||||||
credentialId: existingConfig.credentialId,
|
credentialId: existingConfig.credentialId,
|
||||||
credentialSetId: existingConfig.credentialSetId,
|
credentialSetId: existingConfig.credentialSetId,
|
||||||
userId: existingConfig.userId,
|
userId: existingConfig.userId,
|
||||||
historyId: existingConfig.historyId,
|
historyId: existingConfig.historyId,
|
||||||
lastCheckedTimestamp: existingConfig.lastCheckedTimestamp,
|
lastCheckedTimestamp: existingConfig.lastCheckedTimestamp,
|
||||||
setupCompleted: existingConfig.setupCompleted,
|
setupCompleted: existingConfig.setupCompleted,
|
||||||
externalId: existingConfig.externalId,
|
externalId: nextProviderConfig.externalId ?? existingConfig.externalId,
|
||||||
}
|
|
||||||
for (const [key, value] of Object.entries(nextProviderConfig)) {
|
|
||||||
if (!(key in originalProviderConfig)) {
|
|
||||||
;(finalProviderConfig as Record<string, unknown>)[key] = value
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { type NextRequest, NextResponse } from 'next/server'
|
|||||||
import { getSession } from '@/lib/auth'
|
import { getSession } from '@/lib/auth'
|
||||||
import { PlatformEvents } from '@/lib/core/telemetry'
|
import { PlatformEvents } from '@/lib/core/telemetry'
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { resolveEnvVarsInObject } from '@/lib/webhooks/env-resolver'
|
|
||||||
import { createExternalWebhookSubscription } from '@/lib/webhooks/provider-subscriptions'
|
import { createExternalWebhookSubscription } from '@/lib/webhooks/provider-subscriptions'
|
||||||
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
|
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
|
||||||
|
|
||||||
@@ -299,10 +298,14 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let savedWebhook: any = null
|
let savedWebhook: any = null // Variable to hold the result of save/update
|
||||||
const originalProviderConfig = providerConfig || {}
|
|
||||||
|
// Use the original provider config - Gmail/Outlook configuration functions will inject userId automatically
|
||||||
|
const finalProviderConfig = providerConfig || {}
|
||||||
|
|
||||||
|
const { resolveEnvVarsInObject } = await import('@/lib/webhooks/env-resolver')
|
||||||
let resolvedProviderConfig = await resolveEnvVarsInObject(
|
let resolvedProviderConfig = await resolveEnvVarsInObject(
|
||||||
originalProviderConfig,
|
finalProviderConfig,
|
||||||
userId,
|
userId,
|
||||||
workflowRecord.workspaceId || undefined
|
workflowRecord.workspaceId || undefined
|
||||||
)
|
)
|
||||||
@@ -466,8 +469,6 @@ export async function POST(request: NextRequest) {
|
|||||||
providerConfig: providerConfigOverride,
|
providerConfig: providerConfigOverride,
|
||||||
})
|
})
|
||||||
|
|
||||||
const configToSave = { ...originalProviderConfig }
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await createExternalWebhookSubscription(
|
const result = await createExternalWebhookSubscription(
|
||||||
request,
|
request,
|
||||||
@@ -476,13 +477,7 @@ export async function POST(request: NextRequest) {
|
|||||||
userId,
|
userId,
|
||||||
requestId
|
requestId
|
||||||
)
|
)
|
||||||
const updatedConfig = result.updatedProviderConfig as Record<string, unknown>
|
resolvedProviderConfig = result.updatedProviderConfig as Record<string, unknown>
|
||||||
for (const [key, value] of Object.entries(updatedConfig)) {
|
|
||||||
if (!(key in originalProviderConfig)) {
|
|
||||||
configToSave[key] = value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
resolvedProviderConfig = updatedConfig
|
|
||||||
externalSubscriptionCreated = result.externalSubscriptionCreated
|
externalSubscriptionCreated = result.externalSubscriptionCreated
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error(`[${requestId}] Error creating external webhook subscription`, err)
|
logger.error(`[${requestId}] Error creating external webhook subscription`, err)
|
||||||
@@ -495,22 +490,25 @@ export async function POST(request: NextRequest) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Now save to database (only if subscription succeeded or provider doesn't need external subscription)
|
||||||
try {
|
try {
|
||||||
if (targetWebhookId) {
|
if (targetWebhookId) {
|
||||||
logger.info(`[${requestId}] Updating existing webhook for path: ${finalPath}`, {
|
logger.info(`[${requestId}] Updating existing webhook for path: ${finalPath}`, {
|
||||||
webhookId: targetWebhookId,
|
webhookId: targetWebhookId,
|
||||||
provider,
|
provider,
|
||||||
hasCredentialId: !!(configToSave as any)?.credentialId,
|
hasCredentialId: !!(resolvedProviderConfig as any)?.credentialId,
|
||||||
credentialId: (configToSave as any)?.credentialId,
|
credentialId: (resolvedProviderConfig as any)?.credentialId,
|
||||||
})
|
})
|
||||||
const updatedResult = await db
|
const updatedResult = await db
|
||||||
.update(webhook)
|
.update(webhook)
|
||||||
.set({
|
.set({
|
||||||
blockId,
|
blockId,
|
||||||
provider,
|
provider,
|
||||||
providerConfig: configToSave,
|
providerConfig: resolvedProviderConfig,
|
||||||
credentialSetId:
|
credentialSetId:
|
||||||
((configToSave as Record<string, unknown>)?.credentialSetId as string | null) || null,
|
((resolvedProviderConfig as Record<string, unknown>)?.credentialSetId as
|
||||||
|
| string
|
||||||
|
| null) || null,
|
||||||
isActive: true,
|
isActive: true,
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
})
|
})
|
||||||
@@ -533,9 +531,11 @@ export async function POST(request: NextRequest) {
|
|||||||
blockId,
|
blockId,
|
||||||
path: finalPath,
|
path: finalPath,
|
||||||
provider,
|
provider,
|
||||||
providerConfig: configToSave,
|
providerConfig: resolvedProviderConfig,
|
||||||
credentialSetId:
|
credentialSetId:
|
||||||
((configToSave as Record<string, unknown>)?.credentialSetId as string | null) || null,
|
((resolvedProviderConfig as Record<string, unknown>)?.credentialSetId as
|
||||||
|
| string
|
||||||
|
| null) || null,
|
||||||
isActive: true,
|
isActive: true,
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
@@ -549,7 +549,7 @@ export async function POST(request: NextRequest) {
|
|||||||
try {
|
try {
|
||||||
const { cleanupExternalWebhook } = await import('@/lib/webhooks/provider-subscriptions')
|
const { cleanupExternalWebhook } = await import('@/lib/webhooks/provider-subscriptions')
|
||||||
await cleanupExternalWebhook(
|
await cleanupExternalWebhook(
|
||||||
createTempWebhookData(configToSave),
|
createTempWebhookData(resolvedProviderConfig),
|
||||||
workflowRecord,
|
workflowRecord,
|
||||||
requestId
|
requestId
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -116,6 +116,7 @@ type AsyncExecutionParams = {
|
|||||||
userId: string
|
userId: string
|
||||||
input: any
|
input: any
|
||||||
triggerType: CoreTriggerType
|
triggerType: CoreTriggerType
|
||||||
|
preflighted?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -138,6 +139,7 @@ async function handleAsyncExecution(params: AsyncExecutionParams): Promise<NextR
|
|||||||
userId,
|
userId,
|
||||||
input,
|
input,
|
||||||
triggerType,
|
triggerType,
|
||||||
|
preflighted: params.preflighted,
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -274,6 +276,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
requestId
|
requestId
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const shouldPreflightEnvVars = isAsyncMode && isTriggerDevEnabled
|
||||||
const preprocessResult = await preprocessExecution({
|
const preprocessResult = await preprocessExecution({
|
||||||
workflowId,
|
workflowId,
|
||||||
userId,
|
userId,
|
||||||
@@ -282,7 +285,9 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
requestId,
|
requestId,
|
||||||
checkDeployment: !shouldUseDraftState,
|
checkDeployment: !shouldUseDraftState,
|
||||||
loggingSession,
|
loggingSession,
|
||||||
|
preflightEnvVars: shouldPreflightEnvVars,
|
||||||
useDraftState: shouldUseDraftState,
|
useDraftState: shouldUseDraftState,
|
||||||
|
envUserId: isClientSession ? userId : undefined,
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!preprocessResult.success) {
|
if (!preprocessResult.success) {
|
||||||
@@ -314,6 +319,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
userId: actorUserId,
|
userId: actorUserId,
|
||||||
input,
|
input,
|
||||||
triggerType: loggingTriggerType,
|
triggerType: loggingTriggerType,
|
||||||
|
preflighted: shouldPreflightEnvVars,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -61,7 +61,6 @@ export function EditChunkModal({
|
|||||||
const [showUnsavedChangesAlert, setShowUnsavedChangesAlert] = useState(false)
|
const [showUnsavedChangesAlert, setShowUnsavedChangesAlert] = useState(false)
|
||||||
const [pendingNavigation, setPendingNavigation] = useState<(() => void) | null>(null)
|
const [pendingNavigation, setPendingNavigation] = useState<(() => void) | null>(null)
|
||||||
const [tokenizerOn, setTokenizerOn] = useState(false)
|
const [tokenizerOn, setTokenizerOn] = useState(false)
|
||||||
const [hoveredTokenIndex, setHoveredTokenIndex] = useState<number | null>(null)
|
|
||||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||||
|
|
||||||
const error = mutationError?.message ?? null
|
const error = mutationError?.message ?? null
|
||||||
@@ -255,8 +254,6 @@ export function EditChunkModal({
|
|||||||
style={{
|
style={{
|
||||||
backgroundColor: getTokenBgColor(index),
|
backgroundColor: getTokenBgColor(index),
|
||||||
}}
|
}}
|
||||||
onMouseEnter={() => setHoveredTokenIndex(index)}
|
|
||||||
onMouseLeave={() => setHoveredTokenIndex(null)}
|
|
||||||
>
|
>
|
||||||
{token}
|
{token}
|
||||||
</span>
|
</span>
|
||||||
@@ -284,11 +281,6 @@ export function EditChunkModal({
|
|||||||
<div className='flex items-center gap-[8px]'>
|
<div className='flex items-center gap-[8px]'>
|
||||||
<span className='text-[12px] text-[var(--text-secondary)]'>Tokenizer</span>
|
<span className='text-[12px] text-[var(--text-secondary)]'>Tokenizer</span>
|
||||||
<Switch checked={tokenizerOn} onCheckedChange={setTokenizerOn} />
|
<Switch checked={tokenizerOn} onCheckedChange={setTokenizerOn} />
|
||||||
{tokenizerOn && hoveredTokenIndex !== null && (
|
|
||||||
<span className='text-[12px] text-[var(--text-tertiary)]'>
|
|
||||||
Token #{hoveredTokenIndex + 1}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
<span className='text-[12px] text-[var(--text-secondary)]'>
|
<span className='text-[12px] text-[var(--text-secondary)]'>
|
||||||
{tokenCount.toLocaleString()}
|
{tokenCount.toLocaleString()}
|
||||||
|
|||||||
@@ -36,7 +36,6 @@ import {
|
|||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { SearchHighlight } from '@/components/ui/search-highlight'
|
import { SearchHighlight } from '@/components/ui/search-highlight'
|
||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
import { formatAbsoluteDate, formatRelativeTime } from '@/lib/core/utils/formatting'
|
|
||||||
import type { ChunkData } from '@/lib/knowledge/types'
|
import type { ChunkData } from '@/lib/knowledge/types'
|
||||||
import {
|
import {
|
||||||
ChunkContextMenu,
|
ChunkContextMenu,
|
||||||
@@ -59,6 +58,55 @@ import {
|
|||||||
|
|
||||||
const logger = createLogger('Document')
|
const logger = createLogger('Document')
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats a date string to relative time (e.g., "2h ago", "3d ago")
|
||||||
|
*/
|
||||||
|
function formatRelativeTime(dateString: string): string {
|
||||||
|
const date = new Date(dateString)
|
||||||
|
const now = new Date()
|
||||||
|
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000)
|
||||||
|
|
||||||
|
if (diffInSeconds < 60) {
|
||||||
|
return 'just now'
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 3600) {
|
||||||
|
const minutes = Math.floor(diffInSeconds / 60)
|
||||||
|
return `${minutes}m ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 86400) {
|
||||||
|
const hours = Math.floor(diffInSeconds / 3600)
|
||||||
|
return `${hours}h ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 604800) {
|
||||||
|
const days = Math.floor(diffInSeconds / 86400)
|
||||||
|
return `${days}d ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 2592000) {
|
||||||
|
const weeks = Math.floor(diffInSeconds / 604800)
|
||||||
|
return `${weeks}w ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 31536000) {
|
||||||
|
const months = Math.floor(diffInSeconds / 2592000)
|
||||||
|
return `${months}mo ago`
|
||||||
|
}
|
||||||
|
const years = Math.floor(diffInSeconds / 31536000)
|
||||||
|
return `${years}y ago`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats a date string to absolute format for tooltip display
|
||||||
|
*/
|
||||||
|
function formatAbsoluteDate(dateString: string): string {
|
||||||
|
const date = new Date(dateString)
|
||||||
|
return date.toLocaleDateString('en-US', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
interface DocumentProps {
|
interface DocumentProps {
|
||||||
knowledgeBaseId: string
|
knowledgeBaseId: string
|
||||||
documentId: string
|
documentId: string
|
||||||
@@ -256,6 +304,7 @@ export function Document({
|
|||||||
|
|
||||||
const [searchQuery, setSearchQuery] = useState('')
|
const [searchQuery, setSearchQuery] = useState('')
|
||||||
const [debouncedSearchQuery, setDebouncedSearchQuery] = useState('')
|
const [debouncedSearchQuery, setDebouncedSearchQuery] = useState('')
|
||||||
|
const [isSearching, setIsSearching] = useState(false)
|
||||||
|
|
||||||
const {
|
const {
|
||||||
chunks: initialChunks,
|
chunks: initialChunks,
|
||||||
@@ -295,6 +344,7 @@ export function Document({
|
|||||||
const handler = setTimeout(() => {
|
const handler = setTimeout(() => {
|
||||||
startTransition(() => {
|
startTransition(() => {
|
||||||
setDebouncedSearchQuery(searchQuery)
|
setDebouncedSearchQuery(searchQuery)
|
||||||
|
setIsSearching(searchQuery.trim().length > 0)
|
||||||
})
|
})
|
||||||
}, 200)
|
}, 200)
|
||||||
|
|
||||||
@@ -303,7 +353,6 @@ export function Document({
|
|||||||
}
|
}
|
||||||
}, [searchQuery])
|
}, [searchQuery])
|
||||||
|
|
||||||
const isSearching = debouncedSearchQuery.trim().length > 0
|
|
||||||
const showingSearch = isSearching && searchQuery.trim().length > 0 && searchResults.length > 0
|
const showingSearch = isSearching && searchQuery.trim().length > 0 && searchResults.length > 0
|
||||||
const SEARCH_PAGE_SIZE = 50
|
const SEARCH_PAGE_SIZE = 50
|
||||||
const maxSearchPages = Math.ceil(searchResults.length / SEARCH_PAGE_SIZE)
|
const maxSearchPages = Math.ceil(searchResults.length / SEARCH_PAGE_SIZE)
|
||||||
|
|||||||
@@ -27,10 +27,6 @@ import {
|
|||||||
ModalContent,
|
ModalContent,
|
||||||
ModalFooter,
|
ModalFooter,
|
||||||
ModalHeader,
|
ModalHeader,
|
||||||
Popover,
|
|
||||||
PopoverContent,
|
|
||||||
PopoverItem,
|
|
||||||
PopoverTrigger,
|
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
TableCell,
|
TableCell,
|
||||||
@@ -44,11 +40,8 @@ import { Input } from '@/components/ui/input'
|
|||||||
import { SearchHighlight } from '@/components/ui/search-highlight'
|
import { SearchHighlight } from '@/components/ui/search-highlight'
|
||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
import { cn } from '@/lib/core/utils/cn'
|
import { cn } from '@/lib/core/utils/cn'
|
||||||
import { formatAbsoluteDate, formatRelativeTime } from '@/lib/core/utils/formatting'
|
|
||||||
import { ALL_TAG_SLOTS, type AllTagSlot, getFieldTypeForSlot } from '@/lib/knowledge/constants'
|
|
||||||
import type { DocumentSortField, SortOrder } from '@/lib/knowledge/documents/types'
|
import type { DocumentSortField, SortOrder } from '@/lib/knowledge/documents/types'
|
||||||
import type { DocumentData } from '@/lib/knowledge/types'
|
import type { DocumentData } from '@/lib/knowledge/types'
|
||||||
import { formatFileSize } from '@/lib/uploads/utils/file-utils'
|
|
||||||
import {
|
import {
|
||||||
ActionBar,
|
ActionBar,
|
||||||
AddDocumentsModal,
|
AddDocumentsModal,
|
||||||
@@ -196,8 +189,8 @@ function KnowledgeBaseLoading({ knowledgeBaseName }: KnowledgeBaseLoadingProps)
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div className='mt-[4px]'>
|
||||||
<Skeleton className='mt-[4px] h-[21px] w-[300px] rounded-[4px]' />
|
<Skeleton className='h-[21px] w-[300px] rounded-[4px]' />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='mt-[16px] flex items-center gap-[8px]'>
|
<div className='mt-[16px] flex items-center gap-[8px]'>
|
||||||
@@ -215,12 +208,9 @@ function KnowledgeBaseLoading({ knowledgeBaseName }: KnowledgeBaseLoadingProps)
|
|||||||
className='flex-1 border-0 bg-transparent px-0 font-medium text-[var(--text-secondary)] text-small leading-none placeholder:text-[var(--text-subtle)] focus-visible:ring-0 focus-visible:ring-offset-0'
|
className='flex-1 border-0 bg-transparent px-0 font-medium text-[var(--text-secondary)] text-small leading-none placeholder:text-[var(--text-subtle)] focus-visible:ring-0 focus-visible:ring-offset-0'
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className='flex items-center gap-[8px]'>
|
<Button disabled variant='tertiary' className='h-[32px] rounded-[6px]'>
|
||||||
<Skeleton className='h-[32px] w-[52px] rounded-[6px]' />
|
Add Documents
|
||||||
<Button disabled variant='tertiary' className='h-[32px] rounded-[6px]'>
|
</Button>
|
||||||
Add Documents
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='mt-[12px] flex flex-1 flex-col overflow-hidden'>
|
<div className='mt-[12px] flex flex-1 flex-col overflow-hidden'>
|
||||||
@@ -232,11 +222,73 @@ function KnowledgeBaseLoading({ knowledgeBaseName }: KnowledgeBaseLoadingProps)
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats a date string to relative time (e.g., "2h ago", "3d ago")
|
||||||
|
*/
|
||||||
|
function formatRelativeTime(dateString: string): string {
|
||||||
|
const date = new Date(dateString)
|
||||||
|
const now = new Date()
|
||||||
|
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000)
|
||||||
|
|
||||||
|
if (diffInSeconds < 60) {
|
||||||
|
return 'just now'
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 3600) {
|
||||||
|
const minutes = Math.floor(diffInSeconds / 60)
|
||||||
|
return `${minutes}m ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 86400) {
|
||||||
|
const hours = Math.floor(diffInSeconds / 3600)
|
||||||
|
return `${hours}h ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 604800) {
|
||||||
|
const days = Math.floor(diffInSeconds / 86400)
|
||||||
|
return `${days}d ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 2592000) {
|
||||||
|
const weeks = Math.floor(diffInSeconds / 604800)
|
||||||
|
return `${weeks}w ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 31536000) {
|
||||||
|
const months = Math.floor(diffInSeconds / 2592000)
|
||||||
|
return `${months}mo ago`
|
||||||
|
}
|
||||||
|
const years = Math.floor(diffInSeconds / 31536000)
|
||||||
|
return `${years}y ago`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats a date string to absolute format for tooltip display
|
||||||
|
*/
|
||||||
|
function formatAbsoluteDate(dateString: string): string {
|
||||||
|
const date = new Date(dateString)
|
||||||
|
return date.toLocaleDateString('en-US', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
interface KnowledgeBaseProps {
|
interface KnowledgeBaseProps {
|
||||||
id: string
|
id: string
|
||||||
knowledgeBaseName?: string
|
knowledgeBaseName?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getFileIcon(mimeType: string, filename: string) {
|
||||||
|
const IconComponent = getDocumentIcon(mimeType, filename)
|
||||||
|
return <IconComponent className='h-6 w-5 flex-shrink-0' />
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatFileSize(bytes: number): string {
|
||||||
|
if (bytes === 0) return '0 Bytes'
|
||||||
|
const k = 1024
|
||||||
|
const sizes = ['Bytes', 'KB', 'MB', 'GB']
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||||
|
return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
|
||||||
|
}
|
||||||
|
|
||||||
const AnimatedLoader = ({ className }: { className?: string }) => (
|
const AnimatedLoader = ({ className }: { className?: string }) => (
|
||||||
<Loader2 className={cn(className, 'animate-spin')} />
|
<Loader2 className={cn(className, 'animate-spin')} />
|
||||||
)
|
)
|
||||||
@@ -284,24 +336,53 @@ const getStatusBadge = (doc: DocumentData) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const TAG_SLOTS = [
|
||||||
|
'tag1',
|
||||||
|
'tag2',
|
||||||
|
'tag3',
|
||||||
|
'tag4',
|
||||||
|
'tag5',
|
||||||
|
'tag6',
|
||||||
|
'tag7',
|
||||||
|
'number1',
|
||||||
|
'number2',
|
||||||
|
'number3',
|
||||||
|
'number4',
|
||||||
|
'number5',
|
||||||
|
'date1',
|
||||||
|
'date2',
|
||||||
|
'boolean1',
|
||||||
|
'boolean2',
|
||||||
|
'boolean3',
|
||||||
|
] as const
|
||||||
|
|
||||||
|
type TagSlot = (typeof TAG_SLOTS)[number]
|
||||||
|
|
||||||
interface TagValue {
|
interface TagValue {
|
||||||
slot: AllTagSlot
|
slot: TagSlot
|
||||||
displayName: string
|
displayName: string
|
||||||
value: string
|
value: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const TAG_FIELD_TYPES: Record<string, string> = {
|
||||||
|
tag: 'text',
|
||||||
|
number: 'number',
|
||||||
|
date: 'date',
|
||||||
|
boolean: 'boolean',
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Computes tag values for a document
|
* Computes tag values for a document
|
||||||
*/
|
*/
|
||||||
function getDocumentTags(doc: DocumentData, definitions: TagDefinition[]): TagValue[] {
|
function getDocumentTags(doc: DocumentData, definitions: TagDefinition[]): TagValue[] {
|
||||||
const result: TagValue[] = []
|
const result: TagValue[] = []
|
||||||
|
|
||||||
for (const slot of ALL_TAG_SLOTS) {
|
for (const slot of TAG_SLOTS) {
|
||||||
const raw = doc[slot]
|
const raw = doc[slot]
|
||||||
if (raw == null) continue
|
if (raw == null) continue
|
||||||
|
|
||||||
const def = definitions.find((d) => d.tagSlot === slot)
|
const def = definitions.find((d) => d.tagSlot === slot)
|
||||||
const fieldType = def?.fieldType || getFieldTypeForSlot(slot) || 'text'
|
const fieldType = def?.fieldType || TAG_FIELD_TYPES[slot.replace(/\d+$/, '')] || 'text'
|
||||||
|
|
||||||
let value: string
|
let value: string
|
||||||
if (fieldType === 'date') {
|
if (fieldType === 'date') {
|
||||||
@@ -343,8 +424,6 @@ export function KnowledgeBase({
|
|||||||
|
|
||||||
const [searchQuery, setSearchQuery] = useState('')
|
const [searchQuery, setSearchQuery] = useState('')
|
||||||
const [showTagsModal, setShowTagsModal] = useState(false)
|
const [showTagsModal, setShowTagsModal] = useState(false)
|
||||||
const [enabledFilter, setEnabledFilter] = useState<'all' | 'enabled' | 'disabled'>('all')
|
|
||||||
const [isFilterPopoverOpen, setIsFilterPopoverOpen] = useState(false)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Memoize the search query setter to prevent unnecessary re-renders
|
* Memoize the search query setter to prevent unnecessary re-renders
|
||||||
@@ -355,7 +434,6 @@ export function KnowledgeBase({
|
|||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const [selectedDocuments, setSelectedDocuments] = useState<Set<string>>(new Set())
|
const [selectedDocuments, setSelectedDocuments] = useState<Set<string>>(new Set())
|
||||||
const [isSelectAllMode, setIsSelectAllMode] = useState(false)
|
|
||||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
|
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
|
||||||
const [showAddDocumentsModal, setShowAddDocumentsModal] = useState(false)
|
const [showAddDocumentsModal, setShowAddDocumentsModal] = useState(false)
|
||||||
const [showDeleteDocumentModal, setShowDeleteDocumentModal] = useState(false)
|
const [showDeleteDocumentModal, setShowDeleteDocumentModal] = useState(false)
|
||||||
@@ -382,6 +460,7 @@ export function KnowledgeBase({
|
|||||||
error: knowledgeBaseError,
|
error: knowledgeBaseError,
|
||||||
refresh: refreshKnowledgeBase,
|
refresh: refreshKnowledgeBase,
|
||||||
} = useKnowledgeBase(id)
|
} = useKnowledgeBase(id)
|
||||||
|
const [hasProcessingDocuments, setHasProcessingDocuments] = useState(false)
|
||||||
|
|
||||||
const {
|
const {
|
||||||
documents,
|
documents,
|
||||||
@@ -390,7 +469,6 @@ export function KnowledgeBase({
|
|||||||
isFetching: isFetchingDocuments,
|
isFetching: isFetchingDocuments,
|
||||||
isPlaceholderData: isPlaceholderDocuments,
|
isPlaceholderData: isPlaceholderDocuments,
|
||||||
error: documentsError,
|
error: documentsError,
|
||||||
hasProcessingDocuments,
|
|
||||||
updateDocument,
|
updateDocument,
|
||||||
refreshDocuments,
|
refreshDocuments,
|
||||||
} = useKnowledgeBaseDocuments(id, {
|
} = useKnowledgeBaseDocuments(id, {
|
||||||
@@ -399,14 +477,7 @@ export function KnowledgeBase({
|
|||||||
offset: (currentPage - 1) * DOCUMENTS_PER_PAGE,
|
offset: (currentPage - 1) * DOCUMENTS_PER_PAGE,
|
||||||
sortBy,
|
sortBy,
|
||||||
sortOrder,
|
sortOrder,
|
||||||
refetchInterval: (data) => {
|
refetchInterval: hasProcessingDocuments && !isDeleting ? 3000 : false,
|
||||||
if (isDeleting) return false
|
|
||||||
const hasPending = data?.documents?.some(
|
|
||||||
(doc) => doc.processingStatus === 'pending' || doc.processingStatus === 'processing'
|
|
||||||
)
|
|
||||||
return hasPending ? 3000 : false
|
|
||||||
},
|
|
||||||
enabledFilter,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const { tagDefinitions } = useKnowledgeBaseTagDefinitions(id)
|
const { tagDefinitions } = useKnowledgeBaseTagDefinitions(id)
|
||||||
@@ -472,52 +543,52 @@ export function KnowledgeBase({
|
|||||||
</TableHead>
|
</TableHead>
|
||||||
)
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const processing = documents.some(
|
||||||
|
(doc) => doc.processingStatus === 'pending' || doc.processingStatus === 'processing'
|
||||||
|
)
|
||||||
|
setHasProcessingDocuments(processing)
|
||||||
|
|
||||||
|
if (processing) {
|
||||||
|
checkForDeadProcesses()
|
||||||
|
}
|
||||||
|
}, [documents])
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks for documents with stale processing states and marks them as failed
|
* Checks for documents with stale processing states and marks them as failed
|
||||||
*/
|
*/
|
||||||
const checkForDeadProcesses = useCallback(
|
const checkForDeadProcesses = () => {
|
||||||
(docsToCheck: DocumentData[]) => {
|
const now = new Date()
|
||||||
const now = new Date()
|
const DEAD_PROCESS_THRESHOLD_MS = 600 * 1000 // 10 minutes
|
||||||
const DEAD_PROCESS_THRESHOLD_MS = 600 * 1000 // 10 minutes
|
|
||||||
|
|
||||||
const staleDocuments = docsToCheck.filter((doc) => {
|
const staleDocuments = documents.filter((doc) => {
|
||||||
if (doc.processingStatus !== 'processing' || !doc.processingStartedAt) {
|
if (doc.processingStatus !== 'processing' || !doc.processingStartedAt) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
const processingDuration = now.getTime() - new Date(doc.processingStartedAt).getTime()
|
const processingDuration = now.getTime() - new Date(doc.processingStartedAt).getTime()
|
||||||
return processingDuration > DEAD_PROCESS_THRESHOLD_MS
|
return processingDuration > DEAD_PROCESS_THRESHOLD_MS
|
||||||
})
|
})
|
||||||
|
|
||||||
if (staleDocuments.length === 0) return
|
if (staleDocuments.length === 0) return
|
||||||
|
|
||||||
logger.warn(`Found ${staleDocuments.length} documents with dead processes`)
|
logger.warn(`Found ${staleDocuments.length} documents with dead processes`)
|
||||||
|
|
||||||
staleDocuments.forEach((doc) => {
|
staleDocuments.forEach((doc) => {
|
||||||
updateDocumentMutation(
|
updateDocumentMutation(
|
||||||
{
|
{
|
||||||
knowledgeBaseId: id,
|
knowledgeBaseId: id,
|
||||||
documentId: doc.id,
|
documentId: doc.id,
|
||||||
updates: { markFailedDueToTimeout: true },
|
updates: { markFailedDueToTimeout: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
logger.info(`Successfully marked dead process as failed for document: ${doc.filename}`)
|
||||||
},
|
},
|
||||||
{
|
}
|
||||||
onSuccess: () => {
|
)
|
||||||
logger.info(
|
})
|
||||||
`Successfully marked dead process as failed for document: ${doc.filename}`
|
}
|
||||||
)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
})
|
|
||||||
},
|
|
||||||
[id, updateDocumentMutation]
|
|
||||||
)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (hasProcessingDocuments) {
|
|
||||||
checkForDeadProcesses(documents)
|
|
||||||
}
|
|
||||||
}, [hasProcessingDocuments, documents, checkForDeadProcesses])
|
|
||||||
|
|
||||||
const handleToggleEnabled = (docId: string) => {
|
const handleToggleEnabled = (docId: string) => {
|
||||||
const document = documents.find((doc) => doc.id === docId)
|
const document = documents.find((doc) => doc.id === docId)
|
||||||
@@ -677,7 +748,6 @@ export function KnowledgeBase({
|
|||||||
setSelectedDocuments(new Set(documents.map((doc) => doc.id)))
|
setSelectedDocuments(new Set(documents.map((doc) => doc.id)))
|
||||||
} else {
|
} else {
|
||||||
setSelectedDocuments(new Set())
|
setSelectedDocuments(new Set())
|
||||||
setIsSelectAllMode(false)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -723,26 +793,6 @@ export function KnowledgeBase({
|
|||||||
* Handles bulk enabling of selected documents
|
* Handles bulk enabling of selected documents
|
||||||
*/
|
*/
|
||||||
const handleBulkEnable = () => {
|
const handleBulkEnable = () => {
|
||||||
if (isSelectAllMode) {
|
|
||||||
bulkDocumentMutation(
|
|
||||||
{
|
|
||||||
knowledgeBaseId: id,
|
|
||||||
operation: 'enable',
|
|
||||||
selectAll: true,
|
|
||||||
enabledFilter,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onSuccess: (result) => {
|
|
||||||
logger.info(`Successfully enabled ${result.successCount} documents`)
|
|
||||||
setSelectedDocuments(new Set())
|
|
||||||
setIsSelectAllMode(false)
|
|
||||||
refreshDocuments()
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const documentsToEnable = documents.filter(
|
const documentsToEnable = documents.filter(
|
||||||
(doc) => selectedDocuments.has(doc.id) && !doc.enabled
|
(doc) => selectedDocuments.has(doc.id) && !doc.enabled
|
||||||
)
|
)
|
||||||
@@ -771,26 +821,6 @@ export function KnowledgeBase({
|
|||||||
* Handles bulk disabling of selected documents
|
* Handles bulk disabling of selected documents
|
||||||
*/
|
*/
|
||||||
const handleBulkDisable = () => {
|
const handleBulkDisable = () => {
|
||||||
if (isSelectAllMode) {
|
|
||||||
bulkDocumentMutation(
|
|
||||||
{
|
|
||||||
knowledgeBaseId: id,
|
|
||||||
operation: 'disable',
|
|
||||||
selectAll: true,
|
|
||||||
enabledFilter,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onSuccess: (result) => {
|
|
||||||
logger.info(`Successfully disabled ${result.successCount} documents`)
|
|
||||||
setSelectedDocuments(new Set())
|
|
||||||
setIsSelectAllMode(false)
|
|
||||||
refreshDocuments()
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const documentsToDisable = documents.filter(
|
const documentsToDisable = documents.filter(
|
||||||
(doc) => selectedDocuments.has(doc.id) && doc.enabled
|
(doc) => selectedDocuments.has(doc.id) && doc.enabled
|
||||||
)
|
)
|
||||||
@@ -815,35 +845,18 @@ export function KnowledgeBase({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens the bulk delete confirmation modal
|
||||||
|
*/
|
||||||
const handleBulkDelete = () => {
|
const handleBulkDelete = () => {
|
||||||
if (selectedDocuments.size === 0) return
|
if (selectedDocuments.size === 0) return
|
||||||
setShowBulkDeleteModal(true)
|
setShowBulkDeleteModal(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Confirms and executes the bulk deletion of selected documents
|
||||||
|
*/
|
||||||
const confirmBulkDelete = () => {
|
const confirmBulkDelete = () => {
|
||||||
if (isSelectAllMode) {
|
|
||||||
bulkDocumentMutation(
|
|
||||||
{
|
|
||||||
knowledgeBaseId: id,
|
|
||||||
operation: 'delete',
|
|
||||||
selectAll: true,
|
|
||||||
enabledFilter,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onSuccess: (result) => {
|
|
||||||
logger.info(`Successfully deleted ${result.successCount} documents`)
|
|
||||||
refreshDocuments()
|
|
||||||
setSelectedDocuments(new Set())
|
|
||||||
setIsSelectAllMode(false)
|
|
||||||
},
|
|
||||||
onSettled: () => {
|
|
||||||
setShowBulkDeleteModal(false)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const documentsToDelete = documents.filter((doc) => selectedDocuments.has(doc.id))
|
const documentsToDelete = documents.filter((doc) => selectedDocuments.has(doc.id))
|
||||||
|
|
||||||
if (documentsToDelete.length === 0) return
|
if (documentsToDelete.length === 0) return
|
||||||
@@ -868,17 +881,14 @@ export function KnowledgeBase({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const selectedDocumentsList = documents.filter((doc) => selectedDocuments.has(doc.id))
|
const selectedDocumentsList = documents.filter((doc) => selectedDocuments.has(doc.id))
|
||||||
const enabledCount = isSelectAllMode
|
const enabledCount = selectedDocumentsList.filter((doc) => doc.enabled).length
|
||||||
? enabledFilter === 'disabled'
|
const disabledCount = selectedDocumentsList.filter((doc) => !doc.enabled).length
|
||||||
? 0
|
|
||||||
: pagination.total
|
|
||||||
: selectedDocumentsList.filter((doc) => doc.enabled).length
|
|
||||||
const disabledCount = isSelectAllMode
|
|
||||||
? enabledFilter === 'enabled'
|
|
||||||
? 0
|
|
||||||
: pagination.total
|
|
||||||
: selectedDocumentsList.filter((doc) => !doc.enabled).length
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle right-click on a document row
|
||||||
|
* If right-clicking on an unselected document, select only that document
|
||||||
|
* If right-clicking on a selected document with multiple selections, keep all selections
|
||||||
|
*/
|
||||||
const handleDocumentContextMenu = useCallback(
|
const handleDocumentContextMenu = useCallback(
|
||||||
(e: React.MouseEvent, doc: DocumentData) => {
|
(e: React.MouseEvent, doc: DocumentData) => {
|
||||||
const isCurrentlySelected = selectedDocuments.has(doc.id)
|
const isCurrentlySelected = selectedDocuments.has(doc.id)
|
||||||
@@ -995,13 +1005,11 @@ export function KnowledgeBase({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
{knowledgeBase?.description && (
|
||||||
{knowledgeBase?.description && (
|
<p className='mt-[4px] line-clamp-2 max-w-[40vw] font-medium text-[14px] text-[var(--text-tertiary)]'>
|
||||||
<p className='mt-[4px] line-clamp-2 max-w-[40vw] font-medium text-[14px] text-[var(--text-tertiary)]'>
|
{knowledgeBase.description}
|
||||||
{knowledgeBase.description}
|
</p>
|
||||||
</p>
|
)}
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className='mt-[16px] flex items-center gap-[8px]'>
|
<div className='mt-[16px] flex items-center gap-[8px]'>
|
||||||
<span className='text-[14px] text-[var(--text-muted)]'>
|
<span className='text-[14px] text-[var(--text-muted)]'>
|
||||||
@@ -1044,76 +1052,21 @@ export function KnowledgeBase({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='flex items-center gap-[8px]'>
|
<Tooltip.Root>
|
||||||
<Popover open={isFilterPopoverOpen} onOpenChange={setIsFilterPopoverOpen}>
|
<Tooltip.Trigger asChild>
|
||||||
<PopoverTrigger asChild>
|
<Button
|
||||||
<Button variant='default' className='h-[32px] rounded-[6px]'>
|
onClick={handleAddDocuments}
|
||||||
{enabledFilter === 'all'
|
disabled={userPermissions.canEdit !== true}
|
||||||
? 'All'
|
variant='tertiary'
|
||||||
: enabledFilter === 'enabled'
|
className='h-[32px] rounded-[6px]'
|
||||||
? 'Enabled'
|
>
|
||||||
: 'Disabled'}
|
Add Documents
|
||||||
<ChevronDown className='ml-2 h-4 w-4 text-muted-foreground' />
|
</Button>
|
||||||
</Button>
|
</Tooltip.Trigger>
|
||||||
</PopoverTrigger>
|
{userPermissions.canEdit !== true && (
|
||||||
<PopoverContent align='end' side='bottom' sideOffset={4}>
|
<Tooltip.Content>Write permission required to add documents</Tooltip.Content>
|
||||||
<div className='flex flex-col gap-[2px]'>
|
)}
|
||||||
<PopoverItem
|
</Tooltip.Root>
|
||||||
active={enabledFilter === 'all'}
|
|
||||||
onClick={() => {
|
|
||||||
setEnabledFilter('all')
|
|
||||||
setIsFilterPopoverOpen(false)
|
|
||||||
setCurrentPage(1)
|
|
||||||
setSelectedDocuments(new Set())
|
|
||||||
setIsSelectAllMode(false)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
All
|
|
||||||
</PopoverItem>
|
|
||||||
<PopoverItem
|
|
||||||
active={enabledFilter === 'enabled'}
|
|
||||||
onClick={() => {
|
|
||||||
setEnabledFilter('enabled')
|
|
||||||
setIsFilterPopoverOpen(false)
|
|
||||||
setCurrentPage(1)
|
|
||||||
setSelectedDocuments(new Set())
|
|
||||||
setIsSelectAllMode(false)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Enabled
|
|
||||||
</PopoverItem>
|
|
||||||
<PopoverItem
|
|
||||||
active={enabledFilter === 'disabled'}
|
|
||||||
onClick={() => {
|
|
||||||
setEnabledFilter('disabled')
|
|
||||||
setIsFilterPopoverOpen(false)
|
|
||||||
setCurrentPage(1)
|
|
||||||
setSelectedDocuments(new Set())
|
|
||||||
setIsSelectAllMode(false)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Disabled
|
|
||||||
</PopoverItem>
|
|
||||||
</div>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
|
|
||||||
<Tooltip.Root>
|
|
||||||
<Tooltip.Trigger asChild>
|
|
||||||
<Button
|
|
||||||
onClick={handleAddDocuments}
|
|
||||||
disabled={userPermissions.canEdit !== true}
|
|
||||||
variant='tertiary'
|
|
||||||
className='h-[32px] rounded-[6px]'
|
|
||||||
>
|
|
||||||
Add Documents
|
|
||||||
</Button>
|
|
||||||
</Tooltip.Trigger>
|
|
||||||
{userPermissions.canEdit !== true && (
|
|
||||||
<Tooltip.Content>Write permission required to add documents</Tooltip.Content>
|
|
||||||
)}
|
|
||||||
</Tooltip.Root>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error && !isLoadingKnowledgeBase && (
|
{error && !isLoadingKnowledgeBase && (
|
||||||
@@ -1136,20 +1089,14 @@ export function KnowledgeBase({
|
|||||||
<div className='mt-[10px] flex h-64 items-center justify-center rounded-lg border border-muted-foreground/25 bg-muted/20'>
|
<div className='mt-[10px] flex h-64 items-center justify-center rounded-lg border border-muted-foreground/25 bg-muted/20'>
|
||||||
<div className='text-center'>
|
<div className='text-center'>
|
||||||
<p className='font-medium text-[var(--text-secondary)] text-sm'>
|
<p className='font-medium text-[var(--text-secondary)] text-sm'>
|
||||||
{searchQuery
|
{searchQuery ? 'No documents found' : 'No documents yet'}
|
||||||
? 'No documents found'
|
|
||||||
: enabledFilter !== 'all'
|
|
||||||
? 'Nothing matches your filter'
|
|
||||||
: 'No documents yet'}
|
|
||||||
</p>
|
</p>
|
||||||
<p className='mt-1 text-[var(--text-muted)] text-xs'>
|
<p className='mt-1 text-[var(--text-muted)] text-xs'>
|
||||||
{searchQuery
|
{searchQuery
|
||||||
? 'Try a different search term'
|
? 'Try a different search term'
|
||||||
: enabledFilter !== 'all'
|
: userPermissions.canEdit === true
|
||||||
? 'Try changing the filter'
|
? 'Add documents to get started'
|
||||||
: userPermissions.canEdit === true
|
: 'Documents will appear here once added'}
|
||||||
? 'Add documents to get started'
|
|
||||||
: 'Documents will appear here once added'}
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1173,7 +1120,7 @@ export function KnowledgeBase({
|
|||||||
{renderSortableHeader('tokenCount', 'Tokens', 'hidden w-[8%] lg:table-cell')}
|
{renderSortableHeader('tokenCount', 'Tokens', 'hidden w-[8%] lg:table-cell')}
|
||||||
{renderSortableHeader('chunkCount', 'Chunks', 'w-[8%]')}
|
{renderSortableHeader('chunkCount', 'Chunks', 'w-[8%]')}
|
||||||
{renderSortableHeader('uploadedAt', 'Uploaded', 'w-[11%]')}
|
{renderSortableHeader('uploadedAt', 'Uploaded', 'w-[11%]')}
|
||||||
{renderSortableHeader('enabled', 'Status', 'w-[10%]')}
|
{renderSortableHeader('processingStatus', 'Status', 'w-[10%]')}
|
||||||
<TableHead className='w-[12%] px-[12px] py-[8px] text-[12px] text-[var(--text-secondary)]'>
|
<TableHead className='w-[12%] px-[12px] py-[8px] text-[12px] text-[var(--text-secondary)]'>
|
||||||
Tags
|
Tags
|
||||||
</TableHead>
|
</TableHead>
|
||||||
@@ -1217,10 +1164,7 @@ export function KnowledgeBase({
|
|||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className='w-[180px] max-w-[180px] px-[12px] py-[8px]'>
|
<TableCell className='w-[180px] max-w-[180px] px-[12px] py-[8px]'>
|
||||||
<div className='flex min-w-0 items-center gap-[8px]'>
|
<div className='flex min-w-0 items-center gap-[8px]'>
|
||||||
{(() => {
|
{getFileIcon(doc.mimeType, doc.filename)}
|
||||||
const IconComponent = getDocumentIcon(doc.mimeType, doc.filename)
|
|
||||||
return <IconComponent className='h-6 w-5 flex-shrink-0' />
|
|
||||||
})()}
|
|
||||||
<Tooltip.Root>
|
<Tooltip.Root>
|
||||||
<Tooltip.Trigger asChild>
|
<Tooltip.Trigger asChild>
|
||||||
<span
|
<span
|
||||||
@@ -1564,14 +1508,6 @@ export function KnowledgeBase({
|
|||||||
enabledCount={enabledCount}
|
enabledCount={enabledCount}
|
||||||
disabledCount={disabledCount}
|
disabledCount={disabledCount}
|
||||||
isLoading={isBulkOperating}
|
isLoading={isBulkOperating}
|
||||||
totalCount={pagination.total}
|
|
||||||
isAllPageSelected={isAllSelected}
|
|
||||||
isAllSelected={isSelectAllMode}
|
|
||||||
onSelectAll={() => setIsSelectAllMode(true)}
|
|
||||||
onClearSelectAll={() => {
|
|
||||||
setIsSelectAllMode(false)
|
|
||||||
setSelectedDocuments(new Set())
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<DocumentContextMenu
|
<DocumentContextMenu
|
||||||
|
|||||||
@@ -13,11 +13,6 @@ interface ActionBarProps {
|
|||||||
disabledCount?: number
|
disabledCount?: number
|
||||||
isLoading?: boolean
|
isLoading?: boolean
|
||||||
className?: string
|
className?: string
|
||||||
totalCount?: number
|
|
||||||
isAllPageSelected?: boolean
|
|
||||||
isAllSelected?: boolean
|
|
||||||
onSelectAll?: () => void
|
|
||||||
onClearSelectAll?: () => void
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ActionBar({
|
export function ActionBar({
|
||||||
@@ -29,21 +24,14 @@ export function ActionBar({
|
|||||||
disabledCount = 0,
|
disabledCount = 0,
|
||||||
isLoading = false,
|
isLoading = false,
|
||||||
className,
|
className,
|
||||||
totalCount = 0,
|
|
||||||
isAllPageSelected = false,
|
|
||||||
isAllSelected = false,
|
|
||||||
onSelectAll,
|
|
||||||
onClearSelectAll,
|
|
||||||
}: ActionBarProps) {
|
}: ActionBarProps) {
|
||||||
const userPermissions = useUserPermissionsContext()
|
const userPermissions = useUserPermissionsContext()
|
||||||
|
|
||||||
if (selectedCount === 0 && !isAllSelected) return null
|
if (selectedCount === 0) return null
|
||||||
|
|
||||||
const canEdit = userPermissions.canEdit
|
const canEdit = userPermissions.canEdit
|
||||||
const showEnableButton = disabledCount > 0 && onEnable && canEdit
|
const showEnableButton = disabledCount > 0 && onEnable && canEdit
|
||||||
const showDisableButton = enabledCount > 0 && onDisable && canEdit
|
const showDisableButton = enabledCount > 0 && onDisable && canEdit
|
||||||
const showSelectAllOption =
|
|
||||||
isAllPageSelected && !isAllSelected && totalCount > selectedCount && onSelectAll
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<motion.div
|
<motion.div
|
||||||
@@ -55,31 +43,7 @@ export function ActionBar({
|
|||||||
>
|
>
|
||||||
<div className='flex items-center gap-[8px] rounded-[10px] border border-[var(--border)] bg-[var(--surface-2)] px-[8px] py-[6px]'>
|
<div className='flex items-center gap-[8px] rounded-[10px] border border-[var(--border)] bg-[var(--surface-2)] px-[8px] py-[6px]'>
|
||||||
<span className='px-[4px] text-[13px] text-[var(--text-secondary)]'>
|
<span className='px-[4px] text-[13px] text-[var(--text-secondary)]'>
|
||||||
{isAllSelected ? totalCount : selectedCount} selected
|
{selectedCount} selected
|
||||||
{showSelectAllOption && (
|
|
||||||
<>
|
|
||||||
{' · '}
|
|
||||||
<button
|
|
||||||
type='button'
|
|
||||||
onClick={onSelectAll}
|
|
||||||
className='text-[var(--brand-primary)] hover:underline'
|
|
||||||
>
|
|
||||||
Select all
|
|
||||||
</button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{isAllSelected && onClearSelectAll && (
|
|
||||||
<>
|
|
||||||
{' · '}
|
|
||||||
<button
|
|
||||||
type='button'
|
|
||||||
onClick={onClearSelectAll}
|
|
||||||
className='text-[var(--brand-primary)] hover:underline'
|
|
||||||
>
|
|
||||||
Clear
|
|
||||||
</button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
<div className='flex items-center gap-[5px]'>
|
<div className='flex items-center gap-[5px]'>
|
||||||
|
|||||||
@@ -123,11 +123,7 @@ export function RenameDocumentModal({
|
|||||||
>
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button variant='tertiary' type='submit' disabled={isSubmitting || !name?.trim()}>
|
||||||
variant='tertiary'
|
|
||||||
type='submit'
|
|
||||||
disabled={isSubmitting || !name?.trim() || name.trim() === initialName}
|
|
||||||
>
|
|
||||||
{isSubmitting ? 'Renaming...' : 'Rename'}
|
{isSubmitting ? 'Renaming...' : 'Rename'}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
import { useCallback, useState } from 'react'
|
import { useCallback, useState } from 'react'
|
||||||
import { useParams, useRouter } from 'next/navigation'
|
import { useParams, useRouter } from 'next/navigation'
|
||||||
import { Badge, DocumentAttachment, Tooltip } from '@/components/emcn'
|
import { Badge, DocumentAttachment, Tooltip } from '@/components/emcn'
|
||||||
import { formatAbsoluteDate, formatRelativeTime } from '@/lib/core/utils/formatting'
|
|
||||||
import { BaseTagsModal } from '@/app/workspace/[workspaceId]/knowledge/[id]/components'
|
import { BaseTagsModal } from '@/app/workspace/[workspaceId]/knowledge/[id]/components'
|
||||||
import { useUserPermissionsContext } from '@/app/workspace/[workspaceId]/providers/workspace-permissions-provider'
|
import { useUserPermissionsContext } from '@/app/workspace/[workspaceId]/providers/workspace-permissions-provider'
|
||||||
import { useContextMenu } from '@/app/workspace/[workspaceId]/w/components/sidebar/hooks'
|
import { useContextMenu } from '@/app/workspace/[workspaceId]/w/components/sidebar/hooks'
|
||||||
@@ -22,6 +21,55 @@ interface BaseCardProps {
|
|||||||
onDelete?: (id: string) => Promise<void>
|
onDelete?: (id: string) => Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats a date string to relative time (e.g., "2h ago", "3d ago")
|
||||||
|
*/
|
||||||
|
function formatRelativeTime(dateString: string): string {
|
||||||
|
const date = new Date(dateString)
|
||||||
|
const now = new Date()
|
||||||
|
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000)
|
||||||
|
|
||||||
|
if (diffInSeconds < 60) {
|
||||||
|
return 'just now'
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 3600) {
|
||||||
|
const minutes = Math.floor(diffInSeconds / 60)
|
||||||
|
return `${minutes}m ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 86400) {
|
||||||
|
const hours = Math.floor(diffInSeconds / 3600)
|
||||||
|
return `${hours}h ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 604800) {
|
||||||
|
const days = Math.floor(diffInSeconds / 86400)
|
||||||
|
return `${days}d ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 2592000) {
|
||||||
|
const weeks = Math.floor(diffInSeconds / 604800)
|
||||||
|
return `${weeks}w ago`
|
||||||
|
}
|
||||||
|
if (diffInSeconds < 31536000) {
|
||||||
|
const months = Math.floor(diffInSeconds / 2592000)
|
||||||
|
return `${months}mo ago`
|
||||||
|
}
|
||||||
|
const years = Math.floor(diffInSeconds / 31536000)
|
||||||
|
return `${years}y ago`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats a date string to absolute format for tooltip display
|
||||||
|
*/
|
||||||
|
function formatAbsoluteDate(dateString: string): string {
|
||||||
|
const date = new Date(dateString)
|
||||||
|
return date.toLocaleDateString('en-US', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Skeleton placeholder for a knowledge base card
|
* Skeleton placeholder for a knowledge base card
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -344,51 +344,53 @@ export function CreateBaseModal({ open, onOpenChange }: CreateBaseModalProps) {
|
|||||||
<Textarea
|
<Textarea
|
||||||
id='description'
|
id='description'
|
||||||
placeholder='Describe this knowledge base (optional)'
|
placeholder='Describe this knowledge base (optional)'
|
||||||
rows={4}
|
rows={3}
|
||||||
{...register('description')}
|
{...register('description')}
|
||||||
className={cn(errors.description && 'border-[var(--text-error)]')}
|
className={cn(errors.description && 'border-[var(--text-error)]')}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='grid grid-cols-2 gap-[12px]'>
|
<div className='space-y-[12px] rounded-[6px] bg-[var(--surface-5)] px-[12px] py-[14px]'>
|
||||||
<div className='flex flex-col gap-[8px]'>
|
<div className='grid grid-cols-2 gap-[12px]'>
|
||||||
<Label htmlFor='minChunkSize'>Min Chunk Size (characters)</Label>
|
<div className='flex flex-col gap-[8px]'>
|
||||||
<Input
|
<Label htmlFor='minChunkSize'>Min Chunk Size (characters)</Label>
|
||||||
id='minChunkSize'
|
<Input
|
||||||
placeholder='100'
|
id='minChunkSize'
|
||||||
{...register('minChunkSize', { valueAsNumber: true })}
|
placeholder='100'
|
||||||
className={cn(errors.minChunkSize && 'border-[var(--text-error)]')}
|
{...register('minChunkSize', { valueAsNumber: true })}
|
||||||
autoComplete='off'
|
className={cn(errors.minChunkSize && 'border-[var(--text-error)]')}
|
||||||
data-form-type='other'
|
autoComplete='off'
|
||||||
name='min-chunk-size'
|
data-form-type='other'
|
||||||
/>
|
name='min-chunk-size'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='flex flex-col gap-[8px]'>
|
||||||
|
<Label htmlFor='maxChunkSize'>Max Chunk Size (tokens)</Label>
|
||||||
|
<Input
|
||||||
|
id='maxChunkSize'
|
||||||
|
placeholder='1024'
|
||||||
|
{...register('maxChunkSize', { valueAsNumber: true })}
|
||||||
|
className={cn(errors.maxChunkSize && 'border-[var(--text-error)]')}
|
||||||
|
autoComplete='off'
|
||||||
|
data-form-type='other'
|
||||||
|
name='max-chunk-size'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='flex flex-col gap-[8px]'>
|
<div className='flex flex-col gap-[8px]'>
|
||||||
<Label htmlFor='maxChunkSize'>Max Chunk Size (tokens)</Label>
|
<Label htmlFor='overlapSize'>Overlap (tokens)</Label>
|
||||||
<Input
|
<Input
|
||||||
id='maxChunkSize'
|
id='overlapSize'
|
||||||
placeholder='1024'
|
placeholder='200'
|
||||||
{...register('maxChunkSize', { valueAsNumber: true })}
|
{...register('overlapSize', { valueAsNumber: true })}
|
||||||
className={cn(errors.maxChunkSize && 'border-[var(--text-error)]')}
|
className={cn(errors.overlapSize && 'border-[var(--text-error)]')}
|
||||||
autoComplete='off'
|
autoComplete='off'
|
||||||
data-form-type='other'
|
data-form-type='other'
|
||||||
name='max-chunk-size'
|
name='overlap-size'
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className='flex flex-col gap-[8px]'>
|
|
||||||
<Label htmlFor='overlapSize'>Overlap (tokens)</Label>
|
|
||||||
<Input
|
|
||||||
id='overlapSize'
|
|
||||||
placeholder='200'
|
|
||||||
{...register('overlapSize', { valueAsNumber: true })}
|
|
||||||
className={cn(errors.overlapSize && 'border-[var(--text-error)]')}
|
|
||||||
autoComplete='off'
|
|
||||||
data-form-type='other'
|
|
||||||
name='overlap-size'
|
|
||||||
/>
|
|
||||||
<p className='text-[11px] text-[var(--text-muted)]'>
|
<p className='text-[11px] text-[var(--text-muted)]'>
|
||||||
1 token ≈ 4 characters. Max chunk size and overlap are in tokens.
|
1 token ≈ 4 characters. Max chunk size and overlap are in tokens.
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ export function EditKnowledgeBaseModal({
|
|||||||
handleSubmit,
|
handleSubmit,
|
||||||
reset,
|
reset,
|
||||||
watch,
|
watch,
|
||||||
formState: { errors, isDirty },
|
formState: { errors },
|
||||||
} = useForm<FormValues>({
|
} = useForm<FormValues>({
|
||||||
resolver: zodResolver(FormSchema),
|
resolver: zodResolver(FormSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
@@ -127,7 +127,7 @@ export function EditKnowledgeBaseModal({
|
|||||||
<Textarea
|
<Textarea
|
||||||
id='description'
|
id='description'
|
||||||
placeholder='Describe this knowledge base (optional)'
|
placeholder='Describe this knowledge base (optional)'
|
||||||
rows={4}
|
rows={3}
|
||||||
{...register('description')}
|
{...register('description')}
|
||||||
className={cn(errors.description && 'border-[var(--text-error)]')}
|
className={cn(errors.description && 'border-[var(--text-error)]')}
|
||||||
/>
|
/>
|
||||||
@@ -161,7 +161,7 @@ export function EditKnowledgeBaseModal({
|
|||||||
<Button
|
<Button
|
||||||
variant='tertiary'
|
variant='tertiary'
|
||||||
type='submit'
|
type='submit'
|
||||||
disabled={isSubmitting || !nameValue?.trim() || !isDirty}
|
disabled={isSubmitting || !nameValue?.trim()}
|
||||||
>
|
>
|
||||||
{isSubmitting ? 'Saving...' : 'Save'}
|
{isSubmitting ? 'Saving...' : 'Save'}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
import type React from 'react'
|
import type React from 'react'
|
||||||
import { memo, useCallback, useMemo, useRef, useState } from 'react'
|
import { memo, useCallback, useMemo, useRef, useState } from 'react'
|
||||||
import { ArrowDown, ArrowUp, Check, Clipboard, Search, X } from 'lucide-react'
|
import clsx from 'clsx'
|
||||||
|
import { ArrowDown, ArrowUp, X } from 'lucide-react'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
@@ -14,11 +15,9 @@ import {
|
|||||||
PopoverContent,
|
PopoverContent,
|
||||||
PopoverDivider,
|
PopoverDivider,
|
||||||
PopoverItem,
|
PopoverItem,
|
||||||
Tooltip,
|
|
||||||
} from '@/components/emcn'
|
} from '@/components/emcn'
|
||||||
import { WorkflowIcon } from '@/components/icons'
|
import { WorkflowIcon } from '@/components/icons'
|
||||||
import { cn } from '@/lib/core/utils/cn'
|
import { cn } from '@/lib/core/utils/cn'
|
||||||
import { formatDuration } from '@/lib/core/utils/formatting'
|
|
||||||
import { LoopTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/subflows/loop/loop-config'
|
import { LoopTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/subflows/loop/loop-config'
|
||||||
import { ParallelTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/subflows/parallel/parallel-config'
|
import { ParallelTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/subflows/parallel/parallel-config'
|
||||||
import { getBlock, getBlockByToolName } from '@/blocks'
|
import { getBlock, getBlockByToolName } from '@/blocks'
|
||||||
@@ -27,6 +26,7 @@ import type { TraceSpan } from '@/stores/logs/filters/types'
|
|||||||
|
|
||||||
interface TraceSpansProps {
|
interface TraceSpansProps {
|
||||||
traceSpans?: TraceSpan[]
|
traceSpans?: TraceSpan[]
|
||||||
|
totalDuration?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -100,20 +100,6 @@ function parseTime(value?: string | number | null): number {
|
|||||||
return Number.isFinite(ms) ? ms : 0
|
return Number.isFinite(ms) ? ms : 0
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if a span or any of its descendants has an error
|
|
||||||
*/
|
|
||||||
function hasErrorInTree(span: TraceSpan): boolean {
|
|
||||||
if (span.status === 'error') return true
|
|
||||||
if (span.children && span.children.length > 0) {
|
|
||||||
return span.children.some((child) => hasErrorInTree(child))
|
|
||||||
}
|
|
||||||
if (span.toolCalls && span.toolCalls.length > 0) {
|
|
||||||
return span.toolCalls.some((tc) => tc.error)
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalizes and sorts trace spans recursively.
|
* Normalizes and sorts trace spans recursively.
|
||||||
* Merges children from both span.children and span.output.childTraceSpans,
|
* Merges children from both span.children and span.output.childTraceSpans,
|
||||||
@@ -156,6 +142,14 @@ function normalizeAndSortSpans(spans: TraceSpan[]): TraceSpan[] {
|
|||||||
|
|
||||||
const DEFAULT_BLOCK_COLOR = '#6b7280'
|
const DEFAULT_BLOCK_COLOR = '#6b7280'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats duration in ms
|
||||||
|
*/
|
||||||
|
function formatDuration(ms: number): string {
|
||||||
|
if (ms < 1000) return `${ms}ms`
|
||||||
|
return `${(ms / 1000).toFixed(2)}s`
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets icon and color for a span type using block config
|
* Gets icon and color for a span type using block config
|
||||||
*/
|
*/
|
||||||
@@ -236,7 +230,7 @@ function ProgressBar({
|
|||||||
}, [span, childSpans, workflowStartTime, totalDuration])
|
}, [span, childSpans, workflowStartTime, totalDuration])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='relative h-[5px] w-full overflow-hidden rounded-[18px] bg-[var(--divider)]'>
|
<div className='relative mb-[8px] h-[5px] w-full overflow-hidden rounded-[18px] bg-[var(--divider)]'>
|
||||||
{segments.map((segment, index) => (
|
{segments.map((segment, index) => (
|
||||||
<div
|
<div
|
||||||
key={index}
|
key={index}
|
||||||
@@ -252,6 +246,143 @@ function ProgressBar({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ExpandableRowHeaderProps {
|
||||||
|
name: string
|
||||||
|
duration: number
|
||||||
|
isError: boolean
|
||||||
|
isExpanded: boolean
|
||||||
|
hasChildren: boolean
|
||||||
|
showIcon: boolean
|
||||||
|
icon: React.ComponentType<{ className?: string }> | null
|
||||||
|
bgColor: string
|
||||||
|
onToggle: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reusable expandable row header with chevron, icon, name, and duration
|
||||||
|
*/
|
||||||
|
function ExpandableRowHeader({
|
||||||
|
name,
|
||||||
|
duration,
|
||||||
|
isError,
|
||||||
|
isExpanded,
|
||||||
|
hasChildren,
|
||||||
|
showIcon,
|
||||||
|
icon: Icon,
|
||||||
|
bgColor,
|
||||||
|
onToggle,
|
||||||
|
}: ExpandableRowHeaderProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={clsx('group flex items-center justify-between', hasChildren && 'cursor-pointer')}
|
||||||
|
onClick={hasChildren ? onToggle : undefined}
|
||||||
|
onKeyDown={
|
||||||
|
hasChildren
|
||||||
|
? (e) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault()
|
||||||
|
onToggle()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
role={hasChildren ? 'button' : undefined}
|
||||||
|
tabIndex={hasChildren ? 0 : undefined}
|
||||||
|
aria-expanded={hasChildren ? isExpanded : undefined}
|
||||||
|
aria-label={hasChildren ? (isExpanded ? 'Collapse' : 'Expand') : undefined}
|
||||||
|
>
|
||||||
|
<div className='flex items-center gap-[8px]'>
|
||||||
|
{hasChildren && (
|
||||||
|
<ChevronDown
|
||||||
|
className='h-[10px] w-[10px] flex-shrink-0 text-[var(--text-tertiary)] transition-transform duration-100 group-hover:text-[var(--text-primary)]'
|
||||||
|
style={{ transform: isExpanded ? 'rotate(0deg)' : 'rotate(-90deg)' }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{showIcon && (
|
||||||
|
<div
|
||||||
|
className='relative flex h-[14px] w-[14px] flex-shrink-0 items-center justify-center overflow-hidden rounded-[4px]'
|
||||||
|
style={{ background: bgColor }}
|
||||||
|
>
|
||||||
|
{Icon && <Icon className={clsx('text-white', '!h-[9px] !w-[9px]')} />}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<span
|
||||||
|
className='font-medium text-[12px]'
|
||||||
|
style={{ color: isError ? 'var(--text-error)' : 'var(--text-secondary)' }}
|
||||||
|
>
|
||||||
|
{name}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>
|
||||||
|
{formatDuration(duration)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SpanContentProps {
|
||||||
|
span: TraceSpan
|
||||||
|
spanId: string
|
||||||
|
isError: boolean
|
||||||
|
workflowStartTime: number
|
||||||
|
totalDuration: number
|
||||||
|
expandedSections: Set<string>
|
||||||
|
onToggle: (section: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reusable component for rendering span content (progress bar + input/output sections)
|
||||||
|
*/
|
||||||
|
function SpanContent({
|
||||||
|
span,
|
||||||
|
spanId,
|
||||||
|
isError,
|
||||||
|
workflowStartTime,
|
||||||
|
totalDuration,
|
||||||
|
expandedSections,
|
||||||
|
onToggle,
|
||||||
|
}: SpanContentProps) {
|
||||||
|
const hasInput = Boolean(span.input)
|
||||||
|
const hasOutput = Boolean(span.output)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<ProgressBar
|
||||||
|
span={span}
|
||||||
|
childSpans={span.children}
|
||||||
|
workflowStartTime={workflowStartTime}
|
||||||
|
totalDuration={totalDuration}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{hasInput && (
|
||||||
|
<InputOutputSection
|
||||||
|
label='Input'
|
||||||
|
data={span.input}
|
||||||
|
isError={false}
|
||||||
|
spanId={spanId}
|
||||||
|
sectionType='input'
|
||||||
|
expandedSections={expandedSections}
|
||||||
|
onToggle={onToggle}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hasInput && hasOutput && <div className='border-[var(--border)] border-t border-dashed' />}
|
||||||
|
|
||||||
|
{hasOutput && (
|
||||||
|
<InputOutputSection
|
||||||
|
label={isError ? 'Error' : 'Output'}
|
||||||
|
data={span.output}
|
||||||
|
isError={isError}
|
||||||
|
spanId={spanId}
|
||||||
|
sectionType='output'
|
||||||
|
expandedSections={expandedSections}
|
||||||
|
onToggle={onToggle}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders input/output section with collapsible content, context menu, and search
|
* Renders input/output section with collapsible content, context menu, and search
|
||||||
*/
|
*/
|
||||||
@@ -275,14 +406,16 @@ function InputOutputSection({
|
|||||||
const sectionKey = `${spanId}-${sectionType}`
|
const sectionKey = `${spanId}-${sectionType}`
|
||||||
const isExpanded = expandedSections.has(sectionKey)
|
const isExpanded = expandedSections.has(sectionKey)
|
||||||
const contentRef = useRef<HTMLDivElement>(null)
|
const contentRef = useRef<HTMLDivElement>(null)
|
||||||
|
const menuRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
// Context menu state
|
// Context menu state
|
||||||
const [isContextMenuOpen, setIsContextMenuOpen] = useState(false)
|
const [isContextMenuOpen, setIsContextMenuOpen] = useState(false)
|
||||||
const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 })
|
const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 })
|
||||||
const [copied, setCopied] = useState(false)
|
|
||||||
|
|
||||||
// Code viewer features
|
// Code viewer features
|
||||||
const {
|
const {
|
||||||
|
wrapText,
|
||||||
|
toggleWrapText,
|
||||||
isSearchActive,
|
isSearchActive,
|
||||||
searchQuery,
|
searchQuery,
|
||||||
setSearchQuery,
|
setSearchQuery,
|
||||||
@@ -314,8 +447,6 @@ function InputOutputSection({
|
|||||||
|
|
||||||
const handleCopy = useCallback(() => {
|
const handleCopy = useCallback(() => {
|
||||||
navigator.clipboard.writeText(jsonString)
|
navigator.clipboard.writeText(jsonString)
|
||||||
setCopied(true)
|
|
||||||
setTimeout(() => setCopied(false), 1500)
|
|
||||||
closeContextMenu()
|
closeContextMenu()
|
||||||
}, [jsonString, closeContextMenu])
|
}, [jsonString, closeContextMenu])
|
||||||
|
|
||||||
@@ -324,8 +455,13 @@ function InputOutputSection({
|
|||||||
closeContextMenu()
|
closeContextMenu()
|
||||||
}, [activateSearch, closeContextMenu])
|
}, [activateSearch, closeContextMenu])
|
||||||
|
|
||||||
|
const handleToggleWrap = useCallback(() => {
|
||||||
|
toggleWrapText()
|
||||||
|
closeContextMenu()
|
||||||
|
}, [toggleWrapText, closeContextMenu])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='relative flex min-w-0 flex-col gap-[6px] overflow-hidden'>
|
<div className='relative flex min-w-0 flex-col gap-[8px] overflow-hidden'>
|
||||||
<div
|
<div
|
||||||
className='group flex cursor-pointer items-center justify-between'
|
className='group flex cursor-pointer items-center justify-between'
|
||||||
onClick={() => onToggle(sectionKey)}
|
onClick={() => onToggle(sectionKey)}
|
||||||
@@ -341,7 +477,7 @@ function InputOutputSection({
|
|||||||
aria-label={`${isExpanded ? 'Collapse' : 'Expand'} ${label.toLowerCase()}`}
|
aria-label={`${isExpanded ? 'Collapse' : 'Expand'} ${label.toLowerCase()}`}
|
||||||
>
|
>
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={clsx(
|
||||||
'font-medium text-[12px] transition-colors',
|
'font-medium text-[12px] transition-colors',
|
||||||
isError
|
isError
|
||||||
? 'text-[var(--text-error)]'
|
? 'text-[var(--text-error)]'
|
||||||
@@ -351,7 +487,9 @@ function InputOutputSection({
|
|||||||
{label}
|
{label}
|
||||||
</span>
|
</span>
|
||||||
<ChevronDown
|
<ChevronDown
|
||||||
className='h-[8px] w-[8px] text-[var(--text-tertiary)] transition-colors transition-transform group-hover:text-[var(--text-primary)]'
|
className={clsx(
|
||||||
|
'h-[10px] w-[10px] text-[var(--text-tertiary)] transition-colors transition-transform group-hover:text-[var(--text-primary)]'
|
||||||
|
)}
|
||||||
style={{
|
style={{
|
||||||
transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
|
transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
|
||||||
}}
|
}}
|
||||||
@@ -359,57 +497,16 @@ function InputOutputSection({
|
|||||||
</div>
|
</div>
|
||||||
{isExpanded && (
|
{isExpanded && (
|
||||||
<>
|
<>
|
||||||
<div ref={contentRef} onContextMenu={handleContextMenu} className='relative'>
|
<div ref={contentRef} onContextMenu={handleContextMenu}>
|
||||||
<Code.Viewer
|
<Code.Viewer
|
||||||
code={jsonString}
|
code={jsonString}
|
||||||
language='json'
|
language='json'
|
||||||
className='!bg-[var(--surface-4)] dark:!bg-[var(--surface-3)] max-h-[300px] min-h-0 max-w-full rounded-[6px] border-0 [word-break:break-all]'
|
className='!bg-[var(--surface-3)] max-h-[300px] min-h-0 max-w-full rounded-[6px] border-0 [word-break:break-all]'
|
||||||
wrapText
|
wrapText={wrapText}
|
||||||
searchQuery={isSearchActive ? searchQuery : undefined}
|
searchQuery={isSearchActive ? searchQuery : undefined}
|
||||||
currentMatchIndex={currentMatchIndex}
|
currentMatchIndex={currentMatchIndex}
|
||||||
onMatchCountChange={handleMatchCountChange}
|
onMatchCountChange={handleMatchCountChange}
|
||||||
/>
|
/>
|
||||||
{/* Glass action buttons overlay */}
|
|
||||||
{!isSearchActive && (
|
|
||||||
<div className='absolute top-[7px] right-[6px] z-10 flex gap-[4px]'>
|
|
||||||
<Tooltip.Root>
|
|
||||||
<Tooltip.Trigger asChild>
|
|
||||||
<Button
|
|
||||||
type='button'
|
|
||||||
variant='default'
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation()
|
|
||||||
handleCopy()
|
|
||||||
}}
|
|
||||||
className='h-[20px] w-[20px] cursor-pointer border border-[var(--border-1)] bg-transparent p-0 backdrop-blur-sm hover:bg-[var(--surface-3)]'
|
|
||||||
>
|
|
||||||
{copied ? (
|
|
||||||
<Check className='h-[10px] w-[10px] text-[var(--text-success)]' />
|
|
||||||
) : (
|
|
||||||
<Clipboard className='h-[10px] w-[10px]' />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</Tooltip.Trigger>
|
|
||||||
<Tooltip.Content side='top'>{copied ? 'Copied' : 'Copy'}</Tooltip.Content>
|
|
||||||
</Tooltip.Root>
|
|
||||||
<Tooltip.Root>
|
|
||||||
<Tooltip.Trigger asChild>
|
|
||||||
<Button
|
|
||||||
type='button'
|
|
||||||
variant='default'
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation()
|
|
||||||
activateSearch()
|
|
||||||
}}
|
|
||||||
className='h-[20px] w-[20px] cursor-pointer border border-[var(--border-1)] bg-transparent p-0 backdrop-blur-sm hover:bg-[var(--surface-3)]'
|
|
||||||
>
|
|
||||||
<Search className='h-[10px] w-[10px]' />
|
|
||||||
</Button>
|
|
||||||
</Tooltip.Trigger>
|
|
||||||
<Tooltip.Content side='top'>Search</Tooltip.Content>
|
|
||||||
</Tooltip.Root>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Search Overlay */}
|
{/* Search Overlay */}
|
||||||
@@ -482,10 +579,13 @@ function InputOutputSection({
|
|||||||
height: '1px',
|
height: '1px',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<PopoverContent align='start' side='bottom' sideOffset={4}>
|
<PopoverContent ref={menuRef} align='start' side='bottom' sideOffset={4}>
|
||||||
<PopoverItem onClick={handleCopy}>Copy</PopoverItem>
|
<PopoverItem onClick={handleCopy}>Copy</PopoverItem>
|
||||||
<PopoverDivider />
|
<PopoverDivider />
|
||||||
<PopoverItem onClick={handleSearch}>Search</PopoverItem>
|
<PopoverItem onClick={handleSearch}>Search</PopoverItem>
|
||||||
|
<PopoverItem showCheck={wrapText} onClick={handleToggleWrap}>
|
||||||
|
Wrap Text
|
||||||
|
</PopoverItem>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>,
|
</Popover>,
|
||||||
document.body
|
document.body
|
||||||
@@ -496,229 +596,355 @@ function InputOutputSection({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TraceSpanNodeProps {
|
interface NestedBlockItemProps {
|
||||||
span: TraceSpan
|
span: TraceSpan
|
||||||
|
parentId: string
|
||||||
|
index: number
|
||||||
|
expandedSections: Set<string>
|
||||||
|
onToggle: (section: string) => void
|
||||||
workflowStartTime: number
|
workflowStartTime: number
|
||||||
totalDuration: number
|
totalDuration: number
|
||||||
depth: number
|
expandedChildren: Set<string>
|
||||||
expandedNodes: Set<string>
|
onToggleChildren: (spanId: string) => void
|
||||||
expandedSections: Set<string>
|
|
||||||
onToggleNode: (nodeId: string) => void
|
|
||||||
onToggleSection: (section: string) => void
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Recursive tree node component for rendering trace spans
|
* Recursive component for rendering nested blocks at any depth
|
||||||
*/
|
*/
|
||||||
const TraceSpanNode = memo(function TraceSpanNode({
|
function NestedBlockItem({
|
||||||
span,
|
span,
|
||||||
|
parentId,
|
||||||
|
index,
|
||||||
|
expandedSections,
|
||||||
|
onToggle,
|
||||||
workflowStartTime,
|
workflowStartTime,
|
||||||
totalDuration,
|
totalDuration,
|
||||||
depth,
|
expandedChildren,
|
||||||
expandedNodes,
|
onToggleChildren,
|
||||||
expandedSections,
|
}: NestedBlockItemProps): React.ReactNode {
|
||||||
onToggleNode,
|
const spanId = span.id || `${parentId}-nested-${index}`
|
||||||
onToggleSection,
|
const isError = span.status === 'error'
|
||||||
}: TraceSpanNodeProps): React.ReactNode {
|
const { icon: SpanIcon, bgColor } = getBlockIconAndColor(span.type, span.name)
|
||||||
|
const hasChildren = Boolean(span.children && span.children.length > 0)
|
||||||
|
const isChildrenExpanded = expandedChildren.has(spanId)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='flex min-w-0 flex-col gap-[8px] overflow-hidden'>
|
||||||
|
<ExpandableRowHeader
|
||||||
|
name={span.name}
|
||||||
|
duration={span.duration || 0}
|
||||||
|
isError={isError}
|
||||||
|
isExpanded={isChildrenExpanded}
|
||||||
|
hasChildren={hasChildren}
|
||||||
|
showIcon={!isIterationType(span.type)}
|
||||||
|
icon={SpanIcon}
|
||||||
|
bgColor={bgColor}
|
||||||
|
onToggle={() => onToggleChildren(spanId)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SpanContent
|
||||||
|
span={span}
|
||||||
|
spanId={spanId}
|
||||||
|
isError={isError}
|
||||||
|
workflowStartTime={workflowStartTime}
|
||||||
|
totalDuration={totalDuration}
|
||||||
|
expandedSections={expandedSections}
|
||||||
|
onToggle={onToggle}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Nested children */}
|
||||||
|
{hasChildren && isChildrenExpanded && (
|
||||||
|
<div className='mt-[2px] flex min-w-0 flex-col gap-[10px] overflow-hidden border-[var(--border)] border-l pl-[10px]'>
|
||||||
|
{span.children!.map((child, childIndex) => (
|
||||||
|
<NestedBlockItem
|
||||||
|
key={child.id || `${spanId}-child-${childIndex}`}
|
||||||
|
span={child}
|
||||||
|
parentId={spanId}
|
||||||
|
index={childIndex}
|
||||||
|
expandedSections={expandedSections}
|
||||||
|
onToggle={onToggle}
|
||||||
|
workflowStartTime={workflowStartTime}
|
||||||
|
totalDuration={totalDuration}
|
||||||
|
expandedChildren={expandedChildren}
|
||||||
|
onToggleChildren={onToggleChildren}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TraceSpanItemProps {
|
||||||
|
span: TraceSpan
|
||||||
|
totalDuration: number
|
||||||
|
workflowStartTime: number
|
||||||
|
isFirstSpan?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Individual trace span card component.
|
||||||
|
* Memoized to prevent re-renders when sibling spans change.
|
||||||
|
*/
|
||||||
|
const TraceSpanItem = memo(function TraceSpanItem({
|
||||||
|
span,
|
||||||
|
totalDuration,
|
||||||
|
workflowStartTime,
|
||||||
|
isFirstSpan = false,
|
||||||
|
}: TraceSpanItemProps): React.ReactNode {
|
||||||
|
const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set())
|
||||||
|
const [expandedChildren, setExpandedChildren] = useState<Set<string>>(new Set())
|
||||||
|
const [isCardExpanded, setIsCardExpanded] = useState(false)
|
||||||
|
const toggleSet = useSetToggle()
|
||||||
|
|
||||||
const spanId = span.id || `span-${span.name}-${span.startTime}`
|
const spanId = span.id || `span-${span.name}-${span.startTime}`
|
||||||
const spanStartTime = new Date(span.startTime).getTime()
|
const spanStartTime = new Date(span.startTime).getTime()
|
||||||
const spanEndTime = new Date(span.endTime).getTime()
|
const spanEndTime = new Date(span.endTime).getTime()
|
||||||
const duration = span.duration || spanEndTime - spanStartTime
|
const duration = span.duration || spanEndTime - spanStartTime
|
||||||
|
|
||||||
const isDirectError = span.status === 'error'
|
const hasChildren = Boolean(span.children && span.children.length > 0)
|
||||||
const hasNestedError = hasErrorInTree(span)
|
const hasToolCalls = Boolean(span.toolCalls && span.toolCalls.length > 0)
|
||||||
const showErrorStyle = isDirectError || hasNestedError
|
const isError = span.status === 'error'
|
||||||
|
|
||||||
|
const inlineChildTypes = new Set([
|
||||||
|
'tool',
|
||||||
|
'model',
|
||||||
|
'loop-iteration',
|
||||||
|
'parallel-iteration',
|
||||||
|
'workflow',
|
||||||
|
])
|
||||||
|
|
||||||
|
// For workflow-in-workflow blocks, all children should be rendered inline/nested
|
||||||
|
const isWorkflowBlock = span.type?.toLowerCase().includes('workflow')
|
||||||
|
const inlineChildren = isWorkflowBlock
|
||||||
|
? span.children || []
|
||||||
|
: span.children?.filter((child) => inlineChildTypes.has(child.type?.toLowerCase() || '')) || []
|
||||||
|
const otherChildren = isWorkflowBlock
|
||||||
|
? []
|
||||||
|
: span.children?.filter((child) => !inlineChildTypes.has(child.type?.toLowerCase() || '')) || []
|
||||||
|
|
||||||
|
const toolCallSpans = useMemo(() => {
|
||||||
|
if (!hasToolCalls) return []
|
||||||
|
return span.toolCalls!.map((toolCall, index) => {
|
||||||
|
const toolStartTime = toolCall.startTime
|
||||||
|
? new Date(toolCall.startTime).getTime()
|
||||||
|
: spanStartTime
|
||||||
|
const toolEndTime = toolCall.endTime
|
||||||
|
? new Date(toolCall.endTime).getTime()
|
||||||
|
: toolStartTime + (toolCall.duration || 0)
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: `${spanId}-tool-${index}`,
|
||||||
|
name: toolCall.name,
|
||||||
|
type: 'tool',
|
||||||
|
duration: toolCall.duration || toolEndTime - toolStartTime,
|
||||||
|
startTime: new Date(toolStartTime).toISOString(),
|
||||||
|
endTime: new Date(toolEndTime).toISOString(),
|
||||||
|
status: toolCall.error ? ('error' as const) : ('success' as const),
|
||||||
|
input: toolCall.input,
|
||||||
|
output: toolCall.error
|
||||||
|
? { error: toolCall.error, ...(toolCall.output || {}) }
|
||||||
|
: toolCall.output,
|
||||||
|
} as TraceSpan
|
||||||
|
})
|
||||||
|
}, [hasToolCalls, span.toolCalls, spanId, spanStartTime])
|
||||||
|
|
||||||
|
const handleSectionToggle = useCallback(
|
||||||
|
(section: string) => toggleSet(setExpandedSections, section),
|
||||||
|
[toggleSet]
|
||||||
|
)
|
||||||
|
|
||||||
|
const handleChildrenToggle = useCallback(
|
||||||
|
(childSpanId: string) => toggleSet(setExpandedChildren, childSpanId),
|
||||||
|
[toggleSet]
|
||||||
|
)
|
||||||
|
|
||||||
const { icon: BlockIcon, bgColor } = getBlockIconAndColor(span.type, span.name)
|
const { icon: BlockIcon, bgColor } = getBlockIconAndColor(span.type, span.name)
|
||||||
|
|
||||||
// Root workflow execution is always expanded and has no toggle
|
// Check if this card has expandable inline content
|
||||||
const isRootWorkflow = depth === 0
|
const hasInlineContent =
|
||||||
|
(isWorkflowBlock && inlineChildren.length > 0) ||
|
||||||
|
(!isWorkflowBlock && (toolCallSpans.length > 0 || inlineChildren.length > 0))
|
||||||
|
|
||||||
// Build all children including tool calls
|
const isExpandable = !isFirstSpan && hasInlineContent
|
||||||
const allChildren = useMemo(() => {
|
|
||||||
const children: TraceSpan[] = []
|
|
||||||
|
|
||||||
// Add tool calls as child spans
|
|
||||||
if (span.toolCalls && span.toolCalls.length > 0) {
|
|
||||||
span.toolCalls.forEach((toolCall, index) => {
|
|
||||||
const toolStartTime = toolCall.startTime
|
|
||||||
? new Date(toolCall.startTime).getTime()
|
|
||||||
: spanStartTime
|
|
||||||
const toolEndTime = toolCall.endTime
|
|
||||||
? new Date(toolCall.endTime).getTime()
|
|
||||||
: toolStartTime + (toolCall.duration || 0)
|
|
||||||
|
|
||||||
children.push({
|
|
||||||
id: `${spanId}-tool-${index}`,
|
|
||||||
name: toolCall.name,
|
|
||||||
type: 'tool',
|
|
||||||
duration: toolCall.duration || toolEndTime - toolStartTime,
|
|
||||||
startTime: new Date(toolStartTime).toISOString(),
|
|
||||||
endTime: new Date(toolEndTime).toISOString(),
|
|
||||||
status: toolCall.error ? ('error' as const) : ('success' as const),
|
|
||||||
input: toolCall.input,
|
|
||||||
output: toolCall.error
|
|
||||||
? { error: toolCall.error, ...(toolCall.output || {}) }
|
|
||||||
: toolCall.output,
|
|
||||||
} as TraceSpan)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add regular children
|
|
||||||
if (span.children && span.children.length > 0) {
|
|
||||||
children.push(...span.children)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort by start time
|
|
||||||
return children.sort((a, b) => parseTime(a.startTime) - parseTime(b.startTime))
|
|
||||||
}, [span, spanId, spanStartTime])
|
|
||||||
|
|
||||||
const hasChildren = allChildren.length > 0
|
|
||||||
const isExpanded = isRootWorkflow || expandedNodes.has(spanId)
|
|
||||||
const isToggleable = !isRootWorkflow
|
|
||||||
|
|
||||||
const hasInput = Boolean(span.input)
|
|
||||||
const hasOutput = Boolean(span.output)
|
|
||||||
|
|
||||||
// For progress bar - show child segments for workflow/iteration types
|
|
||||||
const lowerType = span.type?.toLowerCase() || ''
|
|
||||||
const showChildrenInProgressBar =
|
|
||||||
isIterationType(lowerType) || lowerType === 'workflow' || lowerType === 'workflow_input'
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='flex min-w-0 flex-col'>
|
<>
|
||||||
{/* Node Header Row */}
|
<div className='flex min-w-0 flex-col gap-[8px] overflow-hidden rounded-[6px] bg-[var(--surface-1)] px-[10px] py-[8px]'>
|
||||||
<div
|
<ExpandableRowHeader
|
||||||
className={cn(
|
name={span.name}
|
||||||
'group flex items-center justify-between gap-[8px] py-[6px]',
|
duration={duration}
|
||||||
isToggleable && 'cursor-pointer'
|
isError={isError}
|
||||||
|
isExpanded={isCardExpanded}
|
||||||
|
hasChildren={isExpandable}
|
||||||
|
showIcon={!isFirstSpan}
|
||||||
|
icon={BlockIcon}
|
||||||
|
bgColor={bgColor}
|
||||||
|
onToggle={() => setIsCardExpanded((prev) => !prev)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SpanContent
|
||||||
|
span={span}
|
||||||
|
spanId={spanId}
|
||||||
|
isError={isError}
|
||||||
|
workflowStartTime={workflowStartTime}
|
||||||
|
totalDuration={totalDuration}
|
||||||
|
expandedSections={expandedSections}
|
||||||
|
onToggle={handleSectionToggle}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* For workflow blocks, keep children nested within the card (not as separate cards) */}
|
||||||
|
{!isFirstSpan && isWorkflowBlock && inlineChildren.length > 0 && isCardExpanded && (
|
||||||
|
<div className='mt-[2px] flex min-w-0 flex-col gap-[10px] overflow-hidden border-[var(--border)] border-l pl-[10px]'>
|
||||||
|
{inlineChildren.map((childSpan, index) => (
|
||||||
|
<NestedBlockItem
|
||||||
|
key={childSpan.id || `${spanId}-nested-${index}`}
|
||||||
|
span={childSpan}
|
||||||
|
parentId={spanId}
|
||||||
|
index={index}
|
||||||
|
expandedSections={expandedSections}
|
||||||
|
onToggle={handleSectionToggle}
|
||||||
|
workflowStartTime={workflowStartTime}
|
||||||
|
totalDuration={totalDuration}
|
||||||
|
expandedChildren={expandedChildren}
|
||||||
|
onToggleChildren={handleChildrenToggle}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
onClick={isToggleable ? () => onToggleNode(spanId) : undefined}
|
|
||||||
onKeyDown={
|
|
||||||
isToggleable
|
|
||||||
? (e) => {
|
|
||||||
if (e.key === 'Enter' || e.key === ' ') {
|
|
||||||
e.preventDefault()
|
|
||||||
onToggleNode(spanId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
role={isToggleable ? 'button' : undefined}
|
|
||||||
tabIndex={isToggleable ? 0 : undefined}
|
|
||||||
aria-expanded={isToggleable ? isExpanded : undefined}
|
|
||||||
aria-label={isToggleable ? (isExpanded ? 'Collapse' : 'Expand') : undefined}
|
|
||||||
>
|
|
||||||
<div className='flex min-w-0 flex-1 items-center gap-[8px]'>
|
|
||||||
{!isIterationType(span.type) && (
|
|
||||||
<div
|
|
||||||
className='relative flex h-[14px] w-[14px] flex-shrink-0 items-center justify-center overflow-hidden rounded-[4px]'
|
|
||||||
style={{ background: bgColor }}
|
|
||||||
>
|
|
||||||
{BlockIcon && <BlockIcon className='h-[9px] w-[9px] text-white' />}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<span
|
|
||||||
className='min-w-0 max-w-[180px] truncate font-medium text-[12px]'
|
|
||||||
style={{ color: showErrorStyle ? 'var(--text-error)' : 'var(--text-secondary)' }}
|
|
||||||
>
|
|
||||||
{span.name}
|
|
||||||
</span>
|
|
||||||
{isToggleable && (
|
|
||||||
<ChevronDown
|
|
||||||
className='h-[8px] w-[8px] flex-shrink-0 text-[var(--text-tertiary)] transition-colors transition-transform duration-100 group-hover:text-[var(--text-primary)]'
|
|
||||||
style={{
|
|
||||||
transform: `translateY(-0.25px) ${isExpanded ? 'rotate(0deg)' : 'rotate(-90deg)'}`,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<span className='flex-shrink-0 font-medium text-[12px] text-[var(--text-tertiary)]'>
|
|
||||||
{formatDuration(duration, { precision: 2 })}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Expanded Content */}
|
{/* For non-workflow blocks, render inline children/tool calls */}
|
||||||
{isExpanded && (
|
{!isFirstSpan && !isWorkflowBlock && isCardExpanded && (
|
||||||
<div className='flex min-w-0 flex-col gap-[10px]'>
|
<div className='mt-[2px] flex min-w-0 flex-col gap-[10px] overflow-hidden border-[var(--border)] border-l pl-[10px]'>
|
||||||
{/* Progress Bar */}
|
{[...toolCallSpans, ...inlineChildren].map((childSpan, index) => {
|
||||||
<ProgressBar
|
const childId = childSpan.id || `${spanId}-inline-${index}`
|
||||||
span={span}
|
const childIsError = childSpan.status === 'error'
|
||||||
childSpans={showChildrenInProgressBar ? span.children : undefined}
|
const childLowerType = childSpan.type?.toLowerCase() || ''
|
||||||
workflowStartTime={workflowStartTime}
|
const hasNestedChildren = Boolean(childSpan.children && childSpan.children.length > 0)
|
||||||
totalDuration={totalDuration}
|
const isNestedExpanded = expandedChildren.has(childId)
|
||||||
/>
|
const showChildrenInProgressBar =
|
||||||
|
isIterationType(childLowerType) || childLowerType === 'workflow'
|
||||||
|
const { icon: ChildIcon, bgColor: childBgColor } = getBlockIconAndColor(
|
||||||
|
childSpan.type,
|
||||||
|
childSpan.name
|
||||||
|
)
|
||||||
|
|
||||||
{/* Input/Output Sections */}
|
return (
|
||||||
{(hasInput || hasOutput) && (
|
<div
|
||||||
<div className='flex min-w-0 flex-col gap-[6px] overflow-hidden py-[2px]'>
|
key={`inline-${childId}`}
|
||||||
{hasInput && (
|
className='flex min-w-0 flex-col gap-[8px] overflow-hidden'
|
||||||
<InputOutputSection
|
>
|
||||||
label='Input'
|
<ExpandableRowHeader
|
||||||
data={span.input}
|
name={childSpan.name}
|
||||||
isError={false}
|
duration={childSpan.duration || 0}
|
||||||
spanId={spanId}
|
isError={childIsError}
|
||||||
sectionType='input'
|
isExpanded={isNestedExpanded}
|
||||||
expandedSections={expandedSections}
|
hasChildren={hasNestedChildren}
|
||||||
onToggle={onToggleSection}
|
showIcon={!isIterationType(childSpan.type)}
|
||||||
/>
|
icon={ChildIcon}
|
||||||
)}
|
bgColor={childBgColor}
|
||||||
|
onToggle={() => handleChildrenToggle(childId)}
|
||||||
|
/>
|
||||||
|
|
||||||
{hasInput && hasOutput && (
|
<ProgressBar
|
||||||
<div className='border-[var(--border)] border-t border-dashed' />
|
span={childSpan}
|
||||||
)}
|
childSpans={showChildrenInProgressBar ? childSpan.children : undefined}
|
||||||
|
|
||||||
{hasOutput && (
|
|
||||||
<InputOutputSection
|
|
||||||
label={isDirectError ? 'Error' : 'Output'}
|
|
||||||
data={span.output}
|
|
||||||
isError={isDirectError}
|
|
||||||
spanId={spanId}
|
|
||||||
sectionType='output'
|
|
||||||
expandedSections={expandedSections}
|
|
||||||
onToggle={onToggleSection}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Nested Children */}
|
|
||||||
{hasChildren && (
|
|
||||||
<div className='flex min-w-0 flex-col gap-[2px] border-[var(--border)] border-l pl-[10px]'>
|
|
||||||
{allChildren.map((child, index) => (
|
|
||||||
<div key={child.id || `${spanId}-child-${index}`} className='pl-[6px]'>
|
|
||||||
<TraceSpanNode
|
|
||||||
span={child}
|
|
||||||
workflowStartTime={workflowStartTime}
|
workflowStartTime={workflowStartTime}
|
||||||
totalDuration={totalDuration}
|
totalDuration={totalDuration}
|
||||||
depth={depth + 1}
|
|
||||||
expandedNodes={expandedNodes}
|
|
||||||
expandedSections={expandedSections}
|
|
||||||
onToggleNode={onToggleNode}
|
|
||||||
onToggleSection={onToggleSection}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{childSpan.input && (
|
||||||
|
<InputOutputSection
|
||||||
|
label='Input'
|
||||||
|
data={childSpan.input}
|
||||||
|
isError={false}
|
||||||
|
spanId={childId}
|
||||||
|
sectionType='input'
|
||||||
|
expandedSections={expandedSections}
|
||||||
|
onToggle={handleSectionToggle}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{childSpan.input && childSpan.output && (
|
||||||
|
<div className='border-[var(--border)] border-t border-dashed' />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{childSpan.output && (
|
||||||
|
<InputOutputSection
|
||||||
|
label={childIsError ? 'Error' : 'Output'}
|
||||||
|
data={childSpan.output}
|
||||||
|
isError={childIsError}
|
||||||
|
spanId={childId}
|
||||||
|
sectionType='output'
|
||||||
|
expandedSections={expandedSections}
|
||||||
|
onToggle={handleSectionToggle}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Nested children */}
|
||||||
|
{showChildrenInProgressBar && hasNestedChildren && isNestedExpanded && (
|
||||||
|
<div className='mt-[2px] flex min-w-0 flex-col gap-[10px] overflow-hidden border-[var(--border)] border-l pl-[10px]'>
|
||||||
|
{childSpan.children!.map((nestedChild, nestedIndex) => (
|
||||||
|
<NestedBlockItem
|
||||||
|
key={nestedChild.id || `${childId}-nested-${nestedIndex}`}
|
||||||
|
span={nestedChild}
|
||||||
|
parentId={childId}
|
||||||
|
index={nestedIndex}
|
||||||
|
expandedSections={expandedSections}
|
||||||
|
onToggle={handleSectionToggle}
|
||||||
|
workflowStartTime={workflowStartTime}
|
||||||
|
totalDuration={totalDuration}
|
||||||
|
expandedChildren={expandedChildren}
|
||||||
|
onToggleChildren={handleChildrenToggle}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
)
|
||||||
</div>
|
})}
|
||||||
)}
|
</div>
|
||||||
</div>
|
)}
|
||||||
)}
|
</div>
|
||||||
</div>
|
|
||||||
|
{/* For the first span (workflow execution), render all children as separate top-level cards */}
|
||||||
|
{isFirstSpan &&
|
||||||
|
hasChildren &&
|
||||||
|
span.children!.map((childSpan, index) => (
|
||||||
|
<TraceSpanItem
|
||||||
|
key={childSpan.id || `${spanId}-child-${index}`}
|
||||||
|
span={childSpan}
|
||||||
|
totalDuration={totalDuration}
|
||||||
|
workflowStartTime={workflowStartTime}
|
||||||
|
isFirstSpan={false}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{!isFirstSpan &&
|
||||||
|
otherChildren.map((childSpan, index) => (
|
||||||
|
<TraceSpanItem
|
||||||
|
key={childSpan.id || `${spanId}-other-${index}`}
|
||||||
|
span={childSpan}
|
||||||
|
totalDuration={totalDuration}
|
||||||
|
workflowStartTime={workflowStartTime}
|
||||||
|
isFirstSpan={false}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Displays workflow execution trace spans with nested tree structure.
|
* Displays workflow execution trace spans with nested structure.
|
||||||
* Memoized to prevent re-renders when parent LogDetails updates.
|
* Memoized to prevent re-renders when parent LogDetails updates.
|
||||||
*/
|
*/
|
||||||
export const TraceSpans = memo(function TraceSpans({ traceSpans }: TraceSpansProps) {
|
export const TraceSpans = memo(function TraceSpans({
|
||||||
const [expandedNodes, setExpandedNodes] = useState<Set<string>>(() => new Set())
|
traceSpans,
|
||||||
const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set())
|
totalDuration = 0,
|
||||||
const toggleSet = useSetToggle()
|
}: TraceSpansProps) {
|
||||||
|
|
||||||
const { workflowStartTime, actualTotalDuration, normalizedSpans } = useMemo(() => {
|
const { workflowStartTime, actualTotalDuration, normalizedSpans } = useMemo(() => {
|
||||||
if (!traceSpans || traceSpans.length === 0) {
|
if (!traceSpans || traceSpans.length === 0) {
|
||||||
return { workflowStartTime: 0, actualTotalDuration: 0, normalizedSpans: [] }
|
return { workflowStartTime: 0, actualTotalDuration: totalDuration, normalizedSpans: [] }
|
||||||
}
|
}
|
||||||
|
|
||||||
let earliest = Number.POSITIVE_INFINITY
|
let earliest = Number.POSITIVE_INFINITY
|
||||||
@@ -736,37 +962,26 @@ export const TraceSpans = memo(function TraceSpans({ traceSpans }: TraceSpansPro
|
|||||||
actualTotalDuration: latest - earliest,
|
actualTotalDuration: latest - earliest,
|
||||||
normalizedSpans: normalizeAndSortSpans(traceSpans),
|
normalizedSpans: normalizeAndSortSpans(traceSpans),
|
||||||
}
|
}
|
||||||
}, [traceSpans])
|
}, [traceSpans, totalDuration])
|
||||||
|
|
||||||
const handleToggleNode = useCallback(
|
|
||||||
(nodeId: string) => toggleSet(setExpandedNodes, nodeId),
|
|
||||||
[toggleSet]
|
|
||||||
)
|
|
||||||
|
|
||||||
const handleToggleSection = useCallback(
|
|
||||||
(section: string) => toggleSet(setExpandedSections, section),
|
|
||||||
[toggleSet]
|
|
||||||
)
|
|
||||||
|
|
||||||
if (!traceSpans || traceSpans.length === 0) {
|
if (!traceSpans || traceSpans.length === 0) {
|
||||||
return <div className='text-[12px] text-[var(--text-secondary)]'>No trace data available</div>
|
return <div className='text-[12px] text-[var(--text-secondary)]'>No trace data available</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='flex w-full min-w-0 flex-col overflow-hidden'>
|
<div className='flex w-full min-w-0 flex-col gap-[6px] overflow-hidden rounded-[6px] bg-[var(--surface-2)] px-[10px] py-[8px]'>
|
||||||
{normalizedSpans.map((span, index) => (
|
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>Trace Span</span>
|
||||||
<TraceSpanNode
|
<div className='flex min-w-0 flex-col gap-[8px] overflow-hidden'>
|
||||||
key={span.id || index}
|
{normalizedSpans.map((span, index) => (
|
||||||
span={span}
|
<TraceSpanItem
|
||||||
workflowStartTime={workflowStartTime}
|
key={span.id || index}
|
||||||
totalDuration={actualTotalDuration}
|
span={span}
|
||||||
depth={0}
|
totalDuration={actualTotalDuration}
|
||||||
expandedNodes={expandedNodes}
|
workflowStartTime={workflowStartTime}
|
||||||
expandedSections={expandedSections}
|
isFirstSpan={index === 0}
|
||||||
onToggleNode={handleToggleNode}
|
/>
|
||||||
onToggleSection={handleToggleSection}
|
))}
|
||||||
/>
|
</div>
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,23 +1,10 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
import { memo, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { ArrowDown, ArrowUp, Check, ChevronUp, Clipboard, Search, X } from 'lucide-react'
|
import { ChevronUp, X } from 'lucide-react'
|
||||||
import { createPortal } from 'react-dom'
|
import { Button, Eye } from '@/components/emcn'
|
||||||
import {
|
|
||||||
Button,
|
|
||||||
Code,
|
|
||||||
Eye,
|
|
||||||
Input,
|
|
||||||
Popover,
|
|
||||||
PopoverAnchor,
|
|
||||||
PopoverContent,
|
|
||||||
PopoverDivider,
|
|
||||||
PopoverItem,
|
|
||||||
Tooltip,
|
|
||||||
} from '@/components/emcn'
|
|
||||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
import { BASE_EXECUTION_CHARGE } from '@/lib/billing/constants'
|
import { BASE_EXECUTION_CHARGE } from '@/lib/billing/constants'
|
||||||
import { cn } from '@/lib/core/utils/cn'
|
|
||||||
import {
|
import {
|
||||||
ExecutionSnapshot,
|
ExecutionSnapshot,
|
||||||
FileCards,
|
FileCards,
|
||||||
@@ -30,194 +17,11 @@ import {
|
|||||||
StatusBadge,
|
StatusBadge,
|
||||||
TriggerBadge,
|
TriggerBadge,
|
||||||
} from '@/app/workspace/[workspaceId]/logs/utils'
|
} from '@/app/workspace/[workspaceId]/logs/utils'
|
||||||
import { useCodeViewerFeatures } from '@/hooks/use-code-viewer'
|
|
||||||
import { usePermissionConfig } from '@/hooks/use-permission-config'
|
import { usePermissionConfig } from '@/hooks/use-permission-config'
|
||||||
import { formatCost } from '@/providers/utils'
|
import { formatCost } from '@/providers/utils'
|
||||||
import type { WorkflowLog } from '@/stores/logs/filters/types'
|
import type { WorkflowLog } from '@/stores/logs/filters/types'
|
||||||
import { useLogDetailsUIStore } from '@/stores/logs/store'
|
import { useLogDetailsUIStore } from '@/stores/logs/store'
|
||||||
|
|
||||||
/**
|
|
||||||
* Workflow Output section with code viewer, copy, search, and context menu functionality
|
|
||||||
*/
|
|
||||||
function WorkflowOutputSection({ output }: { output: Record<string, unknown> }) {
|
|
||||||
const contentRef = useRef<HTMLDivElement>(null)
|
|
||||||
const [copied, setCopied] = useState(false)
|
|
||||||
|
|
||||||
// Context menu state
|
|
||||||
const [isContextMenuOpen, setIsContextMenuOpen] = useState(false)
|
|
||||||
const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 })
|
|
||||||
|
|
||||||
const {
|
|
||||||
isSearchActive,
|
|
||||||
searchQuery,
|
|
||||||
setSearchQuery,
|
|
||||||
matchCount,
|
|
||||||
currentMatchIndex,
|
|
||||||
activateSearch,
|
|
||||||
closeSearch,
|
|
||||||
goToNextMatch,
|
|
||||||
goToPreviousMatch,
|
|
||||||
handleMatchCountChange,
|
|
||||||
searchInputRef,
|
|
||||||
} = useCodeViewerFeatures({ contentRef })
|
|
||||||
|
|
||||||
const jsonString = useMemo(() => JSON.stringify(output, null, 2), [output])
|
|
||||||
|
|
||||||
const handleContextMenu = useCallback((e: React.MouseEvent) => {
|
|
||||||
e.preventDefault()
|
|
||||||
e.stopPropagation()
|
|
||||||
setContextMenuPosition({ x: e.clientX, y: e.clientY })
|
|
||||||
setIsContextMenuOpen(true)
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const closeContextMenu = useCallback(() => {
|
|
||||||
setIsContextMenuOpen(false)
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const handleCopy = useCallback(() => {
|
|
||||||
navigator.clipboard.writeText(jsonString)
|
|
||||||
setCopied(true)
|
|
||||||
setTimeout(() => setCopied(false), 1500)
|
|
||||||
closeContextMenu()
|
|
||||||
}, [jsonString, closeContextMenu])
|
|
||||||
|
|
||||||
const handleSearch = useCallback(() => {
|
|
||||||
activateSearch()
|
|
||||||
closeContextMenu()
|
|
||||||
}, [activateSearch, closeContextMenu])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className='relative flex min-w-0 flex-col overflow-hidden'>
|
|
||||||
<div ref={contentRef} onContextMenu={handleContextMenu} className='relative'>
|
|
||||||
<Code.Viewer
|
|
||||||
code={jsonString}
|
|
||||||
language='json'
|
|
||||||
className='!bg-[var(--surface-4)] dark:!bg-[var(--surface-3)] max-h-[300px] min-h-0 max-w-full rounded-[6px] border-0 [word-break:break-all]'
|
|
||||||
wrapText
|
|
||||||
searchQuery={isSearchActive ? searchQuery : undefined}
|
|
||||||
currentMatchIndex={currentMatchIndex}
|
|
||||||
onMatchCountChange={handleMatchCountChange}
|
|
||||||
/>
|
|
||||||
{/* Glass action buttons overlay */}
|
|
||||||
{!isSearchActive && (
|
|
||||||
<div className='absolute top-[7px] right-[6px] z-10 flex gap-[4px]'>
|
|
||||||
<Tooltip.Root>
|
|
||||||
<Tooltip.Trigger asChild>
|
|
||||||
<Button
|
|
||||||
type='button'
|
|
||||||
variant='default'
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation()
|
|
||||||
handleCopy()
|
|
||||||
}}
|
|
||||||
className='h-[20px] w-[20px] cursor-pointer border border-[var(--border-1)] bg-transparent p-0 backdrop-blur-sm hover:bg-[var(--surface-3)]'
|
|
||||||
>
|
|
||||||
{copied ? (
|
|
||||||
<Check className='h-[10px] w-[10px] text-[var(--text-success)]' />
|
|
||||||
) : (
|
|
||||||
<Clipboard className='h-[10px] w-[10px]' />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</Tooltip.Trigger>
|
|
||||||
<Tooltip.Content side='top'>{copied ? 'Copied' : 'Copy'}</Tooltip.Content>
|
|
||||||
</Tooltip.Root>
|
|
||||||
<Tooltip.Root>
|
|
||||||
<Tooltip.Trigger asChild>
|
|
||||||
<Button
|
|
||||||
type='button'
|
|
||||||
variant='default'
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation()
|
|
||||||
activateSearch()
|
|
||||||
}}
|
|
||||||
className='h-[20px] w-[20px] cursor-pointer border border-[var(--border-1)] bg-transparent p-0 backdrop-blur-sm hover:bg-[var(--surface-3)]'
|
|
||||||
>
|
|
||||||
<Search className='h-[10px] w-[10px]' />
|
|
||||||
</Button>
|
|
||||||
</Tooltip.Trigger>
|
|
||||||
<Tooltip.Content side='top'>Search</Tooltip.Content>
|
|
||||||
</Tooltip.Root>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Search Overlay */}
|
|
||||||
{isSearchActive && (
|
|
||||||
<div
|
|
||||||
className='absolute top-0 right-0 z-30 flex h-[34px] items-center gap-[6px] rounded-[4px] border border-[var(--border)] bg-[var(--surface-1)] px-[6px] shadow-sm'
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
ref={searchInputRef}
|
|
||||||
type='text'
|
|
||||||
value={searchQuery}
|
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
|
||||||
placeholder='Search...'
|
|
||||||
className='mr-[2px] h-[23px] w-[94px] text-[12px]'
|
|
||||||
/>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'min-w-[45px] text-center text-[11px]',
|
|
||||||
matchCount > 0 ? 'text-[var(--text-secondary)]' : 'text-[var(--text-tertiary)]'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{matchCount > 0 ? `${currentMatchIndex + 1}/${matchCount}` : '0/0'}
|
|
||||||
</span>
|
|
||||||
<Button
|
|
||||||
variant='ghost'
|
|
||||||
className='!p-1'
|
|
||||||
onClick={goToPreviousMatch}
|
|
||||||
disabled={matchCount === 0}
|
|
||||||
aria-label='Previous match'
|
|
||||||
>
|
|
||||||
<ArrowUp className='h-[12px] w-[12px]' />
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant='ghost'
|
|
||||||
className='!p-1'
|
|
||||||
onClick={goToNextMatch}
|
|
||||||
disabled={matchCount === 0}
|
|
||||||
aria-label='Next match'
|
|
||||||
>
|
|
||||||
<ArrowDown className='h-[12px] w-[12px]' />
|
|
||||||
</Button>
|
|
||||||
<Button variant='ghost' className='!p-1' onClick={closeSearch} aria-label='Close search'>
|
|
||||||
<X className='h-[12px] w-[12px]' />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Context Menu - rendered in portal to avoid transform/overflow clipping */}
|
|
||||||
{typeof document !== 'undefined' &&
|
|
||||||
createPortal(
|
|
||||||
<Popover
|
|
||||||
open={isContextMenuOpen}
|
|
||||||
onOpenChange={closeContextMenu}
|
|
||||||
variant='secondary'
|
|
||||||
size='sm'
|
|
||||||
colorScheme='inverted'
|
|
||||||
>
|
|
||||||
<PopoverAnchor
|
|
||||||
style={{
|
|
||||||
position: 'fixed',
|
|
||||||
left: `${contextMenuPosition.x}px`,
|
|
||||||
top: `${contextMenuPosition.y}px`,
|
|
||||||
width: '1px',
|
|
||||||
height: '1px',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<PopoverContent align='start' side='bottom' sideOffset={4}>
|
|
||||||
<PopoverItem onClick={handleCopy}>Copy</PopoverItem>
|
|
||||||
<PopoverDivider />
|
|
||||||
<PopoverItem onClick={handleSearch}>Search</PopoverItem>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>,
|
|
||||||
document.body
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
interface LogDetailsProps {
|
interface LogDetailsProps {
|
||||||
/** The log to display details for */
|
/** The log to display details for */
|
||||||
log: WorkflowLog | null
|
log: WorkflowLog | null
|
||||||
@@ -274,18 +78,6 @@ export const LogDetails = memo(function LogDetails({
|
|||||||
return isWorkflowExecutionLog && log?.cost
|
return isWorkflowExecutionLog && log?.cost
|
||||||
}, [log, isWorkflowExecutionLog])
|
}, [log, isWorkflowExecutionLog])
|
||||||
|
|
||||||
// Extract and clean the workflow final output (remove childTraceSpans for cleaner display)
|
|
||||||
const workflowOutput = useMemo(() => {
|
|
||||||
const executionData = log?.executionData as
|
|
||||||
| { finalOutput?: Record<string, unknown> }
|
|
||||||
| undefined
|
|
||||||
if (!executionData?.finalOutput) return null
|
|
||||||
const { childTraceSpans, ...cleanOutput } = executionData.finalOutput as {
|
|
||||||
childTraceSpans?: unknown
|
|
||||||
} & Record<string, unknown>
|
|
||||||
return cleanOutput
|
|
||||||
}, [log?.executionData])
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleKeyDown = (e: KeyboardEvent) => {
|
const handleKeyDown = (e: KeyboardEvent) => {
|
||||||
if (e.key === 'Escape' && isOpen) {
|
if (e.key === 'Escape' && isOpen) {
|
||||||
@@ -295,12 +87,12 @@ export const LogDetails = memo(function LogDetails({
|
|||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
if (e.key === 'ArrowUp' && hasPrev && onNavigatePrev) {
|
if (e.key === 'ArrowUp' && hasPrev && onNavigatePrev) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
onNavigatePrev()
|
handleNavigate(onNavigatePrev)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (e.key === 'ArrowDown' && hasNext && onNavigateNext) {
|
if (e.key === 'ArrowDown' && hasNext && onNavigateNext) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
onNavigateNext()
|
handleNavigate(onNavigateNext)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -309,6 +101,10 @@ export const LogDetails = memo(function LogDetails({
|
|||||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||||
}, [isOpen, onClose, hasPrev, hasNext, onNavigatePrev, onNavigateNext])
|
}, [isOpen, onClose, hasPrev, hasNext, onNavigatePrev, onNavigateNext])
|
||||||
|
|
||||||
|
const handleNavigate = (navigateFunction: () => void) => {
|
||||||
|
navigateFunction()
|
||||||
|
}
|
||||||
|
|
||||||
const formattedTimestamp = useMemo(
|
const formattedTimestamp = useMemo(
|
||||||
() => (log ? formatDate(log.createdAt) : null),
|
() => (log ? formatDate(log.createdAt) : null),
|
||||||
[log?.createdAt]
|
[log?.createdAt]
|
||||||
@@ -346,7 +142,7 @@ export const LogDetails = memo(function LogDetails({
|
|||||||
<Button
|
<Button
|
||||||
variant='ghost'
|
variant='ghost'
|
||||||
className='!p-[4px]'
|
className='!p-[4px]'
|
||||||
onClick={() => hasPrev && onNavigatePrev?.()}
|
onClick={() => hasPrev && handleNavigate(onNavigatePrev!)}
|
||||||
disabled={!hasPrev}
|
disabled={!hasPrev}
|
||||||
aria-label='Previous log'
|
aria-label='Previous log'
|
||||||
>
|
>
|
||||||
@@ -355,7 +151,7 @@ export const LogDetails = memo(function LogDetails({
|
|||||||
<Button
|
<Button
|
||||||
variant='ghost'
|
variant='ghost'
|
||||||
className='!p-[4px]'
|
className='!p-[4px]'
|
||||||
onClick={() => hasNext && onNavigateNext?.()}
|
onClick={() => hasNext && handleNavigate(onNavigateNext!)}
|
||||||
disabled={!hasNext}
|
disabled={!hasNext}
|
||||||
aria-label='Next log'
|
aria-label='Next log'
|
||||||
>
|
>
|
||||||
@@ -408,7 +204,7 @@ export const LogDetails = memo(function LogDetails({
|
|||||||
|
|
||||||
{/* Execution ID */}
|
{/* Execution ID */}
|
||||||
{log.executionId && (
|
{log.executionId && (
|
||||||
<div className='flex flex-col gap-[6px] rounded-[6px] border border-[var(--border)] bg-[var(--surface-2)] px-[10px] py-[8px]'>
|
<div className='flex flex-col gap-[6px] rounded-[6px] bg-[var(--surface-2)] px-[10px] py-[8px]'>
|
||||||
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>
|
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>
|
||||||
Execution ID
|
Execution ID
|
||||||
</span>
|
</span>
|
||||||
@@ -419,7 +215,7 @@ export const LogDetails = memo(function LogDetails({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Details Section */}
|
{/* Details Section */}
|
||||||
<div className='-my-[4px] flex min-w-0 flex-col overflow-hidden'>
|
<div className='flex min-w-0 flex-col overflow-hidden'>
|
||||||
{/* Level */}
|
{/* Level */}
|
||||||
<div className='flex h-[48px] items-center justify-between border-[var(--border)] border-b p-[8px]'>
|
<div className='flex h-[48px] items-center justify-between border-[var(--border)] border-b p-[8px]'>
|
||||||
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>
|
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>
|
||||||
@@ -471,35 +267,19 @@ export const LogDetails = memo(function LogDetails({
|
|||||||
|
|
||||||
{/* Workflow State */}
|
{/* Workflow State */}
|
||||||
{isWorkflowExecutionLog && log.executionId && !permissionConfig.hideTraceSpans && (
|
{isWorkflowExecutionLog && log.executionId && !permissionConfig.hideTraceSpans && (
|
||||||
<div className='-mt-[8px] flex flex-col gap-[6px] rounded-[6px] border border-[var(--border)] bg-[var(--surface-2)] px-[10px] py-[8px]'>
|
<div className='flex flex-col gap-[6px] rounded-[6px] bg-[var(--surface-2)] px-[10px] py-[8px]'>
|
||||||
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>
|
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>
|
||||||
Workflow State
|
Workflow State
|
||||||
</span>
|
</span>
|
||||||
<Button
|
<button
|
||||||
variant='active'
|
|
||||||
onClick={() => setIsExecutionSnapshotOpen(true)}
|
onClick={() => setIsExecutionSnapshotOpen(true)}
|
||||||
className='flex w-full items-center justify-between px-[10px] py-[6px]'
|
className='flex items-center justify-between rounded-[6px] bg-[var(--surface-1)] px-[10px] py-[8px] transition-colors hover:bg-[var(--surface-4)]'
|
||||||
>
|
>
|
||||||
<span className='font-medium text-[12px]'>View Snapshot</span>
|
<span className='font-medium text-[12px] text-[var(--text-secondary)]'>
|
||||||
<Eye className='h-[14px] w-[14px]' />
|
View Snapshot
|
||||||
</Button>
|
</span>
|
||||||
</div>
|
<Eye className='h-[14px] w-[14px] text-[var(--text-subtle)]' />
|
||||||
)}
|
</button>
|
||||||
|
|
||||||
{/* Workflow Output */}
|
|
||||||
{isWorkflowExecutionLog && workflowOutput && !permissionConfig.hideTraceSpans && (
|
|
||||||
<div className='mt-[4px] flex flex-col gap-[6px] rounded-[6px] border border-[var(--border)] bg-[var(--surface-2)] px-[10px] py-[8px] dark:bg-transparent'>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'font-medium text-[12px]',
|
|
||||||
workflowOutput.error
|
|
||||||
? 'text-[var(--text-error)]'
|
|
||||||
: 'text-[var(--text-tertiary)]'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Workflow Output
|
|
||||||
</span>
|
|
||||||
<WorkflowOutputSection output={workflowOutput} />
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -507,12 +287,10 @@ export const LogDetails = memo(function LogDetails({
|
|||||||
{isWorkflowExecutionLog &&
|
{isWorkflowExecutionLog &&
|
||||||
log.executionData?.traceSpans &&
|
log.executionData?.traceSpans &&
|
||||||
!permissionConfig.hideTraceSpans && (
|
!permissionConfig.hideTraceSpans && (
|
||||||
<div className='mt-[4px] flex flex-col gap-[6px] rounded-[6px] border border-[var(--border)] bg-[var(--surface-2)] px-[10px] py-[8px] dark:bg-transparent'>
|
<TraceSpans
|
||||||
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>
|
traceSpans={log.executionData.traceSpans}
|
||||||
Trace Span
|
totalDuration={log.executionData.totalDuration}
|
||||||
</span>
|
/>
|
||||||
<TraceSpans traceSpans={log.executionData.traceSpans} />
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Files */}
|
{/* Files */}
|
||||||
|
|||||||
@@ -94,9 +94,7 @@ export default function Logs() {
|
|||||||
const [previewLogId, setPreviewLogId] = useState<string | null>(null)
|
const [previewLogId, setPreviewLogId] = useState<string | null>(null)
|
||||||
|
|
||||||
const activeLogId = isPreviewOpen ? previewLogId : selectedLogId
|
const activeLogId = isPreviewOpen ? previewLogId : selectedLogId
|
||||||
const activeLogQuery = useLogDetail(activeLogId ?? undefined, {
|
const activeLogQuery = useLogDetail(activeLogId ?? undefined)
|
||||||
refetchInterval: isLive ? 3000 : false,
|
|
||||||
})
|
|
||||||
|
|
||||||
const logFilters = useMemo(
|
const logFilters = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
@@ -115,7 +113,7 @@ export default function Logs() {
|
|||||||
|
|
||||||
const logsQuery = useLogsList(workspaceId, logFilters, {
|
const logsQuery = useLogsList(workspaceId, logFilters, {
|
||||||
enabled: Boolean(workspaceId) && isInitialized.current,
|
enabled: Boolean(workspaceId) && isInitialized.current,
|
||||||
refetchInterval: isLive ? 3000 : false,
|
refetchInterval: isLive ? 5000 : false,
|
||||||
})
|
})
|
||||||
|
|
||||||
const dashboardFilters = useMemo(
|
const dashboardFilters = useMemo(
|
||||||
@@ -134,7 +132,7 @@ export default function Logs() {
|
|||||||
|
|
||||||
const dashboardStatsQuery = useDashboardStats(workspaceId, dashboardFilters, {
|
const dashboardStatsQuery = useDashboardStats(workspaceId, dashboardFilters, {
|
||||||
enabled: Boolean(workspaceId) && isInitialized.current,
|
enabled: Boolean(workspaceId) && isInitialized.current,
|
||||||
refetchInterval: isLive ? 3000 : false,
|
refetchInterval: isLive ? 5000 : false,
|
||||||
})
|
})
|
||||||
|
|
||||||
const logs = useMemo(() => {
|
const logs = useMemo(() => {
|
||||||
@@ -162,6 +160,12 @@ export default function Logs() {
|
|||||||
}
|
}
|
||||||
}, [debouncedSearchQuery, setStoreSearchQuery])
|
}, [debouncedSearchQuery, setStoreSearchQuery])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isLive || !selectedLogId) return
|
||||||
|
const interval = setInterval(() => activeLogQuery.refetch(), 5000)
|
||||||
|
return () => clearInterval(interval)
|
||||||
|
}, [isLive, selectedLogId, activeLogQuery])
|
||||||
|
|
||||||
const handleLogClick = useCallback(
|
const handleLogClick = useCallback(
|
||||||
(log: WorkflowLog) => {
|
(log: WorkflowLog) => {
|
||||||
if (selectedLogId === log.id && isSidebarOpen) {
|
if (selectedLogId === log.id && isSidebarOpen) {
|
||||||
@@ -275,11 +279,8 @@ export default function Logs() {
|
|||||||
setIsVisuallyRefreshing(true)
|
setIsVisuallyRefreshing(true)
|
||||||
setTimeout(() => setIsVisuallyRefreshing(false), REFRESH_SPINNER_DURATION_MS)
|
setTimeout(() => setIsVisuallyRefreshing(false), REFRESH_SPINNER_DURATION_MS)
|
||||||
logsQuery.refetch()
|
logsQuery.refetch()
|
||||||
if (selectedLogId) {
|
|
||||||
activeLogQuery.refetch()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}, [isLive, logsQuery, activeLogQuery, selectedLogId])
|
}, [isLive, logsQuery])
|
||||||
|
|
||||||
const prevIsFetchingRef = useRef(logsQuery.isFetching)
|
const prevIsFetchingRef = useRef(logsQuery.isFetching)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ export const ActionBar = memo(
|
|||||||
'dark:border-transparent dark:bg-[var(--surface-4)]'
|
'dark:border-transparent dark:bg-[var(--surface-4)]'
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{!isNoteBlock && (
|
{!isNoteBlock && !isSubflowBlock && (
|
||||||
<Tooltip.Root>
|
<Tooltip.Root>
|
||||||
<Tooltip.Trigger asChild>
|
<Tooltip.Trigger asChild>
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -78,10 +78,9 @@ const CopilotMessage: FC<CopilotMessageProps> = memo(
|
|||||||
mode,
|
mode,
|
||||||
setMode,
|
setMode,
|
||||||
isAborting,
|
isAborting,
|
||||||
|
maskCredentialValue,
|
||||||
} = useCopilotStore()
|
} = useCopilotStore()
|
||||||
|
|
||||||
const maskCredentialValue = useCopilotStore((s) => s.maskCredentialValue)
|
|
||||||
|
|
||||||
const messageCheckpoints = isUser ? allMessageCheckpoints[message.id] || [] : []
|
const messageCheckpoints = isUser ? allMessageCheckpoints[message.id] || [] : []
|
||||||
const hasCheckpoints = messageCheckpoints.length > 0 && messageCheckpoints.some((cp) => cp?.id)
|
const hasCheckpoints = messageCheckpoints.length > 0 && messageCheckpoints.some((cp) => cp?.id)
|
||||||
|
|
||||||
@@ -266,7 +265,7 @@ const CopilotMessage: FC<CopilotMessageProps> = memo(
|
|||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
})
|
})
|
||||||
}, [message.contentBlocks, isActivelyStreaming, parsedTags, isLastMessage])
|
}, [message.contentBlocks, isActivelyStreaming, parsedTags, isLastMessage, maskCredentialValue])
|
||||||
|
|
||||||
if (isUser) {
|
if (isUser) {
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1425,7 +1425,10 @@ function RunSkipButtons({
|
|||||||
setIsProcessing(true)
|
setIsProcessing(true)
|
||||||
setButtonsHidden(true)
|
setButtonsHidden(true)
|
||||||
try {
|
try {
|
||||||
|
// Add to auto-allowed list - this also executes all pending integration tools of this type
|
||||||
await addAutoAllowedTool(toolCall.name)
|
await addAutoAllowedTool(toolCall.name)
|
||||||
|
// For client tools with interrupts (not integration tools), we still need to call handleRun
|
||||||
|
// since executeIntegrationTool only works for server-side tools
|
||||||
if (!isIntegrationTool(toolCall.name)) {
|
if (!isIntegrationTool(toolCall.name)) {
|
||||||
await handleRun(toolCall, setToolCallState, onStateChange, editedParams)
|
await handleRun(toolCall, setToolCallState, onStateChange, editedParams)
|
||||||
}
|
}
|
||||||
@@ -1523,11 +1526,7 @@ export function ToolCall({
|
|||||||
toolCall.name === 'user_memory' ||
|
toolCall.name === 'user_memory' ||
|
||||||
toolCall.name === 'edit_respond' ||
|
toolCall.name === 'edit_respond' ||
|
||||||
toolCall.name === 'debug_respond' ||
|
toolCall.name === 'debug_respond' ||
|
||||||
toolCall.name === 'plan_respond' ||
|
toolCall.name === 'plan_respond'
|
||||||
toolCall.name === 'research_respond' ||
|
|
||||||
toolCall.name === 'info_respond' ||
|
|
||||||
toolCall.name === 'deploy_respond' ||
|
|
||||||
toolCall.name === 'superagent_respond'
|
|
||||||
)
|
)
|
||||||
return null
|
return null
|
||||||
|
|
||||||
|
|||||||
@@ -209,20 +209,9 @@ export interface SlashCommand {
|
|||||||
export const TOP_LEVEL_COMMANDS: readonly SlashCommand[] = [
|
export const TOP_LEVEL_COMMANDS: readonly SlashCommand[] = [
|
||||||
{ id: 'fast', label: 'Fast' },
|
{ id: 'fast', label: 'Fast' },
|
||||||
{ id: 'research', label: 'Research' },
|
{ id: 'research', label: 'Research' },
|
||||||
{ id: 'actions', label: 'Actions' },
|
{ id: 'superagent', label: 'Actions' },
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
/**
|
|
||||||
* Maps UI command IDs to API command IDs.
|
|
||||||
* Some commands have different IDs for display vs API (e.g., "actions" -> "superagent")
|
|
||||||
*/
|
|
||||||
export function getApiCommandId(uiCommandId: string): string {
|
|
||||||
const commandMapping: Record<string, string> = {
|
|
||||||
actions: 'superagent',
|
|
||||||
}
|
|
||||||
return commandMapping[uiCommandId] || uiCommandId
|
|
||||||
}
|
|
||||||
|
|
||||||
export const WEB_COMMANDS: readonly SlashCommand[] = [
|
export const WEB_COMMANDS: readonly SlashCommand[] = [
|
||||||
{ id: 'search', label: 'Search' },
|
{ id: 'search', label: 'Search' },
|
||||||
{ id: 'read', label: 'Read' },
|
{ id: 'read', label: 'Read' },
|
||||||
|
|||||||
@@ -38,7 +38,6 @@ import type { GenerationType } from '@/blocks/types'
|
|||||||
import { normalizeName } from '@/executor/constants'
|
import { normalizeName } from '@/executor/constants'
|
||||||
import { createEnvVarPattern, createReferencePattern } from '@/executor/utils/reference-validation'
|
import { createEnvVarPattern, createReferencePattern } from '@/executor/utils/reference-validation'
|
||||||
import { useTagSelection } from '@/hooks/kb/use-tag-selection'
|
import { useTagSelection } from '@/hooks/kb/use-tag-selection'
|
||||||
import { createShouldHighlightEnvVar, useAvailableEnvVarKeys } from '@/hooks/use-available-env-vars'
|
|
||||||
|
|
||||||
const logger = createLogger('Code')
|
const logger = createLogger('Code')
|
||||||
|
|
||||||
@@ -89,27 +88,21 @@ interface CodePlaceholder {
|
|||||||
/**
|
/**
|
||||||
* Creates a syntax highlighter function with custom reference and environment variable highlighting.
|
* Creates a syntax highlighter function with custom reference and environment variable highlighting.
|
||||||
* @param effectiveLanguage - The language to use for syntax highlighting
|
* @param effectiveLanguage - The language to use for syntax highlighting
|
||||||
* @param shouldHighlightReference - Function to determine if a block reference should be highlighted
|
* @param shouldHighlightReference - Function to determine if a reference should be highlighted
|
||||||
* @param shouldHighlightEnvVar - Function to determine if an env var should be highlighted
|
|
||||||
* @returns A function that highlights code with syntax and custom highlights
|
* @returns A function that highlights code with syntax and custom highlights
|
||||||
*/
|
*/
|
||||||
const createHighlightFunction = (
|
const createHighlightFunction = (
|
||||||
effectiveLanguage: 'javascript' | 'python' | 'json',
|
effectiveLanguage: 'javascript' | 'python' | 'json',
|
||||||
shouldHighlightReference: (part: string) => boolean,
|
shouldHighlightReference: (part: string) => boolean
|
||||||
shouldHighlightEnvVar: (varName: string) => boolean
|
|
||||||
) => {
|
) => {
|
||||||
return (codeToHighlight: string): string => {
|
return (codeToHighlight: string): string => {
|
||||||
const placeholders: CodePlaceholder[] = []
|
const placeholders: CodePlaceholder[] = []
|
||||||
let processedCode = codeToHighlight
|
let processedCode = codeToHighlight
|
||||||
|
|
||||||
processedCode = processedCode.replace(createEnvVarPattern(), (match) => {
|
processedCode = processedCode.replace(createEnvVarPattern(), (match) => {
|
||||||
const varName = match.slice(2, -2).trim()
|
const placeholder = `__ENV_VAR_${placeholders.length}__`
|
||||||
if (shouldHighlightEnvVar(varName)) {
|
placeholders.push({ placeholder, original: match, type: 'env' })
|
||||||
const placeholder = `__ENV_VAR_${placeholders.length}__`
|
return placeholder
|
||||||
placeholders.push({ placeholder, original: match, type: 'env' })
|
|
||||||
return placeholder
|
|
||||||
}
|
|
||||||
return match
|
|
||||||
})
|
})
|
||||||
|
|
||||||
processedCode = processedCode.replace(createReferencePattern(), (match) => {
|
processedCode = processedCode.replace(createReferencePattern(), (match) => {
|
||||||
@@ -219,7 +212,6 @@ export const Code = memo(function Code({
|
|||||||
const accessiblePrefixes = useAccessibleReferencePrefixes(blockId)
|
const accessiblePrefixes = useAccessibleReferencePrefixes(blockId)
|
||||||
const emitTagSelection = useTagSelection(blockId, subBlockId)
|
const emitTagSelection = useTagSelection(blockId, subBlockId)
|
||||||
const [languageValue] = useSubBlockValue<string>(blockId, 'language')
|
const [languageValue] = useSubBlockValue<string>(blockId, 'language')
|
||||||
const availableEnvVars = useAvailableEnvVarKeys(workspaceId)
|
|
||||||
|
|
||||||
const effectiveLanguage = (languageValue as 'javascript' | 'python' | 'json') || language
|
const effectiveLanguage = (languageValue as 'javascript' | 'python' | 'json') || language
|
||||||
|
|
||||||
@@ -611,15 +603,9 @@ export const Code = memo(function Code({
|
|||||||
[generateCodeStream, isPromptVisible, isAiStreaming]
|
[generateCodeStream, isPromptVisible, isAiStreaming]
|
||||||
)
|
)
|
||||||
|
|
||||||
const shouldHighlightEnvVar = useMemo(
|
|
||||||
() => createShouldHighlightEnvVar(availableEnvVars),
|
|
||||||
[availableEnvVars]
|
|
||||||
)
|
|
||||||
|
|
||||||
const highlightCode = useMemo(
|
const highlightCode = useMemo(
|
||||||
() =>
|
() => createHighlightFunction(effectiveLanguage, shouldHighlightReference),
|
||||||
createHighlightFunction(effectiveLanguage, shouldHighlightReference, shouldHighlightEnvVar),
|
[effectiveLanguage, shouldHighlightReference]
|
||||||
[effectiveLanguage, shouldHighlightReference, shouldHighlightEnvVar]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const handleValueChange = useCallback(
|
const handleValueChange = useCallback(
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { ReactElement } from 'react'
|
import type { ReactElement } from 'react'
|
||||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { ChevronDown, ChevronsUpDown, ChevronUp, Plus } from 'lucide-react'
|
import { ChevronDown, ChevronsUpDown, ChevronUp, Plus } from 'lucide-react'
|
||||||
import { useParams } from 'next/navigation'
|
import { useParams } from 'next/navigation'
|
||||||
@@ -35,7 +35,6 @@ import { useAccessibleReferencePrefixes } from '@/app/workspace/[workspaceId]/w/
|
|||||||
import { normalizeName } from '@/executor/constants'
|
import { normalizeName } from '@/executor/constants'
|
||||||
import { createEnvVarPattern, createReferencePattern } from '@/executor/utils/reference-validation'
|
import { createEnvVarPattern, createReferencePattern } from '@/executor/utils/reference-validation'
|
||||||
import { useTagSelection } from '@/hooks/kb/use-tag-selection'
|
import { useTagSelection } from '@/hooks/kb/use-tag-selection'
|
||||||
import { createShouldHighlightEnvVar, useAvailableEnvVarKeys } from '@/hooks/use-available-env-vars'
|
|
||||||
import { useWorkflowStore } from '@/stores/workflows/workflow/store'
|
import { useWorkflowStore } from '@/stores/workflows/workflow/store'
|
||||||
|
|
||||||
const logger = createLogger('ConditionInput')
|
const logger = createLogger('ConditionInput')
|
||||||
@@ -124,11 +123,6 @@ export function ConditionInput({
|
|||||||
|
|
||||||
const emitTagSelection = useTagSelection(blockId, subBlockId)
|
const emitTagSelection = useTagSelection(blockId, subBlockId)
|
||||||
const accessiblePrefixes = useAccessibleReferencePrefixes(blockId)
|
const accessiblePrefixes = useAccessibleReferencePrefixes(blockId)
|
||||||
const availableEnvVars = useAvailableEnvVarKeys(workspaceId)
|
|
||||||
const shouldHighlightEnvVar = useMemo(
|
|
||||||
() => createShouldHighlightEnvVar(availableEnvVars),
|
|
||||||
[availableEnvVars]
|
|
||||||
)
|
|
||||||
|
|
||||||
const containerRef = useRef<HTMLDivElement>(null)
|
const containerRef = useRef<HTMLDivElement>(null)
|
||||||
const inputRefs = useRef<Map<string, HTMLTextAreaElement>>(new Map())
|
const inputRefs = useRef<Map<string, HTMLTextAreaElement>>(new Map())
|
||||||
@@ -1142,18 +1136,14 @@ export function ConditionInput({
|
|||||||
let processedCode = codeToHighlight
|
let processedCode = codeToHighlight
|
||||||
|
|
||||||
processedCode = processedCode.replace(createEnvVarPattern(), (match) => {
|
processedCode = processedCode.replace(createEnvVarPattern(), (match) => {
|
||||||
const varName = match.slice(2, -2).trim()
|
const placeholder = `__ENV_VAR_${placeholders.length}__`
|
||||||
if (shouldHighlightEnvVar(varName)) {
|
placeholders.push({
|
||||||
const placeholder = `__ENV_VAR_${placeholders.length}__`
|
placeholder,
|
||||||
placeholders.push({
|
original: match,
|
||||||
placeholder,
|
type: 'env',
|
||||||
original: match,
|
shouldHighlight: true,
|
||||||
type: 'env',
|
})
|
||||||
shouldHighlight: true,
|
return placeholder
|
||||||
})
|
|
||||||
return placeholder
|
|
||||||
}
|
|
||||||
return match
|
|
||||||
})
|
})
|
||||||
|
|
||||||
processedCode = processedCode.replace(
|
processedCode = processedCode.replace(
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { createCombinedPattern } from '@/executor/utils/reference-validation'
|
|||||||
|
|
||||||
export interface HighlightContext {
|
export interface HighlightContext {
|
||||||
accessiblePrefixes?: Set<string>
|
accessiblePrefixes?: Set<string>
|
||||||
availableEnvVars?: Set<string>
|
|
||||||
highlightAll?: boolean
|
highlightAll?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,17 +43,9 @@ export function formatDisplayText(text: string, context?: HighlightContext): Rea
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
const shouldHighlightEnvVar = (varName: string): boolean => {
|
|
||||||
if (context?.highlightAll) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if (context?.availableEnvVars === undefined) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return context.availableEnvVars.has(varName)
|
|
||||||
}
|
|
||||||
|
|
||||||
const nodes: ReactNode[] = []
|
const nodes: ReactNode[] = []
|
||||||
|
// Match variable references without allowing nested brackets to prevent matching across references
|
||||||
|
// e.g., "<3. text <real.ref>" should match "<3" and "<real.ref>", not the whole string
|
||||||
const regex = createCombinedPattern()
|
const regex = createCombinedPattern()
|
||||||
let lastIndex = 0
|
let lastIndex = 0
|
||||||
let key = 0
|
let key = 0
|
||||||
@@ -74,16 +65,11 @@ export function formatDisplayText(text: string, context?: HighlightContext): Rea
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (matchText.startsWith(REFERENCE.ENV_VAR_START)) {
|
if (matchText.startsWith(REFERENCE.ENV_VAR_START)) {
|
||||||
const varName = matchText.slice(2, -2).trim()
|
nodes.push(
|
||||||
if (shouldHighlightEnvVar(varName)) {
|
<span key={key++} className='text-[var(--brand-secondary)]'>
|
||||||
nodes.push(
|
{matchText}
|
||||||
<span key={key++} className='text-[var(--brand-secondary)]'>
|
</span>
|
||||||
{matchText}
|
)
|
||||||
</span>
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
nodes.push(<span key={key++}>{matchText}</span>)
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
const split = splitReferenceSegment(matchText)
|
const split = splitReferenceSegment(matchText)
|
||||||
|
|
||||||
|
|||||||
@@ -1312,16 +1312,15 @@ export const TagDropdown: React.FC<TagDropdownProps> = ({
|
|||||||
if (currentLoop && isLoopBlock) {
|
if (currentLoop && isLoopBlock) {
|
||||||
containingLoopBlockId = blockId
|
containingLoopBlockId = blockId
|
||||||
const loopType = currentLoop.loopType || 'for'
|
const loopType = currentLoop.loopType || 'for'
|
||||||
|
const contextualTags: string[] = ['index']
|
||||||
|
if (loopType === 'forEach') {
|
||||||
|
contextualTags.push('currentItem')
|
||||||
|
contextualTags.push('items')
|
||||||
|
}
|
||||||
|
|
||||||
const loopBlock = blocks[blockId]
|
const loopBlock = blocks[blockId]
|
||||||
if (loopBlock) {
|
if (loopBlock) {
|
||||||
const loopBlockName = loopBlock.name || loopBlock.type
|
const loopBlockName = loopBlock.name || loopBlock.type
|
||||||
const normalizedLoopName = normalizeName(loopBlockName)
|
|
||||||
const contextualTags: string[] = [`${normalizedLoopName}.index`]
|
|
||||||
if (loopType === 'forEach') {
|
|
||||||
contextualTags.push(`${normalizedLoopName}.currentItem`)
|
|
||||||
contextualTags.push(`${normalizedLoopName}.items`)
|
|
||||||
}
|
|
||||||
|
|
||||||
loopBlockGroup = {
|
loopBlockGroup = {
|
||||||
blockName: loopBlockName,
|
blockName: loopBlockName,
|
||||||
@@ -1329,23 +1328,21 @@ export const TagDropdown: React.FC<TagDropdownProps> = ({
|
|||||||
blockType: 'loop',
|
blockType: 'loop',
|
||||||
tags: contextualTags,
|
tags: contextualTags,
|
||||||
distance: 0,
|
distance: 0,
|
||||||
isContextual: true,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (containingLoop) {
|
} else if (containingLoop) {
|
||||||
const [loopId, loop] = containingLoop
|
const [loopId, loop] = containingLoop
|
||||||
containingLoopBlockId = loopId
|
containingLoopBlockId = loopId
|
||||||
const loopType = loop.loopType || 'for'
|
const loopType = loop.loopType || 'for'
|
||||||
|
const contextualTags: string[] = ['index']
|
||||||
|
if (loopType === 'forEach') {
|
||||||
|
contextualTags.push('currentItem')
|
||||||
|
contextualTags.push('items')
|
||||||
|
}
|
||||||
|
|
||||||
const containingLoopBlock = blocks[loopId]
|
const containingLoopBlock = blocks[loopId]
|
||||||
if (containingLoopBlock) {
|
if (containingLoopBlock) {
|
||||||
const loopBlockName = containingLoopBlock.name || containingLoopBlock.type
|
const loopBlockName = containingLoopBlock.name || containingLoopBlock.type
|
||||||
const normalizedLoopName = normalizeName(loopBlockName)
|
|
||||||
const contextualTags: string[] = [`${normalizedLoopName}.index`]
|
|
||||||
if (loopType === 'forEach') {
|
|
||||||
contextualTags.push(`${normalizedLoopName}.currentItem`)
|
|
||||||
contextualTags.push(`${normalizedLoopName}.items`)
|
|
||||||
}
|
|
||||||
|
|
||||||
loopBlockGroup = {
|
loopBlockGroup = {
|
||||||
blockName: loopBlockName,
|
blockName: loopBlockName,
|
||||||
@@ -1353,7 +1350,6 @@ export const TagDropdown: React.FC<TagDropdownProps> = ({
|
|||||||
blockType: 'loop',
|
blockType: 'loop',
|
||||||
tags: contextualTags,
|
tags: contextualTags,
|
||||||
distance: 0,
|
distance: 0,
|
||||||
isContextual: true,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1367,16 +1363,15 @@ export const TagDropdown: React.FC<TagDropdownProps> = ({
|
|||||||
const [parallelId, parallel] = containingParallel
|
const [parallelId, parallel] = containingParallel
|
||||||
containingParallelBlockId = parallelId
|
containingParallelBlockId = parallelId
|
||||||
const parallelType = parallel.parallelType || 'count'
|
const parallelType = parallel.parallelType || 'count'
|
||||||
|
const contextualTags: string[] = ['index']
|
||||||
|
if (parallelType === 'collection') {
|
||||||
|
contextualTags.push('currentItem')
|
||||||
|
contextualTags.push('items')
|
||||||
|
}
|
||||||
|
|
||||||
const containingParallelBlock = blocks[parallelId]
|
const containingParallelBlock = blocks[parallelId]
|
||||||
if (containingParallelBlock) {
|
if (containingParallelBlock) {
|
||||||
const parallelBlockName = containingParallelBlock.name || containingParallelBlock.type
|
const parallelBlockName = containingParallelBlock.name || containingParallelBlock.type
|
||||||
const normalizedParallelName = normalizeName(parallelBlockName)
|
|
||||||
const contextualTags: string[] = [`${normalizedParallelName}.index`]
|
|
||||||
if (parallelType === 'collection') {
|
|
||||||
contextualTags.push(`${normalizedParallelName}.currentItem`)
|
|
||||||
contextualTags.push(`${normalizedParallelName}.items`)
|
|
||||||
}
|
|
||||||
|
|
||||||
parallelBlockGroup = {
|
parallelBlockGroup = {
|
||||||
blockName: parallelBlockName,
|
blockName: parallelBlockName,
|
||||||
@@ -1384,7 +1379,6 @@ export const TagDropdown: React.FC<TagDropdownProps> = ({
|
|||||||
blockType: 'parallel',
|
blockType: 'parallel',
|
||||||
tags: contextualTags,
|
tags: contextualTags,
|
||||||
distance: 0,
|
distance: 0,
|
||||||
isContextual: true,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1651,29 +1645,38 @@ export const TagDropdown: React.FC<TagDropdownProps> = ({
|
|||||||
const nestedBlockTagGroups: NestedBlockTagGroup[] = useMemo(() => {
|
const nestedBlockTagGroups: NestedBlockTagGroup[] = useMemo(() => {
|
||||||
return filteredBlockTagGroups.map((group: BlockTagGroup) => {
|
return filteredBlockTagGroups.map((group: BlockTagGroup) => {
|
||||||
const normalizedBlockName = normalizeName(group.blockName)
|
const normalizedBlockName = normalizeName(group.blockName)
|
||||||
|
|
||||||
|
// Handle loop/parallel contextual tags (index, currentItem, items)
|
||||||
const directTags: NestedTag[] = []
|
const directTags: NestedTag[] = []
|
||||||
const tagsForTree: string[] = []
|
const tagsForTree: string[] = []
|
||||||
|
|
||||||
group.tags.forEach((tag: string) => {
|
group.tags.forEach((tag: string) => {
|
||||||
const tagParts = tag.split('.')
|
const tagParts = tag.split('.')
|
||||||
|
|
||||||
if (tagParts.length === 1) {
|
// Loop/parallel contextual tags without block prefix
|
||||||
|
if (
|
||||||
|
(group.blockType === 'loop' || group.blockType === 'parallel') &&
|
||||||
|
tagParts.length === 1
|
||||||
|
) {
|
||||||
directTags.push({
|
directTags.push({
|
||||||
key: tag,
|
key: tag,
|
||||||
display: tag,
|
display: tag,
|
||||||
fullTag: tag,
|
fullTag: tag,
|
||||||
})
|
})
|
||||||
} else if (tagParts.length === 2) {
|
} else if (tagParts.length === 2) {
|
||||||
|
// Direct property like blockname.property
|
||||||
directTags.push({
|
directTags.push({
|
||||||
key: tagParts[1],
|
key: tagParts[1],
|
||||||
display: tagParts[1],
|
display: tagParts[1],
|
||||||
fullTag: tag,
|
fullTag: tag,
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
|
// Nested property - add to tree builder
|
||||||
tagsForTree.push(tag)
|
tagsForTree.push(tag)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Build recursive tree from nested tags
|
||||||
const nestedTags = [...directTags, ...buildNestedTagTree(tagsForTree, normalizedBlockName)]
|
const nestedTags = [...directTags, ...buildNestedTagTree(tagsForTree, normalizedBlockName)]
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -1797,19 +1800,13 @@ export const TagDropdown: React.FC<TagDropdownProps> = ({
|
|||||||
processedTag = tag
|
processedTag = tag
|
||||||
}
|
}
|
||||||
} else if (
|
} else if (
|
||||||
blockGroup?.isContextual &&
|
blockGroup &&
|
||||||
(blockGroup.blockType === 'loop' || blockGroup.blockType === 'parallel')
|
(blockGroup.blockType === 'loop' || blockGroup.blockType === 'parallel')
|
||||||
) {
|
) {
|
||||||
const tagParts = tag.split('.')
|
if (!tag.includes('.') && ['index', 'currentItem', 'items'].includes(tag)) {
|
||||||
if (tagParts.length === 1) {
|
processedTag = `${blockGroup.blockType}.${tag}`
|
||||||
processedTag = blockGroup.blockType
|
|
||||||
} else {
|
} else {
|
||||||
const lastPart = tagParts[tagParts.length - 1]
|
processedTag = tag
|
||||||
if (['index', 'currentItem', 'items'].includes(lastPart)) {
|
|
||||||
processedTag = `${blockGroup.blockType}.${lastPart}`
|
|
||||||
} else {
|
|
||||||
processedTag = tag
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ export interface BlockTagGroup {
|
|||||||
blockType: string
|
blockType: string
|
||||||
tags: string[]
|
tags: string[]
|
||||||
distance: number
|
distance: number
|
||||||
/** True if this is a contextual group (loop/parallel iteration context available inside the subflow) */
|
|
||||||
isContextual?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -19,9 +19,6 @@ interface TextProps {
|
|||||||
* - Automatically detects and renders HTML content safely
|
* - Automatically detects and renders HTML content safely
|
||||||
* - Applies prose styling for HTML content (links, code, lists, etc.)
|
* - Applies prose styling for HTML content (links, code, lists, etc.)
|
||||||
* - Falls back to plain text rendering for non-HTML content
|
* - Falls back to plain text rendering for non-HTML content
|
||||||
*
|
|
||||||
* Note: This component renders trusted, internally-defined content only
|
|
||||||
* (e.g., trigger setup instructions). It is NOT used for user-generated content.
|
|
||||||
*/
|
*/
|
||||||
export function Text({ blockId, subBlockId, content, className }: TextProps) {
|
export function Text({ blockId, subBlockId, content, className }: TextProps) {
|
||||||
const containsHtml = /<[^>]+>/.test(content)
|
const containsHtml = /<[^>]+>/.test(content)
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { useCallback, useMemo, useRef, useState } from 'react'
|
import { useCallback, useRef, useState } from 'react'
|
||||||
import { useParams } from 'next/navigation'
|
|
||||||
import { highlight, languages } from '@/components/emcn'
|
import { highlight, languages } from '@/components/emcn'
|
||||||
import {
|
import {
|
||||||
isLikelyReferenceSegment,
|
isLikelyReferenceSegment,
|
||||||
@@ -10,7 +9,6 @@ import { checkTagTrigger } from '@/app/workspace/[workspaceId]/w/[workflowId]/co
|
|||||||
import { useAccessibleReferencePrefixes } from '@/app/workspace/[workspaceId]/w/[workflowId]/hooks/use-accessible-reference-prefixes'
|
import { useAccessibleReferencePrefixes } from '@/app/workspace/[workspaceId]/w/[workflowId]/hooks/use-accessible-reference-prefixes'
|
||||||
import { normalizeName, REFERENCE } from '@/executor/constants'
|
import { normalizeName, REFERENCE } from '@/executor/constants'
|
||||||
import { createEnvVarPattern, createReferencePattern } from '@/executor/utils/reference-validation'
|
import { createEnvVarPattern, createReferencePattern } from '@/executor/utils/reference-validation'
|
||||||
import { createShouldHighlightEnvVar, useAvailableEnvVarKeys } from '@/hooks/use-available-env-vars'
|
|
||||||
import { useCollaborativeWorkflow } from '@/hooks/use-collaborative-workflow'
|
import { useCollaborativeWorkflow } from '@/hooks/use-collaborative-workflow'
|
||||||
import { useWorkflowStore } from '@/stores/workflows/workflow/store'
|
import { useWorkflowStore } from '@/stores/workflows/workflow/store'
|
||||||
import type { BlockState } from '@/stores/workflows/workflow/types'
|
import type { BlockState } from '@/stores/workflows/workflow/types'
|
||||||
@@ -55,9 +53,6 @@ const SUBFLOW_CONFIG = {
|
|||||||
* @returns Subflow editor state and handlers
|
* @returns Subflow editor state and handlers
|
||||||
*/
|
*/
|
||||||
export function useSubflowEditor(currentBlock: BlockState | null, currentBlockId: string | null) {
|
export function useSubflowEditor(currentBlock: BlockState | null, currentBlockId: string | null) {
|
||||||
const params = useParams()
|
|
||||||
const workspaceId = params.workspaceId as string
|
|
||||||
|
|
||||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null)
|
const textareaRef = useRef<HTMLTextAreaElement | null>(null)
|
||||||
const editorContainerRef = useRef<HTMLDivElement>(null)
|
const editorContainerRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
@@ -86,13 +81,6 @@ export function useSubflowEditor(currentBlock: BlockState | null, currentBlockId
|
|||||||
// Get accessible prefixes for tag dropdown
|
// Get accessible prefixes for tag dropdown
|
||||||
const accessiblePrefixes = useAccessibleReferencePrefixes(currentBlockId || '')
|
const accessiblePrefixes = useAccessibleReferencePrefixes(currentBlockId || '')
|
||||||
|
|
||||||
// Get available env vars for highlighting validation
|
|
||||||
const availableEnvVars = useAvailableEnvVarKeys(workspaceId)
|
|
||||||
const shouldHighlightEnvVar = useMemo(
|
|
||||||
() => createShouldHighlightEnvVar(availableEnvVars),
|
|
||||||
[availableEnvVars]
|
|
||||||
)
|
|
||||||
|
|
||||||
// Collaborative actions
|
// Collaborative actions
|
||||||
const {
|
const {
|
||||||
collaborativeUpdateLoopType,
|
collaborativeUpdateLoopType,
|
||||||
@@ -152,13 +140,9 @@ export function useSubflowEditor(currentBlock: BlockState | null, currentBlockId
|
|||||||
let processedCode = code
|
let processedCode = code
|
||||||
|
|
||||||
processedCode = processedCode.replace(createEnvVarPattern(), (match) => {
|
processedCode = processedCode.replace(createEnvVarPattern(), (match) => {
|
||||||
const varName = match.slice(2, -2).trim()
|
const placeholder = `__ENV_VAR_${placeholders.length}__`
|
||||||
if (shouldHighlightEnvVar(varName)) {
|
placeholders.push({ placeholder, original: match, type: 'env' })
|
||||||
const placeholder = `__ENV_VAR_${placeholders.length}__`
|
return placeholder
|
||||||
placeholders.push({ placeholder, original: match, type: 'env' })
|
|
||||||
return placeholder
|
|
||||||
}
|
|
||||||
return match
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// Use [^<>]+ to prevent matching across nested brackets (e.g., "<3 <real.ref>" should match separately)
|
// Use [^<>]+ to prevent matching across nested brackets (e.g., "<3 <real.ref>" should match separately)
|
||||||
@@ -190,7 +174,7 @@ export function useSubflowEditor(currentBlock: BlockState | null, currentBlockId
|
|||||||
|
|
||||||
return highlightedCode
|
return highlightedCode
|
||||||
},
|
},
|
||||||
[shouldHighlightReference, shouldHighlightEnvVar]
|
[shouldHighlightReference]
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { useStoreWithEqualityFn } from 'zustand/traditional'
|
|||||||
import { Badge, Tooltip } from '@/components/emcn'
|
import { Badge, Tooltip } from '@/components/emcn'
|
||||||
import { cn } from '@/lib/core/utils/cn'
|
import { cn } from '@/lib/core/utils/cn'
|
||||||
import { getBaseUrl } from '@/lib/core/utils/urls'
|
import { getBaseUrl } from '@/lib/core/utils/urls'
|
||||||
import { createMcpToolId } from '@/lib/mcp/shared'
|
import { createMcpToolId } from '@/lib/mcp/utils'
|
||||||
import { getProviderIdFromServiceId } from '@/lib/oauth'
|
import { getProviderIdFromServiceId } from '@/lib/oauth'
|
||||||
import { BLOCK_DIMENSIONS, HANDLE_POSITIONS } from '@/lib/workflows/blocks/block-dimensions'
|
import { BLOCK_DIMENSIONS, HANDLE_POSITIONS } from '@/lib/workflows/blocks/block-dimensions'
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import {
|
|||||||
import { ReactFlowProvider } from 'reactflow'
|
import { ReactFlowProvider } from 'reactflow'
|
||||||
import { Badge, Button, ChevronDown, Code, Combobox, Input, Label } from '@/components/emcn'
|
import { Badge, Button, ChevronDown, Code, Combobox, Input, Label } from '@/components/emcn'
|
||||||
import { cn } from '@/lib/core/utils/cn'
|
import { cn } from '@/lib/core/utils/cn'
|
||||||
import { formatDuration } from '@/lib/core/utils/formatting'
|
|
||||||
import { extractReferencePrefixes } from '@/lib/workflows/sanitization/references'
|
import { extractReferencePrefixes } from '@/lib/workflows/sanitization/references'
|
||||||
import {
|
import {
|
||||||
buildCanonicalIndex,
|
buildCanonicalIndex,
|
||||||
@@ -705,6 +704,14 @@ interface PreviewEditorProps {
|
|||||||
onClose?: () => void
|
onClose?: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format duration for display
|
||||||
|
*/
|
||||||
|
function formatDuration(ms: number): string {
|
||||||
|
if (ms < 1000) return `${ms}ms`
|
||||||
|
return `${(ms / 1000).toFixed(2)}s`
|
||||||
|
}
|
||||||
|
|
||||||
/** Minimum height for the connections section (header only) */
|
/** Minimum height for the connections section (header only) */
|
||||||
const MIN_CONNECTIONS_HEIGHT = 30
|
const MIN_CONNECTIONS_HEIGHT = 30
|
||||||
/** Maximum height for the connections section */
|
/** Maximum height for the connections section */
|
||||||
@@ -1173,7 +1180,7 @@ function PreviewEditorContent({
|
|||||||
)}
|
)}
|
||||||
{executionData.durationMs !== undefined && (
|
{executionData.durationMs !== undefined && (
|
||||||
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>
|
<span className='font-medium text-[12px] text-[var(--text-tertiary)]'>
|
||||||
{formatDuration(executionData.durationMs, { precision: 2 })}
|
{formatDuration(executionData.durationMs)}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -448,7 +448,7 @@ export const SearchModal = memo(function SearchModal({
|
|||||||
}, [workspaces, workflows, pages, blocks, triggers, tools, toolOperations, docs])
|
}, [workspaces, workflows, pages, blocks, triggers, tools, toolOperations, docs])
|
||||||
|
|
||||||
const sectionOrder = useMemo<SearchItem['type'][]>(
|
const sectionOrder = useMemo<SearchItem['type'][]>(
|
||||||
() => ['block', 'tool', 'trigger', 'doc', 'tool-operation', 'workflow', 'workspace', 'page'],
|
() => ['block', 'tool', 'tool-operation', 'trigger', 'workflow', 'workspace', 'page', 'doc'],
|
||||||
[]
|
[]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -102,47 +102,6 @@ function calculateAliasScore(
|
|||||||
return { score: 0, matchType: null }
|
return { score: 0, matchType: null }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Calculate multi-word match score
|
|
||||||
* Each word in the query must appear somewhere in the field
|
|
||||||
* Returns a score based on how well the words match
|
|
||||||
*/
|
|
||||||
function calculateMultiWordScore(
|
|
||||||
queryWords: string[],
|
|
||||||
field: string
|
|
||||||
): { score: number; matchType: 'word-boundary' | 'substring' | null } {
|
|
||||||
const normalizedField = field.toLowerCase().trim()
|
|
||||||
const fieldWords = normalizedField.split(/[\s\-_/:]+/)
|
|
||||||
|
|
||||||
let allWordsMatch = true
|
|
||||||
let totalScore = 0
|
|
||||||
let hasWordBoundary = false
|
|
||||||
|
|
||||||
for (const queryWord of queryWords) {
|
|
||||||
const wordBoundaryMatch = fieldWords.some((fw) => fw.startsWith(queryWord))
|
|
||||||
const substringMatch = normalizedField.includes(queryWord)
|
|
||||||
|
|
||||||
if (wordBoundaryMatch) {
|
|
||||||
totalScore += SCORE_WORD_BOUNDARY
|
|
||||||
hasWordBoundary = true
|
|
||||||
} else if (substringMatch) {
|
|
||||||
totalScore += SCORE_SUBSTRING_MATCH
|
|
||||||
} else {
|
|
||||||
allWordsMatch = false
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!allWordsMatch) {
|
|
||||||
return { score: 0, matchType: null }
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
score: totalScore / queryWords.length,
|
|
||||||
matchType: hasWordBoundary ? 'word-boundary' : 'substring',
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Search items using tiered matching algorithm
|
* Search items using tiered matching algorithm
|
||||||
* Returns items sorted by relevance (highest score first)
|
* Returns items sorted by relevance (highest score first)
|
||||||
@@ -158,8 +117,6 @@ export function searchItems<T extends SearchableItem>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const results: SearchResult<T>[] = []
|
const results: SearchResult<T>[] = []
|
||||||
const queryWords = normalizedQuery.toLowerCase().split(/\s+/).filter(Boolean)
|
|
||||||
const isMultiWord = queryWords.length > 1
|
|
||||||
|
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
const nameMatch = calculateFieldScore(normalizedQuery, item.name)
|
const nameMatch = calculateFieldScore(normalizedQuery, item.name)
|
||||||
@@ -170,35 +127,16 @@ export function searchItems<T extends SearchableItem>(
|
|||||||
|
|
||||||
const aliasMatch = calculateAliasScore(normalizedQuery, item.aliases)
|
const aliasMatch = calculateAliasScore(normalizedQuery, item.aliases)
|
||||||
|
|
||||||
let nameScore = nameMatch.score
|
const nameScore = nameMatch.score
|
||||||
let descScore = descMatch.score * DESCRIPTION_WEIGHT
|
const descScore = descMatch.score * DESCRIPTION_WEIGHT
|
||||||
const aliasScore = aliasMatch.score
|
const aliasScore = aliasMatch.score
|
||||||
|
|
||||||
let bestMatchType = nameMatch.matchType
|
|
||||||
|
|
||||||
// For multi-word queries, also try matching each word independently and take the better score
|
|
||||||
if (isMultiWord) {
|
|
||||||
const multiWordNameMatch = calculateMultiWordScore(queryWords, item.name)
|
|
||||||
if (multiWordNameMatch.score > nameScore) {
|
|
||||||
nameScore = multiWordNameMatch.score
|
|
||||||
bestMatchType = multiWordNameMatch.matchType
|
|
||||||
}
|
|
||||||
|
|
||||||
if (item.description) {
|
|
||||||
const multiWordDescMatch = calculateMultiWordScore(queryWords, item.description)
|
|
||||||
const multiWordDescScore = multiWordDescMatch.score * DESCRIPTION_WEIGHT
|
|
||||||
if (multiWordDescScore > descScore) {
|
|
||||||
descScore = multiWordDescScore
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const bestScore = Math.max(nameScore, descScore, aliasScore)
|
const bestScore = Math.max(nameScore, descScore, aliasScore)
|
||||||
|
|
||||||
if (bestScore > 0) {
|
if (bestScore > 0) {
|
||||||
let matchType: SearchResult<T>['matchType'] = 'substring'
|
let matchType: SearchResult<T>['matchType'] = 'substring'
|
||||||
if (nameScore >= descScore && nameScore >= aliasScore) {
|
if (nameScore >= descScore && nameScore >= aliasScore) {
|
||||||
matchType = bestMatchType || 'substring'
|
matchType = nameMatch.matchType || 'substring'
|
||||||
} else if (aliasScore >= descScore) {
|
} else if (aliasScore >= descScore) {
|
||||||
matchType = 'alias'
|
matchType = 'alias'
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -688,7 +688,7 @@ export function AccessControl() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='flex items-center justify-between'>
|
<div className='flex items-center justify-between rounded-[8px] border border-[var(--border)] px-[12px] py-[10px]'>
|
||||||
<div className='flex flex-col gap-[2px]'>
|
<div className='flex flex-col gap-[2px]'>
|
||||||
<span className='font-medium text-[13px] text-[var(--text-primary)]'>
|
<span className='font-medium text-[13px] text-[var(--text-primary)]'>
|
||||||
Auto-add new members
|
Auto-add new members
|
||||||
@@ -705,7 +705,7 @@ export function AccessControl() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='min-h-0 flex-1 overflow-y-auto'>
|
<div className='min-h-0 flex-1 overflow-y-auto'>
|
||||||
<div className='flex flex-col gap-[8px]'>
|
<div className='flex flex-col gap-[16px]'>
|
||||||
<div className='flex items-center justify-between'>
|
<div className='flex items-center justify-between'>
|
||||||
<span className='font-medium text-[13px] text-[var(--text-secondary)]'>
|
<span className='font-medium text-[13px] text-[var(--text-secondary)]'>
|
||||||
Members
|
Members
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import {
|
|||||||
} from '@/components/emcn'
|
} from '@/components/emcn'
|
||||||
import { Input, Skeleton } from '@/components/ui'
|
import { Input, Skeleton } from '@/components/ui'
|
||||||
import { useSession } from '@/lib/auth/auth-client'
|
import { useSession } from '@/lib/auth/auth-client'
|
||||||
import { formatDate } from '@/lib/core/utils/formatting'
|
|
||||||
import { useUserPermissionsContext } from '@/app/workspace/[workspaceId]/providers/workspace-permissions-provider'
|
import { useUserPermissionsContext } from '@/app/workspace/[workspaceId]/providers/workspace-permissions-provider'
|
||||||
import {
|
import {
|
||||||
type ApiKey,
|
type ApiKey,
|
||||||
@@ -134,9 +133,13 @@ export function ApiKeys({ onOpenChange, registerCloseHandler }: ApiKeysProps) {
|
|||||||
}
|
}
|
||||||
}, [shouldScrollToBottom])
|
}, [shouldScrollToBottom])
|
||||||
|
|
||||||
const formatLastUsed = (dateString?: string) => {
|
const formatDate = (dateString?: string) => {
|
||||||
if (!dateString) return 'Never'
|
if (!dateString) return 'Never'
|
||||||
return formatDate(new Date(dateString))
|
return new Date(dateString).toLocaleDateString('en-US', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -213,7 +216,7 @@ export function ApiKeys({ onOpenChange, registerCloseHandler }: ApiKeysProps) {
|
|||||||
{key.name}
|
{key.name}
|
||||||
</span>
|
</span>
|
||||||
<span className='text-[13px] text-[var(--text-secondary)]'>
|
<span className='text-[13px] text-[var(--text-secondary)]'>
|
||||||
(last used: {formatLastUsed(key.lastUsed).toLowerCase()})
|
(last used: {formatDate(key.lastUsed).toLowerCase()})
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<p className='truncate text-[13px] text-[var(--text-muted)]'>
|
<p className='truncate text-[13px] text-[var(--text-muted)]'>
|
||||||
@@ -248,7 +251,7 @@ export function ApiKeys({ onOpenChange, registerCloseHandler }: ApiKeysProps) {
|
|||||||
{key.name}
|
{key.name}
|
||||||
</span>
|
</span>
|
||||||
<span className='text-[13px] text-[var(--text-secondary)]'>
|
<span className='text-[13px] text-[var(--text-secondary)]'>
|
||||||
(last used: {formatLastUsed(key.lastUsed).toLowerCase()})
|
(last used: {formatDate(key.lastUsed).toLowerCase()})
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<p className='truncate text-[13px] text-[var(--text-muted)]'>
|
<p className='truncate text-[13px] text-[var(--text-muted)]'>
|
||||||
@@ -288,7 +291,7 @@ export function ApiKeys({ onOpenChange, registerCloseHandler }: ApiKeysProps) {
|
|||||||
{key.name}
|
{key.name}
|
||||||
</span>
|
</span>
|
||||||
<span className='text-[13px] text-[var(--text-secondary)]'>
|
<span className='text-[13px] text-[var(--text-secondary)]'>
|
||||||
(last used: {formatLastUsed(key.lastUsed).toLowerCase()})
|
(last used: {formatDate(key.lastUsed).toLowerCase()})
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<p className='truncate text-[13px] text-[var(--text-muted)]'>
|
<p className='truncate text-[13px] text-[var(--text-muted)]'>
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import {
|
|||||||
ModalHeader,
|
ModalHeader,
|
||||||
} from '@/components/emcn'
|
} from '@/components/emcn'
|
||||||
import { Input, Skeleton } from '@/components/ui'
|
import { Input, Skeleton } from '@/components/ui'
|
||||||
import { formatDate } from '@/lib/core/utils/formatting'
|
|
||||||
import {
|
import {
|
||||||
type CopilotKey,
|
type CopilotKey,
|
||||||
useCopilotKeys,
|
useCopilotKeys,
|
||||||
@@ -116,9 +115,13 @@ export function Copilot() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const formatLastUsed = (dateString?: string | null) => {
|
const formatDate = (dateString?: string | null) => {
|
||||||
if (!dateString) return 'Never'
|
if (!dateString) return 'Never'
|
||||||
return formatDate(new Date(dateString))
|
return new Date(dateString).toLocaleDateString('en-US', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasKeys = keys.length > 0
|
const hasKeys = keys.length > 0
|
||||||
@@ -177,7 +180,7 @@ export function Copilot() {
|
|||||||
{key.name || 'Unnamed Key'}
|
{key.name || 'Unnamed Key'}
|
||||||
</span>
|
</span>
|
||||||
<span className='text-[13px] text-[var(--text-secondary)]'>
|
<span className='text-[13px] text-[var(--text-secondary)]'>
|
||||||
(last used: {formatLastUsed(key.lastUsed).toLowerCase()})
|
(last used: {formatDate(key.lastUsed).toLowerCase()})
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<p className='truncate text-[13px] text-[var(--text-muted)]'>
|
<p className='truncate text-[13px] text-[var(--text-muted)]'>
|
||||||
|
|||||||
@@ -39,7 +39,6 @@ import {
|
|||||||
useRefreshMcpServer,
|
useRefreshMcpServer,
|
||||||
useStoredMcpTools,
|
useStoredMcpTools,
|
||||||
} from '@/hooks/queries/mcp'
|
} from '@/hooks/queries/mcp'
|
||||||
import { useAvailableEnvVarKeys } from '@/hooks/use-available-env-vars'
|
|
||||||
import { useWorkflowRegistry } from '@/stores/workflows/registry/store'
|
import { useWorkflowRegistry } from '@/stores/workflows/registry/store'
|
||||||
import { useSubBlockStore } from '@/stores/workflows/subblock/store'
|
import { useSubBlockStore } from '@/stores/workflows/subblock/store'
|
||||||
import { FormField, McpServerSkeleton } from './components'
|
import { FormField, McpServerSkeleton } from './components'
|
||||||
@@ -158,7 +157,6 @@ interface FormattedInputProps {
|
|||||||
scrollLeft: number
|
scrollLeft: number
|
||||||
showEnvVars: boolean
|
showEnvVars: boolean
|
||||||
envVarProps: EnvVarDropdownConfig
|
envVarProps: EnvVarDropdownConfig
|
||||||
availableEnvVars?: Set<string>
|
|
||||||
className?: string
|
className?: string
|
||||||
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
|
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
|
||||||
onScroll: (scrollLeft: number) => void
|
onScroll: (scrollLeft: number) => void
|
||||||
@@ -171,7 +169,6 @@ function FormattedInput({
|
|||||||
scrollLeft,
|
scrollLeft,
|
||||||
showEnvVars,
|
showEnvVars,
|
||||||
envVarProps,
|
envVarProps,
|
||||||
availableEnvVars,
|
|
||||||
className,
|
className,
|
||||||
onChange,
|
onChange,
|
||||||
onScroll,
|
onScroll,
|
||||||
@@ -193,7 +190,7 @@ function FormattedInput({
|
|||||||
/>
|
/>
|
||||||
<div className='pointer-events-none absolute inset-0 flex items-center overflow-hidden px-[8px] py-[6px] font-medium font-sans text-sm'>
|
<div className='pointer-events-none absolute inset-0 flex items-center overflow-hidden px-[8px] py-[6px] font-medium font-sans text-sm'>
|
||||||
<div className='whitespace-nowrap' style={{ transform: `translateX(-${scrollLeft}px)` }}>
|
<div className='whitespace-nowrap' style={{ transform: `translateX(-${scrollLeft}px)` }}>
|
||||||
{formatDisplayText(value, { availableEnvVars })}
|
{formatDisplayText(value)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{showEnvVars && (
|
{showEnvVars && (
|
||||||
@@ -224,7 +221,6 @@ interface HeaderRowProps {
|
|||||||
envSearchTerm: string
|
envSearchTerm: string
|
||||||
cursorPosition: number
|
cursorPosition: number
|
||||||
workspaceId: string
|
workspaceId: string
|
||||||
availableEnvVars?: Set<string>
|
|
||||||
onInputChange: (field: InputFieldType, value: string, index?: number) => void
|
onInputChange: (field: InputFieldType, value: string, index?: number) => void
|
||||||
onHeaderScroll: (key: string, scrollLeft: number) => void
|
onHeaderScroll: (key: string, scrollLeft: number) => void
|
||||||
onEnvVarSelect: (value: string) => void
|
onEnvVarSelect: (value: string) => void
|
||||||
@@ -242,7 +238,6 @@ function HeaderRow({
|
|||||||
envSearchTerm,
|
envSearchTerm,
|
||||||
cursorPosition,
|
cursorPosition,
|
||||||
workspaceId,
|
workspaceId,
|
||||||
availableEnvVars,
|
|
||||||
onInputChange,
|
onInputChange,
|
||||||
onHeaderScroll,
|
onHeaderScroll,
|
||||||
onEnvVarSelect,
|
onEnvVarSelect,
|
||||||
@@ -270,7 +265,6 @@ function HeaderRow({
|
|||||||
scrollLeft={headerScrollLeft[`key-${index}`] || 0}
|
scrollLeft={headerScrollLeft[`key-${index}`] || 0}
|
||||||
showEnvVars={isKeyActive}
|
showEnvVars={isKeyActive}
|
||||||
envVarProps={envVarProps}
|
envVarProps={envVarProps}
|
||||||
availableEnvVars={availableEnvVars}
|
|
||||||
className='flex-1'
|
className='flex-1'
|
||||||
onChange={(e) => onInputChange('header-key', e.target.value, index)}
|
onChange={(e) => onInputChange('header-key', e.target.value, index)}
|
||||||
onScroll={(scrollLeft) => onHeaderScroll(`key-${index}`, scrollLeft)}
|
onScroll={(scrollLeft) => onHeaderScroll(`key-${index}`, scrollLeft)}
|
||||||
@@ -282,7 +276,6 @@ function HeaderRow({
|
|||||||
scrollLeft={headerScrollLeft[`value-${index}`] || 0}
|
scrollLeft={headerScrollLeft[`value-${index}`] || 0}
|
||||||
showEnvVars={isValueActive}
|
showEnvVars={isValueActive}
|
||||||
envVarProps={envVarProps}
|
envVarProps={envVarProps}
|
||||||
availableEnvVars={availableEnvVars}
|
|
||||||
className='flex-1'
|
className='flex-1'
|
||||||
onChange={(e) => onInputChange('header-value', e.target.value, index)}
|
onChange={(e) => onInputChange('header-value', e.target.value, index)}
|
||||||
onScroll={(scrollLeft) => onHeaderScroll(`value-${index}`, scrollLeft)}
|
onScroll={(scrollLeft) => onHeaderScroll(`value-${index}`, scrollLeft)}
|
||||||
@@ -378,7 +371,6 @@ export function MCP({ initialServerId }: MCPProps) {
|
|||||||
const deleteServerMutation = useDeleteMcpServer()
|
const deleteServerMutation = useDeleteMcpServer()
|
||||||
const refreshServerMutation = useRefreshMcpServer()
|
const refreshServerMutation = useRefreshMcpServer()
|
||||||
const { testResult, isTestingConnection, testConnection, clearTestResult } = useMcpServerTest()
|
const { testResult, isTestingConnection, testConnection, clearTestResult } = useMcpServerTest()
|
||||||
const availableEnvVars = useAvailableEnvVarKeys(workspaceId)
|
|
||||||
|
|
||||||
const urlInputRef = useRef<HTMLInputElement>(null)
|
const urlInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
@@ -1069,7 +1061,6 @@ export function MCP({ initialServerId }: MCPProps) {
|
|||||||
onSelect: handleEnvVarSelect,
|
onSelect: handleEnvVarSelect,
|
||||||
onClose: resetEnvVarState,
|
onClose: resetEnvVarState,
|
||||||
}}
|
}}
|
||||||
availableEnvVars={availableEnvVars}
|
|
||||||
onChange={(e) => handleInputChange('url', e.target.value)}
|
onChange={(e) => handleInputChange('url', e.target.value)}
|
||||||
onScroll={(scrollLeft) => handleUrlScroll(scrollLeft)}
|
onScroll={(scrollLeft) => handleUrlScroll(scrollLeft)}
|
||||||
/>
|
/>
|
||||||
@@ -1103,7 +1094,6 @@ export function MCP({ initialServerId }: MCPProps) {
|
|||||||
envSearchTerm={envSearchTerm}
|
envSearchTerm={envSearchTerm}
|
||||||
cursorPosition={cursorPosition}
|
cursorPosition={cursorPosition}
|
||||||
workspaceId={workspaceId}
|
workspaceId={workspaceId}
|
||||||
availableEnvVars={availableEnvVars}
|
|
||||||
onInputChange={handleInputChange}
|
onInputChange={handleInputChange}
|
||||||
onHeaderScroll={handleHeaderScroll}
|
onHeaderScroll={handleHeaderScroll}
|
||||||
onEnvVarSelect={handleEnvVarSelect}
|
onEnvVarSelect={handleEnvVarSelect}
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import { useParams } from 'next/navigation'
|
|||||||
import { Combobox, Label, Switch, Tooltip } from '@/components/emcn'
|
import { Combobox, Label, Switch, Tooltip } from '@/components/emcn'
|
||||||
import { Skeleton } from '@/components/ui'
|
import { Skeleton } from '@/components/ui'
|
||||||
import { useSession } from '@/lib/auth/auth-client'
|
import { useSession } from '@/lib/auth/auth-client'
|
||||||
import { USAGE_THRESHOLDS } from '@/lib/billing/client/consts'
|
|
||||||
import { useSubscriptionUpgrade } from '@/lib/billing/client/upgrade'
|
import { useSubscriptionUpgrade } from '@/lib/billing/client/upgrade'
|
||||||
|
import { USAGE_THRESHOLDS } from '@/lib/billing/client/usage-visualization'
|
||||||
import { getEffectiveSeats } from '@/lib/billing/subscriptions/utils'
|
import { getEffectiveSeats } from '@/lib/billing/subscriptions/utils'
|
||||||
import { cn } from '@/lib/core/utils/cn'
|
import { cn } from '@/lib/core/utils/cn'
|
||||||
import { getBaseUrl } from '@/lib/core/utils/urls'
|
import { getBaseUrl } from '@/lib/core/utils/urls'
|
||||||
|
|||||||
@@ -2,7 +2,11 @@
|
|||||||
|
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { Badge } from '@/components/emcn'
|
import { Badge } from '@/components/emcn'
|
||||||
import { getFilledPillColor, USAGE_PILL_COLORS, USAGE_THRESHOLDS } from '@/lib/billing/client'
|
import {
|
||||||
|
getFilledPillColor,
|
||||||
|
USAGE_PILL_COLORS,
|
||||||
|
USAGE_THRESHOLDS,
|
||||||
|
} from '@/lib/billing/client/usage-visualization'
|
||||||
|
|
||||||
const PILL_COUNT = 5
|
const PILL_COUNT = 5
|
||||||
|
|
||||||
|
|||||||
@@ -5,14 +5,13 @@ import { createLogger } from '@sim/logger'
|
|||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
import { Badge } from '@/components/emcn'
|
import { Badge } from '@/components/emcn'
|
||||||
import { Skeleton } from '@/components/ui'
|
import { Skeleton } from '@/components/ui'
|
||||||
import { USAGE_PILL_COLORS, USAGE_THRESHOLDS } from '@/lib/billing/client/consts'
|
|
||||||
import { useSubscriptionUpgrade } from '@/lib/billing/client/upgrade'
|
import { useSubscriptionUpgrade } from '@/lib/billing/client/upgrade'
|
||||||
import {
|
import {
|
||||||
getBillingStatus,
|
|
||||||
getFilledPillColor,
|
getFilledPillColor,
|
||||||
getSubscriptionStatus,
|
USAGE_PILL_COLORS,
|
||||||
getUsage,
|
USAGE_THRESHOLDS,
|
||||||
} from '@/lib/billing/client/utils'
|
} from '@/lib/billing/client/usage-visualization'
|
||||||
|
import { getBillingStatus, getSubscriptionStatus, getUsage } from '@/lib/billing/client/utils'
|
||||||
import { useContextMenu } from '@/app/workspace/[workspaceId]/w/components/sidebar/hooks'
|
import { useContextMenu } from '@/app/workspace/[workspaceId]/w/components/sidebar/hooks'
|
||||||
import { useSocket } from '@/app/workspace/providers/socket-provider'
|
import { useSocket } from '@/app/workspace/providers/socket-provider'
|
||||||
import { subscriptionKeys, useSubscriptionData } from '@/hooks/queries/subscription'
|
import { subscriptionKeys, useSubscriptionData } from '@/hooks/queries/subscription'
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { task } from '@trigger.dev/sdk'
|
|||||||
import { Cron } from 'croner'
|
import { Cron } from 'croner'
|
||||||
import { eq } from 'drizzle-orm'
|
import { eq } from 'drizzle-orm'
|
||||||
import { v4 as uuidv4 } from 'uuid'
|
import { v4 as uuidv4 } from 'uuid'
|
||||||
|
import type { ZodRecord, ZodString } from 'zod'
|
||||||
|
import { getPersonalAndWorkspaceEnv } from '@/lib/environment/utils'
|
||||||
import { preprocessExecution } from '@/lib/execution/preprocessing'
|
import { preprocessExecution } from '@/lib/execution/preprocessing'
|
||||||
import { LoggingSession } from '@/lib/logs/execution/logging-session'
|
import { LoggingSession } from '@/lib/logs/execution/logging-session'
|
||||||
import { buildTraceSpans } from '@/lib/logs/execution/trace-spans/trace-spans'
|
import { buildTraceSpans } from '@/lib/logs/execution/trace-spans/trace-spans'
|
||||||
@@ -120,6 +122,7 @@ async function runWorkflowExecution({
|
|||||||
loggingSession,
|
loggingSession,
|
||||||
requestId,
|
requestId,
|
||||||
executionId,
|
executionId,
|
||||||
|
EnvVarsSchema,
|
||||||
}: {
|
}: {
|
||||||
payload: ScheduleExecutionPayload
|
payload: ScheduleExecutionPayload
|
||||||
workflowRecord: WorkflowRecord
|
workflowRecord: WorkflowRecord
|
||||||
@@ -127,6 +130,7 @@ async function runWorkflowExecution({
|
|||||||
loggingSession: LoggingSession
|
loggingSession: LoggingSession
|
||||||
requestId: string
|
requestId: string
|
||||||
executionId: string
|
executionId: string
|
||||||
|
EnvVarsSchema: ZodRecord<ZodString, ZodString>
|
||||||
}): Promise<RunWorkflowResult> {
|
}): Promise<RunWorkflowResult> {
|
||||||
try {
|
try {
|
||||||
logger.debug(`[${requestId}] Loading deployed workflow ${payload.workflowId}`)
|
logger.debug(`[${requestId}] Loading deployed workflow ${payload.workflowId}`)
|
||||||
@@ -152,12 +156,31 @@ async function runWorkflowExecution({
|
|||||||
throw new Error(`Workflow ${payload.workflowId} has no associated workspace`)
|
throw new Error(`Workflow ${payload.workflowId} has no associated workspace`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const personalEnvUserId = workflowRecord.userId
|
||||||
|
|
||||||
|
const { personalEncrypted, workspaceEncrypted } = await getPersonalAndWorkspaceEnv(
|
||||||
|
personalEnvUserId,
|
||||||
|
workspaceId
|
||||||
|
)
|
||||||
|
|
||||||
|
const variables = EnvVarsSchema.parse({
|
||||||
|
...personalEncrypted,
|
||||||
|
...workspaceEncrypted,
|
||||||
|
})
|
||||||
|
|
||||||
const input = {
|
const input = {
|
||||||
_context: {
|
_context: {
|
||||||
workflowId: payload.workflowId,
|
workflowId: payload.workflowId,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await loggingSession.safeStart({
|
||||||
|
userId: actorUserId,
|
||||||
|
workspaceId,
|
||||||
|
variables: variables || {},
|
||||||
|
deploymentVersionId,
|
||||||
|
})
|
||||||
|
|
||||||
const metadata: ExecutionMetadata = {
|
const metadata: ExecutionMetadata = {
|
||||||
requestId,
|
requestId,
|
||||||
executionId,
|
executionId,
|
||||||
@@ -256,6 +279,7 @@ export type ScheduleExecutionPayload = {
|
|||||||
failedCount?: number
|
failedCount?: number
|
||||||
now: string
|
now: string
|
||||||
scheduledFor?: string
|
scheduledFor?: string
|
||||||
|
preflighted?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
function calculateNextRunTime(
|
function calculateNextRunTime(
|
||||||
@@ -295,6 +319,9 @@ export async function executeScheduleJob(payload: ScheduleExecutionPayload) {
|
|||||||
executionId,
|
executionId,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const zod = await import('zod')
|
||||||
|
const EnvVarsSchema = zod.z.record(zod.z.string())
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const loggingSession = new LoggingSession(
|
const loggingSession = new LoggingSession(
|
||||||
payload.workflowId,
|
payload.workflowId,
|
||||||
@@ -312,6 +339,7 @@ export async function executeScheduleJob(payload: ScheduleExecutionPayload) {
|
|||||||
checkRateLimit: true,
|
checkRateLimit: true,
|
||||||
checkDeployment: true,
|
checkDeployment: true,
|
||||||
loggingSession,
|
loggingSession,
|
||||||
|
preflightEnvVars: !payload.preflighted,
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!preprocessResult.success) {
|
if (!preprocessResult.success) {
|
||||||
@@ -454,6 +482,7 @@ export async function executeScheduleJob(payload: ScheduleExecutionPayload) {
|
|||||||
loggingSession,
|
loggingSession,
|
||||||
requestId,
|
requestId,
|
||||||
executionId,
|
executionId,
|
||||||
|
EnvVarsSchema,
|
||||||
})
|
})
|
||||||
|
|
||||||
if (executionResult.status === 'skip') {
|
if (executionResult.status === 'skip') {
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import { getWorkflowById } from '@/lib/workflows/utils'
|
|||||||
import { ExecutionSnapshot } from '@/executor/execution/snapshot'
|
import { ExecutionSnapshot } from '@/executor/execution/snapshot'
|
||||||
import type { ExecutionMetadata } from '@/executor/execution/types'
|
import type { ExecutionMetadata } from '@/executor/execution/types'
|
||||||
import type { ExecutionResult } from '@/executor/types'
|
import type { ExecutionResult } from '@/executor/types'
|
||||||
import { safeAssign } from '@/tools/safe-assign'
|
|
||||||
import { getTrigger, isTriggerValid } from '@/triggers'
|
import { getTrigger, isTriggerValid } from '@/triggers'
|
||||||
|
|
||||||
const logger = createLogger('TriggerWebhookExecution')
|
const logger = createLogger('TriggerWebhookExecution')
|
||||||
@@ -398,7 +397,7 @@ async function executeWebhookJobInternal(
|
|||||||
requestId,
|
requestId,
|
||||||
userId: payload.userId,
|
userId: payload.userId,
|
||||||
})
|
})
|
||||||
safeAssign(input, processedInput as Record<string, unknown>)
|
Object.assign(input, processedInput)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
logger.debug(`[${requestId}] No valid triggerId found for block ${payload.blockId}`)
|
logger.debug(`[${requestId}] No valid triggerId found for block ${payload.blockId}`)
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export type WorkflowExecutionPayload = {
|
|||||||
input?: any
|
input?: any
|
||||||
triggerType?: CoreTriggerType
|
triggerType?: CoreTriggerType
|
||||||
metadata?: Record<string, any>
|
metadata?: Record<string, any>
|
||||||
|
preflighted?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -51,6 +52,7 @@ export async function executeWorkflowJob(payload: WorkflowExecutionPayload) {
|
|||||||
checkRateLimit: true,
|
checkRateLimit: true,
|
||||||
checkDeployment: true,
|
checkDeployment: true,
|
||||||
loggingSession: loggingSession,
|
loggingSession: loggingSession,
|
||||||
|
preflightEnvVars: !payload.preflighted,
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!preprocessResult.success) {
|
if (!preprocessResult.success) {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { McpIcon } from '@/components/icons'
|
import { McpIcon } from '@/components/icons'
|
||||||
import { createMcpToolId } from '@/lib/mcp/shared'
|
import { createMcpToolId } from '@/lib/mcp/utils'
|
||||||
import type { BlockConfig } from '@/blocks/types'
|
import type { BlockConfig } from '@/blocks/types'
|
||||||
import type { ToolResponse } from '@/tools/types'
|
import type { ToolResponse } from '@/tools/types'
|
||||||
|
|
||||||
|
|||||||
@@ -23,13 +23,7 @@ import { cn } from '@/lib/core/utils/cn'
|
|||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
const checkboxVariants = cva(
|
const checkboxVariants = cva(
|
||||||
[
|
'peer shrink-0 rounded-sm border border-[var(--border-1)] bg-[var(--surface-4)] ring-offset-background transition-colors hover:border-[var(--border-muted)] hover:bg-[var(--surface-7)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[state=checked]:border-[var(--text-muted)] data-[state=checked]:bg-[var(--text-muted)] data-[state=checked]:text-white dark:bg-[var(--surface-5)] dark:data-[state=checked]:border-[var(--surface-7)] dark:data-[state=checked]:bg-[var(--surface-7)] dark:data-[state=checked]:text-[var(--text-primary)] dark:hover:border-[var(--surface-7)] dark:hover:bg-[var(--border-1)]',
|
||||||
'peer shrink-0 cursor-pointer rounded-[4px] border transition-colors',
|
|
||||||
'border-[var(--border-1)] bg-transparent',
|
|
||||||
'focus-visible:outline-none',
|
|
||||||
'data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50',
|
|
||||||
'data-[state=checked]:border-[var(--text-primary)] data-[state=checked]:bg-[var(--text-primary)]',
|
|
||||||
].join(' '),
|
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
size: {
|
size: {
|
||||||
@@ -89,7 +83,7 @@ const Checkbox = React.forwardRef<React.ElementRef<typeof CheckboxPrimitive.Root
|
|||||||
className={cn(checkboxVariants({ size }), className)}
|
className={cn(checkboxVariants({ size }), className)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<CheckboxPrimitive.Indicator className='flex items-center justify-center text-[var(--white)]'>
|
<CheckboxPrimitive.Indicator className={cn('flex items-center justify-center text-current')}>
|
||||||
<Check className={cn(checkboxIconVariants({ size }))} />
|
<Check className={cn(checkboxIconVariants({ size }))} />
|
||||||
</CheckboxPrimitive.Indicator>
|
</CheckboxPrimitive.Indicator>
|
||||||
</CheckboxPrimitive.Root>
|
</CheckboxPrimitive.Root>
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
'use client'
|
|
||||||
|
|
||||||
import { useState } from 'react'
|
|
||||||
import { ArrowRight, ChevronRight } from 'lucide-react'
|
|
||||||
|
|
||||||
interface ContactButtonProps {
|
|
||||||
href: string
|
|
||||||
children: React.ReactNode
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ContactButton({ href, children }: ContactButtonProps) {
|
|
||||||
const [isHovered, setIsHovered] = useState(false)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<a
|
|
||||||
href={href}
|
|
||||||
target='_blank'
|
|
||||||
rel='noopener noreferrer'
|
|
||||||
onMouseEnter={() => setIsHovered(true)}
|
|
||||||
onMouseLeave={() => setIsHovered(false)}
|
|
||||||
style={{
|
|
||||||
display: 'inline-flex',
|
|
||||||
alignItems: 'center',
|
|
||||||
gap: '4px',
|
|
||||||
borderRadius: '10px',
|
|
||||||
background: 'linear-gradient(to bottom, #8357ff, #6f3dfa)',
|
|
||||||
border: '1px solid #6f3dfa',
|
|
||||||
boxShadow: 'inset 0 2px 4px 0 #9b77ff',
|
|
||||||
paddingTop: '6px',
|
|
||||||
paddingBottom: '6px',
|
|
||||||
paddingLeft: '12px',
|
|
||||||
paddingRight: '10px',
|
|
||||||
fontSize: '15px',
|
|
||||||
fontWeight: 500,
|
|
||||||
color: '#ffffff',
|
|
||||||
textDecoration: 'none',
|
|
||||||
opacity: isHovered ? 0.9 : 1,
|
|
||||||
transition: 'opacity 200ms',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
<span style={{ display: 'inline-flex' }}>
|
|
||||||
{isHovered ? (
|
|
||||||
<ArrowRight style={{ height: '16px', width: '16px' }} aria-hidden='true' />
|
|
||||||
) : (
|
|
||||||
<ChevronRight style={{ height: '16px', width: '16px' }} aria-hidden='true' />
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</a>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
---
|
|
||||||
slug: enterprise
|
|
||||||
title: 'Build with Sim for Enterprise'
|
|
||||||
description: 'Access control, BYOK, self-hosted deployments, on-prem Copilot, SSO & SAML, whitelabeling, Admin API, and flexible data retention—enterprise features for teams with strict security and compliance requirements.'
|
|
||||||
date: 2026-01-23
|
|
||||||
updated: 2026-01-23
|
|
||||||
authors:
|
|
||||||
- vik
|
|
||||||
readingTime: 10
|
|
||||||
tags: [Enterprise, Security, Self-Hosted, SSO, SAML, Compliance, BYOK, Access Control, Copilot, Whitelabel, API, Import, Export]
|
|
||||||
ogImage: /studio/enterprise/cover.png
|
|
||||||
ogAlt: 'Sim Enterprise features overview'
|
|
||||||
about: ['Enterprise Software', 'Security', 'Compliance', 'Self-Hosting']
|
|
||||||
timeRequired: PT10M
|
|
||||||
canonical: https://sim.ai/studio/enterprise
|
|
||||||
featured: false
|
|
||||||
draft: true
|
|
||||||
---
|
|
||||||
|
|
||||||
We've been working with security teams at larger organizations to bring Sim into environments with strict compliance and data handling requirements. This post covers the enterprise capabilities we've built: granular access control, bring-your-own-keys, self-hosted deployments, on-prem Copilot, SSO & SAML, whitelabeling, compliance, and programmatic management via the Admin API.
|
|
||||||
|
|
||||||
## Access Control
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Permission groups let administrators control what features and integrations are available to different teams within an organization. This isn't just UI filtering—restrictions are enforced at the execution layer.
|
|
||||||
|
|
||||||
### Model Provider Restrictions
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Allowlist specific providers while blocking others. Users in a restricted group see only approved providers in the model selector. A workflow that tries to use an unapproved provider won't execute.
|
|
||||||
|
|
||||||
This is useful when you've approved certain providers for production use, negotiated enterprise agreements with specific vendors, or need to comply with data residency requirements that only certain providers meet.
|
|
||||||
|
|
||||||
### Integration Controls
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Restrict which workflow blocks appear in the editor. Disable the HTTP block to prevent arbitrary external API calls. Block access to integrations that haven't completed your security review.
|
|
||||||
|
|
||||||
### Platform Feature Toggles
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Control access to platform capabilities per permission group:
|
|
||||||
|
|
||||||
- **[Knowledge Base](https://docs.sim.ai/blocks/knowledge)** — Disable document uploads if RAG workflows aren't approved
|
|
||||||
- **[MCP Tools](https://docs.sim.ai/mcp)** — Block deployment of workflows as external tool endpoints
|
|
||||||
- **Custom Tools** — Prevent creation of arbitrary HTTP integrations
|
|
||||||
- **Invitations** — Disable self-service team invitations to maintain centralized control
|
|
||||||
|
|
||||||
Users not assigned to any permission group have full access, so restrictions are opt-in per team rather than requiring you to grant permissions to everyone.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Bring Your Own Keys
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
When you configure your own API keys for model providers—OpenAI, Anthropic, Google, Azure OpenAI, AWS Bedrock, or any supported provider—your prompts and completions route directly between Sim and that provider. The traffic doesn't pass through our infrastructure.
|
|
||||||
|
|
||||||
This matters because LLM requests contain the context you've assembled: customer data, internal documents, proprietary business logic. With your own keys, you maintain a direct relationship with your model provider. Their data handling policies and compliance certifications apply to your usage without an intermediary.
|
|
||||||
|
|
||||||
BYOK is available to everyone, not just enterprise plans. Connect your credentials in workspace settings, and all model calls use your keys. For self-hosted deployments, this is the default—there are no Sim-managed keys involved.
|
|
||||||
|
|
||||||
A healthcare organization can use Azure OpenAI with their BAA-covered subscription. A financial services firm can route through their approved API gateway with additional logging controls. The workflow builder stays the same; only the underlying data flow changes.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Self-Hosted Deployments
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Run Sim entirely on your infrastructure. Deploy with [Docker Compose](https://docs.sim.ai/self-hosting/docker) or [Helm charts](https://docs.sim.ai/self-hosting/kubernetes) for Kubernetes—the application, WebSocket server, and PostgreSQL database all stay within your network.
|
|
||||||
|
|
||||||
**Single-node** — Docker Compose setup for smaller teams getting started.
|
|
||||||
|
|
||||||
**High availability** — Multi-replica Kubernetes deployments with horizontal pod autoscaling.
|
|
||||||
|
|
||||||
**Air-gapped** — No external network access required. Pair with [Ollama](https://docs.sim.ai/self-hosting/ollama) or [vLLM](https://docs.sim.ai/self-hosting/vllm) for local model inference.
|
|
||||||
|
|
||||||
Enterprise features like access control, SSO, and organization management are enabled through environment variables—no connection to our billing infrastructure required.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## On-Prem Copilot
|
|
||||||
|
|
||||||
Copilot—our context-aware AI assistant for building and debugging workflows—can run entirely within your self-hosted deployment using your own LLM keys.
|
|
||||||
|
|
||||||
When you configure Copilot with your API credentials, all assistant interactions route directly to your chosen provider. The prompts Copilot generates—which include context from your workflows, execution logs, and workspace configuration—never leave your network. You get the same capabilities as the hosted version: natural language workflow generation, error diagnosis, documentation lookup, and iterative editing through diffs.
|
|
||||||
|
|
||||||
This is particularly relevant for organizations where the context Copilot needs to be helpful is also the context that can't leave the building. Your workflow definitions, block configurations, and execution traces stay within your infrastructure even when you're asking Copilot for help debugging a failure or generating a new integration.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## SSO & SAML
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Integrate with your existing identity provider through SAML 2.0 or OIDC. We support Okta, Azure AD (Entra ID), Google Workspace, OneLogin, Auth0, JumpCloud, Ping Identity, ADFS, and any compliant identity provider.
|
|
||||||
|
|
||||||
Once enabled, users authenticate through your IdP instead of Sim credentials. Your MFA policies apply automatically. Session management ties to your IdP—logout there terminates Sim sessions. Account deprovisioning immediately revokes access.
|
|
||||||
|
|
||||||
New users are provisioned on first SSO login based on IdP attributes. No invitation emails, no password setup, no manual account creation required.
|
|
||||||
|
|
||||||
This centralizes your authentication and audit trail. Your security team's policies apply to Sim access through the same system that tracks everything else.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Whitelabeling
|
|
||||||
|
|
||||||
Customize Sim's appearance to match your brand. For self-hosted deployments, whitelabeling is configured through environment variables—no code changes required.
|
|
||||||
|
|
||||||
**Brand name & logo** — Replace "Sim" with your company name and logo throughout the interface.
|
|
||||||
|
|
||||||
**Theme colors** — Set primary, accent, and background colors to align with your brand palette.
|
|
||||||
|
|
||||||
**Support & documentation links** — Point help links to your internal documentation and support channels instead of ours.
|
|
||||||
|
|
||||||
**Legal pages** — Redirect terms of service and privacy policy links to your own policies.
|
|
||||||
|
|
||||||
This is useful for internal platforms, customer-facing deployments, or any scenario where you want Sim to feel like a native part of your product rather than a third-party tool.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Compliance & Data Retention
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Sim maintains **SOC 2 Type II** certification with annual audits covering security, availability, and confidentiality controls. We share our SOC 2 report directly with prospective customers under NDA.
|
|
||||||
|
|
||||||
**HIPAA** — Business Associate Agreements available for healthcare organizations. Requires self-hosted deployment or dedicated infrastructure.
|
|
||||||
|
|
||||||
**Data Retention** — Configure how long workflow execution traces, inputs, and outputs are stored before automatic deletion. We work with enterprise customers to set retention policies that match their compliance requirements.
|
|
||||||
|
|
||||||
We provide penetration test reports, architecture documentation, and completed security questionnaires (SIG, CAIQ, and custom formats) for your vendor review process.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Admin API
|
|
||||||
|
|
||||||
Manage Sim programmatically through the Admin API. Every operation available in the UI has a corresponding API endpoint, enabling infrastructure-as-code workflows and integration with your existing tooling.
|
|
||||||
|
|
||||||
**User & Organization Management** — Provision users, create organizations, assign roles, and manage team membership. Integrate with your HR systems to automatically onboard and offboard employees.
|
|
||||||
|
|
||||||
**Workspace Administration** — Create workspaces, configure settings, and manage access. Useful for setting up isolated environments for different teams or clients.
|
|
||||||
|
|
||||||
**Workflow Lifecycle** — Deploy, undeploy, and manage workflow versions programmatically. Build CI/CD pipelines that promote workflows from development to staging to production.
|
|
||||||
|
|
||||||
The API uses standard REST conventions with JSON payloads. Authentication is via API keys scoped to your organization.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Import & Export
|
|
||||||
|
|
||||||
Move workflows between environments, create backups, and maintain version control inside or outside of Sim.
|
|
||||||
|
|
||||||
**Workflow Export** — Export individual workflows or entire folders as JSON. The export includes block configurations, connections, environment variable references, and metadata. Use this to back up critical workflows or move them between Sim instances.
|
|
||||||
|
|
||||||
**Workspace Export** — Export an entire workspace as a ZIP archive containing all workflows, folder structure, and configuration. Useful for disaster recovery or migrating to a self-hosted deployment.
|
|
||||||
|
|
||||||
**Import** — Import workflows into any workspace. Sim handles ID remapping and validates the structure before import. This enables workflow templates, sharing between teams, and restoring from backups.
|
|
||||||
|
|
||||||
**Version History** — Each deployment creates a version snapshot. Roll back to previous versions if a deployment causes issues. The Admin API exposes version history for integration with your change management processes.
|
|
||||||
|
|
||||||
For teams practicing GitOps, export workflows to your repository and use the Admin API to deploy from CI/CD pipelines.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Get Started
|
|
||||||
|
|
||||||
Enterprise features are available now. Check out our [self-hosting](https://docs.sim.ai/self-hosting) and [enterprise](https://docs.sim.ai/enterprise) docs to get started.
|
|
||||||
|
|
||||||
*Questions about enterprise deployments?*
|
|
||||||
|
|
||||||
<ContactButton href="https://form.typeform.com/to/jqCO12pF">Contact Us</ContactButton>
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export { DiffControlsDemo } from './components/diff-controls-demo'
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
'use client'
|
|
||||||
|
|
||||||
import { useState } from 'react'
|
|
||||||
|
|
||||||
export function DiffControlsDemo() {
|
|
||||||
const [rejectHover, setRejectHover] = useState(false)
|
|
||||||
const [acceptHover, setAcceptHover] = useState(false)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div style={{ display: 'flex', justifyContent: 'center', margin: '24px 0' }}>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
position: 'relative',
|
|
||||||
display: 'flex',
|
|
||||||
height: '30px',
|
|
||||||
overflow: 'hidden',
|
|
||||||
borderRadius: '4px',
|
|
||||||
isolation: 'isolate',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{/* Reject button */}
|
|
||||||
<button
|
|
||||||
onClick={() => {}}
|
|
||||||
onMouseEnter={() => setRejectHover(true)}
|
|
||||||
onMouseLeave={() => setRejectHover(false)}
|
|
||||||
title='Reject changes'
|
|
||||||
style={{
|
|
||||||
position: 'relative',
|
|
||||||
display: 'flex',
|
|
||||||
height: '100%',
|
|
||||||
alignItems: 'center',
|
|
||||||
border: '1px solid #e0e0e0',
|
|
||||||
backgroundColor: rejectHover ? '#f0f0f0' : '#f5f5f5',
|
|
||||||
paddingRight: '20px',
|
|
||||||
paddingLeft: '12px',
|
|
||||||
fontWeight: 500,
|
|
||||||
fontSize: '13px',
|
|
||||||
color: rejectHover ? '#2d2d2d' : '#404040',
|
|
||||||
clipPath: 'polygon(0 0, calc(100% + 10px) 0, 100% 100%, 0 100%)',
|
|
||||||
borderRadius: '4px 0 0 4px',
|
|
||||||
cursor: 'default',
|
|
||||||
transition: 'color 150ms, background-color 150ms, border-color 150ms',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Reject
|
|
||||||
</button>
|
|
||||||
{/* Slanted divider - split gray/green */}
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
pointerEvents: 'none',
|
|
||||||
position: 'absolute',
|
|
||||||
top: 0,
|
|
||||||
bottom: 0,
|
|
||||||
left: '66px',
|
|
||||||
width: '2px',
|
|
||||||
transform: 'skewX(-18.4deg)',
|
|
||||||
background: 'linear-gradient(to right, #e0e0e0 50%, #238458 50%)',
|
|
||||||
zIndex: 10,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
{/* Accept button */}
|
|
||||||
<button
|
|
||||||
onClick={() => {}}
|
|
||||||
onMouseEnter={() => setAcceptHover(true)}
|
|
||||||
onMouseLeave={() => setAcceptHover(false)}
|
|
||||||
title='Accept changes (⇧⌘⏎)'
|
|
||||||
style={{
|
|
||||||
position: 'relative',
|
|
||||||
display: 'flex',
|
|
||||||
height: '100%',
|
|
||||||
alignItems: 'center',
|
|
||||||
border: '1px solid rgba(0, 0, 0, 0.15)',
|
|
||||||
backgroundColor: '#32bd7e',
|
|
||||||
paddingRight: '12px',
|
|
||||||
paddingLeft: '20px',
|
|
||||||
fontWeight: 500,
|
|
||||||
fontSize: '13px',
|
|
||||||
color: '#ffffff',
|
|
||||||
clipPath: 'polygon(10px 0, 100% 0, 100% 100%, 0 100%)',
|
|
||||||
borderRadius: '0 4px 4px 0',
|
|
||||||
marginLeft: '-10px',
|
|
||||||
cursor: 'default',
|
|
||||||
filter: acceptHover ? 'brightness(1.1)' : undefined,
|
|
||||||
transition: 'background-color 150ms, border-color 150ms',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Accept
|
|
||||||
<kbd
|
|
||||||
style={{
|
|
||||||
marginLeft: '8px',
|
|
||||||
borderRadius: '4px',
|
|
||||||
border: '1px solid rgba(255, 255, 255, 0.2)',
|
|
||||||
backgroundColor: 'rgba(255, 255, 255, 0.1)',
|
|
||||||
paddingLeft: '6px',
|
|
||||||
paddingRight: '6px',
|
|
||||||
paddingTop: '2px',
|
|
||||||
paddingBottom: '2px',
|
|
||||||
fontWeight: 500,
|
|
||||||
fontFamily:
|
|
||||||
'ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
|
|
||||||
fontSize: '10px',
|
|
||||||
color: '#ffffff',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
⇧⌘<span style={{ display: 'inline-block', transform: 'translateY(-1px)' }}>⏎</span>
|
|
||||||
</kbd>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,204 +0,0 @@
|
|||||||
---
|
|
||||||
slug: v0-5
|
|
||||||
title: 'Introducing Sim v0.5'
|
|
||||||
description: 'This new release brings a state of the art Copilot, seamless MCP server and tool deployment, 100+ integrations with 300+ tools, comprehensive execution logs, and realtime collaboration—built for teams shipping AI agents in production.'
|
|
||||||
date: 2026-01-22
|
|
||||||
updated: 2026-01-22
|
|
||||||
authors:
|
|
||||||
- waleed
|
|
||||||
readingTime: 8
|
|
||||||
tags: [Release, Copilot, MCP, Observability, Collaboration, Integrations, Sim]
|
|
||||||
ogImage: /studio/v0-5/cover.png
|
|
||||||
ogAlt: 'Sim v0.5 release announcement'
|
|
||||||
about: ['AI Agents', 'Workflow Automation', 'Developer Tools']
|
|
||||||
timeRequired: PT8M
|
|
||||||
canonical: https://sim.ai/studio/v0-5
|
|
||||||
featured: true
|
|
||||||
draft: false
|
|
||||||
---
|
|
||||||
|
|
||||||
**Sim v0.5** is the next evolution of our agent workflow platform—built for teams shipping AI agents to production.
|
|
||||||
|
|
||||||
## Copilot
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Copilot is a context-aware assistant embedded in the Sim editor. Unlike general-purpose AI assistants, Copilot has direct access to your workspace: workflows, block configurations, execution logs, connected credentials, and documentation. It can also search the web to pull in external context when needed.
|
|
||||||
|
|
||||||
Your workspace is indexed for hybrid retrieval. When you ask a question, Copilot queries this index to ground its responses in your actual workflow state. Ask "why did my workflow fail at 3am?" and it retrieves the relevant execution trace, identifies the error, and explains what happened.
|
|
||||||
|
|
||||||
Copilot supports slash commands that trigger specialized capabilities:
|
|
||||||
|
|
||||||
- `/fast` — uses a faster model for quick responses when you need speed over depth
|
|
||||||
- `/research` — performs multi-step web research on a topic, synthesizing results from multiple sources
|
|
||||||
- `/actions` — enables agentic mode where Copilot can take actions on your behalf, like modifying blocks or creating workflows
|
|
||||||
- `/search` — searches the web for relevant information
|
|
||||||
- `/read` — reads and extracts content from a URL
|
|
||||||
- `/scrape` — scrapes structured data from web pages
|
|
||||||
- `/crawl` — crawls multiple pages from a website to gather comprehensive information
|
|
||||||
|
|
||||||
Use `@` commands to pull specific context into your conversation. `@block` references a specific block's configuration and recent outputs. `@workflow` includes the full workflow structure. `@logs` pulls in recent execution traces. This lets you ask targeted questions like "why is `@Slack1` returning an error?" and Copilot has the exact context it needs to diagnose the issue.
|
|
||||||
|
|
||||||
For complex tasks, Copilot uses subagents—breaking requests into discrete operations and executing them sequentially. Ask it to "add error handling to this workflow" and it will analyze your blocks, determine where failures could occur, add appropriate condition blocks, and wire up notification paths. Each change surfaces as a diff for your review before applying.
|
|
||||||
|
|
||||||
<DiffControlsDemo />
|
|
||||||
|
|
||||||
## MCP Deployment
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Deploy any workflow as an [MCP](https://modelcontextprotocol.io) server. Once deployed, the workflow becomes a callable tool for any MCP-compatible agent—[Claude Desktop](https://claude.ai/download), [Cursor](https://cursor.com), or your own applications.
|
|
||||||
|
|
||||||
Sim generates a tool definition from your workflow: the name and description you specify, plus a JSON schema derived from your Start block's input format. The MCP server uses Streamable HTTP transport, so agents connect via a single URL. Authentication is handled via API key headers or public access, depending on your configuration.
|
|
||||||
|
|
||||||
Consider a lead enrichment workflow: it queries Apollo for contact data, checks Salesforce for existing records, formats the output, and posts a summary to Slack. That's 8 blocks in Sim. Deploy it as MCP, and any agent can call `enrich_lead("jane@acme.com")` and receive structured data back. The agent treats it as a single tool call—it doesn't need to know about Apollo, Salesforce, or Slack.
|
|
||||||
|
|
||||||
This pattern scales to research pipelines, data processing workflows, approval chains, and internal tooling. Anything you build in Sim becomes a tool any agent can invoke.
|
|
||||||
|
|
||||||
## Logs & Dashboard
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Every workflow execution generates a full trace. Each block records its start time, end time, inputs, outputs, and any errors. For LLM blocks, we capture prompt tokens, completion tokens, and cost by model.
|
|
||||||
|
|
||||||
The dashboard aggregates this data into queryable views:
|
|
||||||
|
|
||||||
- **Trace spans**: Hierarchical view of block executions with timing waterfall
|
|
||||||
- **Cost attribution**: Token usage and spend broken down by model per execution
|
|
||||||
- **Error context**: Full stack traces with the block, input values, and failure reason
|
|
||||||
- **Filtering**: Query by time range, trigger type, workflow, or status
|
|
||||||
- **Execution snapshots**: Each run captures the workflow state at execution time—restore to see exactly what was running
|
|
||||||
|
|
||||||
This level of observability is necessary when workflows handle production traffic—sending customer emails, processing payments, or making API calls on behalf of users.
|
|
||||||
|
|
||||||
## Realtime Collaboration
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Multiple users can edit the same workflow simultaneously. Changes propagate in real time—you see teammates' cursors, block additions, and configuration updates as they happen.
|
|
||||||
|
|
||||||
The editor now supports full undo/redo history (Cmd+Z / Cmd+Shift+Z), so you can step back through changes without losing work. Copy and paste works for individual blocks, groups of blocks, or entire subflows—select what you need, Cmd+C, and paste into the same workflow or a different one. This makes it easy to duplicate patterns, share components across workflows, or quickly prototype variations.
|
|
||||||
|
|
||||||
This is particularly useful during development sessions where engineers, product managers, and domain experts need to iterate together. Everyone works on the same workflow state, and changes sync immediately across all connected clients.
|
|
||||||
|
|
||||||
## Versioning
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Every deployment creates a new version. The version history shows who deployed what and when, with a preview of the workflow state at that point in time. Roll back to any previous version with one click—the live deployment updates immediately.
|
|
||||||
|
|
||||||
This matters when something breaks in production. You can instantly revert to the last known good version while you debug, rather than scrambling to fix forward. It also provides a clear audit trail: you can see exactly what changed between versions and who made the change.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 100+ Integrations
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
v0.5 adds **100+ integrations** with **300+ actions**. These cover the specific operations you need—not just generic CRUD, but actions like "send Slack message to channel," "create Jira ticket with custom fields," "query Postgres with parameterized SQL," or "enrich contact via Apollo."
|
|
||||||
|
|
||||||
- **CRMs & Sales**: Salesforce, HubSpot, Pipedrive, Apollo, Wealthbox
|
|
||||||
- **Communication**: Slack, Discord, Microsoft Teams, Telegram, WhatsApp, Twilio
|
|
||||||
- **Productivity**: Notion, Confluence, Google Workspace, Microsoft 365, Airtable, Asana, Trello
|
|
||||||
- **Developer Tools**: GitHub, GitLab, Jira, Linear, Sentry, Datadog, Grafana
|
|
||||||
- **Databases**: PostgreSQL, MySQL, MongoDB, [Supabase](https://supabase.com), DynamoDB, Elasticsearch, [Pinecone](https://pinecone.io), [Qdrant](https://qdrant.tech), Neo4j
|
|
||||||
- **Finance**: Stripe, Kalshi, Polymarket
|
|
||||||
- **Web & Search**: [Firecrawl](https://firecrawl.dev), [Exa](https://exa.ai), [Tavily](https://tavily.com), [Jina](https://jina.ai), [Serper](https://serper.dev)
|
|
||||||
- **Cloud**: AWS (S3, RDS, SQS, Textract, Bedrock), [Browser Use](https://browser-use.com), [Stagehand](https://github.com/browserbase/stagehand)
|
|
||||||
|
|
||||||
Each integration handles OAuth or API key authentication. Connect once, and the credentials are available across all workflows in your workspace.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Triggers
|
|
||||||
|
|
||||||
Workflows can be triggered through multiple mechanisms:
|
|
||||||
|
|
||||||
**Webhooks**: Sim provisions a unique HTTPS endpoint for each workflow. Incoming POST requests are parsed and passed to the first block as input. Supports standard webhook patterns including signature verification for services that provide it.
|
|
||||||
|
|
||||||
**Schedules**: Cron-based scheduling with timezone support. Use the visual scheduler or write expressions directly. Execution locks prevent overlapping runs.
|
|
||||||
|
|
||||||
**Chat**: Deploy workflows as conversational interfaces. Messages stream to your workflow, responses stream back to the user. Supports multi-turn context.
|
|
||||||
|
|
||||||
**API**: REST endpoint with your workflow's input schema. Call it from any system that can make HTTP requests.
|
|
||||||
|
|
||||||
**Integration triggers**: Event-driven triggers for specific services—GitHub (PR opened, issue created, push), Stripe (payment succeeded, subscription updated), TypeForm (form submitted), RSS (new item), and more.
|
|
||||||
|
|
||||||
**Forms**: Coming soon—build custom input forms that trigger workflows directly.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Knowledge Base
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Upload documents—PDFs, text files, markdown, HTML—and make them queryable by your agents. This is [RAG](https://en.wikipedia.org/wiki/Retrieval-augmented_generation) (Retrieval Augmented Generation) built directly into Sim.
|
|
||||||
|
|
||||||
Documents are chunked, embedded, and indexed using hybrid search ([BM25](https://en.wikipedia.org/wiki/Okapi_BM25) + vector embeddings). Agent blocks can query the knowledge base as a tool, retrieving relevant passages based on semantic similarity and keyword matching. When documents are updated, they re-index automatically.
|
|
||||||
|
|
||||||
Use cases:
|
|
||||||
|
|
||||||
- **Customer support agents** that reference your help docs and troubleshooting guides to resolve tickets
|
|
||||||
- **Sales assistants** that pull from product specs, pricing sheets, and competitive intel
|
|
||||||
- **Internal Q&A bots** that answer questions about company policies, HR docs, or engineering runbooks
|
|
||||||
- **Research workflows** that synthesize information from uploaded papers, reports, or data exports
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## New Blocks
|
|
||||||
|
|
||||||
### Human in the Loop
|
|
||||||
|
|
||||||
Pause workflow execution pending human approval. The block sends a notification (email, Slack, or webhook) with approve/reject actions. Execution resumes only on approval—useful for high-stakes operations like customer-facing emails, financial transactions, or content publishing.
|
|
||||||
|
|
||||||
### Agent Block
|
|
||||||
|
|
||||||
The Agent block now supports three additional tool types:
|
|
||||||
|
|
||||||
- **Workflows as tools**: Agents can invoke other Sim workflows, enabling hierarchical architectures where a coordinator agent delegates to specialized sub-workflows
|
|
||||||
- **Knowledge base queries**: Agents search your indexed documents directly, retrieving relevant context for their responses
|
|
||||||
- **Custom functions**: Execute JavaScript or Python code in isolated sandboxes with configurable timeout and memory limits
|
|
||||||
|
|
||||||
### Subflows
|
|
||||||
|
|
||||||
Group blocks into collapsible subflows. Use them for loops (iterate over arrays), parallel execution (run branches concurrently), or logical organization. Subflows can be nested and keep complex workflows manageable.
|
|
||||||
|
|
||||||
### Router
|
|
||||||
|
|
||||||
Conditional branching based on data or LLM classification. Define rules or let the router use an LLM to determine intent and select the appropriate path.
|
|
||||||
|
|
||||||
The router now exposes its reasoning in execution logs—when debugging unexpected routing, you can see exactly why a particular branch was selected.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Model Providers
|
|
||||||
|
|
||||||
Sim supports 14 providers: [OpenAI](https://openai.com), [Anthropic](https://anthropic.com), [Google](https://ai.google.dev), [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service), [xAI](https://x.ai), [Mistral](https://mistral.ai), [Deepseek](https://deepseek.com), [Groq](https://groq.com), [Cerebras](https://cerebras.ai), [Ollama](https://ollama.com), and [OpenRouter](https://openrouter.ai).
|
|
||||||
|
|
||||||
New in v0.5:
|
|
||||||
|
|
||||||
- **[AWS Bedrock](https://aws.amazon.com/bedrock)**: Claude, Nova, Llama, Mistral, and Cohere models via your AWS account
|
|
||||||
- **[Google Vertex AI](https://cloud.google.com/vertex-ai)**: Gemini models through Google Cloud
|
|
||||||
- **[vLLM](https://github.com/vllm-project/vllm)**: Self-hosted models on your own infrastructure
|
|
||||||
|
|
||||||
Model selection is per-block, so you can use faster/cheaper models for simple tasks and more capable models where needed.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Developer Experience
|
|
||||||
|
|
||||||
**Custom Tools**: Define your own integrations with custom HTTP endpoints, authentication (API key, OAuth, Bearer token), and request/response schemas. Custom tools appear in the block palette alongside built-in integrations.
|
|
||||||
|
|
||||||
**Environment Variables**: Encrypted key-value storage for secrets and configuration. Variables are decrypted at runtime and can be referenced in any block configuration.
|
|
||||||
|
|
||||||
**Import/Export**: Export workflows or entire workspaces as JSON. Imports preserve all blocks, connections, configurations, and variable references.
|
|
||||||
|
|
||||||
**File Manager**: Upload files to your workspace for use in workflows—templates, seed data, static assets. Files are accessible via internal references or presigned URLs.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Get Started
|
|
||||||
|
|
||||||
Available now at [sim.ai](https://sim.ai). Check out the [docs](https://docs.sim.ai) to dive deeper.
|
|
||||||
|
|
||||||
*Questions? [help@sim.ai](mailto:help@sim.ai) · [Discord](https://sim.ai/discord)*
|
|
||||||
@@ -120,12 +120,6 @@ export const SPECIAL_REFERENCE_PREFIXES = [
|
|||||||
REFERENCE.PREFIX.VARIABLE,
|
REFERENCE.PREFIX.VARIABLE,
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
export const RESERVED_BLOCK_NAMES = [
|
|
||||||
REFERENCE.PREFIX.LOOP,
|
|
||||||
REFERENCE.PREFIX.PARALLEL,
|
|
||||||
REFERENCE.PREFIX.VARIABLE,
|
|
||||||
] as const
|
|
||||||
|
|
||||||
export const LOOP_REFERENCE = {
|
export const LOOP_REFERENCE = {
|
||||||
ITERATION: 'iteration',
|
ITERATION: 'iteration',
|
||||||
INDEX: 'index',
|
INDEX: 'index',
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
|
import { db } from '@sim/db'
|
||||||
|
import { mcpServers } from '@sim/db/schema'
|
||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
|
import { and, eq, inArray, isNull } from 'drizzle-orm'
|
||||||
import { getBaseUrl } from '@/lib/core/utils/urls'
|
import { getBaseUrl } from '@/lib/core/utils/urls'
|
||||||
import {
|
import {
|
||||||
containsUserFileWithMetadata,
|
containsUserFileWithMetadata,
|
||||||
@@ -83,6 +86,10 @@ export class BlockExecutor {
|
|||||||
|
|
||||||
resolvedInputs = this.resolver.resolveInputs(ctx, node.id, block.config.params, block)
|
resolvedInputs = this.resolver.resolveInputs(ctx, node.id, block.config.params, block)
|
||||||
|
|
||||||
|
if (block.metadata?.id === BlockType.AGENT && resolvedInputs.tools) {
|
||||||
|
resolvedInputs = await this.filterUnavailableMcpToolsForLog(ctx, resolvedInputs)
|
||||||
|
}
|
||||||
|
|
||||||
if (blockLog) {
|
if (blockLog) {
|
||||||
blockLog.input = resolvedInputs
|
blockLog.input = resolvedInputs
|
||||||
}
|
}
|
||||||
@@ -430,6 +437,60 @@ export class BlockExecutor {
|
|||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Filters out unavailable MCP tools from agent inputs for logging.
|
||||||
|
* Only includes tools from servers with 'connected' status.
|
||||||
|
*/
|
||||||
|
private async filterUnavailableMcpToolsForLog(
|
||||||
|
ctx: ExecutionContext,
|
||||||
|
inputs: Record<string, any>
|
||||||
|
): Promise<Record<string, any>> {
|
||||||
|
const tools = inputs.tools
|
||||||
|
if (!Array.isArray(tools) || tools.length === 0) return inputs
|
||||||
|
|
||||||
|
const mcpTools = tools.filter((t: any) => t.type === 'mcp')
|
||||||
|
if (mcpTools.length === 0) return inputs
|
||||||
|
|
||||||
|
const serverIds = [
|
||||||
|
...new Set(mcpTools.map((t: any) => t.params?.serverId).filter(Boolean)),
|
||||||
|
] as string[]
|
||||||
|
if (serverIds.length === 0) return inputs
|
||||||
|
|
||||||
|
const availableServerIds = new Set<string>()
|
||||||
|
if (ctx.workspaceId && serverIds.length > 0) {
|
||||||
|
try {
|
||||||
|
const servers = await db
|
||||||
|
.select({ id: mcpServers.id, connectionStatus: mcpServers.connectionStatus })
|
||||||
|
.from(mcpServers)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(mcpServers.workspaceId, ctx.workspaceId),
|
||||||
|
inArray(mcpServers.id, serverIds),
|
||||||
|
isNull(mcpServers.deletedAt)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
for (const server of servers) {
|
||||||
|
if (server.connectionStatus === 'connected') {
|
||||||
|
availableServerIds.add(server.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('Failed to check MCP server availability for logging:', error)
|
||||||
|
return inputs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const filteredTools = tools.filter((tool: any) => {
|
||||||
|
if (tool.type !== 'mcp') return true
|
||||||
|
const serverId = tool.params?.serverId
|
||||||
|
if (!serverId) return false
|
||||||
|
return availableServerIds.has(serverId)
|
||||||
|
})
|
||||||
|
|
||||||
|
return { ...inputs, tools: filteredTools }
|
||||||
|
}
|
||||||
|
|
||||||
private preparePauseResumeSelfReference(
|
private preparePauseResumeSelfReference(
|
||||||
ctx: ExecutionContext,
|
ctx: ExecutionContext,
|
||||||
node: DAGNode,
|
node: DAGNode,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { StartBlockPath } from '@/lib/workflows/triggers/triggers'
|
import { StartBlockPath } from '@/lib/workflows/triggers/triggers'
|
||||||
|
import type { BlockOutput } from '@/blocks/types'
|
||||||
import { DAGBuilder } from '@/executor/dag/builder'
|
import { DAGBuilder } from '@/executor/dag/builder'
|
||||||
import { BlockExecutor } from '@/executor/execution/block-executor'
|
import { BlockExecutor } from '@/executor/execution/block-executor'
|
||||||
import { EdgeManager } from '@/executor/execution/edge-manager'
|
import { EdgeManager } from '@/executor/execution/edge-manager'
|
||||||
@@ -23,6 +24,7 @@ const logger = createLogger('DAGExecutor')
|
|||||||
|
|
||||||
export interface DAGExecutorOptions {
|
export interface DAGExecutorOptions {
|
||||||
workflow: SerializedWorkflow
|
workflow: SerializedWorkflow
|
||||||
|
currentBlockStates?: Record<string, BlockOutput>
|
||||||
envVarValues?: Record<string, string>
|
envVarValues?: Record<string, string>
|
||||||
workflowInput?: WorkflowInput
|
workflowInput?: WorkflowInput
|
||||||
workflowVariables?: Record<string, unknown>
|
workflowVariables?: Record<string, unknown>
|
||||||
|
|||||||
@@ -28,23 +28,6 @@ export interface EnvVarResolveOptions {
|
|||||||
missingKeys?: string[]
|
missingKeys?: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Standard defaults for env var resolution across all contexts.
|
|
||||||
*
|
|
||||||
* - `resolveExactMatch: true` - Resolves `{{VAR}}` when it's the entire value
|
|
||||||
* - `allowEmbedded: true` - Resolves `{{VAR}}` embedded in strings like `https://{{HOST}}/api`
|
|
||||||
* - `trimKeys: true` - `{{ VAR }}` works the same as `{{VAR}}` (whitespace tolerant)
|
|
||||||
* - `onMissing: 'keep'` - Unknown patterns pass through (e.g., Grafana's `{{instance}}`)
|
|
||||||
* - `deep: false` - Only processes strings by default; set `true` for nested objects
|
|
||||||
*/
|
|
||||||
export const ENV_VAR_RESOLVE_DEFAULTS: Required<Omit<EnvVarResolveOptions, 'missingKeys'>> = {
|
|
||||||
resolveExactMatch: true,
|
|
||||||
allowEmbedded: true,
|
|
||||||
trimKeys: true,
|
|
||||||
onMissing: 'keep',
|
|
||||||
deep: false,
|
|
||||||
} as const
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve {{ENV_VAR}} references in values using provided env vars.
|
* Resolve {{ENV_VAR}} references in values using provided env vars.
|
||||||
*/
|
*/
|
||||||
@@ -54,11 +37,11 @@ export function resolveEnvVarReferences(
|
|||||||
options: EnvVarResolveOptions = {}
|
options: EnvVarResolveOptions = {}
|
||||||
): unknown {
|
): unknown {
|
||||||
const {
|
const {
|
||||||
allowEmbedded = ENV_VAR_RESOLVE_DEFAULTS.allowEmbedded,
|
allowEmbedded = true,
|
||||||
resolveExactMatch = ENV_VAR_RESOLVE_DEFAULTS.resolveExactMatch,
|
resolveExactMatch = true,
|
||||||
trimKeys = ENV_VAR_RESOLVE_DEFAULTS.trimKeys,
|
trimKeys = false,
|
||||||
onMissing = ENV_VAR_RESOLVE_DEFAULTS.onMissing,
|
onMissing = 'keep',
|
||||||
deep = ENV_VAR_RESOLVE_DEFAULTS.deep,
|
deep = true,
|
||||||
} = options
|
} = options
|
||||||
|
|
||||||
if (typeof value === 'string') {
|
if (typeof value === 'string') {
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import {
|
|||||||
import type { InputFormatField } from '@/lib/workflows/types'
|
import type { InputFormatField } from '@/lib/workflows/types'
|
||||||
import type { NormalizedBlockOutput, UserFile } from '@/executor/types'
|
import type { NormalizedBlockOutput, UserFile } from '@/executor/types'
|
||||||
import type { SerializedBlock } from '@/serializer/types'
|
import type { SerializedBlock } from '@/serializer/types'
|
||||||
import { safeAssign } from '@/tools/safe-assign'
|
|
||||||
|
|
||||||
type ExecutionKind = 'chat' | 'manual' | 'api'
|
type ExecutionKind = 'chat' | 'manual' | 'api'
|
||||||
|
|
||||||
@@ -347,7 +346,7 @@ function buildLegacyStarterOutput(
|
|||||||
const finalObject = isPlainObject(finalInput) ? finalInput : undefined
|
const finalObject = isPlainObject(finalInput) ? finalInput : undefined
|
||||||
|
|
||||||
if (finalObject) {
|
if (finalObject) {
|
||||||
safeAssign(output, finalObject)
|
Object.assign(output, finalObject)
|
||||||
output.input = { ...finalObject }
|
output.input = { ...finalObject }
|
||||||
} else {
|
} else {
|
||||||
output.input = finalInput
|
output.input = finalInput
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { loggerMock } from '@sim/testing'
|
import { loggerMock } from '@sim/testing'
|
||||||
import { describe, expect, it, vi } from 'vitest'
|
import { describe, expect, it, vi } from 'vitest'
|
||||||
import type { LoopScope } from '@/executor/execution/state'
|
import type { LoopScope } from '@/executor/execution/state'
|
||||||
import { InvalidFieldError } from '@/executor/utils/block-reference'
|
|
||||||
import { LoopResolver } from './loop'
|
import { LoopResolver } from './loop'
|
||||||
import type { ResolutionContext } from './reference'
|
import type { ResolutionContext } from './reference'
|
||||||
|
|
||||||
@@ -63,12 +62,7 @@ function createTestContext(
|
|||||||
|
|
||||||
describe('LoopResolver', () => {
|
describe('LoopResolver', () => {
|
||||||
describe('canResolve', () => {
|
describe('canResolve', () => {
|
||||||
it.concurrent('should return true for bare loop reference', () => {
|
it.concurrent('should return true for loop references', () => {
|
||||||
const resolver = new LoopResolver(createTestWorkflow())
|
|
||||||
expect(resolver.canResolve('<loop>')).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it.concurrent('should return true for known loop properties', () => {
|
|
||||||
const resolver = new LoopResolver(createTestWorkflow())
|
const resolver = new LoopResolver(createTestWorkflow())
|
||||||
expect(resolver.canResolve('<loop.index>')).toBe(true)
|
expect(resolver.canResolve('<loop.index>')).toBe(true)
|
||||||
expect(resolver.canResolve('<loop.iteration>')).toBe(true)
|
expect(resolver.canResolve('<loop.iteration>')).toBe(true)
|
||||||
@@ -84,13 +78,6 @@ describe('LoopResolver', () => {
|
|||||||
expect(resolver.canResolve('<loop.items.0>')).toBe(true)
|
expect(resolver.canResolve('<loop.items.0>')).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it.concurrent('should return true for unknown loop properties (validates in resolve)', () => {
|
|
||||||
const resolver = new LoopResolver(createTestWorkflow())
|
|
||||||
expect(resolver.canResolve('<loop.results>')).toBe(true)
|
|
||||||
expect(resolver.canResolve('<loop.output>')).toBe(true)
|
|
||||||
expect(resolver.canResolve('<loop.unknownProperty>')).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it.concurrent('should return false for non-loop references', () => {
|
it.concurrent('should return false for non-loop references', () => {
|
||||||
const resolver = new LoopResolver(createTestWorkflow())
|
const resolver = new LoopResolver(createTestWorkflow())
|
||||||
expect(resolver.canResolve('<block.output>')).toBe(false)
|
expect(resolver.canResolve('<block.output>')).toBe(false)
|
||||||
@@ -194,34 +181,20 @@ describe('LoopResolver', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('edge cases', () => {
|
describe('edge cases', () => {
|
||||||
it.concurrent('should return context object for bare loop reference', () => {
|
it.concurrent('should return undefined for invalid loop reference (missing property)', () => {
|
||||||
const resolver = new LoopResolver(createTestWorkflow())
|
|
||||||
const loopScope = createLoopScope({ iteration: 2, item: 'test', items: ['a', 'b', 'c'] })
|
|
||||||
const ctx = createTestContext('block-1', loopScope)
|
|
||||||
|
|
||||||
expect(resolver.resolve('<loop>', ctx)).toEqual({
|
|
||||||
index: 2,
|
|
||||||
currentItem: 'test',
|
|
||||||
items: ['a', 'b', 'c'],
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it.concurrent('should return minimal context object for for-loop (no items)', () => {
|
|
||||||
const resolver = new LoopResolver(createTestWorkflow())
|
|
||||||
const loopScope = createLoopScope({ iteration: 5 })
|
|
||||||
const ctx = createTestContext('block-1', loopScope)
|
|
||||||
|
|
||||||
expect(resolver.resolve('<loop>', ctx)).toEqual({
|
|
||||||
index: 5,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it.concurrent('should throw InvalidFieldError for unknown loop property', () => {
|
|
||||||
const resolver = new LoopResolver(createTestWorkflow())
|
const resolver = new LoopResolver(createTestWorkflow())
|
||||||
const loopScope = createLoopScope({ iteration: 0 })
|
const loopScope = createLoopScope({ iteration: 0 })
|
||||||
const ctx = createTestContext('block-1', loopScope)
|
const ctx = createTestContext('block-1', loopScope)
|
||||||
|
|
||||||
expect(() => resolver.resolve('<loop.unknownProperty>', ctx)).toThrow(InvalidFieldError)
|
expect(resolver.resolve('<loop>', ctx)).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it.concurrent('should return undefined for unknown loop property', () => {
|
||||||
|
const resolver = new LoopResolver(createTestWorkflow())
|
||||||
|
const loopScope = createLoopScope({ iteration: 0 })
|
||||||
|
const ctx = createTestContext('block-1', loopScope)
|
||||||
|
|
||||||
|
expect(resolver.resolve('<loop.unknownProperty>', ctx)).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it.concurrent('should handle iteration index 0 correctly', () => {
|
it.concurrent('should handle iteration index 0 correctly', () => {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { isReference, parseReferencePath, REFERENCE } from '@/executor/constants'
|
import { isReference, parseReferencePath, REFERENCE } from '@/executor/constants'
|
||||||
import { InvalidFieldError } from '@/executor/utils/block-reference'
|
|
||||||
import { extractBaseBlockId } from '@/executor/utils/subflow-utils'
|
import { extractBaseBlockId } from '@/executor/utils/subflow-utils'
|
||||||
import {
|
import {
|
||||||
navigatePath,
|
navigatePath,
|
||||||
@@ -14,8 +13,6 @@ const logger = createLogger('LoopResolver')
|
|||||||
export class LoopResolver implements Resolver {
|
export class LoopResolver implements Resolver {
|
||||||
constructor(private workflow: SerializedWorkflow) {}
|
constructor(private workflow: SerializedWorkflow) {}
|
||||||
|
|
||||||
private static KNOWN_PROPERTIES = ['iteration', 'index', 'item', 'currentItem', 'items']
|
|
||||||
|
|
||||||
canResolve(reference: string): boolean {
|
canResolve(reference: string): boolean {
|
||||||
if (!isReference(reference)) {
|
if (!isReference(reference)) {
|
||||||
return false
|
return false
|
||||||
@@ -30,15 +27,16 @@ export class LoopResolver implements Resolver {
|
|||||||
|
|
||||||
resolve(reference: string, context: ResolutionContext): any {
|
resolve(reference: string, context: ResolutionContext): any {
|
||||||
const parts = parseReferencePath(reference)
|
const parts = parseReferencePath(reference)
|
||||||
if (parts.length === 0) {
|
if (parts.length < 2) {
|
||||||
logger.warn('Invalid loop reference', { reference })
|
logger.warn('Invalid loop reference - missing property', { reference })
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
const loopId = this.findLoopForBlock(context.currentNodeId)
|
const [_, property, ...pathParts] = parts
|
||||||
let loopScope = context.loopScope
|
let loopScope = context.loopScope
|
||||||
|
|
||||||
if (!loopScope) {
|
if (!loopScope) {
|
||||||
|
const loopId = this.findLoopForBlock(context.currentNodeId)
|
||||||
if (!loopId) {
|
if (!loopId) {
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
@@ -50,27 +48,6 @@ export class LoopResolver implements Resolver {
|
|||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
const isForEach = loopId ? this.isForEachLoop(loopId) : loopScope.items !== undefined
|
|
||||||
|
|
||||||
if (parts.length === 1) {
|
|
||||||
const result: Record<string, any> = {
|
|
||||||
index: loopScope.iteration,
|
|
||||||
}
|
|
||||||
if (loopScope.item !== undefined) {
|
|
||||||
result.currentItem = loopScope.item
|
|
||||||
}
|
|
||||||
if (loopScope.items !== undefined) {
|
|
||||||
result.items = loopScope.items
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
const [_, property, ...pathParts] = parts
|
|
||||||
if (!LoopResolver.KNOWN_PROPERTIES.includes(property)) {
|
|
||||||
const availableFields = isForEach ? ['index', 'currentItem', 'items'] : ['index']
|
|
||||||
throw new InvalidFieldError('loop', property, availableFields)
|
|
||||||
}
|
|
||||||
|
|
||||||
let value: any
|
let value: any
|
||||||
switch (property) {
|
switch (property) {
|
||||||
case 'iteration':
|
case 'iteration':
|
||||||
@@ -84,8 +61,12 @@ export class LoopResolver implements Resolver {
|
|||||||
case 'items':
|
case 'items':
|
||||||
value = loopScope.items
|
value = loopScope.items
|
||||||
break
|
break
|
||||||
|
default:
|
||||||
|
logger.warn('Unknown loop property', { property })
|
||||||
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If there are additional path parts, navigate deeper
|
||||||
if (pathParts.length > 0) {
|
if (pathParts.length > 0) {
|
||||||
return navigatePath(value, pathParts)
|
return navigatePath(value, pathParts)
|
||||||
}
|
}
|
||||||
@@ -104,9 +85,4 @@ export class LoopResolver implements Resolver {
|
|||||||
|
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
private isForEachLoop(loopId: string): boolean {
|
|
||||||
const loopConfig = this.workflow.loops?.[loopId]
|
|
||||||
return loopConfig?.loopType === 'forEach'
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { loggerMock } from '@sim/testing'
|
import { loggerMock } from '@sim/testing'
|
||||||
import { describe, expect, it, vi } from 'vitest'
|
import { describe, expect, it, vi } from 'vitest'
|
||||||
import { InvalidFieldError } from '@/executor/utils/block-reference'
|
|
||||||
import { ParallelResolver } from './parallel'
|
import { ParallelResolver } from './parallel'
|
||||||
import type { ResolutionContext } from './reference'
|
import type { ResolutionContext } from './reference'
|
||||||
|
|
||||||
@@ -82,12 +81,7 @@ function createTestContext(
|
|||||||
|
|
||||||
describe('ParallelResolver', () => {
|
describe('ParallelResolver', () => {
|
||||||
describe('canResolve', () => {
|
describe('canResolve', () => {
|
||||||
it.concurrent('should return true for bare parallel reference', () => {
|
it.concurrent('should return true for parallel references', () => {
|
||||||
const resolver = new ParallelResolver(createTestWorkflow())
|
|
||||||
expect(resolver.canResolve('<parallel>')).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it.concurrent('should return true for known parallel properties', () => {
|
|
||||||
const resolver = new ParallelResolver(createTestWorkflow())
|
const resolver = new ParallelResolver(createTestWorkflow())
|
||||||
expect(resolver.canResolve('<parallel.index>')).toBe(true)
|
expect(resolver.canResolve('<parallel.index>')).toBe(true)
|
||||||
expect(resolver.canResolve('<parallel.currentItem>')).toBe(true)
|
expect(resolver.canResolve('<parallel.currentItem>')).toBe(true)
|
||||||
@@ -100,16 +94,6 @@ describe('ParallelResolver', () => {
|
|||||||
expect(resolver.canResolve('<parallel.items.0>')).toBe(true)
|
expect(resolver.canResolve('<parallel.items.0>')).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it.concurrent(
|
|
||||||
'should return true for unknown parallel properties (validates in resolve)',
|
|
||||||
() => {
|
|
||||||
const resolver = new ParallelResolver(createTestWorkflow())
|
|
||||||
expect(resolver.canResolve('<parallel.results>')).toBe(true)
|
|
||||||
expect(resolver.canResolve('<parallel.output>')).toBe(true)
|
|
||||||
expect(resolver.canResolve('<parallel.unknownProperty>')).toBe(true)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
it.concurrent('should return false for non-parallel references', () => {
|
it.concurrent('should return false for non-parallel references', () => {
|
||||||
const resolver = new ParallelResolver(createTestWorkflow())
|
const resolver = new ParallelResolver(createTestWorkflow())
|
||||||
expect(resolver.canResolve('<block.output>')).toBe(false)
|
expect(resolver.canResolve('<block.output>')).toBe(false)
|
||||||
@@ -270,40 +254,24 @@ describe('ParallelResolver', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('edge cases', () => {
|
describe('edge cases', () => {
|
||||||
it.concurrent('should return context object for bare parallel reference', () => {
|
it.concurrent(
|
||||||
const workflow = createTestWorkflow({
|
'should return undefined for invalid parallel reference (missing property)',
|
||||||
'parallel-1': { nodes: ['block-1'], distribution: ['a', 'b', 'c'] },
|
() => {
|
||||||
})
|
const resolver = new ParallelResolver(createTestWorkflow())
|
||||||
const resolver = new ParallelResolver(workflow)
|
const ctx = createTestContext('block-1₍0₎')
|
||||||
const ctx = createTestContext('block-1₍1₎')
|
|
||||||
|
|
||||||
expect(resolver.resolve('<parallel>', ctx)).toEqual({
|
expect(resolver.resolve('<parallel>', ctx)).toBeUndefined()
|
||||||
index: 1,
|
}
|
||||||
currentItem: 'b',
|
)
|
||||||
items: ['a', 'b', 'c'],
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it.concurrent('should return minimal context object when no distribution', () => {
|
it.concurrent('should return undefined for unknown parallel property', () => {
|
||||||
const workflow = createTestWorkflow({
|
|
||||||
'parallel-1': { nodes: ['block-1'] },
|
|
||||||
})
|
|
||||||
const resolver = new ParallelResolver(workflow)
|
|
||||||
const ctx = createTestContext('block-1₍0₎')
|
|
||||||
|
|
||||||
const result = resolver.resolve('<parallel>', ctx)
|
|
||||||
expect(result).toHaveProperty('index', 0)
|
|
||||||
expect(result).toHaveProperty('items')
|
|
||||||
})
|
|
||||||
|
|
||||||
it.concurrent('should throw InvalidFieldError for unknown parallel property', () => {
|
|
||||||
const workflow = createTestWorkflow({
|
const workflow = createTestWorkflow({
|
||||||
'parallel-1': { nodes: ['block-1'], distribution: ['a'] },
|
'parallel-1': { nodes: ['block-1'], distribution: ['a'] },
|
||||||
})
|
})
|
||||||
const resolver = new ParallelResolver(workflow)
|
const resolver = new ParallelResolver(workflow)
|
||||||
const ctx = createTestContext('block-1₍0₎')
|
const ctx = createTestContext('block-1₍0₎')
|
||||||
|
|
||||||
expect(() => resolver.resolve('<parallel.unknownProperty>', ctx)).toThrow(InvalidFieldError)
|
expect(resolver.resolve('<parallel.unknownProperty>', ctx)).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it.concurrent('should return undefined when block is not in any parallel', () => {
|
it.concurrent('should return undefined when block is not in any parallel', () => {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { isReference, parseReferencePath, REFERENCE } from '@/executor/constants'
|
import { isReference, parseReferencePath, REFERENCE } from '@/executor/constants'
|
||||||
import { InvalidFieldError } from '@/executor/utils/block-reference'
|
|
||||||
import { extractBaseBlockId, extractBranchIndex } from '@/executor/utils/subflow-utils'
|
import { extractBaseBlockId, extractBranchIndex } from '@/executor/utils/subflow-utils'
|
||||||
import {
|
import {
|
||||||
navigatePath,
|
navigatePath,
|
||||||
@@ -14,8 +13,6 @@ const logger = createLogger('ParallelResolver')
|
|||||||
export class ParallelResolver implements Resolver {
|
export class ParallelResolver implements Resolver {
|
||||||
constructor(private workflow: SerializedWorkflow) {}
|
constructor(private workflow: SerializedWorkflow) {}
|
||||||
|
|
||||||
private static KNOWN_PROPERTIES = ['index', 'currentItem', 'items']
|
|
||||||
|
|
||||||
canResolve(reference: string): boolean {
|
canResolve(reference: string): boolean {
|
||||||
if (!isReference(reference)) {
|
if (!isReference(reference)) {
|
||||||
return false
|
return false
|
||||||
@@ -30,11 +27,12 @@ export class ParallelResolver implements Resolver {
|
|||||||
|
|
||||||
resolve(reference: string, context: ResolutionContext): any {
|
resolve(reference: string, context: ResolutionContext): any {
|
||||||
const parts = parseReferencePath(reference)
|
const parts = parseReferencePath(reference)
|
||||||
if (parts.length === 0) {
|
if (parts.length < 2) {
|
||||||
logger.warn('Invalid parallel reference', { reference })
|
logger.warn('Invalid parallel reference - missing property', { reference })
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const [_, property, ...pathParts] = parts
|
||||||
const parallelId = this.findParallelForBlock(context.currentNodeId)
|
const parallelId = this.findParallelForBlock(context.currentNodeId)
|
||||||
if (!parallelId) {
|
if (!parallelId) {
|
||||||
return undefined
|
return undefined
|
||||||
@@ -51,33 +49,11 @@ export class ParallelResolver implements Resolver {
|
|||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// First try to get items from the parallel scope (resolved at runtime)
|
||||||
|
// This is the same pattern as LoopResolver reading from loopScope.items
|
||||||
const parallelScope = context.executionContext.parallelExecutions?.get(parallelId)
|
const parallelScope = context.executionContext.parallelExecutions?.get(parallelId)
|
||||||
const distributionItems = parallelScope?.items ?? this.getDistributionItems(parallelConfig)
|
const distributionItems = parallelScope?.items ?? this.getDistributionItems(parallelConfig)
|
||||||
|
|
||||||
if (parts.length === 1) {
|
|
||||||
const result: Record<string, any> = {
|
|
||||||
index: branchIndex,
|
|
||||||
}
|
|
||||||
if (distributionItems !== undefined) {
|
|
||||||
result.items = distributionItems
|
|
||||||
if (Array.isArray(distributionItems)) {
|
|
||||||
result.currentItem = distributionItems[branchIndex]
|
|
||||||
} else if (typeof distributionItems === 'object' && distributionItems !== null) {
|
|
||||||
const keys = Object.keys(distributionItems)
|
|
||||||
const key = keys[branchIndex]
|
|
||||||
result.currentItem = key !== undefined ? distributionItems[key] : undefined
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
const [_, property, ...pathParts] = parts
|
|
||||||
if (!ParallelResolver.KNOWN_PROPERTIES.includes(property)) {
|
|
||||||
const isCollection = parallelConfig.parallelType === 'collection'
|
|
||||||
const availableFields = isCollection ? ['index', 'currentItem', 'items'] : ['index']
|
|
||||||
throw new InvalidFieldError('parallel', property, availableFields)
|
|
||||||
}
|
|
||||||
|
|
||||||
let value: any
|
let value: any
|
||||||
switch (property) {
|
switch (property) {
|
||||||
case 'index':
|
case 'index':
|
||||||
@@ -97,8 +73,12 @@ export class ParallelResolver implements Resolver {
|
|||||||
case 'items':
|
case 'items':
|
||||||
value = distributionItems
|
value = distributionItems
|
||||||
break
|
break
|
||||||
|
default:
|
||||||
|
logger.warn('Unknown parallel property', { property })
|
||||||
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If there are additional path parts, navigate deeper
|
||||||
if (pathParts.length > 0) {
|
if (pathParts.length > 0) {
|
||||||
return navigatePath(value, pathParts)
|
return navigatePath(value, pathParts)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useCallback } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { createLogger } from '@sim/logger'
|
||||||
import type { AllTagSlot } from '@/lib/knowledge/constants'
|
import type { AllTagSlot } from '@/lib/knowledge/constants'
|
||||||
import { knowledgeKeys, useTagDefinitionsQuery } from '@/hooks/queries/knowledge'
|
|
||||||
|
const logger = createLogger('useKnowledgeBaseTagDefinitions')
|
||||||
|
|
||||||
export interface TagDefinition {
|
export interface TagDefinition {
|
||||||
id: string
|
id: string
|
||||||
@@ -16,23 +17,54 @@ export interface TagDefinition {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Hook for fetching KB-scoped tag definitions (for filtering/selection)
|
* Hook for fetching KB-scoped tag definitions (for filtering/selection)
|
||||||
* Uses React Query as single source of truth
|
* @param knowledgeBaseId - The knowledge base ID
|
||||||
*/
|
*/
|
||||||
export function useKnowledgeBaseTagDefinitions(knowledgeBaseId: string | null) {
|
export function useKnowledgeBaseTagDefinitions(knowledgeBaseId: string | null) {
|
||||||
const queryClient = useQueryClient()
|
const [tagDefinitions, setTagDefinitions] = useState<TagDefinition[]>([])
|
||||||
const query = useTagDefinitionsQuery(knowledgeBaseId)
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
const fetchTagDefinitions = useCallback(async () => {
|
const fetchTagDefinitions = useCallback(async () => {
|
||||||
if (!knowledgeBaseId) return
|
if (!knowledgeBaseId) {
|
||||||
await queryClient.invalidateQueries({
|
setTagDefinitions([])
|
||||||
queryKey: knowledgeKeys.tagDefinitions(knowledgeBaseId),
|
return
|
||||||
})
|
}
|
||||||
}, [queryClient, knowledgeBaseId])
|
|
||||||
|
setIsLoading(true)
|
||||||
|
setError(null)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/knowledge/${knowledgeBaseId}/tag-definitions`)
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Failed to fetch tag definitions: ${response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json()
|
||||||
|
|
||||||
|
if (data.success && Array.isArray(data.data)) {
|
||||||
|
setTagDefinitions(data.data)
|
||||||
|
} else {
|
||||||
|
throw new Error('Invalid response format')
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'
|
||||||
|
logger.error('Error fetching tag definitions:', err)
|
||||||
|
setError(errorMessage)
|
||||||
|
setTagDefinitions([])
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false)
|
||||||
|
}
|
||||||
|
}, [knowledgeBaseId])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchTagDefinitions()
|
||||||
|
}, [fetchTagDefinitions])
|
||||||
|
|
||||||
return {
|
return {
|
||||||
tagDefinitions: (query.data ?? []) as TagDefinition[],
|
tagDefinitions,
|
||||||
isLoading: query.isLoading,
|
isLoading,
|
||||||
error: query.error instanceof Error ? query.error.message : null,
|
error,
|
||||||
fetchTagDefinitions,
|
fetchTagDefinitions,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useMemo } from 'react'
|
import { useCallback } from 'react'
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
import type { ChunkData, DocumentData, KnowledgeBaseData } from '@/lib/knowledge/types'
|
import type { ChunkData, DocumentData, KnowledgeBaseData } from '@/lib/knowledge/types'
|
||||||
import {
|
import {
|
||||||
@@ -67,17 +67,12 @@ export function useKnowledgeBaseDocuments(
|
|||||||
sortBy?: string
|
sortBy?: string
|
||||||
sortOrder?: string
|
sortOrder?: string
|
||||||
enabled?: boolean
|
enabled?: boolean
|
||||||
refetchInterval?:
|
refetchInterval?: number | false
|
||||||
| number
|
|
||||||
| false
|
|
||||||
| ((data: KnowledgeDocumentsResponse | undefined) => number | false)
|
|
||||||
enabledFilter?: 'all' | 'enabled' | 'disabled'
|
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const requestLimit = options?.limit ?? DEFAULT_PAGE_SIZE
|
const requestLimit = options?.limit ?? DEFAULT_PAGE_SIZE
|
||||||
const requestOffset = options?.offset ?? 0
|
const requestOffset = options?.offset ?? 0
|
||||||
const enabledFilter = options?.enabledFilter ?? 'all'
|
|
||||||
const paramsKey = serializeDocumentParams({
|
const paramsKey = serializeDocumentParams({
|
||||||
knowledgeBaseId,
|
knowledgeBaseId,
|
||||||
limit: requestLimit,
|
limit: requestLimit,
|
||||||
@@ -85,19 +80,8 @@ export function useKnowledgeBaseDocuments(
|
|||||||
search: options?.search,
|
search: options?.search,
|
||||||
sortBy: options?.sortBy,
|
sortBy: options?.sortBy,
|
||||||
sortOrder: options?.sortOrder,
|
sortOrder: options?.sortOrder,
|
||||||
enabledFilter,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const refetchIntervalFn = useMemo(() => {
|
|
||||||
if (typeof options?.refetchInterval === 'function') {
|
|
||||||
const userFn = options.refetchInterval
|
|
||||||
return (query: { state: { data?: KnowledgeDocumentsResponse } }) => {
|
|
||||||
return userFn(query.state.data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return options?.refetchInterval
|
|
||||||
}, [options?.refetchInterval])
|
|
||||||
|
|
||||||
const query = useKnowledgeDocumentsQuery(
|
const query = useKnowledgeDocumentsQuery(
|
||||||
{
|
{
|
||||||
knowledgeBaseId,
|
knowledgeBaseId,
|
||||||
@@ -106,11 +90,10 @@ export function useKnowledgeBaseDocuments(
|
|||||||
search: options?.search,
|
search: options?.search,
|
||||||
sortBy: options?.sortBy,
|
sortBy: options?.sortBy,
|
||||||
sortOrder: options?.sortOrder,
|
sortOrder: options?.sortOrder,
|
||||||
enabledFilter,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
enabled: (options?.enabled ?? true) && Boolean(knowledgeBaseId),
|
enabled: (options?.enabled ?? true) && Boolean(knowledgeBaseId),
|
||||||
refetchInterval: refetchIntervalFn,
|
refetchInterval: options?.refetchInterval,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -122,14 +105,6 @@ export function useKnowledgeBaseDocuments(
|
|||||||
hasMore: false,
|
hasMore: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasProcessingDocs = useMemo(
|
|
||||||
() =>
|
|
||||||
documents.some(
|
|
||||||
(doc) => doc.processingStatus === 'pending' || doc.processingStatus === 'processing'
|
|
||||||
),
|
|
||||||
[documents]
|
|
||||||
)
|
|
||||||
|
|
||||||
const refreshDocuments = useCallback(async () => {
|
const refreshDocuments = useCallback(async () => {
|
||||||
await queryClient.invalidateQueries({
|
await queryClient.invalidateQueries({
|
||||||
queryKey: knowledgeKeys.documents(knowledgeBaseId, paramsKey),
|
queryKey: knowledgeKeys.documents(knowledgeBaseId, paramsKey),
|
||||||
@@ -161,7 +136,6 @@ export function useKnowledgeBaseDocuments(
|
|||||||
isFetching: query.isFetching,
|
isFetching: query.isFetching,
|
||||||
isPlaceholderData: query.isPlaceholderData,
|
isPlaceholderData: query.isPlaceholderData,
|
||||||
error: query.error instanceof Error ? query.error.message : null,
|
error: query.error instanceof Error ? query.error.message : null,
|
||||||
hasProcessingDocuments: hasProcessingDocs,
|
|
||||||
refreshDocuments,
|
refreshDocuments,
|
||||||
updateDocument,
|
updateDocument,
|
||||||
}
|
}
|
||||||
@@ -259,8 +233,8 @@ export function useDocumentChunks(
|
|||||||
const hasPrevPage = currentPage > 1
|
const hasPrevPage = currentPage > 1
|
||||||
|
|
||||||
const goToPage = useCallback(
|
const goToPage = useCallback(
|
||||||
(newPage: number): boolean => {
|
async (newPage: number) => {
|
||||||
return newPage >= 1 && newPage <= totalPages
|
if (newPage < 1 || newPage > totalPages) return
|
||||||
},
|
},
|
||||||
[totalPages]
|
[totalPages]
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,15 +1,10 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useCallback } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { createLogger } from '@sim/logger'
|
||||||
import type { AllTagSlot } from '@/lib/knowledge/constants'
|
import type { AllTagSlot } from '@/lib/knowledge/constants'
|
||||||
import {
|
|
||||||
type DocumentTagDefinitionInput,
|
const logger = createLogger('useTagDefinitions')
|
||||||
knowledgeKeys,
|
|
||||||
useDeleteDocumentTagDefinitions,
|
|
||||||
useDocumentTagDefinitionsQuery,
|
|
||||||
useSaveDocumentTagDefinitions,
|
|
||||||
} from '@/hooks/queries/knowledge'
|
|
||||||
|
|
||||||
export interface TagDefinition {
|
export interface TagDefinition {
|
||||||
id: string
|
id: string
|
||||||
@@ -24,30 +19,57 @@ export interface TagDefinitionInput {
|
|||||||
tagSlot: AllTagSlot
|
tagSlot: AllTagSlot
|
||||||
displayName: string
|
displayName: string
|
||||||
fieldType: string
|
fieldType: string
|
||||||
|
// Optional: for editing existing definitions
|
||||||
_originalDisplayName?: string
|
_originalDisplayName?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Hook for managing document-scoped tag definitions
|
* Hook for managing KB-scoped tag definitions
|
||||||
* Uses React Query as single source of truth
|
* @param knowledgeBaseId - The knowledge base ID
|
||||||
|
* @param documentId - The document ID (required for API calls)
|
||||||
*/
|
*/
|
||||||
export function useTagDefinitions(
|
export function useTagDefinitions(
|
||||||
knowledgeBaseId: string | null,
|
knowledgeBaseId: string | null,
|
||||||
documentId: string | null = null
|
documentId: string | null = null
|
||||||
) {
|
) {
|
||||||
const queryClient = useQueryClient()
|
const [tagDefinitions, setTagDefinitions] = useState<TagDefinition[]>([])
|
||||||
const query = useDocumentTagDefinitionsQuery(knowledgeBaseId, documentId)
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
const { mutateAsync: saveTagDefinitionsMutation } = useSaveDocumentTagDefinitions()
|
const [error, setError] = useState<string | null>(null)
|
||||||
const { mutateAsync: deleteTagDefinitionsMutation } = useDeleteDocumentTagDefinitions()
|
|
||||||
|
|
||||||
const tagDefinitions = (query.data ?? []) as TagDefinition[]
|
|
||||||
|
|
||||||
const fetchTagDefinitions = useCallback(async () => {
|
const fetchTagDefinitions = useCallback(async () => {
|
||||||
if (!knowledgeBaseId || !documentId) return
|
if (!knowledgeBaseId || !documentId) {
|
||||||
await queryClient.invalidateQueries({
|
setTagDefinitions([])
|
||||||
queryKey: knowledgeKeys.documentTagDefinitions(knowledgeBaseId, documentId),
|
return
|
||||||
})
|
}
|
||||||
}, [queryClient, knowledgeBaseId, documentId])
|
|
||||||
|
setIsLoading(true)
|
||||||
|
setError(null)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/knowledge/${knowledgeBaseId}/documents/${documentId}/tag-definitions`
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Failed to fetch tag definitions: ${response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json()
|
||||||
|
|
||||||
|
if (data.success && Array.isArray(data.data)) {
|
||||||
|
setTagDefinitions(data.data)
|
||||||
|
} else {
|
||||||
|
throw new Error('Invalid response format')
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'
|
||||||
|
logger.error('Error fetching tag definitions:', err)
|
||||||
|
setError(errorMessage)
|
||||||
|
setTagDefinitions([])
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false)
|
||||||
|
}
|
||||||
|
}, [knowledgeBaseId, documentId])
|
||||||
|
|
||||||
const saveTagDefinitions = useCallback(
|
const saveTagDefinitions = useCallback(
|
||||||
async (definitions: TagDefinitionInput[]) => {
|
async (definitions: TagDefinitionInput[]) => {
|
||||||
@@ -55,13 +77,43 @@ export function useTagDefinitions(
|
|||||||
throw new Error('Knowledge base ID and document ID are required')
|
throw new Error('Knowledge base ID and document ID are required')
|
||||||
}
|
}
|
||||||
|
|
||||||
return saveTagDefinitionsMutation({
|
// Simple validation
|
||||||
knowledgeBaseId,
|
const validDefinitions = (definitions || []).filter(
|
||||||
documentId,
|
(def) => def?.tagSlot && def.displayName && def.displayName.trim()
|
||||||
definitions: definitions as DocumentTagDefinitionInput[],
|
)
|
||||||
})
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/knowledge/${knowledgeBaseId}/documents/${documentId}/tag-definitions`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ definitions: validDefinitions }),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Failed to save tag definitions: ${response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json()
|
||||||
|
|
||||||
|
if (!data.success) {
|
||||||
|
throw new Error(data.error || 'Failed to save tag definitions')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the definitions after saving
|
||||||
|
await fetchTagDefinitions()
|
||||||
|
|
||||||
|
return data.data
|
||||||
|
} catch (err) {
|
||||||
|
logger.error('Error saving tag definitions:', err)
|
||||||
|
throw err
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[knowledgeBaseId, documentId, saveTagDefinitionsMutation]
|
[knowledgeBaseId, documentId, fetchTagDefinitions]
|
||||||
)
|
)
|
||||||
|
|
||||||
const deleteTagDefinitions = useCallback(async () => {
|
const deleteTagDefinitions = useCallback(async () => {
|
||||||
@@ -69,11 +121,25 @@ export function useTagDefinitions(
|
|||||||
throw new Error('Knowledge base ID and document ID are required')
|
throw new Error('Knowledge base ID and document ID are required')
|
||||||
}
|
}
|
||||||
|
|
||||||
return deleteTagDefinitionsMutation({
|
try {
|
||||||
knowledgeBaseId,
|
const response = await fetch(
|
||||||
documentId,
|
`/api/knowledge/${knowledgeBaseId}/documents/${documentId}/tag-definitions`,
|
||||||
})
|
{
|
||||||
}, [knowledgeBaseId, documentId, deleteTagDefinitionsMutation])
|
method: 'DELETE',
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Failed to delete tag definitions: ${response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the definitions after deleting
|
||||||
|
await fetchTagDefinitions()
|
||||||
|
} catch (err) {
|
||||||
|
logger.error('Error deleting tag definitions:', err)
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
}, [knowledgeBaseId, documentId, fetchTagDefinitions])
|
||||||
|
|
||||||
const getTagLabel = useCallback(
|
const getTagLabel = useCallback(
|
||||||
(tagSlot: string): string => {
|
(tagSlot: string): string => {
|
||||||
@@ -90,10 +156,15 @@ export function useTagDefinitions(
|
|||||||
[tagDefinitions]
|
[tagDefinitions]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Auto-fetch on mount and when dependencies change
|
||||||
|
useEffect(() => {
|
||||||
|
fetchTagDefinitions()
|
||||||
|
}, [fetchTagDefinitions])
|
||||||
|
|
||||||
return {
|
return {
|
||||||
tagDefinitions,
|
tagDefinitions,
|
||||||
isLoading: query.isLoading,
|
isLoading,
|
||||||
error: query.error instanceof Error ? query.error.message : null,
|
error,
|
||||||
fetchTagDefinitions,
|
fetchTagDefinitions,
|
||||||
saveTagDefinitions,
|
saveTagDefinitions,
|
||||||
deleteTagDefinitions,
|
deleteTagDefinitions,
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user