Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions apps/sim/app/workspace/[workspaceId]/home/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,14 @@ export function Home({ chatId }: HomeProps = {}) {
[resolveResourceFromContext, addResource, handleResourceEvent]
)

const handleInitialContextRemove = useCallback(
(context: ChatContext) => {
const resolved = resolveResourceFromContext(context)
if (resolved) removeResource(resolved.type, resolved.id)
},
[resolveResourceFromContext, removeResource]
)

const handleWorkspaceResourceSelect = useCallback(
(resource: MothershipResource) => {
const wasAdded = addResource(resource)
Expand Down Expand Up @@ -345,6 +353,7 @@ export function Home({ chatId }: HomeProps = {}) {
onStopGeneration={handleStopGeneration}
userId={session?.user?.id}
onContextAdd={handleContextAdd}
onContextRemove={handleInitialContextRemove}
/>
</div>
</div>
Expand Down
16 changes: 5 additions & 11 deletions apps/sim/app/workspace/[workspaceId]/home/hooks/use-chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -951,7 +951,7 @@ export function useChat(
selectedChatIdRef.current = initialChatId
const appliedChatHistoryKeyRef = useRef<string | undefined>(undefined)
const activeTurnRef = useRef<ActiveTurn | null>(null)
const pendingUserMsgRef = useRef<{ id: string; content: string } | null>(null)
const pendingUserMsgRef = useRef<PersistedMessage | null>(null)
const streamIdRef = useRef<string | undefined>(undefined)
const locallyTerminalStreamIdRef = useRef<string | undefined>(undefined)
const lastCursorRef = useRef('0')
Expand Down Expand Up @@ -1079,6 +1079,7 @@ export function useChat(

const removeResource = useCallback((resourceType: MothershipResourceType, resourceId: string) => {
setResources((prev) => prev.filter((r) => !(r.type === resourceType && r.id === resourceId)))
setActiveResourceId((prev) => (prev === resourceId ? null : prev))
}, [])

const reorderResources = useCallback((newOrder: MothershipResource[]) => {
Expand Down Expand Up @@ -1594,16 +1595,9 @@ export function useChat(
queryClient.setQueryData<TaskChatHistory>(taskKeys.detail(payloadChatId), {
id: payloadChatId,
title: null,
messages: [
{
id: userMsg.id,
role: 'user',
content: userMsg.content,
timestamp: new Date().toISOString(),
},
],
messages: [userMsg],
activeStreamId,
resources: [],
resources: resourcesRef.current,
})
}
if (!workflowIdRef.current) {
Expand Down Expand Up @@ -2652,7 +2646,6 @@ export function useChat(
const userMessageId = generateId()
const assistantId = generateId()

pendingUserMsgRef.current = { id: userMessageId, content: message }
streamIdRef.current = userMessageId
lastCursorRef.current = '0'
resetStreamingBuffers()
Expand Down Expand Up @@ -2686,6 +2679,7 @@ export function useChat(
...(storedAttachments && { fileAttachments: storedAttachments }),
...(messageContexts && messageContexts.length > 0 ? { contexts: messageContexts } : {}),
}
pendingUserMsgRef.current = cachedUserMsg

const userAttachments = storedAttachments?.map((f) => ({
id: f.id,
Expand Down
22 changes: 22 additions & 0 deletions apps/sim/lib/copilot/chat/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
releasePendingChatStream,
} from '@/lib/copilot/request/session'
import type { ExecutionContext, OrchestratorResult } from '@/lib/copilot/request/types'
import { persistChatResources } from '@/lib/copilot/resources/persistence'
import { taskPubSub } from '@/lib/copilot/tasks'
import { prepareExecutionContext } from '@/lib/copilot/tools/handlers/context'
import { getEffectiveDecryptedEnv } from '@/lib/environment/utils'
Expand Down Expand Up @@ -57,6 +58,14 @@ const ResourceAttachmentSchema = z.object({
active: z.boolean().optional(),
})

const GENERIC_RESOURCE_TITLE: Record<z.infer<typeof ResourceAttachmentSchema>['type'], string> = {
workflow: 'Workflow',
table: 'Table',
file: 'File',
knowledgebase: 'Knowledge Base',
folder: 'Folder',
}

const ChatContextSchema = z.object({
kind: z.enum([
'past_chat',
Expand Down Expand Up @@ -549,6 +558,7 @@ export async function handleUnifiedChatPost(req: NextRequest) {

let currentChat: ChatLoadResult['chat'] = null
let conversationHistory: unknown[] = []
let chatIsNew = false
actualChatId = body.chatId

if (body.chatId || body.createNewChat) {
Expand All @@ -562,6 +572,7 @@ export async function handleUnifiedChatPost(req: NextRequest) {
})
currentChat = chatResult.chat
actualChatId = chatResult.chatId || body.chatId
chatIsNew = chatResult.isNew
conversationHistory = Array.isArray(chatResult.conversationHistory)
? chatResult.conversationHistory
: []
Expand All @@ -571,6 +582,17 @@ export async function handleUnifiedChatPost(req: NextRequest) {
}
}

if (chatIsNew && actualChatId && body.resourceAttachments?.length) {
await persistChatResources(
actualChatId,
body.resourceAttachments.map((r) => ({
type: r.type,
id: r.id,
title: r.title ?? GENERIC_RESOURCE_TITLE[r.type],
}))
)
}

if (actualChatId) {
chatStreamLockAcquired = await acquirePendingChatStream(actualChatId, userMessageId)
if (!chatStreamLockAcquired) {
Expand Down
Loading