Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore(ai): replace hooks with context (#1437)

Eric Hayese1631fc7fa8a
diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsx
index cc67b12073..d9a520bca2 100644
--- a/js/app/packages/app/component/SoupChatInput.tsx
+++ b/js/app/packages/app/component/SoupChatInput.tsx
@@ -1,4 +1,7 @@
-import { useChatInput } from '@core/component/AI/component/input/useChatInput';
+import { ChatContextProvider } from '@core/component/AI/context';
+import { ChatInput } from '@core/component/AI/component/input/useChatInput';
+import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';
+import { useChatContext } from '@core/component/AI/context';
import { setPendingSendData } from '@core/component/AI/signal/pendingSend';
import type { CreateAndSend, Send } from '@core/component/AI/types';
import { isErr } from '@core/util/maybeResult';
@@ -8,12 +11,16 @@ import { onMount, Show } from 'solid-js';
import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
import { useSoup } from '@app/component/next-soup/soup-context';
-export function SoupChatInput() {
+function SoupChatInputInner() {
let containerRef!: HTMLDivElement;
const splitPanelContext = useSplitPanelOrThrow();
const soup = useSoup();
+ const ctx = useChatContext();
+
+ const chatMarkdownArea = useChatMarkdownArea({
+ addAttachment: (a) => ctx.attachments.addAttachment(a),
+ });
- const { ChatInput } = useChatInput({ autoAttach: false });
const [attachHotkeys] = useHotkeyDOMScope('soup.chatInput');
onMount(() => {
@@ -58,6 +65,7 @@ export function SoupChatInput() {
<div class="w-full max-w-3xl">
<div class="pointer-events-auto">
<ChatInput
+ markdown={chatMarkdownArea}
onSend={handleSend}
isPersistent={true}
autoFocusOnMount={false}
@@ -68,3 +76,11 @@ export function SoupChatInput() {
</Show>
);
}
+
+export function SoupChatInput() {
+ return (
+ <ChatContextProvider autoAttach={false}>
+ <SoupChatInputInner />
+ </ChatContextProvider>
+ );
+}
diff --git a/js/app/packages/app/component/rightbar/Rightbar.tsx b/js/app/packages/app/component/rightbar/Rightbar.tsx
index c12c54e0fd..be95fb1339 100644
--- a/js/app/packages/app/component/rightbar/Rightbar.tsx
+++ b/js/app/packages/app/component/rightbar/Rightbar.tsx
@@ -3,8 +3,13 @@ import { useIsAuthenticated } from '@core/auth';
import { AiChatEmptyState } from '@core/component/AI/component/AIChatEmptyState';
import { DragDropWrapper } from '@core/component/AI/component/DragDrop';
import { useBuildChatSendRequest } from '@core/component/AI/component/input/buildRequest';
-import { useChatInput } from '@core/component/AI/component/input/useChatInput';
+import { ChatInput } from '@core/component/AI/component/input/useChatInput';
+import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';
import { ChatMessages } from '@core/component/AI/component/message/ChatMessages';
+import {
+ ChatContextProvider,
+ useChatContext,
+} from '@core/component/AI/context';
import { useEntityDropAttachment } from '@core/component/AI/hook/useEntityDropAttachment';
import { getPendingSend } from '@core/component/AI/signal/pendingSend';
import { registerToolHandler } from '@core/component/AI/signal/tool';
@@ -272,81 +277,70 @@ function TopBar(props: {
}
export function Rightbar(props: {
- chatId: string | undefined;
- chatName: string | undefined;
- stream: Accessor<MessageStream | undefined>;
onSend: (args: CreateAndSend | Send) => void;
stopGenerating: () => void;
+ chatName: string | undefined;
+ isBig?: boolean;
+ userPermissions: Accessor<Permissions>;
onUnmount?: () => void;
- messages: Accessor<ChatMessageWithAttachments[]>;
initialState?: {
model: Model | undefined;
attachments: Attachment[];
text: string | undefined;
};
- userPermissions: Accessor<Permissions>;
setState: {
setChatId: (chatId: string | undefined) => void;
setModel: Setter<Model | undefined>;
setAttachments: Setter<Attachment[]>;
setText: Setter<string | undefined>;
- setMessages: Setter<ChatMessageWithAttachments[]>;
- setStream: Setter<MessageStream | undefined>;
};
- isBig?: boolean;
- setIsBig?: (val: boolean) => void;
}) {
+ const ctx = useChatContext();
const [messagesContainerRef, setMessagesContainerRef] =
createSignal<HTMLElement>();
createEffect(() => {
- const stream_ = props.stream();
+ const stream_ = ctx.stream?.();
if (stream_ && stream_.data().length > 0) {
invalidateUserQuota();
}
});
createEffect(() => {
- const stream_ = props.stream();
+ const stream_ = ctx.stream?.();
if (!stream_ || stream_.isDone()) {
- setIsGenerating(false);
+ ctx.setIsGenerating(false);
if (stream_?.isDone()) {
invalidateUserQuota();
}
return;
} else {
- setIsGenerating(true);
+ ctx.setIsGenerating(true);
}
});
- registerToolHandler(props.stream);
+ registerToolHandler(ctx.stream!);
const stopGenerating = props.stopGenerating;
// NOTE: due to mount race condition in the markdown area, we need to set the initial value here
- const {
- ChatInput,
- setChatId,
- attachments,
- chatMarkdownArea,
- model,
- setModel,
- setIsGenerating,
- uploadQueue,
- } = useChatInput({ initialValue: props.initialState?.text });
+ const chatMarkdownArea = useChatMarkdownArea({
+ initialValue: props.initialState?.text,
+ addAttachment: (a) => ctx.attachments.addAttachment(a),
+ });
// Entity drag-and-drop support
const { droppable, isDraggingOver } = useEntityDropAttachment(
'rightbar-chat-input',
- attachments
+ ctx.attachments
);
false && droppable;
createEffect(() => {
- setChatId(props.chatId);
+ ctx.setChatId(ctx.chatId());
if (!props.initialState) return;
- setModel(props.initialState.model);
- attachments.setAttached(props.initialState.attachments);
+ ctx.setModel(props.initialState.model);
+ ctx.attachments.setAttached(props.initialState.attachments);
});
onCleanup(() => {
@@ -355,8 +349,8 @@ export function Rightbar(props: {
createEffect(() => {
const input = chatMarkdownArea.markdownText();
- const attached = attachments.attached();
- const model_ = model();
+ const attached = ctx.attachments.attached();
+ const model_ = ctx.model();
props.setState.setText(input);
props.setState.setAttachments(attached);
props.setState.setModel(model_);
@@ -414,24 +408,23 @@ export function Rightbar(props: {
return (
<DragDropWrapper
class="relative flex flex-col size-full select-none"
- uploadQueue={uploadQueue}
isEntityDraggingOver={isDraggingOver}
>
<div class="overflow-hidden size-full flex flex-col items-center relative">
<div class="absolute inset-0 pointer-events-none" use:droppable />
<TopBar
- chatId={props.chatId}
+ chatId={ctx.chatId()}
setChatId={props.setState.setChatId}
chatName={props.chatName}
userPermissions={props.userPermissions}
/>
<div class="flex flex-col flex-1 min-h-0 p-2 w-full items-center">
- <Show when={props.messages().length === 0}>
+ <Show when={ctx.messages!().length === 0}>
<div class="h-full flex flex-col items-center justify-center">
<AiChatEmptyState />
</div>
</Show>
- <Show when={props.messages().length > 0 || !props.isBig}>
+ <Show when={ctx.messages!().length > 0 || !props.isBig}>
<div class="relative flex-1 min-h-0 w-full">
<div
data-chat-scroll
@@ -439,12 +432,7 @@ export function Rightbar(props: {
ref={setMessagesContainerRef}
>
<div class="w-full macro-message-width">
- <ChatMessages
- chatId={props.chatId}
- messages={[props.messages, props.setState.setMessages]}
- messageActions={undefined}
- stream={[props.stream, props.setState.setStream]}
- />
+ <ChatMessages messageActions={undefined} />
</div>
</div>
<CustomScrollbar scrollContainer={messagesContainerRef} />
@@ -454,6 +442,7 @@ export function Rightbar(props: {
<div class="w-full">
<div class="flex-shrink-0 pt-2 macro-message-width mx-auto">
<ChatInput
+ markdown={chatMarkdownArea}
isPersistent
showActiveTabs
onSend={props.onSend}
@@ -722,26 +711,29 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {
tr={!bigChatOpen() && !settingsOpen()}
>
<Suspense>
- <Rightbar
- chatId={chatId()}
- chatName={chatName()}
- messages={messages}
- onUnmount={getChatInputState}
- initialState={initialChatState()}
- onSend={onSend}
- stream={stream}
- stopGenerating={stopGenerating}
- userPermissions={userPermissions}
- setState={{
- setChatId,
- setModel,
- setAttachments,
- setText,
- setMessages,
- setStream,
+ <ChatContextProvider
+ external={{
+ chatId: [chatId, setChatId],
+ messages: [messages, setMessages],
+ stream: [stream, setStream],
}}
- isBig={bigChatOpen()}
- />
+ >
+ <Rightbar
+ chatName={chatName()}
+ onUnmount={getChatInputState}
+ initialState={initialChatState()}
+ onSend={onSend}
+ stopGenerating={stopGenerating}
+ userPermissions={userPermissions}
+ setState={{
+ setChatId,
+ setModel,
+ setAttachments,
+ setText,
+ }}
+ isBig={bigChatOpen()}
+ />
+ </ChatContextProvider>
</Suspense>
</SplitlikeContainer>
</div>
diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsx
index fa8aa8d583..88d0f5bc59 100644
--- a/js/app/packages/block-chat/component/Chat.tsx
+++ b/js/app/packages/block-chat/component/Chat.tsx
@@ -4,8 +4,13 @@ import { TopBar } from '@block-chat/component/TopBar';
import type { ChatData } from '@block-chat/definition';
import { DragDropWrapper } from '@core/component/AI/component/DragDrop';
import { useBuildChatSendRequest } from '@core/component/AI/component/input/buildRequest';
-import { useChatInput } from '@core/component/AI/component/input/useChatInput';
-import { useChatMessages } from '@core/component/AI/component/message';
+import { ChatInput } from '@core/component/AI/component/input/useChatInput';
+import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';
+import { ChatMessages } from '@core/component/AI/component/message/ChatMessages';
+import {
+ ChatContextProvider,
+ useChatContext,
+} from '@core/component/AI/context';
import { useEntityDropAttachment } from '@core/component/AI/hook/useEntityDropAttachment';
import { getPendingSend } from '@core/component/AI/signal/pendingSend';
import { registerToolHandler } from '@core/component/AI/signal/tool';
@@ -39,6 +44,25 @@ import { createEffect, createSignal, Show } from 'solid-js';
import { pendingLocationParamsSignal } from '../signal/pendingLocationParams';
export function Chat(props: { data: ChatData }) {
+ const loadedState = getChatInputStoredState(props.data.chat.id);
+
+ return (
+ <ChatContextProvider
+ chatId={props.data.chat.id}
+ messages={props.data.chat.messages}
+ initialAttachments={loadedState.attachments}
+ model={loadedState.model}
+ >
+ <ChatInner data={props.data} loadedInputText={loadedState.input} />
+ </ChatContextProvider>
+ );
+}
+
+function ChatInner(props: {
+ data: ChatData;
+ loadedInputText: string | undefined;
+}) {
+ const ctx = useChatContext();
const canEdit = useCanEdit();
const disabled = () => !canEdit();
const scopeId = blockHotkeyScopeSignal.get;
@@ -47,6 +71,12 @@ export function Chat(props: { data: ChatData }) {
const [chatEditor, setChatEditor] = createSignal<LexicalEditor>();
const [scrollRef, setScrollRef] = createSignal<HTMLElement>();
+ const chatMarkdownArea = useChatMarkdownArea({
+ initialValue: props.loadedInputText,
+ addAttachment: (a) => ctx.attachments.addAttachment(a),
+ });
+
+ // Local stream signal for cancelStream and registerToolHandler
const [stream, setStream] = createSignal<MessageStream>();
const cancelStream = () => {
const s = stream();
@@ -57,45 +87,14 @@ export function Chat(props: { data: ChatData }) {
s.close();
}
};
- const {
- ChatMessages,
- addMessage,
- setStream: setMessagesStream,
- } = useChatMessages({
- messages: props.data.chat.messages,
- chatId: props.data.chat.id,
- editDisabled: disabled,
- pendingLocationParams: pendingLocationParamsSignal.get,
- });
- const blockHandle = blockHandleSignal.get;
-
- const loadedState = getChatInputStoredState(props.data.chat.id);
-
- const {
- ChatInput,
- setIsGenerating,
- attachments,
- chatMarkdownArea,
- model,
- setModel,
- uploadQueue,
- } = useChatInput({
- chatId: props.data.chat.id,
- initialValue: loadedState.input,
- });
- if (loadedState.attachments) {
- attachments.setAttached(loadedState.attachments);
- }
- if (loadedState.model) {
- setModel(loadedState.model);
- }
+ const blockHandle = blockHandleSignal.get;
// Entity drag-and-drop support
const chatId = useBlockId();
const { droppable, isDraggingOver } = useEntityDropAttachment(
'chat-input-' + chatId,
- attachments
+ ctx.attachments
);
false && droppable;
@@ -112,16 +111,16 @@ export function Chat(props: { data: ChatData }) {
return onSend(response);
}
} else {
- addMessage({
+ ctx.addMessage!({
attachments: request.request.attachments ?? [],
content: request.request.content,
role: 'user',
id: '',
});
const stream = request.call();
- setMessagesStream(stream);
+ ctx.setStream!(stream);
setStream(stream);
- setIsGenerating(true);
+ ctx.setIsGenerating(true);
invalidateUserQuota();
createEffect(() => {
if (stream.data().length > 0) {
@@ -130,7 +129,7 @@ export function Chat(props: { data: ChatData }) {
});
createEffect(() => {
if (stream.isDone()) {
- setIsGenerating(false);
+ ctx.setIsGenerating(false);
invalidateUserQuota();
}
});
@@ -143,8 +142,8 @@ export function Chat(props: { data: ChatData }) {
createEffect(() => {
const input = chatMarkdownArea.markdownText();
- const attached = attachments.attached();
- const model_ = model();
+ const attached = ctx.attachments.attached();
+ const model_ = ctx.model();
saveChatState({ attachments: attached, input, model: model_ });
});
@@ -201,7 +200,6 @@ export function Chat(props: { data: ChatData }) {
return (
<DragDropWrapper
class="size-full bg-panel overscroll-none overflow-hidden flex flex-col"
- uploadQueue={uploadQueue}
isEntityDraggingOver={isDraggingOver}
>
<TopBar />
@@ -213,7 +211,10 @@ export function Chat(props: { data: ChatData }) {
ref={setScrollRef}
>
<div class="mx-auto w-full max-w-3xl">
- <ChatMessages />
+ <ChatMessages
+ editDisabled={disabled()}
+ pendingLocationParams={pendingLocationParamsSignal.get}
+ />
</div>
</div>
<CustomScrollbar scrollContainer={scrollRef} />
@@ -222,6 +223,7 @@ export function Chat(props: { data: ChatData }) {
<div class="flex w-full justify-center pb-2 px-4">
<div class="w-3xl">
<ChatInput
+ markdown={chatMarkdownArea}
onSend={onSend}
onStop={cancelStream}
captureEditor={setChatEditor}
diff --git a/js/app/packages/core/component/AI/component/DragDrop.tsx b/js/app/packages/core/component/AI/component/DragDrop.tsx
index b766435c1f..543f9e38c7 100644
--- a/js/app/packages/core/component/AI/component/DragDrop.tsx
+++ b/js/app/packages/core/component/AI/component/DragDrop.tsx
@@ -5,14 +5,13 @@ import { fileDrop } from '@core/directive/fileDrop';
const { track, TrackingEvents } = withAnalytics();
import { SUPPORTED_ATTACHMENT_EXTENSIONS } from '@core/component/AI/constant';
-import type { UploadQueue } from '@core/component/AI/types';
+import { useChatContext } from '@core/component/AI/context';
import type { Accessor, Component, ParentProps } from 'solid-js';
import { createSignal, Show } from 'solid-js';
false && fileDrop; // Reference for SolidJS directive
type DragDropWrapperProps = ParentProps<{
- uploadQueue: UploadQueue;
class?: string;
overlayMessage?: string;
/** Signal indicating if an entity is being dragged over (from useEntityDropAttachment) */
@@ -24,6 +23,9 @@ type DragDropWrapperProps = ParentProps<{
* to its children. Shows a visual overlay when files are dragged over the area.
*/
export const DragDropWrapper: Component<DragDropWrapperProps> = (props) => {
+ const ctx = useChatContext();
+ const uploadQueue = ctx.uploadQueue;
+
const [isFileDragging, setIsFileDragging] = createSignal(false);
const showOverlay = () => isFileDragging() || props.isEntityDraggingOver?.();
@@ -38,7 +40,7 @@ export const DragDropWrapper: Component<DragDropWrapperProps> = (props) => {
onDragEnd: () => setIsFileDragging(false),
onDrop: (files) => {
track(TrackingEvents.CHAT.ATTACHMENT.DROP);
- props.uploadQueue.upload(files);
+ uploadQueue.upload(files);
},
}}
>
diff --git a/js/app/packages/core/component/AI/component/debug/Component.tsx b/js/app/packages/core/component/AI/component/debug/Component.tsx
index 3181587e69..c7984f36dc 100644
--- a/js/app/packages/core/component/AI/component/debug/Component.tsx
+++ b/js/app/packages/core/component/AI/component/debug/Component.tsx
@@ -6,12 +6,13 @@ import type {
} from '@core/component/AI/types';
import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
import { createEffect, createSignal } from 'solid-js';
+import { ChatContextProvider, useChatContext } from '../../context';
import { useAttachments } from '../../signal/attachment';
import { pausableStream } from '../../util/stream';
+import { ChatInput } from '../input/useChatInput';
import { ModelSelector } from '../input/ModelSelector';
-import { useChatInput } from '../input/useChatInput';
import { useChatMarkdownArea } from '../input/useChatMarkdownArea';
-import { useChatMessages } from '../message/ChatMessages';
+import { ChatMessages } from '../message/ChatMessages';
import {
blockDone,
createStream,
@@ -84,30 +85,57 @@ function ChatModelSelector() {
}
function ChatInputBox() {
- const { ChatInput, setIsGenerating: setGen } = useChatInput();
+ return (
+ <ChatContextProvider>
+ <ChatInputBoxInner />
+ </ChatContextProvider>
+ );
+}
+
+function ChatInputBoxInner() {
+ const ctx = useChatContext();
+ const chatMarkdownArea = useChatMarkdownArea({
+ addAttachment: (a) => ctx.attachments.addAttachment(a),
+ });
return (
<Item label="Chat input - not connected to backend">
<div class="w-full h-full">
<div class="flex gap-2 py-2">
<DeprecatedTextButton
- onClick={() => setGen(true)}
+ onClick={() => ctx.setIsGenerating(true)}
theme="accent"
text="Generate"
/>
<DeprecatedTextButton
- onClick={() => setGen(false)}
+ onClick={() => ctx.setIsGenerating(false)}
theme="accent"
text="Stop"
/>
</div>
- <ChatInput onSend={(request) => console.log('request', request)} />
+ <ChatInput
+ markdown={chatMarkdownArea}
+ onSend={(request) => console.log('request', request)}
+ />
</div>
</Item>
);
}
function ChatInputBoxConnected() {
+ return (
+ <ChatContextProvider>
+ <ChatInputBoxConnectedInner />
+ </ChatContextProvider>
+ );
+}
+
+function ChatInputBoxConnectedInner() {
+ const ctx = useChatContext();
+ const chatMarkdownArea = useChatMarkdownArea({
+ addAttachment: (a) => ctx.attachments.addAttachment(a),
+ });
+
const [_gen, setGen] = createSignal(false);
const onSend = async (request: Send | CreateAndSend) => {
if (request.type === 'createAndSend') {
@@ -131,21 +159,25 @@ function ChatInputBoxConnected() {
}
};
- const { ChatInput } = useChatInput();
-
return (
<Item label="Chat input - connected (console)">
<div class="w-full h-full">
- <ChatInput onSend={onSend} />
+ <ChatInput markdown={chatMarkdownArea} onSend={onSend} />
</div>
</Item>
);
}
function StreamMessages() {
- const { ChatMessages, setStream: setMessageStream } = useChatMessages({
- messages: [],
- });
+ return (
+ <ChatContextProvider messages={[]}>
+ <StreamMessagesInner />
+ </ChatContextProvider>
+ );
+}
+
+function StreamMessagesInner() {
+ const ctx = useChatContext();
const [stream, setStream] = createSignal<MessageStream>();
const makeStream = () => delayStream(poem(), slowFirst);
@@ -156,7 +188,7 @@ function StreamMessages() {
onClick={() => {
const poemStream = makeStream();
setStream(poemStream);
- setMessageStream(poemStream);
+ ctx.setStream!(poemStream);
}}
>
Stream
@@ -171,23 +203,33 @@ function StreamMessages() {
function StaticMessages() {
const messages = simpleMessageChain();
- const { ChatMessages } = useChatMessages({ messages: messages });
console.log(JSON.stringify(messages, null, 2));
return (
- <Item col label="Chat messages - static render">
- <div data-chat-scroll class="min-h-0 max-h-[400px] overflow-y-auto">
- <ChatMessages />
- </div>
- </Item>
+ <ChatContextProvider messages={messages}>
+ <Item col label="Chat messages - static render">
+ <div data-chat-scroll class="min-h-0 max-h-[400px] overflow-y-auto">
+ <ChatMessages />
+ </div>
+ </Item>
+ </ChatContextProvider>
);
}
function FullChat() {
+ return (
+ <ChatContextProvider messages={[]}>
+ <FullChatInner />
+ </ChatContextProvider>
+ );
+}
+
+function FullChatInner() {
+ const ctx = useChatContext();
+ const chatMarkdownArea = useChatMarkdownArea({
+ addAttachment: (a) => ctx.attachments.addAttachment(a),
+ });
const [_isGen, setIsGen] = createSignal(false);
const [stream, setDebugStream] = createSignal<MessageStream>();
- const { ChatMessages, addMessage, setStream } = useChatMessages({
- messages: [],
- });
const onSend = async (request: Send | CreateAndSend) => {
if (request.type === 'createAndSend') {
@@ -200,7 +242,7 @@ function FullChat() {
return onSend(response);
}
} else {
- addMessage({
+ ctx.addMessage!({
attachments: request.request.attachments ?? [],
content: request.request.content,
role: 'user',
@@ -208,7 +250,7 @@ function FullChat() {
});
const stream = request.call();
console.log('set stream');
- setStream(stream);
+ ctx.setStream!(stream);
setDebugStream(stream);
setIsGen(true);
createEffect(() => {
@@ -226,8 +268,6 @@ function FullChat() {
}
};
- const { ChatInput } = useChatInput();
-
return (
<Item label="Input and messages - connected">
<div
@@ -236,7 +276,11 @@ function FullChat() {
>
<StreamStatus stream={stream} />
<ChatMessages />
- <ChatInput onSend={onSend} onStop={() => {}} />
+ <ChatInput
+ markdown={chatMarkdownArea}
+ onSend={onSend}
+ onStop={() => {}}
+ />
</div>
</Item>
);
@@ -244,24 +288,28 @@ function FullChat() {
function ToolCallRender() {
const stream = toolCall(() => 1);
+ const initialMessages = mockMessages([
+ { text: 'read this file for me', type: 'user' },
+ ]);
- const { ChatMessages, setStream } = useChatMessages({
- messages: mockMessages([
- {
- text: 'read this file for me',
- type: 'user',
- },
- ]),
- });
+ return (
+ <ChatContextProvider messages={initialMessages}>
+ <ToolCallRenderInner stream={stream} />
+ </ChatContextProvider>
+ );
+}
+
+function ToolCallRenderInner(props: { stream: MessageStream }) {
+ const ctx = useChatContext();
+ ctx.setStream!(props.stream);
- setStream(stream);
return (
<Item label="Tool call - static">
<div
data-chat-scroll
class="size-full flex space-y-1 flex-col overflow-y-auto max-h-[400px]"
>
- <StreamStatus stream={() => stream} />
+ <StreamStatus stream={() => props.stream} />
<ChatMessages />
</div>
</Item>
@@ -368,27 +416,31 @@ function LoadingMessageScroll() {
}
function TableStream() {
+ const initialMessages = mockMessages([
+ {
+ type: 'user',
+ text: 'Can you show me a comparison of frontend frameworks?',
+ },
+ ]);
+
+ return (
+ <ChatContextProvider messages={initialMessages}>
+ <TableStreamInner />
+ </ChatContextProvider>
+ );
+}
+
+function TableStreamInner() {
+ const ctx = useChatContext();
const [isPaused, setIsPaused] = createSignal(false);
const [isSlow, setIsSlow] = createSignal(false);
const [showRaw, setShowRaw] = createSignal(false);
const [stream, setStream] = createSignal<MessageStream>();
const [rawText, setRawText] = createSignal('');
- const {
- ChatMessages,
- setStream: setMessageStream,
- reset,
- } = useChatMessages({
- messages: mockMessages([
- {
- type: 'user',
- text: 'Can you show me a comparison of frontend frameworks?',
- },
- ]),
- });
-
const startStream = () => {
- reset();
+ ctx.setMessages!([]);
+ ctx.setStream!(undefined);
setRawText('');
const baseStream = table();
const controlled = pausableStream(baseStream, {
@@ -397,7 +449,7 @@ function TableStream() {
onChunk: (text) => setRawText((prev) => prev + text),
});
setStream(controlled);
- setMessageStream(controlled);
+ ctx.setStream!(controlled);
};
return (
@@ -435,7 +487,8 @@ function TableStream() {
onClick={() => {
setStream(undefined);
setRawText('');
- reset();
+ ctx.setMessages!([]);
+ ctx.setStream!(undefined);
}}
/>
</div>
diff --git a/js/app/packages/core/component/AI/component/debug/stream/StreamDebugger.tsx b/js/app/packages/core/component/AI/component/debug/stream/StreamDebugger.tsx
index 1bf4bc3a9b..0ec47ecfb2 100644
--- a/js/app/packages/core/component/AI/component/debug/stream/StreamDebugger.tsx
+++ b/js/app/packages/core/component/AI/component/debug/stream/StreamDebugger.tsx
@@ -2,7 +2,8 @@ import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
import type { ChatMessageWithAttachments } from '@service-cognition/generated/schemas';
import type { MessageStream } from '@service-cognition/websocket';
import { createSignal } from 'solid-js';
-import { useChatMessages } from '../../message';
+import { ChatContextProvider, useChatContext } from '../../../context';
+import { ChatMessages } from '../../message/ChatMessages';
import { StreamStatus } from './StreamStatus';
export function StreamDebuggerWithControls(props: {
@@ -10,18 +11,26 @@ export function StreamDebuggerWithControls(props: {
messages?: ChatMessageWithAttachments[];
autoStart?: true;
}) {
+ return (
+ <ChatContextProvider messages={props.messages ?? []}>
+ <StreamDebuggerWithControlsInner
+ stream={props.stream}
+ autoStart={props.autoStart}
+ />
+ </ChatContextProvider>
+ );
+}
+
+function StreamDebuggerWithControlsInner(props: {
+ stream: () => MessageStream;
+ autoStart?: true;
+}) {
+ const ctx = useChatContext();
const [stream, setStream] = createSignal<MessageStream>();
- const {
- ChatMessages,
- setStream: setMessageStream,
- reset,
- } = useChatMessages({
- messages: props.messages ?? [],
- });
if (props.autoStart) {
setStream(props.stream());
- setMessageStream(props.stream());
+ ctx.setStream!(props.stream());
}
return (
@@ -32,7 +41,7 @@ export function StreamDebuggerWithControls(props: {
onClick={() => {
const stream = props.stream();
setStream(stream);
- setMessageStream(stream);
+ ctx.setStream!(stream);
}}
theme="accent"
/>
@@ -41,7 +50,8 @@ export function StreamDebuggerWithControls(props: {
theme="accent"
onClick={() => {
setStream(undefined);
- reset();
+ ctx.setMessages!([]);
+ ctx.setStream!(undefined);
}}
/>
</div>
@@ -57,11 +67,16 @@ export function StreamDebugger(props: {
stream: MessageStream;
messages?: ChatMessageWithAttachments[];
}) {
- const { ChatMessages, setStream: setMessageStream } = useChatMessages({
- messages: props.messages ?? [],
- });
+ return (
+ <ChatContextProvider messages={props.messages ?? []}>
+ <StreamDebuggerInner stream={props.stream} />
+ </ChatContextProvider>
+ );
+}
- setMessageStream(props.stream);
+function StreamDebuggerInner(props: { stream: MessageStream }) {
+ const ctx = useChatContext();
+ ctx.setStream!(props.stream);
return (
<div
data-chat-scroll
diff --git a/js/app/packages/core/component/AI/component/input/ChatAttachMenu.tsx b/js/app/packages/core/component/AI/component/input/ChatAttachMenu.tsx
index df3d34e5ee..a5f3e21625 100644
--- a/js/app/packages/core/component/AI/component/input/ChatAttachMenu.tsx
+++ b/js/app/packages/core/component/AI/component/input/ChatAttachMenu.tsx
@@ -1,10 +1,11 @@
import { withAnalytics } from '@coparse/analytics';
import { SUPPORTED_ATTACHMENT_EXTENSIONS } from '@core/component/AI/constant';
+import { useChatContext } from '@core/component/AI/context';
import {
useChatAttachableHistory,
useGetChatAttachmentInfo,
} from '@core/component/AI/signal/attachment';
-import type { Attachment, UploadQueue } from '@core/component/AI/types';
+import type { Attachment } from '@core/component/AI/types';
import { EntityIcon } from '@core/component/EntityIcon';
import { OldMenu, OldMenuItem } from '@core/component/OldMenu';
import clickOutside from '@core/directive/clickOutside';
@@ -45,7 +46,6 @@ type ChatAttachMenuProps = {
anchorRef: HTMLDivElement;
containerRef: HTMLElement;
onAttach: (attachment: Attachment) => void;
- uploadQueue: UploadQueue;
};
function truncate(str: string, maxLength: number = 30) {
@@ -56,6 +56,9 @@ function truncate(str: string, maxLength: number = 30) {
// TODO: create a shared component for chat attach menu and block channel AttachMenu
// TODO: add other supported attachment types, e.g. chat/channel
export function ChatAttachMenu(props: ChatAttachMenuProps) {
+ const ctx = useChatContext();
+ const uploadQueue = ctx.uploadQueue;
+
const [position, setPosition] = createSignal({ x: 0, y: 0 });
const [popupRef, setPopupRef] = createSignal<HTMLDivElement>();
const history = useChatAttachableHistory();
@@ -340,7 +343,7 @@ export function ChatAttachMenu(props: ChatAttachMenuProps) {
acceptedFileExtensions: SUPPORTED_ATTACHMENT_EXTENSIONS,
multiple: true,
onSelect: (files) => {
- props.uploadQueue.upload(files);
+ uploadQueue.upload(files);
props.close();
},
}}
diff --git a/js/app/packages/core/component/AI/component/input/index.ts b/js/app/packages/core/component/AI/component/input/index.ts
index e69de29bb2..85eee5afc4 100644
--- a/js/app/packages/core/component/AI/component/input/index.ts
+++ b/js/app/packages/core/component/AI/component/input/index.ts
@@ -0,0 +1,5 @@
+export {
+ ChatInput,
+ type ChatInputProps,
+ type ChatInputComponentProps,
+} from './useChatInput';
diff --git a/js/app/packages/core/component/AI/component/input/useChatInput.tsx b/js/app/packages/core/component/AI/component/input/useChatInput.tsx
index d5f3aa9b38..a2a2f4f1a5 100644
--- a/js/app/packages/core/component/AI/component/input/useChatInput.tsx
+++ b/js/app/packages/core/component/AI/component/input/useChatInput.tsx
@@ -1,24 +1,17 @@
import { withAnalytics } from '@coparse/analytics';
import { useBuildChatSendRequest } from '@core/component/AI/component/input/buildRequest';
-import { DEFAULT_MODEL, SMART_MODE_MODEL } from '@core/component/AI/constant';
-import {
- useAttachments,
- useChatAttachableHistory,
-} from '@core/component/AI/signal/attachment';
+import { SMART_MODE_MODEL } from '@core/component/AI/constant';
+import { useChatContext } from '@core/component/AI/context';
+import { useChatAttachableHistory } from '@core/component/AI/signal/attachment';
import type {
- Attachment,
- Attachments,
CreateAndSend,
Model,
Send,
ToolSet,
- UploadQueue,
} from '@core/component/AI/types';
-import { useUploadAttachment } from '@core/component/AI/util/uploadToChat';
import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
import { Hotkey, modifierMap } from '@core/component/Hotkey';
import { Tooltip } from '@core/component/Tooltip';
-import { ENABLE_AI_AUTO_TAB_ATTACHMENTS } from '@core/constant/featureFlags';
import { pressedKeys } from '@core/hotkey/state';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import ArrowUp from '@icon/bold/arrow-up-bold.svg';
@@ -28,16 +21,11 @@ import Stop from '@phosphor-icons/core/regular/stop.svg';
import { createCallback } from '@solid-primitives/rootless';
import { Button } from '@ui/components/Button';
import type { LexicalEditor } from 'lexical';
-import type { Accessor, Component, Setter } from 'solid-js';
-import { createEffect, createSignal, Match, on, Show, Switch } from 'solid-js';
-import { useTabAttachments } from '../../signal/tabAttachments';
+import { createEffect, createSignal, Match, Show, Switch } from 'solid-js';
import { AttachmentList } from './Attachment';
import { ChatAttachMenu } from './ChatAttachMenu';
import type { Source } from './ToolsetSelector';
-import {
- type UseChatMarkdown,
- useChatMarkdownArea,
-} from './useChatMarkdownArea';
+import type { UseChatMarkdown } from './useChatMarkdownArea';
import { cn } from '@ui/utils/classname';
const { track, TrackingEvents } = withAnalytics();
@@ -51,109 +39,19 @@ export type ChatInputProps = {
autoFocusOnMount?: boolean;
};
-type ChatInputInternalProps = {
- uploadQueue: UploadQueue;
- isGenerating: Accessor<boolean>;
- attachments: Attachments;
- chatId: Accessor<string | undefined>;
- model: Accessor<Model>;
- setModel: Setter<Model>;
+export type ChatInputComponentProps = {
markdown: UseChatMarkdown;
} & ChatInputProps;
-export type ChatInput = {
- ChatInput: Component<ChatInputProps>;
- uploadQueue: UploadQueue;
- setChatId: (chatId: string | undefined) => void;
- chatId: Accessor<string | undefined>;
- model: Accessor<Model>;
- setModel: (model?: Model) => void;
- attachments: Attachments;
- isGenerating: Accessor<boolean>;
- setIsGenerating: (generating: boolean) => void;
- chatMarkdownArea: UseChatMarkdown;
-};
-
-export function useChatInput(
- args: {
- chatId?: string;
- model?: Model;
- isGenerating?: boolean;
- initialAttachments?: Attachment[];
- initialValue?: string;
- autoAttach?: boolean;
- } = {}
-): ChatInput {
- const [chatId, setChatId] = createSignal<string | undefined>(args.chatId);
- const [model, setModel] = createSignal<Model>(args.model ?? DEFAULT_MODEL);
- const [isGenerating, setIsGenerating] = createSignal<boolean>(
- args.isGenerating ?? false
- );
- const uploadQueue = useUploadAttachment();
- const attachments = useAttachments(args.initialAttachments);
-
- const chatMarkdownArea = useChatMarkdownArea({
- initialValue: args.initialValue,
- addAttachment: (a) => {
- attachments.addAttachment(a);
- },
- });
-
- const tabAttachments = useTabAttachments();
- if (ENABLE_AI_AUTO_TAB_ATTACHMENTS && args.autoAttach !== false) {
- createEffect(
- on(tabAttachments, (tabs, p) => {
- for (const prev of p ?? []) {
- // remove stuff from closed tabs
- if (!tabs.find((t) => t.attachmentId === prev.attachmentId)) {
- attachments.removeAttachment(prev.attachmentId);
- }
- }
- for (const tab of tabs) {
- attachments.addAttachment(tab);
- }
- })
- );
- }
-
- const ChatInputComponent = (innerProps: ChatInputProps) => (
- <ChatInput
- {...innerProps}
- chatId={chatId}
- uploadQueue={uploadQueue}
- model={model}
- setModel={setModel}
- isGenerating={isGenerating}
- attachments={attachments}
- markdown={chatMarkdownArea}
- />
- );
-
- const setModelWithDefault = (model?: Model) => {
- if (model === undefined) {
- setModel(DEFAULT_MODEL);
- } else {
- setModel(model);
- }
- };
-
- return {
- setChatId,
- chatId,
- model,
- setModel: setModelWithDefault,
- attachments,
- isGenerating,
- setIsGenerating,
- uploadQueue,
- ChatInput: ChatInputComponent,
- chatMarkdownArea,
- };
-}
+export function ChatInput(props: ChatInputComponentProps) {
+ const ctx = useChatContext();
+ const uploadQueue = ctx.uploadQueue;
+ const attachments = ctx.attachments;
+ const chatId = ctx.chatId;
+ const model = ctx.model;
+ const generating = ctx.isGenerating;
-function ChatInput(props: ChatInputInternalProps) {
let containerRef!: HTMLDivElement;
- const generating = props.isGenerating ?? (() => false);
const toolsetSignal = createSignal<ToolSet>({ type: 'all' });
const [source] = createSignal<Source>('everything');
@@ -162,18 +60,17 @@ function ChatInput(props: ChatInputInternalProps) {
createSignal<HTMLDivElement>();
createEffect(() => {
- const uploaded = props.uploadQueue.popComplete();
+ const uploaded = uploadQueue.popComplete();
uploaded
.filter((upload) => upload.type === 'ok')
.forEach((upload) => {
track(TrackingEvents.CHAT.ATTACHMENT.ADD);
- props.attachments.addAttachment(upload.attachment);
+ attachments.addAttachment(upload.attachment);
});
});
const isEmptyInput = () => props.markdown.markdownText().trim().length === 0;
- const hasUploadingAttachments = () =>
- props.uploadQueue.uploading().length > 0;
+ const hasUploadingAttachments = () => uploadQueue.uploading().length > 0;
const canSendMessage = () =>
!isEmptyInput() && !generating() && !hasUploadingAttachments();
@@ -193,11 +90,11 @@ function ChatInput(props: ChatInputInternalProps) {
if (!canSendMessage()) return;
const request = await buildChatSendRequest({
- chatId: props.chatId(),
+ chatId: chatId(),
userRequest: props.markdown.markdownText(),
isPersistent: props.isPersistent,
- attachments: props.attachments.attached(),
- model: modelOverride ?? props.model(),
+ attachments: attachments.attached(),
+ model: modelOverride ?? model(),
toolset: toolsetSignal[0](),
source: source(),
});
@@ -225,8 +122,7 @@ function ChatInput(props: ChatInputInternalProps) {
const availableAttachments = useChatAttachableHistory();
const hasAttachments = () =>
- props.attachments.attached().length > 0 ||
- props.uploadQueue.uploading().length > 0;
+ attachments.attached().length > 0 || uploadQueue.uploading().length > 0;
const LeftButton = () => (
<div ref={setAttachMenuAnchorRef} class="shrink-0">
@@ -316,15 +212,13 @@ function ChatInput(props: ChatInputInternalProps) {
<Show when={hasAttachments()}>
<div class="px-2 pt-2 w-full">
<AttachmentList
- attached={props.attachments.attached}
+ attached={attachments.attached}
removeAttachment={(id) => {
track(TrackingEvents.CHAT.ATTACHMENT.REMOVE);
- props.attachments.removeAttachment(id);
+ attachments.removeAttachment(id);
}}
uploading={() =>
- props.uploadQueue
- .uploading()
- .map((uploading) => uploading.preview)
+ uploadQueue.uploading().map((uploading) => uploading.preview)
}
/>
</div>
@@ -338,9 +232,8 @@ function ChatInput(props: ChatInputInternalProps) {
open={showAttachMenu()}
onAttach={(attachment) => {
track(TrackingEvents.CHAT.ATTACHMENT.ADD);
- props.attachments.addAttachment(attachment);
+ attachments.addAttachment(attachment);
}}
- uploadQueue={props.uploadQueue}
/>
</Show>
@@ -365,7 +258,7 @@ function ChatInput(props: ChatInputInternalProps) {
dontFocusOnMount={
isTouchDevice() || props.autoFocusOnMount === false
}
- onPasteFile={props.uploadQueue.upload}
+ onPasteFile={uploadQueue.upload}
captureEditor={props.captureEditor}
/>
</div>
diff --git a/js/app/packages/core/component/AI/component/message/ChatMessages.tsx b/js/app/packages/core/component/AI/component/message/ChatMessages.tsx
index 727113f1e9..a1e6b250fb 100644
--- a/js/app/packages/core/component/AI/component/message/ChatMessages.tsx
+++ b/js/app/packages/core/component/AI/component/message/ChatMessages.tsx
@@ -1,3 +1,4 @@
+import { useChatContext } from '@core/component/AI/context';
import type {
ChatMessageWithAttachments,
MessageStream,
@@ -39,63 +40,7 @@ function OnMount(props: {
return <div ref={ref}>{props.children}</div>;
}
-type ChatMessages = {
- ChatMessages: () => JSXElement;
- addMessage: (message: ChatMessageWithAttachments) => void;
- setStream: (stream: MessageStream) => void;
- reset: () => void;
- messages: Accessor<ChatMessageWithAttachments[]>;
-};
-
-export function useChatMessages(args: {
- messages: ChatMessageWithAttachments[];
- actions?: MessageActions;
- chatId?: string;
- editDisabled?: Accessor<boolean>;
- pendingLocationParams?: Accessor<Record<string, string> | undefined>;
-}): ChatMessages {
- const [messages, setMessages] = createSignal(args.messages);
- const [stream, setStream] = createSignal<MessageStream>();
- const addMessage = (message: ChatMessageWithAttachments) => {
- setMessages((p) => [...p, message]);
- };
- const editDisabled = createMemo(() => args.editDisabled?.());
-
- const CurriedChatMessages = createMemo(() => (
- <ChatMessages
- chatId={args.chatId}
- messages={[messages, setMessages]}
- messageActions={args.actions}
- stream={[stream, setStream]}
- editDisabled={editDisabled()}
- pendingLocationParams={args.pendingLocationParams}
- />
- ));
-
- const reset = () => {
- setMessages([]);
- setStream();
- };
-
- return {
- ChatMessages: CurriedChatMessages,
- addMessage,
- setStream,
- reset,
- messages,
- };
-}
-
export type ChatMessagesProps = {
- messages: [
- Accessor<ChatMessageWithAttachments[]>,
- Setter<ChatMessageWithAttachments[]>,
- ];
- stream?: [
- Accessor<MessageStream | undefined>,
- Setter<MessageStream | undefined>,
- ];
- chatId?: string;
messageActions?: MessageActions;
editDisabled?: boolean;
pendingLocationParams?: Accessor<Record<string, string> | undefined>;
@@ -110,10 +55,16 @@ function messageContentIsEmpty(message: ChatMessageWithAttachments) {
}
export function ChatMessages(props: ChatMessagesProps) {
- const [messages, setMessages] = props.messages;
+ const ctx = useChatContext();
+ const [messages, setMessages] = [ctx.messages!, ctx.setMessages!];
+ const streamTuple:
+ | [Accessor<MessageStream | undefined>, Setter<MessageStream | undefined>]
+ | undefined =
+ ctx.stream && ctx.setStream ? [ctx.stream, ctx.setStream] : undefined;
+ const chatId = () => ctx.chatId?.();
const extendedStream = createMemo(() => {
- const s = props.stream?.[0]?.();
+ const s = streamTuple?.[0]?.();
if (!s) return;
return timeStream(idStream(s));
});
@@ -134,7 +85,7 @@ export function ChatMessages(props: ChatMessagesProps) {
let messagesRef: HTMLDivElement | undefined;
const generatingMessage = () => {
- const streamAccessor = props.stream?.[0];
+ const streamAccessor = streamTuple?.[0];
if (!streamAccessor) return;
const stream = streamAccessor();
if (!stream) return;
@@ -147,7 +98,7 @@ export function ChatMessages(props: ChatMessagesProps) {
};
const generatingAfterToolCall = () => {
- const streamAccessor = props.stream?.[0];
+ const streamAccessor = streamTuple?.[0];
if (!streamAccessor) return;
const stream = streamAccessor();
if (!stream || stream.isDone()) return;
@@ -160,7 +111,7 @@ export function ChatMessages(props: ChatMessagesProps) {
};
const isStream = () => {
- const streamSignal = props.stream?.[0];
+ const streamSignal = streamTuple?.[0];
if (!streamSignal) return false;
const stream = streamSignal();
if (!stream) return false;
@@ -168,7 +119,7 @@ export function ChatMessages(props: ChatMessagesProps) {
};
const streamRequestAttachments = () => {
- const streamable = props.stream?.[0];
+ const streamable = streamTuple?.[0];
if (!streamable) return [];
const stream = streamable();
if (!stream || !('attachments' in stream.request)) return [];
@@ -177,8 +128,8 @@ export function ChatMessages(props: ChatMessagesProps) {
// when messages finish streaming, append and scroll
createEffect(() => {
- if (!props.stream?.[0]) return;
- const s = props.stream?.[0]();
+ if (!streamTuple?.[0]) return;
+ const s = streamTuple?.[0]();
if (!s) return;
if (s.isDone()) {
const message = asChatMessage(s.data());
@@ -350,9 +301,9 @@ export function ChatMessages(props: ChatMessagesProps) {
props.editDisabled
? undefined
: {
- chatId: props.chatId!,
+ chatId: chatId()!,
makeEdit: (send) => {
- const setStream = props?.stream?.[1];
+ const setStream = streamTuple?.[1];
if (setStream) {
setMessages((p) => {
const last = p.at(-1);
diff --git a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx
index 52e16b0f9e..ab234ff19b 100644
--- a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx
+++ b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx
@@ -1,22 +1,24 @@
-import { useChatInput } from '@core/component/AI/component/input/useChatInput';
+import {
+ ChatContextProvider,
+ useChatContext,
+} from '@core/component/AI/context';
+import { ChatInput } from '@core/component/AI/component/input/useChatInput';
+import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';
import type { Attachment, Model, Send } from '@core/component/AI/types';
import { asEditRequest } from '@core/component/AI/types/util';
import { onMount } from 'solid-js';
-export function EditableChatMessage(props: {
- chatId: string;
+function EditableChatMessageInner(props: {
initialText: string;
attachments: Attachment[];
onAccept: (r: Send) => void;
onCancel: () => void;
model: Model;
}) {
- const { ChatInput, chatMarkdownArea } = useChatInput({
- initialAttachments: props.attachments,
- chatId: props.chatId,
+ const ctx = useChatContext();
+ const chatMarkdownArea = useChatMarkdownArea({
initialValue: props.initialText,
- model: props.model,
- isGenerating: false,
+ addAttachment: (a) => ctx.attachments.addAttachment(a),
});
onMount(() => {
@@ -32,6 +34,7 @@ export function EditableChatMessage(props: {
return (
<div onKeyDown={handleKey} class="w-full">
<ChatInput
+ markdown={chatMarkdownArea}
onSend={(request) => {
if (request.type === 'send') props.onAccept(asEditRequest(request));
}}
@@ -39,3 +42,29 @@ export function EditableChatMessage(props: {
</div>
);
}
+
+export function EditableChatMessage(props: {
+ chatId: string;
+ initialText: string;
+ attachments: Attachment[];
+ onAccept: (r: Send) => void;
+ onCancel: () => void;
+ model: Model;
+}) {
+ return (
+ <ChatContextProvider
+ chatId={props.chatId}
+ model={props.model}
+ isGenerating={false}
+ initialAttachments={props.attachments}
+ >
+ <EditableChatMessageInner
+ initialText={props.initialText}
+ attachments={props.attachments}
+ onAccept={props.onAccept}
+ onCancel={props.onCancel}
+ model={props.model}
+ />
+ </ChatContextProvider>
+ );
+}
diff --git a/js/app/packages/core/component/AI/component/message/index.ts b/js/app/packages/core/component/AI/component/message/index.ts
index b8f586fbe3..f5a70381b5 100644
--- a/js/app/packages/core/component/AI/component/message/index.ts
+++ b/js/app/packages/core/component/AI/component/message/index.ts
@@ -1 +1 @@
-export { useChatMessages } from './ChatMessages';
+export { ChatMessages, type ChatMessagesProps } from './ChatMessages';
diff --git a/js/app/packages/core/component/AI/context/ChatContext.tsx b/js/app/packages/core/component/AI/context/ChatContext.tsx
new file mode 100644
index 0000000000..47ca44287c
--- /dev/null
+++ b/js/app/packages/core/component/AI/context/ChatContext.tsx
@@ -0,0 +1,175 @@
+import { DEFAULT_MODEL } from '@core/component/AI/constant';
+import { useAttachments } from '@core/component/AI/signal/attachment';
+import { useTabAttachments } from '@core/component/AI/signal/tabAttachments';
+import type {
+ Attachment,
+ Attachments,
+ ChatMessageWithAttachments,
+ MessageStream,
+ Model,
+ UploadQueue,
+} from '@core/component/AI/types';
+import { useUploadAttachment } from '@core/component/AI/util/uploadToChat';
+import { ENABLE_AI_AUTO_TAB_ATTACHMENTS } from '@core/constant/featureFlags';
+import {
+ createContextProvider,
+ type ContextProviderProps,
+} from '@solid-primitives/context';
+import type { Accessor, Setter } from 'solid-js';
+import { createEffect, createSignal, on } from 'solid-js';
+
+export type ChatContextValue = {
+ // Identity
+ chatId: Accessor<string | undefined>;
+ setChatId: (chatId: string | undefined) => void;
+
+ // Input state
+ model: Accessor<Model>;
+ setModel: (model?: Model) => void;
+ isGenerating: Accessor<boolean>;
+ setIsGenerating: (generating: boolean) => void;
+ attachments: Attachments;
+ uploadQueue: UploadQueue;
+
+ // Message state (undefined for input-only consumers like SoupChatInput)
+ messages: Accessor<ChatMessageWithAttachments[]> | undefined;
+ setMessages: Setter<ChatMessageWithAttachments[]> | undefined;
+ addMessage: ((msg: ChatMessageWithAttachments) => void) | undefined;
+ stream: Accessor<MessageStream | undefined> | undefined;
+ setStream: Setter<MessageStream | undefined> | undefined;
+};
+
+export type ChatContextProviderProps = ContextProviderProps & {
+ // Initial values for self-owned mode
+ chatId?: string;
+ model?: Model;
+ isGenerating?: boolean;
+ initialAttachments?: Attachment[];
+ autoAttach?: boolean;
+
+ // When provided, creates message/stream signals with initial messages
+ messages?: ChatMessageWithAttachments[];
+
+ // External state injection (for Rightbar)
+ external?: {
+ chatId: [Accessor<string | undefined>, (id: string | undefined) => void];
+ messages: [
+ Accessor<ChatMessageWithAttachments[]>,
+ Setter<ChatMessageWithAttachments[]>,
+ ];
+ stream: [
+ Accessor<MessageStream | undefined>,
+ Setter<MessageStream | undefined>,
+ ];
+ };
+};
+
+function createChatContext(props: ChatContextProviderProps): ChatContextValue {
+ // --- chatId ---
+ let chatId: Accessor<string | undefined>;
+ let setChatId: (id: string | undefined) => void;
+ if (props.external) {
+ [chatId, setChatId] = props.external.chatId;
+ } else {
+ const [_chatId, _setChatId] = createSignal<string | undefined>(
+ props.chatId
+ );
+ chatId = _chatId;
+ setChatId = _setChatId;
+ }
+
+ // --- model (always self-owned) ---
+ const [model, _setModel] = createSignal<Model>(props.model ?? DEFAULT_MODEL);
+ const setModel = (m?: Model) => _setModel(m ?? DEFAULT_MODEL);
+
+ // --- isGenerating (always self-owned) ---
+ const [isGenerating, setIsGenerating] = createSignal<boolean>(
+ props.isGenerating ?? false
+ );
+
+ // --- attachments (always self-owned) ---
+ const attachments = useAttachments(props.initialAttachments);
+
+ // --- uploadQueue (always self-owned) ---
+ const uploadQueue = useUploadAttachment();
+
+ // --- tab auto-attachment ---
+ const tabAttachments = useTabAttachments();
+ if (ENABLE_AI_AUTO_TAB_ATTACHMENTS && props.autoAttach !== false) {
+ createEffect(
+ on(tabAttachments, (tabs, p) => {
+ for (const prev of p ?? []) {
+ if (!tabs.find((t) => t.attachmentId === prev.attachmentId)) {
+ attachments.removeAttachment(prev.attachmentId);
+ }
+ }
+ for (const tab of tabs) {
+ attachments.addAttachment(tab);
+ }
+ })
+ );
+ }
+
+ // --- messages / stream ---
+ let messages: Accessor<ChatMessageWithAttachments[]> | undefined;
+ let setMessages: Setter<ChatMessageWithAttachments[]> | undefined;
+ let addMessage: ((msg: ChatMessageWithAttachments) => void) | undefined;
+ let stream: Accessor<MessageStream | undefined> | undefined;
+ let setStream: Setter<MessageStream | undefined> | undefined;
+
+ if (props.external) {
+ [messages, setMessages] = props.external.messages;
+ [stream, setStream] = props.external.stream;
+ addMessage = (msg: ChatMessageWithAttachments) => {
+ setMessages!((p) => [...p, msg]);
+ };
+ } else if (props.messages !== undefined) {
+ const [_messages, _setMessages] = createSignal<
+ ChatMessageWithAttachments[]
+ >(props.messages);
+ const [_stream, _setStream] = createSignal<MessageStream>();
+ messages = _messages;
+ setMessages = _setMessages;
+ stream = _stream;
+ setStream = _setStream;
+ addMessage = (msg: ChatMessageWithAttachments) => {
+ _setMessages((p) => [...p, msg]);
+ };
+ }
+ // else: messages/stream remain undefined (input-only mode)
+
+ return {
+ chatId,
+ setChatId,
+ model,
+ setModel,
+ isGenerating,
+ setIsGenerating,
+ attachments,
+ uploadQueue,
+ messages,
+ setMessages,
+ addMessage,
+ stream,
+ setStream,
+ };
+}
+
+const [ChatContextProvider, useContextInternal] =
+ createContextProvider(createChatContext);
+
+export { ChatContextProvider };
+
+export function useChatContext(): ChatContextValue {
+ const ctx = useContextInternal();
+ if (ctx === undefined) {
+ throw new Error(
+ 'useChatContext must be used within <ChatContextProvider />'
+ );
+ }
+ return ctx;
+}
+
+export function useChatContextOptional(): ChatContextValue | undefined {
+ return useContextInternal();
+}
diff --git a/js/app/packages/core/component/AI/context/index.ts b/js/app/packages/core/component/AI/context/index.ts
new file mode 100644
index 0000000000..bbc65d6661
--- /dev/null
+++ b/js/app/packages/core/component/AI/context/index.ts
@@ -0,0 +1,7 @@
+export {
+ ChatContextProvider,
+ useChatContext,
+ useChatContextOptional,
+ type ChatContextValue,
+ type ChatContextProviderProps,
+} from './ChatContext';
diff --git a/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts b/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts
index f00458f07f..69ebe4c28c 100644
--- a/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts
+++ b/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts
@@ -14,7 +14,7 @@ import { type Accessor, createMemo } from 'solid-js';
* Creates a droppable zone and handles converting dropped entities to attachments.
*
* @param droppableId - Unique ID for the droppable zone
- * @param attachments - The attachments object from useChatInput
+ * @param attachments - The attachments object from ChatContext
* @returns Object with droppable directive and isDraggingOver signal
*/
export function useEntityDropAttachment(