-
Notifications
You must be signed in to change notification settings - Fork 3.4k
v0.6.2: mothership stability, chat iframe embedding, KB upserts, new blog post #3650
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+3,669
−774
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
cdd0f75
fix(mothership): fix mothership file uploads (#3640)
Sg312 75a3e2c
fix(workspace): prevent stale placeholder data from corrupting workfl…
waleedlatif1 c9f082d
feat(csp): allow chat UI to be embedded in iframes (#3643)
waleedlatif1 67478bb
fix(logs): add durable execution diagnostics foundation (#3564)
PlaneInABottle 2bc11a7
waleedlatif1/hangzhou v2 (#3647)
waleedlatif1 5f89c71
feat(knowledge): add upsert document operation (#3644)
waleedlatif1 168cd58
feat(mothership): request ids (#3645)
Sg312 28de288
improvement(landing): added enterprise section (#3637)
waleedlatif1 b84f30e
fix(db): reduce connection pool sizes to prevent exhaustion (#3649)
waleedlatif1 8a4c161
feat(home): resizable chat/resource panel divider (#3648)
waleedlatif1 60bb942
feat(blog): add v0.6 blog post and email broadcast (#3636)
waleedlatif1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
476 changes: 473 additions & 3 deletions
476
apps/sim/app/(home)/components/enterprise/enterprise.tsx
Large diffs are not rendered by default.
Oops, something went wrong.
312 changes: 230 additions & 82 deletions
312
apps/sim/app/(home)/components/features/components/features-preview.tsx
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
248 changes: 248 additions & 0 deletions
248
apps/sim/app/api/knowledge/[id]/documents/upsert/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,248 @@ | ||
| import { randomUUID } from 'crypto' | ||
| import { db } from '@sim/db' | ||
| import { document } from '@sim/db/schema' | ||
| import { createLogger } from '@sim/logger' | ||
| import { and, eq, isNull } from 'drizzle-orm' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { z } from 'zod' | ||
| import { AuditAction, AuditResourceType, recordAudit } from '@/lib/audit/log' | ||
| import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' | ||
| import { | ||
| createDocumentRecords, | ||
| deleteDocument, | ||
| getProcessingConfig, | ||
| processDocumentsWithQueue, | ||
| } from '@/lib/knowledge/documents/service' | ||
| import { authorizeWorkflowByWorkspacePermission } from '@/lib/workflows/utils' | ||
| import { checkKnowledgeBaseWriteAccess } from '@/app/api/knowledge/utils' | ||
|
|
||
| const logger = createLogger('DocumentUpsertAPI') | ||
|
|
||
| const UpsertDocumentSchema = z.object({ | ||
| documentId: z.string().optional(), | ||
| filename: z.string().min(1, 'Filename is required'), | ||
| fileUrl: z.string().min(1, 'File URL is required'), | ||
| fileSize: z.number().min(1, 'File size must be greater than 0'), | ||
| mimeType: z.string().min(1, 'MIME type is required'), | ||
| documentTagsData: z.string().optional(), | ||
| processingOptions: z.object({ | ||
| chunkSize: z.number().min(100).max(4000), | ||
| minCharactersPerChunk: z.number().min(1).max(2000), | ||
| recipe: z.string(), | ||
| lang: z.string(), | ||
| chunkOverlap: z.number().min(0).max(500), | ||
| }), | ||
| workflowId: z.string().optional(), | ||
| }) | ||
|
|
||
| export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { | ||
| const requestId = randomUUID().slice(0, 8) | ||
| const { id: knowledgeBaseId } = await params | ||
|
|
||
| try { | ||
| const body = await req.json() | ||
|
|
||
| logger.info(`[${requestId}] Knowledge base document upsert request`, { | ||
| knowledgeBaseId, | ||
| hasDocumentId: !!body.documentId, | ||
| filename: body.filename, | ||
| }) | ||
|
|
||
| const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false }) | ||
| if (!auth.success || !auth.userId) { | ||
| logger.warn(`[${requestId}] Authentication failed: ${auth.error || 'Unauthorized'}`) | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
| } | ||
| const userId = auth.userId | ||
|
|
||
| const validatedData = UpsertDocumentSchema.parse(body) | ||
|
|
||
| if (validatedData.workflowId) { | ||
| const authorization = await authorizeWorkflowByWorkspacePermission({ | ||
| workflowId: validatedData.workflowId, | ||
| userId, | ||
| action: 'write', | ||
| }) | ||
| if (!authorization.allowed) { | ||
| return NextResponse.json( | ||
| { error: authorization.message || 'Access denied' }, | ||
| { status: authorization.status } | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| const accessCheck = await checkKnowledgeBaseWriteAccess(knowledgeBaseId, userId) | ||
|
|
||
| if (!accessCheck.hasAccess) { | ||
| if ('notFound' in accessCheck && accessCheck.notFound) { | ||
| logger.warn(`[${requestId}] Knowledge base not found: ${knowledgeBaseId}`) | ||
| return NextResponse.json({ error: 'Knowledge base not found' }, { status: 404 }) | ||
| } | ||
| logger.warn( | ||
| `[${requestId}] User ${userId} attempted to upsert document in unauthorized knowledge base ${knowledgeBaseId}` | ||
| ) | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
| } | ||
|
|
||
| let existingDocumentId: string | null = null | ||
| let isUpdate = false | ||
|
|
||
| if (validatedData.documentId) { | ||
| const existingDoc = await db | ||
| .select({ id: document.id }) | ||
| .from(document) | ||
| .where( | ||
| and( | ||
| eq(document.id, validatedData.documentId), | ||
| eq(document.knowledgeBaseId, knowledgeBaseId), | ||
| isNull(document.deletedAt) | ||
| ) | ||
| ) | ||
| .limit(1) | ||
|
|
||
| if (existingDoc.length > 0) { | ||
| existingDocumentId = existingDoc[0].id | ||
| } | ||
| } else { | ||
| const docsByFilename = await db | ||
| .select({ id: document.id }) | ||
| .from(document) | ||
| .where( | ||
| and( | ||
| eq(document.filename, validatedData.filename), | ||
| eq(document.knowledgeBaseId, knowledgeBaseId), | ||
| isNull(document.deletedAt) | ||
| ) | ||
| ) | ||
| .limit(1) | ||
|
|
||
| if (docsByFilename.length > 0) { | ||
| existingDocumentId = docsByFilename[0].id | ||
| } | ||
| } | ||
|
|
||
| if (existingDocumentId) { | ||
| isUpdate = true | ||
| logger.info( | ||
| `[${requestId}] Found existing document ${existingDocumentId}, creating replacement before deleting old` | ||
| ) | ||
| } | ||
|
|
||
| const createdDocuments = await createDocumentRecords( | ||
| [ | ||
| { | ||
| filename: validatedData.filename, | ||
| fileUrl: validatedData.fileUrl, | ||
| fileSize: validatedData.fileSize, | ||
| mimeType: validatedData.mimeType, | ||
| ...(validatedData.documentTagsData && { | ||
| documentTagsData: validatedData.documentTagsData, | ||
| }), | ||
| }, | ||
| ], | ||
| knowledgeBaseId, | ||
| requestId | ||
| ) | ||
|
|
||
| const firstDocument = createdDocuments[0] | ||
| if (!firstDocument) { | ||
| logger.error(`[${requestId}] createDocumentRecords returned empty array unexpectedly`) | ||
| return NextResponse.json({ error: 'Failed to create document record' }, { status: 500 }) | ||
| } | ||
|
|
||
| if (existingDocumentId) { | ||
| try { | ||
| await deleteDocument(existingDocumentId, requestId) | ||
| } catch (deleteError) { | ||
| logger.error( | ||
| `[${requestId}] Failed to delete old document ${existingDocumentId}, rolling back new record`, | ||
| deleteError | ||
| ) | ||
| await deleteDocument(firstDocument.documentId, requestId).catch(() => {}) | ||
| return NextResponse.json({ error: 'Failed to replace existing document' }, { status: 500 }) | ||
| } | ||
| } | ||
|
|
||
| processDocumentsWithQueue( | ||
| createdDocuments, | ||
| knowledgeBaseId, | ||
| validatedData.processingOptions, | ||
| requestId | ||
| ).catch((error: unknown) => { | ||
| logger.error(`[${requestId}] Critical error in document processing pipeline:`, error) | ||
| }) | ||
|
|
||
| try { | ||
| const { PlatformEvents } = await import('@/lib/core/telemetry') | ||
| PlatformEvents.knowledgeBaseDocumentsUploaded({ | ||
| knowledgeBaseId, | ||
| documentsCount: 1, | ||
| uploadType: 'single', | ||
| chunkSize: validatedData.processingOptions.chunkSize, | ||
| recipe: validatedData.processingOptions.recipe, | ||
| }) | ||
| } catch (_e) { | ||
| // Silently fail | ||
| } | ||
|
|
||
| recordAudit({ | ||
| workspaceId: accessCheck.knowledgeBase?.workspaceId ?? null, | ||
| actorId: userId, | ||
| actorName: auth.userName, | ||
| actorEmail: auth.userEmail, | ||
| action: isUpdate ? AuditAction.DOCUMENT_UPDATED : AuditAction.DOCUMENT_UPLOADED, | ||
| resourceType: AuditResourceType.DOCUMENT, | ||
| resourceId: knowledgeBaseId, | ||
| resourceName: validatedData.filename, | ||
| description: isUpdate | ||
| ? `Upserted (replaced) document "${validatedData.filename}" in knowledge base "${knowledgeBaseId}"` | ||
| : `Upserted (created) document "${validatedData.filename}" in knowledge base "${knowledgeBaseId}"`, | ||
| metadata: { | ||
| fileName: validatedData.filename, | ||
| previousDocumentId: existingDocumentId, | ||
| isUpdate, | ||
| }, | ||
| request: req, | ||
| }) | ||
|
|
||
| return NextResponse.json({ | ||
| success: true, | ||
| data: { | ||
| documentsCreated: [ | ||
| { | ||
| documentId: firstDocument.documentId, | ||
| filename: firstDocument.filename, | ||
| status: 'pending', | ||
| }, | ||
| ], | ||
| isUpdate, | ||
| previousDocumentId: existingDocumentId, | ||
| processingMethod: 'background', | ||
| processingConfig: { | ||
| maxConcurrentDocuments: getProcessingConfig().maxConcurrentDocuments, | ||
| batchSize: getProcessingConfig().batchSize, | ||
| }, | ||
| }, | ||
| }) | ||
| } catch (error) { | ||
| if (error instanceof z.ZodError) { | ||
| logger.warn(`[${requestId}] Invalid upsert request data`, { errors: error.errors }) | ||
| return NextResponse.json( | ||
| { error: 'Invalid request data', details: error.errors }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
|
|
||
| logger.error(`[${requestId}] Error upserting document`, error) | ||
|
|
||
| const errorMessage = error instanceof Error ? error.message : 'Failed to upsert document' | ||
| const isStorageLimitError = | ||
| errorMessage.includes('Storage limit exceeded') || errorMessage.includes('storage limit') | ||
| const isMissingKnowledgeBase = errorMessage === 'Knowledge base not found' | ||
|
|
||
| return NextResponse.json( | ||
| { error: errorMessage }, | ||
| { status: isMissingKnowledgeBase ? 404 : isStorageLimitError ? 413 : 500 } | ||
| ) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletions
1
apps/sim/app/workspace/[workspaceId]/components/message-actions/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { MessageActions } from './message-actions' |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The create-then-delete rollback silently swallows errors:
If the rollback itself fails (e.g. transient DB error), both the old document and the newly created document record will exist in the knowledge base simultaneously. The caller receives a 500, but neither record is cleaned up, leading to duplicate documents that are invisible to normal user flows but still consume storage and can surface in search results.
Since the whole operation is logically atomic (replace), wrapping
createDocumentRecordsanddeleteDocumentin a database transaction would be the safest fix. If a transaction isn't feasible here (e.g. the service layer doesn't expose transaction contexts), at minimum the rollback failure should be logged aterrorlevel with enough context to trigger manual cleanup: