bolt.diy/app/shared/hooks/useMessageParser.ts
KevIsDev 6913e9471f refactor: move workbench components and stores to its own directory structure
Restructure the workbench module by moving components and stores from shared/workbench to workbench directory. This includes terminal components, editor utilities, preview stores, and UI components. Update all import paths to reflect the new structure.

The changes include:
- Moving terminal components and theme files
- Relocating editor utilities like EnvMasking and indent
- Transferring stores for previews, editor, and terminal
- Updating all affected import statements across the codebase
- Moving UI components like PortDropdown and Inspector
2025-06-20 15:40:44 +01:00

74 lines
2.3 KiB
TypeScript

import type { Message } from 'ai';
import { useCallback, useState } from 'react';
import { StreamingMessageParser } from '~/shared/lib/runtime/message-parser';
import { workbenchStore } from '~/workbench/stores/workbench';
import { createScopedLogger } from '~/shared/utils/logger';
const logger = createScopedLogger('useMessageParser');
const messageParser = new StreamingMessageParser({
callbacks: {
onArtifactOpen: (data) => {
logger.trace('onArtifactOpen', data);
workbenchStore.showWorkbench.set(true);
workbenchStore.addArtifact(data);
},
onArtifactClose: (data) => {
logger.trace('onArtifactClose');
workbenchStore.updateArtifact(data, { closed: true });
},
onActionOpen: (data) => {
logger.trace('onActionOpen', data.action);
// we only add shell actions when when the close tag got parsed because only then we have the content
if (data.action.type === 'file') {
workbenchStore.addAction(data);
}
},
onActionClose: (data) => {
logger.trace('onActionClose', data.action);
if (data.action.type !== 'file') {
workbenchStore.addAction(data);
}
workbenchStore.runAction(data);
},
onActionStream: (data) => {
logger.trace('onActionStream', data.action);
workbenchStore.runAction(data, true);
},
},
});
const extractTextContent = (message: Message) =>
Array.isArray(message.content)
? (message.content.find((item) => item.type === 'text')?.text as string) || ''
: message.content;
export function useMessageParser() {
const [parsedMessages, setParsedMessages] = useState<{ [key: number]: string }>({});
const parseMessages = useCallback((messages: Message[], isLoading: boolean) => {
let reset = false;
if (import.meta.env.DEV && !isLoading) {
reset = true;
messageParser.reset();
}
for (const [index, message] of messages.entries()) {
if (message.role === 'assistant' || message.role === 'user') {
const newParsedContent = messageParser.parse(message.id, extractTextContent(message));
setParsedMessages((prevParsed) => ({
...prevParsed,
[index]: !reset ? (prevParsed[index] || '') + newParsedContent : newParsedContent,
}));
}
}
}, []);
return { parsedMessages, parseMessages };
}