feat: improve chat input, themed menus and agent proposal cancellation

This commit is contained in:
2026-10-19 13:12:04 +09:00
parent 105342fbf3
commit 7b32668e1d
18 changed files with 641 additions and 94 deletions
+24 -1
View File
@@ -1,6 +1,29 @@
import { BrowserWindow, clipboard, Menu } from 'electron'
import type { IpcMainInvokeEvent, MenuItemConstructorOptions } from 'electron'
import type { ChatTextMenuAction, ChatTextMenuOptions } from '../shared/chatTextMenu'
import type { ChatClipboardAction, ChatTextMenuAction, ChatTextMenuOptions } from '../shared/chatTextMenu'
function trustedChatFrame(event: IpcMainInvokeEvent): boolean {
if (event.sender.isDestroyed() || event.senderFrame !== event.sender.mainFrame) return false
const window = BrowserWindow.fromWebContents(event.sender)
return Boolean(window && !window.isDestroyed())
}
export function readChatClipboardState(event: IpcMainInvokeEvent): { hasText: boolean } {
return { hasText: trustedChatFrame(event) && clipboard.readText().length > 0 }
}
export function performChatClipboardAction(event: IpcMainInvokeEvent, input: ChatClipboardAction): boolean {
if (!trustedChatFrame(event) || !input) return false
if (input.action === 'copy' && typeof input.text === 'string' && input.text.length > 0 && input.text.length <= 5_000_000) {
clipboard.writeText(input.text)
return true
}
if (input.action === 'paste' && clipboard.readText().length > 0) {
event.sender.paste()
return true
}
return false
}
export function showChatTextMenu(event: IpcMainInvokeEvent, input: ChatTextMenuOptions): Promise<ChatTextMenuAction> | null {
if (!input || !['message', 'input'].includes(input.kind) || event.sender.isDestroyed() || event.senderFrame !== event.sender.mainFrame) return null
+3 -1
View File
@@ -1,7 +1,7 @@
import { app, BrowserWindow, dialog, Menu, globalShortcut, ipcMain, screen, shell } from 'electron'
import { appLog } from './appLogging'
import { checkDockerStatus } from './dockerStatus'
import { showChatTextMenu } from './chatTextMenu'
import { performChatClipboardAction, readChatClipboardState, showChatTextMenu } from './chatTextMenu'
import { cameraRuntimeArtifacts } from './cameraRuntime'
import { remoteModuleFilesScript } from './remoteModuleFiles'
import { applyAgentFiles, runAgentFileTool } from './agentFileTools'
@@ -7037,6 +7037,8 @@ app.whenReady().then(() => {
})
ipcMain.handle('app-diagnostics:read', () => readAppDiagnostics())
ipcMain.handle('chat-text:context-menu', showChatTextMenu)
ipcMain.handle('chat-text:clipboard-state', readChatClipboardState)
ipcMain.handle('chat-text:clipboard-action', performChatClipboardAction)
ipcMain.on('titlebar-close', (event) => BrowserWindow.fromWebContents(event.sender)?.close())
ipcMain.on('app-quit', () => app.quit())
ipcMain.handle('learning-video:open', (event, input: LearningVideoInput) => openLearningVideoWindow(BrowserWindow.fromWebContents(event.sender), input))
+3 -1
View File
@@ -118,7 +118,9 @@ console.info('[lms-preload] launcher auth resolved', {
contextBridge.exposeInMainWorld('electron', electronAPI)
contextBridge.exposeInMainWorld('chatTextMenu', {
show: (options: import('../shared/chatTextMenu').ChatTextMenuOptions) => ipcRenderer.invoke('chat-text:context-menu', options)
show: (options: import('../shared/chatTextMenu').ChatTextMenuOptions) => ipcRenderer.invoke('chat-text:context-menu', options),
readClipboardState: () => ipcRenderer.invoke('chat-text:clipboard-state'),
perform: (action: import('../shared/chatTextMenu').ChatClipboardAction) => ipcRenderer.invoke('chat-text:clipboard-action', action)
})
contextBridge.exposeInMainWorld('launcherAuth', launcherAuth)
contextBridge.exposeInMainWorld('lmsBootSplash', {
+7 -2
View File
@@ -634,6 +634,7 @@ function LocalPcWorkspaceMockup({
persistenceError: agentPersistenceError,
requestPlan: requestAgentPlan,
applyPlan: applyAgentPlan,
cancelPlan: cancelAgentPlan,
updateCommandExecution: updateAgentCommandExecution,
stop: stopAgent,
clear: clearAgentConversation
@@ -3728,7 +3729,7 @@ function LocalPcWorkspaceMockup({
const runStructuredAgentCommand = async (messageId: string, command: AgentCommand, approval?: { starts: string[]; parameters: Record<string, string[]>; runtimeSettings: string }): Promise<void> => {
if (agentActionControllerRef.current || agentPending || agentApplying) return
const message = agentMessages.find(item => item.id === messageId)
if (!message?.plan || !command.operation) return
if (!message?.plan || message.applyState === 'cancelled' || !command.operation) return
const controller = new AbortController()
agentActionControllerRef.current = controller
setAgentActionBusy(true)
@@ -3800,7 +3801,7 @@ function LocalPcWorkspaceMockup({
if (agentActionControllerRef.current || agentPending) return
const message = agentMessages.find((item) => item.id === messageId)
const currentExecution = message?.commandExecutions?.[command.id]
if (!message?.plan || (currentExecution && !['pending', 'failed'].includes(currentExecution.status))) return
if (!message?.plan || message.applyState === 'cancelled' || (currentExecution && !['pending', 'failed'].includes(currentExecution.status))) return
const requiresAppliedChanges = message.plan.changes.length > 0 || message.plan.createModule !== null
if (requiresAppliedChanges && message.applyState !== 'applied') {
onTitlebarNotice('코드 변경을 먼저 적용한 뒤 명령을 실행하세요.', 'error')
@@ -4743,6 +4744,10 @@ function LocalPcWorkspaceMockup({
onOpenAgentChange={(messageId, change) => void openAgentChangePreview(messageId, change)}
onRunAgentCommand={(messageId, command) => void runWorkspaceAgentCommand(messageId, command)}
onRejectAgentCommand={rejectWorkspaceAgentCommand}
onCancelAgentPlan={messageId => {
if (agentActionControllerRef.current || agentPending) return
if (cancelAgentPlan(messageId)) closeAgentDiffPreviewsForMessage(messageId)
}}
onApplyAgentPlan={(messageId, plan) => void applyAgentPlan(messageId, async () => {
await applyWorkspaceAgentPlan(plan)
closeAgentDiffPreviewsForMessage(messageId)
@@ -0,0 +1,106 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { ClipboardPaste, Copy, Trash2 } from 'lucide-react'
import { t, useLocaleRender } from '../i18n'
export type ChatTextContextMenuState = {
kind: 'message' | 'input'
x: number
y: number
text: string
input?: HTMLTextAreaElement
selectionStart?: number
selectionEnd?: number
}
export function ChatTextContextMenu({ dark, menu, canClear = false, onClose, onClear, onPasteText }: {
dark: boolean
menu: ChatTextContextMenuState | null
canClear?: boolean
onClose: () => void
onClear?: () => void
onPasteText?: (text: string, menu: ChatTextContextMenuState) => void
}): React.JSX.Element | null {
useLocaleRender()
const menuRef = useRef<HTMLDivElement>(null)
const [clipboardState, setClipboardState] = useState<{ menu: ChatTextContextMenuState; hasText: boolean } | null>(null)
const [position, setPosition] = useState({ x: 0, y: 0 })
const closeRef = useRef(onClose)
closeRef.current = onClose
useLayoutEffect(() => {
if (!menu || !menuRef.current) return
const bounds = menuRef.current.getBoundingClientRect()
setPosition({ x: Math.max(8, Math.min(menu.x, window.innerWidth - bounds.width - 8)), y: Math.max(8, Math.min(menu.y, window.innerHeight - bounds.height - 8)) })
}, [menu])
useEffect(() => {
if (!menu) return
let disposed = false
if (menu.kind === 'input') {
const read = Promise.resolve().then(() => window.chatTextMenu?.readClipboardState
? window.chatTextMenu.readClipboardState()
: navigator.clipboard.readText().then(text => ({ hasText: text.length > 0 })))
void read.then(state => { if (!disposed) setClipboardState({ menu, hasText: state.hasText }) })
.catch(() => { if (!disposed) setClipboardState({ menu, hasText: false }) })
}
const outside = (event: Event): void => {
if (!menuRef.current?.contains(event.target as Node)) closeRef.current()
}
const keydown = (event: KeyboardEvent): void => {
if (event.key === 'Escape') { event.preventDefault(); closeRef.current() }
}
const close = (): void => closeRef.current()
window.addEventListener('pointerdown', outside, true)
window.addEventListener('contextmenu', outside)
window.addEventListener('scroll', outside, true)
window.addEventListener('resize', close)
window.addEventListener('blur', close)
window.addEventListener('keydown', keydown)
return () => {
disposed = true
window.removeEventListener('pointerdown', outside, true)
window.removeEventListener('contextmenu', outside)
window.removeEventListener('scroll', outside, true)
window.removeEventListener('resize', close)
window.removeEventListener('blur', close)
window.removeEventListener('keydown', keydown)
}
}, [menu])
if (!menu) return null
const pasteEnabled = menu.kind === 'input' && !menu.input?.disabled && !menu.input?.readOnly && clipboardState?.menu === menu && clipboardState.hasText
const itemClass = ['flex h-8 w-full cursor-pointer items-center gap-2 px-3 text-left transition disabled:cursor-default disabled:opacity-35', dark ? 'enabled:hover:bg-[#37373d] enabled:hover:text-white' : 'enabled:hover:bg-[#eef1f7] enabled:hover:text-[#111520]'].join(' ')
const copy = async (): Promise<void> => {
if (!menu.text) return
onClose()
if (window.chatTextMenu?.perform) await window.chatTextMenu.perform({ action: 'copy', text: menu.text })
else await navigator.clipboard.writeText(menu.text)
}
const paste = async (): Promise<void> => {
if (!pasteEnabled || !menu.input?.isConnected || menu.input.disabled || menu.input.readOnly) return
const input = menu.input
input.focus({ preventScroll: true })
input.setSelectionRange(menu.selectionStart ?? input.selectionStart, menu.selectionEnd ?? input.selectionEnd)
onClose()
if (window.chatTextMenu?.perform) await window.chatTextMenu.perform({ action: 'paste' })
else {
const text = await navigator.clipboard.readText()
if (text) onPasteText?.(text, menu)
}
}
return createPortal(
<div ref={menuRef} role="menu" aria-label={t('질의응답')} className={[
'fixed z-[160] w-[160px] overflow-hidden rounded-md border py-1 text-[12px] font-medium shadow-[0_14px_32px_rgba(0,0,0,0.32)]',
dark ? 'border-white/10 bg-[#252526] text-white/80' : 'border-[#d8dee9] bg-white text-[#374151]'
].join(' ')} style={{ left: position.x, top: position.y }} onMouseDown={event => event.preventDefault()} onContextMenu={event => { event.preventDefault(); event.stopPropagation() }}>
<button type="button" role="menuitem" disabled={!menu.text} onClick={() => void copy().catch(error => console.error('[chat] copy failed', error))} className={itemClass}><Copy size={13} />{t('복사')}</button>
{menu.kind === 'input' ? (
<button type="button" role="menuitem" disabled={!pasteEnabled} onClick={() => void paste().catch(error => console.error('[chat] paste failed', error))} className={itemClass}><ClipboardPaste size={13} />{t('붙여넣기')}</button>
) : onClear ? <>
<div role="separator" className={['my-1 border-t', dark ? 'border-white/10' : 'border-[#d8dee9]'].join(' ')} />
<button type="button" role="menuitem" disabled={!canClear} onClick={() => { onClose(); onClear() }} className={itemClass}><Trash2 size={13} />{t('대화내역 삭제')}</button>
</> : null}
</div>, document.body
)
}
+54 -9
View File
@@ -1,10 +1,11 @@
import { t, useLocaleRender } from '../i18n'
import { ChevronDown, Paperclip, Send, Square, Trash2, X } from 'lucide-react'
import type React from 'react'
import { memo, useEffect, useRef, useState } from 'react'
import { memo, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { CHAT_ATTACHMENT_ACCEPT, readChatAttachments, type ChatAttachment } from './chatAttachments'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { ChatTextContextMenu, type ChatTextContextMenuState } from './ChatTextContextMenu'
export function ChatAvatar({
accessToken,
@@ -264,6 +265,22 @@ export function ExpandablePlainMessage({
)
}
function resizeQaInput(input: HTMLTextAreaElement): void {
const styles = window.getComputedStyle(input)
const lineHeight = Number.parseFloat(styles.lineHeight)
const padding = Number.parseFloat(styles.paddingTop) + Number.parseFloat(styles.paddingBottom)
const border = Number.parseFloat(styles.borderTopWidth) + Number.parseFloat(styles.borderBottomWidth)
const minHeight = Number.parseFloat(styles.minHeight)
const maxHeight = Math.ceil(lineHeight * 8 + padding + border)
input.style.height = 'auto'
input.style.overflowY = 'hidden'
const contentHeight = input.scrollHeight + border
input.style.maxHeight = `${maxHeight}px`
input.style.height = `${Math.min(Math.max(contentHeight, minHeight), maxHeight)}px`
input.style.overflowY = contentHeight > maxHeight ? 'auto' : 'hidden'
}
export const QaInputBox = memo(function QaInputBox({
dark,
busy,
@@ -289,10 +306,29 @@ export const QaInputBox = memo(function QaInputBox({
const [attachments, setAttachments] = useState<ChatAttachment[]>([])
const [attachmentError, setAttachmentError] = useState<string | null>(null)
const [readingAttachments, setReadingAttachments] = useState(false)
const [contextMenu, setContextMenu] = useState<ChatTextContextMenuState | null>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const attachmentReadRef = useRef(0)
const canSubmit = busy || (Boolean(draft.trim()) && !disabled && !readingAttachments)
useLayoutEffect(() => {
if (textareaRef.current) resizeQaInput(textareaRef.current)
}, [draft])
useEffect(() => {
const input = textareaRef.current
if (!input) return
let width = input.getBoundingClientRect().width
const observer = new ResizeObserver(([entry]) => {
if (!entry || entry.contentRect.width === width) return
width = entry.contentRect.width
resizeQaInput(input)
})
observer.observe(input)
return () => observer.disconnect()
}, [])
useEffect(() => {
attachmentReadRef.current += 1
if (!attachmentsEnabled) {
@@ -317,25 +353,28 @@ export const QaInputBox = memo(function QaInputBox({
}
return (
<div className={['m-3 rounded-lg border p-2', dark ? 'border-white/10 bg-[#202020]' : 'border-[#d8dee9] bg-white'].join(' ')}>
<div className={['m-3 shrink-0 rounded-lg border p-2', dark ? 'border-white/10 bg-[#202020]' : 'border-[#d8dee9] bg-white'].join(' ')}>
<div className={['flex min-h-[56px] items-stretch overflow-hidden rounded-md pl-3 text-[12px]', dark ? 'bg-[#252525]' : 'bg-[#f8f9fc]'].join(' ')}>
<textarea
ref={textareaRef}
rows={2}
spellCheck={false}
autoCorrect="off"
value={draft}
onChange={(event) => setDraft(event.target.value)}
onContextMenu={(event) => {
if (!window.chatTextMenu) return
event.preventDefault()
event.stopPropagation()
const input = event.currentTarget
void window.chatTextMenu.show({
setContextMenu({
kind: 'input',
canCopy: input.selectionEnd > input.selectionStart,
canPaste: !input.disabled && !input.readOnly,
labels: { copy: t('복사'), paste: t('붙여넣기') }
}).catch((error) => console.error('[chat] input menu failed', error))
x: event.clientX,
y: event.clientY,
text: input.value.slice(input.selectionStart, input.selectionEnd),
input,
selectionStart: input.selectionStart,
selectionEnd: input.selectionEnd
})
}}
onKeyDown={(event) => {
if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
@@ -345,7 +384,7 @@ export const QaInputBox = memo(function QaInputBox({
}}
placeholder={t("질문하세요...")}
className={[
'min-h-[56px] min-w-0 flex-1 resize-none bg-transparent py-2.5 pr-3 text-[12px] font-medium leading-relaxed outline-none placeholder:font-medium',
'box-border min-h-[56px] min-w-0 flex-1 self-start resize-none overflow-y-hidden bg-transparent py-2.5 pr-3 text-[12px] font-medium leading-relaxed outline-none placeholder:font-medium',
dark ? 'text-white/80 placeholder:text-white/40' : 'text-[#111520] placeholder:text-[#727b8c]'
].join(' ')}
/>
@@ -364,6 +403,12 @@ export const QaInputBox = memo(function QaInputBox({
{busy ? <Square size={13} fill="currentColor" /> : <Send size={14} />}
</button>
</div>
<ChatTextContextMenu dark={dark} menu={contextMenu} onClose={() => setContextMenu(null)} onPasteText={(text, menu) => {
const start = menu.selectionStart ?? draft.length
const end = menu.selectionEnd ?? start
setDraft(current => current.slice(0, start) + text + current.slice(end))
window.requestAnimationFrame(() => textareaRef.current?.setSelectionRange(start + text.length, start + text.length))
}} />
{attachmentsEnabled && attachments.length > 0 && (
<div className="flex flex-wrap gap-1.5 pt-2">
{attachments.map((file, index) => (
+2
View File
@@ -69,6 +69,8 @@ interface Window {
}
chatTextMenu?: {
show: (options: import('../../shared/chatTextMenu').ChatTextMenuOptions) => Promise<import('../../shared/chatTextMenu').ChatTextMenuAction>
readClipboardState: () => Promise<{ hasText: boolean }>
perform: (action: import('../../shared/chatTextMenu').ChatClipboardAction) => Promise<boolean>
}
appDiagnostics?: {
read: () => Promise<{ path: string; content: string }>
@@ -5,6 +5,7 @@ import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { ConfirmStatusModal } from '../../components/AppStatusModals'
import { ProgressiveChatResponse } from '../../components/ProgressiveChatResponse'
import { ChatTextContextMenu, type ChatTextContextMenuState } from '../../components/ChatTextContextMenu'
import { ChatAvatar, ChatEmptyState, ChatResponseSkeleton, ExpandablePlainMessage, MarkdownMessage, QaInputBox } from '../../components/ChatWidgets'
import type { AgentCommand, AgentConversationMessage, AgentFileChange, AgentPlan } from './useAiAgent'
import type { ChatAttachment } from '../../components/chatAttachments'
@@ -56,6 +57,7 @@ type WorkspaceQaPanelProps = {
onSubmit: (content: string, attachments?: ChatAttachment[]) => void
onClearConversation: () => void
onApplyAgentPlan: (messageId: string, plan: AgentPlan) => void
onCancelAgentPlan: (messageId: string) => void
onOpenAgentChange: (messageId: string, change: AgentFileChange) => void
onRunAgentCommand: (messageId: string, command: AgentCommand) => void
onRejectAgentCommand: (messageId: string, command: AgentCommand) => void
@@ -127,12 +129,13 @@ export default function WorkspaceQaPanel({
onSubmit,
onClearConversation,
onApplyAgentPlan,
onCancelAgentPlan,
onOpenAgentChange,
onRunAgentCommand,
onRejectAgentCommand
}: WorkspaceQaPanelProps): React.JSX.Element {
useLocaleRender()
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; text: string } | null>(null)
const [contextMenu, setContextMenu] = useState<ChatTextContextMenuState | null>(null)
const [clearConfirmationOpen, setClearConfirmationOpen] = useState(false)
const activeMessages = qaMode === 'ai' ? visibleAiMessages : qaMode === 'agent' ? agentMessages : visibleTeacherMessages
const lastMessage = activeMessages[activeMessages.length - 1]
@@ -140,6 +143,7 @@ export default function WorkspaceQaPanel({
useEffect(() => {
setClearConfirmationOpen(false)
setContextMenu(null)
}, [qaMode, workspaceActive, minimized])
const requestClearConversation = (): void => {
@@ -153,17 +157,6 @@ export default function WorkspaceQaPanel({
}
}, [agentEnabled, agentStatusLoading, onModeChange, qaMode, teacherQaDisabled])
useEffect(() => {
if (!contextMenu) return
const closeContextMenu = (): void => setContextMenu(null)
window.addEventListener('click', closeContextMenu)
window.addEventListener('contextmenu', closeContextMenu)
return () => {
window.removeEventListener('click', closeContextMenu)
window.removeEventListener('contextmenu', closeContextMenu)
}
}, [contextMenu])
useEffect(() => {
if (minimized || qaMessagesLoading) return
const target = workspaceChatScrollRef.current
@@ -219,19 +212,7 @@ export default function WorkspaceQaPanel({
const text = selection?.anchorNode && selection.focusNode && event.currentTarget.contains(selection.anchorNode) && event.currentTarget.contains(selection.focusNode)
? selection.toString()
: ''
if (window.chatTextMenu) {
setContextMenu(null)
void window.chatTextMenu.show({
kind: 'message',
canCopy: text.length > 0,
canClear: !clearDisabled,
labels: { copy: t('복사'), clear: t('대화내역 삭제') }
}).then((action) => {
if (action === 'clear') requestClearConversation()
}).catch((error) => console.error('[chat] message menu failed', error))
return
}
setContextMenu({ x: event.clientX, y: event.clientY, text })
setContextMenu({ kind: 'message', x: event.clientX, y: event.clientY, text })
}
return (
@@ -321,6 +302,7 @@ export default function WorkspaceQaPanel({
busy={agentPending || agentActionBusy}
messages={agentMessages}
onApply={onApplyAgentPlan}
onCancel={onCancelAgentPlan}
onOpenChange={onOpenAgentChange}
onRunCommand={onRunAgentCommand}
onRejectCommand={onRejectAgentCommand}
@@ -335,31 +317,7 @@ export default function WorkspaceQaPanel({
/>
)}
</div>
{contextMenu && (
<div
className={['fixed z-[140] min-w-[150px] overflow-hidden rounded-md border py-1 shadow-[0_18px_42px_rgba(0,0,0,0.28)]', dark ? 'border-white/10 bg-[#2b2b2b]' : 'border-[#d5dbe7] bg-white'].join(' ')}
style={{ left: contextMenu.x, top: contextMenu.y }}
onMouseDown={(event) => event.preventDefault()}
onClick={(event) => event.stopPropagation()}
>
<button
type="button"
disabled={!contextMenu.text}
className={['flex w-full items-center gap-2 px-3 py-2 text-left text-[12px] font-semibold transition disabled:cursor-default disabled:opacity-35', dark ? 'text-white/78 enabled:hover:bg-white/10' : 'text-[#334155] enabled:hover:bg-[#f1f5f9]'].join(' ')}
onClick={() => {
const text = contextMenu.text
setContextMenu(null)
if (text) void navigator.clipboard.writeText(text).catch((error) => console.error('[chat] copy failed', error))
}}
><Copy size={13} />{t('복사')}</button>
<button
type="button"
disabled={clearDisabled}
className={['block w-full px-3 py-2 text-left text-[12px] font-semibold transition disabled:cursor-default disabled:opacity-35', dark ? 'text-white/78 hover:bg-white/10' : 'text-[#334155] hover:bg-[#f1f5f9]'].join(' ')}
onClick={requestClearConversation}
>{t("대화내역 삭제")}</button>
</div>
)}
<ChatTextContextMenu dark={dark} menu={contextMenu} canClear={!clearDisabled} onClose={() => setContextMenu(null)} onClear={requestClearConversation} />
<QaInputBox
dark={dark}
busy={inputBusy}
@@ -400,6 +358,7 @@ function AgentMessages({
busy,
messages,
onApply,
onCancel,
onOpenChange,
onRunCommand,
onRejectCommand
@@ -412,6 +371,7 @@ function AgentMessages({
busy?: boolean
messages: AgentConversationMessage[]
onApply: (messageId: string, plan: AgentPlan) => void
onCancel: (messageId: string) => void
onOpenChange: (messageId: string, change: AgentFileChange) => void
onRunCommand: (messageId: string, command: AgentCommand) => void
onRejectCommand: (messageId: string, command: AgentCommand) => void
@@ -504,7 +464,7 @@ function AgentMessages({
const execution = message.commandExecutions?.[command.id] ?? { status: 'pending' as const }
const moduleStartAction = command.command.trim() === 'lms module start' || command.operation?.name === 'modules.start'
const finished = execution.status === 'completed' || execution.status === 'failed'
const policyRejected = execution.status === 'rejected'
const policyRejected = message.applyState === 'cancelled' || execution.status === 'rejected'
|| (execution.status === 'failed' && /허용되지|실행할 수 없습니다/.test(execution.error ?? ''))
const waitingForChanges = (message.plan!.changes.length > 0 || message.plan!.createModule !== null) && message.applyState !== 'applied'
return (
@@ -526,7 +486,9 @@ function AgentMessages({
) : null}
{execution.error ? <p className="mt-2 text-[11px] font-bold text-[#ef4444]">{execution.error}</p> : null}
<div className="mt-2 flex items-center justify-end gap-2">
{execution.status === 'pending' ? <>
{message.applyState === 'cancelled' ? (
<span className={['text-[11px] font-bold', dark ? 'text-white/40' : 'text-[#64748b]'].join(' ')}>{execution.status === 'completed' ? t("실행 완료") : t("취소됨")}</span>
) : execution.status === 'pending' ? <>
<button type="button" onClick={() => onRejectCommand(message.id, command)} className={['inline-flex h-7 items-center gap-1 rounded px-2 text-[11px] font-bold transition', dark ? 'text-white/55 hover:bg-white/8 hover:text-white' : 'text-[#64748b] hover:bg-[#e2e8f0]'].join(' ')}><X size={12} />{t("거부")}</button>
<button type="button" disabled={waitingForChanges} title={waitingForChanges ? t("코드 변경을 먼저 적용하세요.") : undefined} onClick={() => onRunCommand(message.id, command)} className="inline-flex h-7 items-center gap-1 rounded bg-[#7c3aed] px-2.5 text-[11px] font-black text-white transition hover:bg-[#6d28d9] disabled:cursor-not-allowed disabled:bg-[#64748b]"><Play size={12} />{waitingForChanges ? t("변경 적용 후 실행") : t("승인")}</button>
</> : execution.status === 'running' ? (
@@ -581,15 +543,27 @@ function AgentMessages({
) : null}
{message.applyError ? <p className="text-[11px] font-bold text-[#ef4444]">{message.applyError}</p> : null}
{message.plan.changes.length > 0 || message.plan.createModule ? (
<div className="flex min-w-0 items-center gap-2">
{message.applyState !== 'applied' && message.applyState !== 'cancelled' && (
<button
type="button"
disabled={busy || message.applyState === 'applying' || Object.values(message.commandExecutions ?? {}).some(execution => execution.status === 'running')}
onClick={() => onCancel(message.id)}
className={['inline-flex h-8 shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-md border px-3 text-[11px] font-bold transition disabled:cursor-not-allowed disabled:opacity-40', dark ? 'border-white/15 text-white/65 hover:bg-white/8' : 'border-[#d8dee9] text-[#64748b] hover:bg-[#e2e8f0]'].join(' ')}
>
<X size={13} className="shrink-0" /><span className="relative top-px leading-none">{t("취소")}</span>
</button>
)}
<button
type="button"
disabled={busy || message.applyState === 'applying' || message.applyState === 'applied' || Object.values(message.commandExecutions ?? {}).some((execution) => execution.status === 'running')}
disabled={busy || message.applyState === 'applying' || message.applyState === 'applied' || message.applyState === 'cancelled' || Object.values(message.commandExecutions ?? {}).some((execution) => execution.status === 'running')}
onClick={() => onApply(message.id, message.plan!)}
className="inline-flex h-8 items-center justify-center gap-1.5 rounded-md bg-[#7c3aed] px-3 text-[11px] font-black text-white transition hover:bg-[#6d28d9] disabled:cursor-not-allowed disabled:bg-[#64748b]"
className="inline-flex h-8 min-w-0 flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md bg-[#7c3aed] px-3 text-[11px] font-black text-white transition hover:bg-[#6d28d9] disabled:cursor-not-allowed disabled:bg-[#64748b]"
>
{message.applyState === 'applying' ? <Loader2 size={13} className="animate-spin" /> : message.applyState === 'applied' ? <Check size={13} /> : <FileCode2 size={13} />}
{message.applyState === 'applying' ? t("적용 중") : message.applyState === 'applied' ? t("적용 완료") : message.applyState === 'error' ? t("다시 적용") : t("변경 적용")}
{message.applyState === 'applying' ? <Loader2 size={13} className="animate-spin" /> : message.applyState === 'cancelled' ? <X size={13} /> : message.applyState === 'applied' ? <Check size={13} /> : <FileCode2 size={13} />}
{message.applyState === 'applying' ? t("적용 중") : message.applyState === 'applied' ? t("적용 완료") : message.applyState === 'cancelled' ? t("취소됨") : message.applyState === 'error' ? t("다시 적용") : t("변경 적용")}
</button>
</div>
) : null}
</>
)}
@@ -77,7 +77,7 @@ export type AgentConversationMessage = {
model?: string
revealStartedAt?: number
plan?: AgentPlan
applyState?: 'ready' | 'applying' | 'applied' | 'error'
applyState?: 'ready' | 'applying' | 'applied' | 'error' | 'cancelled'
applyError?: string
commandExecutions?: Record<string, AgentCommandExecution>
usage?: {
@@ -336,8 +336,9 @@ export function useAiAgent({ accessToken, studentEmail, courseId, weekNumber, ap
}
const applyPlan = async (messageId: string, apply: (plan: AgentPlan) => Promise<void>): Promise<void> => {
const message = messages.find((item) => item.id === messageId)
if (applyingRef.current || !message?.plan || message.applyState === 'applying' || message.applyState === 'applied') return
if (messageStateRef.current.session !== session) return
const message = messageStateRef.current.messages.find((item) => item.id === messageId)
if (applyingRef.current || !message?.plan || message.applyState === 'applying' || message.applyState === 'applied' || message.applyState === 'cancelled') return
if (Object.values(message.commandExecutions ?? {}).some((execution) => execution.status === 'running')) return
applyingRef.current = true
updateMessages((current) => current.map((item) => item.id === messageId ? { ...item, applyState: 'applying', applyError: undefined } : item))
@@ -362,6 +363,24 @@ export function useAiAgent({ accessToken, studentEmail, courseId, weekNumber, ap
}
}
const cancelPlan = (messageId: string): boolean => {
if (messageStateRef.current.session !== session || applyingRef.current || abortControllerRef.current) return false
const message = messageStateRef.current.messages.find((item) => item.id === messageId)
if (!message?.plan || (!message.plan.changes.length && !message.plan.createModule)
|| message.applyState === 'applying' || message.applyState === 'applied' || message.applyState === 'cancelled'
|| Object.values(message.commandExecutions ?? {}).some(execution => execution.status === 'running')) return false
updateMessages(current => current.map(item => item.id === messageId ? {
...item,
applyState: 'cancelled',
applyError: undefined,
commandExecutions: Object.fromEntries(item.plan!.commands.map(command => {
const execution = item.commandExecutions?.[command.id]
return [command.id, execution?.status === 'completed' ? execution : { ...execution, status: 'rejected' as const, error: undefined }]
}))
} : item))
return true
}
const stop = (): void => {
abortControllerRef.current?.abort()
abortControllerRef.current = null
@@ -410,6 +429,7 @@ export function useAiAgent({ accessToken, studentEmail, courseId, weekNumber, ap
persistenceError: persistenceError ?? historyError,
requestPlan,
applyPlan,
cancelPlan,
updateCommandExecution,
stop,
clear
+1
View File
@@ -601,6 +601,7 @@
"추가 중": "Adding",
"추가할 ROS2 모듈의 기본 정보를 입력합니다.": "Enter details for the new ROS2 module.",
"취소": "Cancel",
"취소됨": "Cancelled",
"카테고리": "Category",
"칸": " spaces",
"커리큘럼": "Curriculum",
+2
View File
@@ -7,3 +7,5 @@ export type ChatTextMenuOptions = {
}
export type ChatTextMenuAction = 'clear' | null
export type ChatClipboardAction = { action: 'copy'; text: string } | { action: 'paste' }