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
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
type ClipboardEventHandler,
type KeyboardEventHandler,
type ReactNode,
type RefObject,
useLayoutEffect,
Expand All @@ -18,6 +19,7 @@ interface SearchInputBarProps {
onChange: (value: string) => void
onSubmit: () => void
onPaste?: ClipboardEventHandler<HTMLTextAreaElement>
onKeyDown?: KeyboardEventHandler<HTMLTextAreaElement>
placeholder?: string
'aria-label'?: string
leadingControls?: ReactNode
Expand All @@ -37,6 +39,7 @@ export function SearchInputBar({
onChange,
onSubmit,
onPaste,
onKeyDown,
placeholder = 'Search your sources',
'aria-label': ariaLabel = 'Search your sources',
selectionControl,
Expand Down Expand Up @@ -108,6 +111,8 @@ export function SearchInputBar({
maxHeight={200}
onChange={(event) => onChange(event.target.value)}
onKeyDown={(event) => {
onKeyDown?.(event)
if (event.defaultPrevented) return
if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
event.preventDefault()
onSubmit()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import { useEffect, useRef } from 'react'
import { Chip, ComposerActionButton, cn, Tooltip, toast } from '@sim/emcn'
import { ArrowUp, Paperclip, Plus, Search, Slash, StopFilled } from '@sim/emcn/icons'
import { escapeRegExp } from '@sim/utils/string'
import { useQueries } from '@tanstack/react-query'
import {
ASSISTANT_IMAGE_ACCEPT_ATTRIBUTE,
Expand All @@ -25,9 +24,9 @@ import {
} from '@/app/workspace/[workspaceId]/home/components/user-input/components/prompt-editor'
import { organizationSkillOptions } from '@/app/workspace/[workspaceId]/home/components/user-input/components/skills-menu-dropdown/organization-skill-options'
import { useConversationModeShortcut } from '@/app/workspace/[workspaceId]/home/components/user-input/hooks/use-conversation-mode-shortcut'
import type { ChatRequestMode } from '@/app/workspace/[workspaceId]/home/types'
import { usePromptHistory } from '@/app/workspace/[workspaceId]/home/components/user-input/hooks/use-prompt-history'
import type { ChatMessage, ChatRequestMode } from '@/app/workspace/[workspaceId]/home/types'
import type { useFileAttachments } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/copilot/components/user-input/hooks/use-file-attachments'
import { SKILL_CHIP_TRIGGER } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/copilot/components/user-input/utils'
import { getSkillsQueryOptions } from '@/hooks/queries/skills'
import { useWorkspacesQuery } from '@/hooks/queries/workspace'
import { useAnimatedPlaceholder } from '@/hooks/use-animated-placeholder'
Expand All @@ -49,6 +48,8 @@ interface ComposerProps {
restoredContexts?: ChatContext[]
onSubmit: (text: string, contexts?: ChatContext[]) => void
onSendQueuedHead?: () => void
onEditQueuedTail?: () => boolean
messages?: readonly ChatMessage[]
onStop: () => void
}

Expand All @@ -69,6 +70,8 @@ export function Composer({
onChange,
onSubmit,
onSendQueuedHead,
onEditQueuedTail,
messages,
restoredContexts,
onStop,
}: ComposerProps) {
Expand Down Expand Up @@ -100,6 +103,12 @@ export function Composer({
initialContexts: restoredContexts,
onPasteFiles: files.processFiles,
})
const history = usePromptHistory({
editor,
attachedFiles: files.attachedFiles,
restoreAttachedFiles: files.restoreAttachedFiles,
getMessages: () => messages ?? [],
})
const { textareaRef } = editor
const searchBlocked =
editor.getActiveContexts().length > 0 ||
Expand Down Expand Up @@ -143,19 +152,9 @@ export function Composer({
}, [editor.value, editor.contexts, onChange])
useEffect(() => {
if (!restoredContexts) return
// A queued skill may belong to a workspace whose picker has never opened here.
// Restore its existing chip from the saved context, without rediscovering it.
let restoredText = editorRef.current.getValue()
for (const context of restoredContexts) {
if (context.kind !== 'skill') continue
restoredText = restoredText.replace(
new RegExp(`(^|\\s)/${escapeRegExp(context.label)}(?=\\s|$)`, 'g'),
`$1${SKILL_CHIP_TRIGGER}${context.label}`
)
}
editorRef.current.setValue(restoredText, { chipify: false })
editorRef.current.setContexts(restoredContexts)
}, [restoredContexts])
history.reset()
editorRef.current.restorePrompt(editorRef.current.getPlainValue(), restoredContexts)
}, [restoredContexts, history.reset])
useChatInputFocus({ textareaRef })
const voice = useVoiceInput({
organizationId: organization.id,
Expand Down Expand Up @@ -184,6 +183,7 @@ export function Composer({
voice.resetTranscript()
const contexts = imagesOnly ? [] : editor.getActiveContexts()
onSubmit(editor.getPlainValue(), contexts.length ? contexts : undefined)
history.reset()
editor.clear()
}

Expand All @@ -207,12 +207,18 @@ export function Composer({
</Tooltip.Root>
)

const recallQueuedTail = () => {
if (attachedFilesRef.current.length > 0) return false
return onEditQueuedTail?.() ?? false
}
const promptEditor = (
<PromptEditor
editor={editor}
placeholder={placeholder}
aria-label='Ask Sim'
onSubmit={submit}
onNavigateHistory={history.navigate}
onArrowUpOnEmpty={recallQueuedTail}
className={cn(
'max-h-[200px] max-md:max-h-[min(200px,calc(var(--mobile-viewport-height,100dvh)*0.25))]',
isInitialView && 'min-h-[56px] max-md:min-h-0'
Expand Down Expand Up @@ -308,6 +314,12 @@ export function Composer({
onChange={(text) => editor.setValue(text)}
onSubmit={submit}
onPaste={editor.handlePaste}
onKeyDown={(event) =>
editor.handleKeyDown(event, {
onNavigateHistory: history.navigate,
onArrowUpOnEmpty: recallQueuedTail,
})
}
placeholder={placeholder}
aria-label='Ask Sim'
leadingControls={leadingControls}
Expand Down
57 changes: 32 additions & 25 deletions apps/sim/app/o/[organizationId]/home/organization-home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,32 @@ function OrganizationHomeContent({
files.clearAttachedFiles()
}

const editQueuedMessage = (id: string) => {
const queued = chat.editQueuedMessage(id)
if (queued) {
const queuedMode = queued.requestMode ?? requestMode
setSelectedMode(queuedMode)
setDraft(queued.content, queued.contexts)
setRestoredContexts(queued.contexts ?? [])
files.restoreAttachedFiles(
(queued.fileAttachments ?? []).map((file) => ({
id: file.id,
key: file.key,
name: file.filename,
type: file.media_type,
size: file.size,
path:
file.path ||
getMothershipAttachmentPreviewUrl(file) ||
getMothershipAttachmentUrl(file),
previewUrl: getMothershipAttachmentPreviewUrl(file),
uploading: false,
}))
)
}
return queued
}

const composer =
requestMode !== 'assistant' && !canBuild ? (
<div className='px-4 py-3 text-[var(--text-muted)] text-sm'>
Expand All @@ -317,6 +343,11 @@ function OrganizationHomeContent({
onModeChange={canSelectMode ? changeMode : undefined}
value={draft}
restoredContexts={restoredContexts}
messages={chat.messages}
onEditQueuedTail={() => {
const tail = chat.messageQueue.at(-1)
return tail ? Boolean(editQueuedMessage(tail.id)) : false
}}
files={files}
isInitialView={!hasChat}
isSending={chat.isSending || chat.isReconnecting}
Expand Down Expand Up @@ -357,31 +388,7 @@ function OrganizationHomeContent({
dispatchingHeadId={chat.dispatchingHeadId}
onRemoveQueuedMessage={chat.removeFromQueue}
onSendQueuedMessage={chat.sendNow}
onEditQueuedMessage={(id) => {
const queued = chat.editQueuedMessage(id)
if (queued) {
const queuedMode = queued.requestMode ?? requestMode
setSelectedMode(queuedMode)
setDraft(queued.content, queued.contexts)
setRestoredContexts(queued.contexts ?? [])
files.restoreAttachedFiles(
(queued.fileAttachments ?? []).map((file) => ({
id: file.id,
key: file.key,
name: file.filename,
type: file.media_type,
size: file.size,
path:
file.path ||
getMothershipAttachmentPreviewUrl(file) ||
getMothershipAttachmentUrl(file),
previewUrl: getMothershipAttachmentPreviewUrl(file),
uploading: false,
}))
)
}
return queued
}}
onEditQueuedMessage={editQueuedMessage}
onCancelQueueEdit={chat.cancelQueueEdit}
userId={session?.user?.id}
chatId={chat.resolvedChatId}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,9 @@ export function MothershipChat({
* starving the main thread on every streaming token.
*/
const messages = useDeferredValue(messagesProp)
const historyMessagesRef = useRef(messagesProp)
historyMessagesRef.current = messagesProp
const getHistoryMessages = useCallback(() => historyMessagesRef.current, [])
const [lastRowAnimating, setLastRowAnimating] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
const scrollElementRef = useRef<HTMLDivElement | null>(null)
Expand Down Expand Up @@ -779,16 +782,17 @@ export function MothershipChat({
const handleEditQueued = useCallback(
(id: string) => {
const msg = onEditQueuedMessage(id)
if (!msg) return
userInputRef.current?.loadQueuedMessage(msg)
if (!msg || !userInputRef.current) return false
userInputRef.current.loadQueuedMessage(msg)
return true
},
[onEditQueuedMessage, userInputRef]
)

const handleEditQueuedTail = useCallback(() => {
const tail = messageQueueRef.current[messageQueueRef.current.length - 1]
if (!tail) return
handleEditQueued(tail.id)
if (!tail) return false
return handleEditQueued(tail.id)
}, [handleEditQueued])

/**
Expand Down Expand Up @@ -988,6 +992,7 @@ export function MothershipChat({
onSendQueuedHead={handleSendQueuedHead}
onEditQueuedTail={handleEditQueuedTail}
draftScopeKey={draftScopeKey}
getMessages={getHistoryMessages}
/>
))}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export function PromptEditor({
'aria-label': ariaLabel,
onSubmit,
onArrowUpOnEmpty,
onNavigateHistory,
}: PromptEditorProps) {
const { textareaRef, value } = editor
const scrollerRef = useRef<HTMLDivElement>(null)
Expand Down Expand Up @@ -198,7 +199,9 @@ export function PromptEditor({
readOnly={readOnly}
onChange={readOnly ? undefined : editor.handleInputChange}
onKeyDown={
readOnly ? undefined : (e) => editor.handleKeyDown(e, { onSubmit, onArrowUpOnEmpty })
readOnly
? undefined
: (e) => editor.handleKeyDown(e, { onSubmit, onArrowUpOnEmpty, onNavigateHistory })
}
onFocus={readOnly ? undefined : () => setHasFocused(true)}
onPaste={readOnly ? undefined : editor.handlePaste}
Expand Down
Loading
Loading