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.

fix(ai): context (#1466)

Eric Hayesc34cdc0b0e3b
diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsx
index d9a520bca2..b6a312c1fe 100644
--- a/js/app/packages/app/component/SoupChatInput.tsx
+++ b/js/app/packages/app/component/SoupChatInput.tsx
@@ -1,7 +1,9 @@
-import { ChatContextProvider } from '@core/component/AI/context';
+import {
+ ChatInputProvider,
+ useChatInputContext,
+} 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';
@@ -15,10 +17,10 @@ function SoupChatInputInner() {
let containerRef!: HTMLDivElement;
const splitPanelContext = useSplitPanelOrThrow();
const soup = useSoup();
- const ctx = useChatContext();
+ const input = useChatInputContext();
const chatMarkdownArea = useChatMarkdownArea({
- addAttachment: (a) => ctx.attachments.addAttachment(a),
+ addAttachment: (a) => input.attachments.addAttachment(a),
});
const [attachHotkeys] = useHotkeyDOMScope('soup.chatInput');
@@ -79,8 +81,8 @@ function SoupChatInputInner() {
export function SoupChatInput() {
return (
- <ChatContextProvider autoAttach={false}>
+ <ChatInputProvider autoAttach={false}>
<SoupChatInputInner />
- </ChatContextProvider>
+ </ChatInputProvider>
);
}
diff --git a/js/app/packages/app/component/rightbar/Rightbar.tsx b/js/app/packages/app/component/rightbar/Rightbar.tsx
index be95fb1339..1e30472449 100644
--- a/js/app/packages/app/component/rightbar/Rightbar.tsx
+++ b/js/app/packages/app/component/rightbar/Rightbar.tsx
@@ -7,8 +7,10 @@ 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,
+ ChatInputProvider,
+ ChatProvider,
useChatContext,
+ useChatInputContext,
} from '@core/component/AI/context';
import { useEntityDropAttachment } from '@core/component/AI/hook/useEntityDropAttachment';
import { getPendingSend } from '@core/component/AI/signal/pendingSend';
@@ -68,6 +70,7 @@ import {
createMemo,
createSignal,
For,
+ type JSXElement,
on,
onCleanup,
type Setter,
@@ -276,71 +279,100 @@ function TopBar(props: {
);
}
-export function Rightbar(props: {
- onSend: (args: CreateAndSend | Send) => void;
- stopGenerating: () => void;
- chatName: string | undefined;
- isBig?: boolean;
- userPermissions: Accessor<Permissions>;
- onUnmount?: () => void;
- initialState?: {
- model: Model | undefined;
- attachments: Attachment[];
- text: string | undefined;
- };
- setState: {
- setChatId: (chatId: string | undefined) => void;
- setModel: Setter<Model | undefined>;
- setAttachments: Setter<Attachment[]>;
- setText: Setter<string | undefined>;
- };
-}) {
- const ctx = useChatContext();
+/** Renders messages + stream effects. Only mounted inside ChatProvider. */
+function RightbarChatArea(props: { isBig?: boolean }) {
+ const chat = useChatContext();
+ const input = useChatInputContext();
const [messagesContainerRef, setMessagesContainerRef] =
createSignal<HTMLElement>();
createEffect(() => {
- const stream_ = ctx.stream?.();
+ const stream_ = chat.stream();
if (stream_ && stream_.data().length > 0) {
invalidateUserQuota();
}
});
createEffect(() => {
- const stream_ = ctx.stream?.();
+ const stream_ = chat.stream();
if (!stream_ || stream_.isDone()) {
- ctx.setIsGenerating(false);
+ input.setIsGenerating(false);
if (stream_?.isDone()) {
invalidateUserQuota();
}
return;
} else {
- ctx.setIsGenerating(true);
+ input.setIsGenerating(true);
}
});
- registerToolHandler(ctx.stream!);
+ registerToolHandler(chat.stream);
+
+ return (
+ <>
+ <Show when={chat.messages().length === 0}>
+ <div class="h-full flex flex-col items-center justify-center">
+ <AiChatEmptyState />
+ </div>
+ </Show>
+ <Show when={chat.messages().length > 0 || !props.isBig}>
+ <div class="relative flex-1 min-h-0 w-full">
+ <div
+ data-chat-scroll
+ class="size-full overflow-y-auto overflow-x-hidden scroll-smooth flex justify-center scrollbar-hidden"
+ ref={setMessagesContainerRef}
+ >
+ <div class="w-full macro-message-width">
+ <ChatMessages messageActions={undefined} />
+ </div>
+ </div>
+ <CustomScrollbar scrollContainer={messagesContainerRef} />
+ </div>
+ </Show>
+ </>
+ );
+}
- const stopGenerating = props.stopGenerating;
+export function Rightbar(props: {
+ chatId: string | undefined;
+ onSend: (args: CreateAndSend | Send) => void;
+ stopGenerating: () => void;
+ chatName: string | undefined;
+ isBig?: boolean;
+ userPermissions: Accessor<Permissions>;
+ onUnmount?: () => void;
+ initialState?: {
+ model: Model | undefined;
+ attachments: Attachment[];
+ text: string | undefined;
+ };
+ setState: {
+ setChatId: (chatId: string | undefined) => void;
+ setModel: Setter<Model | undefined>;
+ setAttachments: Setter<Attachment[]>;
+ setText: Setter<string | undefined>;
+ };
+ children?: JSXElement;
+}) {
+ const input = useChatInputContext();
// NOTE: due to mount race condition in the markdown area, we need to set the initial value here
const chatMarkdownArea = useChatMarkdownArea({
initialValue: props.initialState?.text,
- addAttachment: (a) => ctx.attachments.addAttachment(a),
+ addAttachment: (a) => input.attachments.addAttachment(a),
});
// Entity drag-and-drop support
const { droppable, isDraggingOver } = useEntityDropAttachment(
'rightbar-chat-input',
- ctx.attachments
+ input.attachments
);
false && droppable;
createEffect(() => {
- ctx.setChatId(ctx.chatId());
if (!props.initialState) return;
- ctx.setModel(props.initialState.model);
- ctx.attachments.setAttached(props.initialState.attachments);
+ input.setModel(props.initialState.model);
+ input.attachments.setAttached(props.initialState.attachments);
});
onCleanup(() => {
@@ -348,10 +380,10 @@ export function Rightbar(props: {
});
createEffect(() => {
- const input = chatMarkdownArea.markdownText();
- const attached = ctx.attachments.attached();
- const model_ = ctx.model();
- props.setState.setText(input);
+ const inputText = chatMarkdownArea.markdownText();
+ const attached = input.attachments.attached();
+ const model_ = input.model();
+ props.setState.setText(inputText);
props.setState.setAttachments(attached);
props.setState.setModel(model_);
});
@@ -413,40 +445,23 @@ export function Rightbar(props: {
<div class="overflow-hidden size-full flex flex-col items-center relative">
<div class="absolute inset-0 pointer-events-none" use:droppable />
<TopBar
- chatId={ctx.chatId()}
+ chatId={props.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={ctx.messages!().length === 0}>
- <div class="h-full flex flex-col items-center justify-center">
- <AiChatEmptyState />
- </div>
- </Show>
- <Show when={ctx.messages!().length > 0 || !props.isBig}>
- <div class="relative flex-1 min-h-0 w-full">
- <div
- data-chat-scroll
- class="size-full overflow-y-auto overflow-x-hidden scroll-smooth flex justify-center scrollbar-hidden"
- ref={setMessagesContainerRef}
- >
- <div class="w-full macro-message-width">
- <ChatMessages messageActions={undefined} />
- </div>
- </div>
- <CustomScrollbar scrollContainer={messagesContainerRef} />
- </div>
- </Show>
+ {props.children}
<div class="w-full">
<div class="flex-shrink-0 pt-2 macro-message-width mx-auto">
<ChatInput
markdown={chatMarkdownArea}
+ chatId={props.chatId}
isPersistent
showActiveTabs
onSend={props.onSend}
- onStop={stopGenerating}
+ onStop={props.stopGenerating}
captureEditor={setEditor}
/>
</div>
@@ -711,14 +726,9 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {
tr={!bigChatOpen() && !settingsOpen()}
>
<Suspense>
- <ChatContextProvider
- external={{
- chatId: [chatId, setChatId],
- messages: [messages, setMessages],
- stream: [stream, setStream],
- }}
- >
+ <ChatInputProvider>
<Rightbar
+ chatId={chatId()}
chatName={chatName()}
onUnmount={getChatInputState}
initialState={initialChatState()}
@@ -732,8 +742,29 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {
setText,
}}
isBig={bigChatOpen()}
- />
- </ChatContextProvider>
+ >
+ <Show
+ when={chatId()}
+ fallback={
+ <div class="h-full flex flex-col items-center justify-center">
+ <AiChatEmptyState />
+ </div>
+ }
+ >
+ {(id) => (
+ <ChatProvider
+ chatId={id()}
+ external={{
+ messages: [messages, setMessages],
+ stream: [stream, setStream],
+ }}
+ >
+ <RightbarChatArea isBig={bigChatOpen()} />
+ </ChatProvider>
+ )}
+ </Show>
+ </Rightbar>
+ </ChatInputProvider>
</Suspense>
</SplitlikeContainer>
</div>
diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsx
index 88d0f5bc59..4ae9e87771 100644
--- a/js/app/packages/block-chat/component/Chat.tsx
+++ b/js/app/packages/block-chat/component/Chat.tsx
@@ -8,8 +8,10 @@ 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,
+ ChatInputProvider,
+ ChatProvider,
useChatContext,
+ useChatInputContext,
} from '@core/component/AI/context';
import { useEntityDropAttachment } from '@core/component/AI/hook/useEntityDropAttachment';
import { getPendingSend } from '@core/component/AI/signal/pendingSend';
@@ -47,14 +49,17 @@ 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}
+ <ChatInputProvider
initialAttachments={loadedState.attachments}
model={loadedState.model}
>
- <ChatInner data={props.data} loadedInputText={loadedState.input} />
- </ChatContextProvider>
+ <ChatProvider
+ chatId={props.data.chat.id}
+ messages={props.data.chat.messages}
+ >
+ <ChatInner data={props.data} loadedInputText={loadedState.input} />
+ </ChatProvider>
+ </ChatInputProvider>
);
}
@@ -62,7 +67,8 @@ function ChatInner(props: {
data: ChatData;
loadedInputText: string | undefined;
}) {
- const ctx = useChatContext();
+ const input = useChatInputContext();
+ const chat = useChatContext();
const canEdit = useCanEdit();
const disabled = () => !canEdit();
const scopeId = blockHotkeyScopeSignal.get;
@@ -73,7 +79,7 @@ function ChatInner(props: {
const chatMarkdownArea = useChatMarkdownArea({
initialValue: props.loadedInputText,
- addAttachment: (a) => ctx.attachments.addAttachment(a),
+ addAttachment: (a) => input.attachments.addAttachment(a),
});
// Local stream signal for cancelStream and registerToolHandler
@@ -94,7 +100,7 @@ function ChatInner(props: {
const chatId = useBlockId();
const { droppable, isDraggingOver } = useEntityDropAttachment(
'chat-input-' + chatId,
- ctx.attachments
+ input.attachments
);
false && droppable;
@@ -111,16 +117,16 @@ function ChatInner(props: {
return onSend(response);
}
} else {
- ctx.addMessage!({
+ chat.addMessage({
attachments: request.request.attachments ?? [],
content: request.request.content,
role: 'user',
id: '',
});
const stream = request.call();
- ctx.setStream!(stream);
+ chat.setStream(stream);
setStream(stream);
- ctx.setIsGenerating(true);
+ input.setIsGenerating(true);
invalidateUserQuota();
createEffect(() => {
if (stream.data().length > 0) {
@@ -129,7 +135,7 @@ function ChatInner(props: {
});
createEffect(() => {
if (stream.isDone()) {
- ctx.setIsGenerating(false);
+ input.setIsGenerating(false);
invalidateUserQuota();
}
});
@@ -141,10 +147,10 @@ function ChatInner(props: {
};
createEffect(() => {
- const input = chatMarkdownArea.markdownText();
- const attached = ctx.attachments.attached();
- const model_ = ctx.model();
- saveChatState({ attachments: attached, input, model: model_ });
+ const inputText = chatMarkdownArea.markdownText();
+ const attached = input.attachments.attached();
+ const model_ = input.model();
+ saveChatState({ attachments: attached, input: inputText, model: model_ });
});
const setPendingLocation = pendingLocationParamsSignal.set;
@@ -224,6 +230,7 @@ function ChatInner(props: {
<div class="w-3xl">
<ChatInput
markdown={chatMarkdownArea}
+ chatId={chat.chatId()}
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 543f9e38c7..e5de3fd5d5 100644
--- a/js/app/packages/core/component/AI/component/DragDrop.tsx
+++ b/js/app/packages/core/component/AI/component/DragDrop.tsx
@@ -5,7 +5,7 @@ import { fileDrop } from '@core/directive/fileDrop';
const { track, TrackingEvents } = withAnalytics();
import { SUPPORTED_ATTACHMENT_EXTENSIONS } from '@core/component/AI/constant';
-import { useChatContext } from '@core/component/AI/context';
+import { useChatInputContext } from '@core/component/AI/context';
import type { Accessor, Component, ParentProps } from 'solid-js';
import { createSignal, Show } from 'solid-js';
@@ -23,8 +23,8 @@ 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 input = useChatInputContext();
+ const uploadQueue = input.uploadQueue;
const [isFileDragging, setIsFileDragging] = createSignal(false);
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 c7984f36dc..8a9356259a 100644
--- a/js/app/packages/core/component/AI/component/debug/Component.tsx
+++ b/js/app/packages/core/component/AI/component/debug/Component.tsx
@@ -6,7 +6,12 @@ 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 {
+ ChatInputProvider,
+ ChatProvider,
+ useChatContext,
+ useChatInputContext,
+} from '../../context';
import { useAttachments } from '../../signal/attachment';
import { pausableStream } from '../../util/stream';
import { ChatInput } from '../input/useChatInput';
@@ -86,16 +91,16 @@ function ChatModelSelector() {
function ChatInputBox() {
return (
- <ChatContextProvider>
+ <ChatInputProvider>
<ChatInputBoxInner />
- </ChatContextProvider>
+ </ChatInputProvider>
);
}
function ChatInputBoxInner() {
- const ctx = useChatContext();
+ const input = useChatInputContext();
const chatMarkdownArea = useChatMarkdownArea({
- addAttachment: (a) => ctx.attachments.addAttachment(a),
+ addAttachment: (a) => input.attachments.addAttachment(a),
});
return (
@@ -103,12 +108,12 @@ function ChatInputBoxInner() {
<div class="w-full h-full">
<div class="flex gap-2 py-2">
<DeprecatedTextButton
- onClick={() => ctx.setIsGenerating(true)}
+ onClick={() => input.setIsGenerating(true)}
theme="accent"
text="Generate"
/>
<DeprecatedTextButton
- onClick={() => ctx.setIsGenerating(false)}
+ onClick={() => input.setIsGenerating(false)}
theme="accent"
text="Stop"
/>
@@ -124,16 +129,16 @@ function ChatInputBoxInner() {
function ChatInputBoxConnected() {
return (
- <ChatContextProvider>
+ <ChatInputProvider>
<ChatInputBoxConnectedInner />
- </ChatContextProvider>
+ </ChatInputProvider>
);
}
function ChatInputBoxConnectedInner() {
- const ctx = useChatContext();
+ const input = useChatInputContext();
const chatMarkdownArea = useChatMarkdownArea({
- addAttachment: (a) => ctx.attachments.addAttachment(a),
+ addAttachment: (a) => input.attachments.addAttachment(a),
});
const [_gen, setGen] = createSignal(false);
@@ -170,14 +175,16 @@ function ChatInputBoxConnectedInner() {
function StreamMessages() {
return (
- <ChatContextProvider messages={[]}>
- <StreamMessagesInner />
- </ChatContextProvider>
+ <ChatInputProvider>
+ <ChatProvider chatId="debug" messages={[]}>
+ <StreamMessagesInner />
+ </ChatProvider>
+ </ChatInputProvider>
);
}
function StreamMessagesInner() {
- const ctx = useChatContext();
+ const chat = useChatContext();
const [stream, setStream] = createSignal<MessageStream>();
const makeStream = () => delayStream(poem(), slowFirst);
@@ -188,7 +195,7 @@ function StreamMessagesInner() {
onClick={() => {
const poemStream = makeStream();
setStream(poemStream);
- ctx.setStream!(poemStream);
+ chat.setStream(poemStream);
}}
>
Stream
@@ -205,28 +212,33 @@ function StaticMessages() {
const messages = simpleMessageChain();
console.log(JSON.stringify(messages, null, 2));
return (
- <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>
+ <ChatInputProvider>
+ <ChatProvider chatId="debug" 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>
+ </ChatProvider>
+ </ChatInputProvider>
);
}
function FullChat() {
return (
- <ChatContextProvider messages={[]}>
- <FullChatInner />
- </ChatContextProvider>
+ <ChatInputProvider>
+ <ChatProvider chatId="debug" messages={[]}>
+ <FullChatInner />
+ </ChatProvider>
+ </ChatInputProvider>
);
}
function FullChatInner() {
- const ctx = useChatContext();
+ const input = useChatInputContext();
+ const chat = useChatContext();
const chatMarkdownArea = useChatMarkdownArea({
- addAttachment: (a) => ctx.attachments.addAttachment(a),
+ addAttachment: (a) => input.attachments.addAttachment(a),
});
const [_isGen, setIsGen] = createSignal(false);
const [stream, setDebugStream] = createSignal<MessageStream>();
@@ -242,7 +254,7 @@ function FullChatInner() {
return onSend(response);
}
} else {
- ctx.addMessage!({
+ chat.addMessage({
attachments: request.request.attachments ?? [],
content: request.request.content,
role: 'user',
@@ -250,7 +262,7 @@ function FullChatInner() {
});
const stream = request.call();
console.log('set stream');
- ctx.setStream!(stream);
+ chat.setStream(stream);
setDebugStream(stream);
setIsGen(true);
createEffect(() => {
@@ -278,6 +290,7 @@ function FullChatInner() {
<ChatMessages />
<ChatInput
markdown={chatMarkdownArea}
+ chatId={chat.chatId()}
onSend={onSend}
onStop={() => {}}
/>
@@ -293,15 +306,17 @@ function ToolCallRender() {
]);
return (
- <ChatContextProvider messages={initialMessages}>
- <ToolCallRenderInner stream={stream} />
- </ChatContextProvider>
+ <ChatInputProvider>
+ <ChatProvider chatId="debug" messages={initialMessages}>
+ <ToolCallRenderInner stream={stream} />
+ </ChatProvider>
+ </ChatInputProvider>
);
}
function ToolCallRenderInner(props: { stream: MessageStream }) {
- const ctx = useChatContext();
- ctx.setStream!(props.stream);
+ const chat = useChatContext();
+ chat.setStream(props.stream);
return (
<Item label="Tool call - static">
@@ -424,14 +439,16 @@ function TableStream() {
]);
return (
- <ChatContextProvider messages={initialMessages}>
- <TableStreamInner />
- </ChatContextProvider>
+ <ChatInputProvider>
+ <ChatProvider chatId="debug" messages={initialMessages}>
+ <TableStreamInner />
+ </ChatProvider>
+ </ChatInputProvider>
);
}
function TableStreamInner() {
- const ctx = useChatContext();
+ const chat = useChatContext();
const [isPaused, setIsPaused] = createSignal(false);
const [isSlow, setIsSlow] = createSignal(false);
const [showRaw, setShowRaw] = createSignal(false);
@@ -439,8 +456,8 @@ function TableStreamInner() {
const [rawText, setRawText] = createSignal('');
const startStream = () => {
- ctx.setMessages!([]);
- ctx.setStream!(undefined);
+ chat.setMessages([]);
+ chat.setStream(undefined);
setRawText('');
const baseStream = table();
const controlled = pausableStream(baseStream, {
@@ -449,7 +466,7 @@ function TableStreamInner() {
onChunk: (text) => setRawText((prev) => prev + text),
});
setStream(controlled);
- ctx.setStream!(controlled);
+ chat.setStream(controlled);
};
return (
@@ -487,8 +504,8 @@ function TableStreamInner() {
onClick={() => {
setStream(undefined);
setRawText('');
- ctx.setMessages!([]);
- ctx.setStream!(undefined);
+ chat.setMessages([]);
+ chat.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 0ec47ecfb2..7b189d6241 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,11 @@ 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 { ChatContextProvider, useChatContext } from '../../../context';
+import {
+ ChatInputProvider,
+ ChatProvider,
+ useChatContext,
+} from '../../../context';
import { ChatMessages } from '../../message/ChatMessages';
import { StreamStatus } from './StreamStatus';
@@ -12,12 +16,14 @@ export function StreamDebuggerWithControls(props: {
autoStart?: true;
}) {
return (
- <ChatContextProvider messages={props.messages ?? []}>
- <StreamDebuggerWithControlsInner
- stream={props.stream}
- autoStart={props.autoStart}
- />
- </ChatContextProvider>
+ <ChatInputProvider>
+ <ChatProvider chatId="debug" messages={props.messages ?? []}>
+ <StreamDebuggerWithControlsInner
+ stream={props.stream}
+ autoStart={props.autoStart}
+ />
+ </ChatProvider>
+ </ChatInputProvider>
);
}
@@ -25,12 +31,12 @@ function StreamDebuggerWithControlsInner(props: {
stream: () => MessageStream;
autoStart?: true;
}) {
- const ctx = useChatContext();
+ const chat = useChatContext();
const [stream, setStream] = createSignal<MessageStream>();
if (props.autoStart) {
setStream(props.stream());
- ctx.setStream!(props.stream());
+ chat.setStream(props.stream());
}
return (
@@ -41,7 +47,7 @@ function StreamDebuggerWithControlsInner(props: {
onClick={() => {
const stream = props.stream();
setStream(stream);
- ctx.setStream!(stream);
+ chat.setStream(stream);
}}
theme="accent"
/>
@@ -50,8 +56,8 @@ function StreamDebuggerWithControlsInner(props: {
theme="accent"
onClick={() => {
setStream(undefined);
- ctx.setMessages!([]);
- ctx.setStream!(undefined);
+ chat.setMessages([]);
+ chat.setStream(undefined);
}}
/>
</div>
@@ -68,15 +74,17 @@ export function StreamDebugger(props: {
messages?: ChatMessageWithAttachments[];
}) {
return (
- <ChatContextProvider messages={props.messages ?? []}>
- <StreamDebuggerInner stream={props.stream} />
- </ChatContextProvider>
+ <ChatInputProvider>
+ <ChatProvider chatId="debug" messages={props.messages ?? []}>
+ <StreamDebuggerInner stream={props.stream} />
+ </ChatProvider>
+ </ChatInputProvider>
);
}
function StreamDebuggerInner(props: { stream: MessageStream }) {
- const ctx = useChatContext();
- ctx.setStream!(props.stream);
+ const chat = useChatContext();
+ chat.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 a5f3e21625..6b66e805e8 100644
--- a/js/app/packages/core/component/AI/component/input/ChatAttachMenu.tsx
+++ b/js/app/packages/core/component/AI/component/input/ChatAttachMenu.tsx
@@ -1,6 +1,6 @@
import { withAnalytics } from '@coparse/analytics';
import { SUPPORTED_ATTACHMENT_EXTENSIONS } from '@core/component/AI/constant';
-import { useChatContext } from '@core/component/AI/context';
+import { useChatInputContext } from '@core/component/AI/context';
import {
useChatAttachableHistory,
useGetChatAttachmentInfo,
@@ -56,8 +56,8 @@ 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 chatInput = useChatInputContext();
+ const uploadQueue = chatInput.uploadQueue;
const [position, setPosition] = createSignal({ x: 0, y: 0 });
const [popupRef, setPopupRef] = createSignal<HTMLDivElement>();
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 84fd0ceb84..c814d072c3 100644
--- a/js/app/packages/core/component/AI/component/input/useChatInput.tsx
+++ b/js/app/packages/core/component/AI/component/input/useChatInput.tsx
@@ -1,7 +1,7 @@
import { withAnalytics } from '@coparse/analytics';
import { useBuildChatSendRequest } from '@core/component/AI/component/input/buildRequest';
import { SMART_MODE_MODEL } from '@core/component/AI/constant';
-import { useChatContext } from '@core/component/AI/context';
+import { useChatInputContext } from '@core/component/AI/context';
import { useChatAttachableHistory } from '@core/component/AI/signal/attachment';
import type {
CreateAndSend,
@@ -39,6 +39,7 @@ export type ChatInputProps = {
showActiveTabs?: boolean;
captureEditor?: (editor: LexicalEditor) => void;
autoFocusOnMount?: boolean;
+ chatId?: string;
};
export type ChatInputComponentProps = {
@@ -46,12 +47,11 @@ export type ChatInputComponentProps = {
} & ChatInputProps;
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;
+ const input = useChatInputContext();
+ const uploadQueue = input.uploadQueue;
+ const attachments = input.attachments;
+ const model = input.model;
+ const generating = input.isGenerating;
let containerRef!: HTMLDivElement;
const toolsetSignal = createSignal<ToolSet>({ type: 'all' });
@@ -98,7 +98,7 @@ export function ChatInput(props: ChatInputComponentProps) {
}
const request = await buildChatSendRequest({
- chatId: chatId(),
+ chatId: props.chatId,
userRequest: props.markdown.markdownText(),
isPersistent: props.isPersistent,
attachments: attachments.attached(),
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 a1e6b250fb..6a7e354476 100644
--- a/js/app/packages/core/component/AI/component/message/ChatMessages.tsx
+++ b/js/app/packages/core/component/AI/component/message/ChatMessages.tsx
@@ -55,13 +55,13 @@ function messageContentIsEmpty(message: ChatMessageWithAttachments) {
}
export function ChatMessages(props: ChatMessagesProps) {
- 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 chat = useChatContext();
+ const [messages, setMessages] = [chat.messages, chat.setMessages];
+ const streamTuple: [
+ Accessor<MessageStream | undefined>,
+ Setter<MessageStream | undefined>,
+ ] = [chat.stream, chat.setStream];
+ const chatId = chat.chatId;
const extendedStream = createMemo(() => {
const s = streamTuple?.[0]?.();
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 ab234ff19b..9e858b5f81 100644
--- a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx
+++ b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx
@@ -1,24 +1,25 @@
-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 {
+ ChatInputProvider,
+ useChatInputContext,
+} from '@core/component/AI/context';
import type { Attachment, Model, Send } from '@core/component/AI/types';
import { asEditRequest } from '@core/component/AI/types/util';
import { onMount } from 'solid-js';
function EditableChatMessageInner(props: {
+ chatId: string;
initialText: string;
attachments: Attachment[];
onAccept: (r: Send) => void;
onCancel: () => void;
model: Model;
}) {
- const ctx = useChatContext();
+ const input = useChatInputContext();
const chatMarkdownArea = useChatMarkdownArea({
initialValue: props.initialText,
- addAttachment: (a) => ctx.attachments.addAttachment(a),
+ addAttachment: (a) => input.attachments.addAttachment(a),
});
onMount(() => {
@@ -35,6 +36,7 @@ function EditableChatMessageInner(props: {
<div onKeyDown={handleKey} class="w-full">
<ChatInput
markdown={chatMarkdownArea}
+ chatId={props.chatId}
onSend={(request) => {
if (request.type === 'send') props.onAccept(asEditRequest(request));
}}
@@ -52,19 +54,19 @@ export function EditableChatMessage(props: {
model: Model;
}) {
return (
- <ChatContextProvider
- chatId={props.chatId}
+ <ChatInputProvider
model={props.model}
isGenerating={false}
initialAttachments={props.attachments}
>
<EditableChatMessageInner
+ chatId={props.chatId}
initialText={props.initialText}
attachments={props.attachments}
onAccept={props.onAccept}
onCancel={props.onCancel}
model={props.model}
/>
- </ChatContextProvider>
+ </ChatInputProvider>
);
}
diff --git a/js/app/packages/core/component/AI/context/ChatContext.tsx b/js/app/packages/core/component/AI/context/ChatContext.tsx
index 47ca44287c..2928d1b166 100644
--- a/js/app/packages/core/component/AI/context/ChatContext.tsx
+++ b/js/app/packages/core/component/AI/context/ChatContext.tsx
@@ -11,89 +11,46 @@ import type {
} from '@core/component/AI/types';
import { useUploadAttachment } from '@core/component/AI/util/uploadToChat';
import { ENABLE_AI_AUTO_TAB_ATTACHMENTS } from '@core/constant/featureFlags';
+import type { Accessor, ParentProps, Setter } from 'solid-js';
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
+ createContext,
+ createEffect,
+ createSignal,
+ on,
+ useContext,
+} from 'solid-js';
+
+// ---- Uncreated state (always present) ----
+
+export type ChatInputState = {
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>,
- ];
- };
-};
+const ChatInputCtx = createContext<ChatInputState>();
-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;
+export function ChatInputProvider(
+ props: ParentProps & {
+ model?: Model;
+ isGenerating?: boolean;
+ initialAttachments?: Attachment[];
+ autoAttach?: boolean;
}
-
- // --- 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(
@@ -110,66 +67,109 @@ function createChatContext(props: ChatContextProviderProps): ChatContextValue {
);
}
- // --- 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;
+ return (
+ <ChatInputCtx.Provider
+ value={{
+ model,
+ setModel,
+ isGenerating,
+ setIsGenerating,
+ attachments,
+ uploadQueue,
+ }}
+ >
+ {props.children}
+ </ChatInputCtx.Provider>
+ );
+}
+
+export function useChatInputContext(): ChatInputState {
+ const ctx = useContext(ChatInputCtx);
+ if (!ctx) {
+ throw new Error(
+ 'useChatInputContext must be used within <ChatInputProvider />'
+ );
+ }
+ return ctx;
+}
+
+// ---- Created state (only when chat exists) ----
+
+export type ChatState = {
+ chatId: Accessor<string>;
+ messages: Accessor<ChatMessageWithAttachments[]>;
+ setMessages: Setter<ChatMessageWithAttachments[]>;
+ addMessage: (msg: ChatMessageWithAttachments) => void;
+ stream: Accessor<MessageStream | undefined>;
+ setStream: Setter<MessageStream | undefined>;
+};
+
+const ChatCtx = createContext<ChatState>();
+
+export function ChatProvider(
+ props: ParentProps & {
+ chatId: string;
+ messages?: ChatMessageWithAttachments[];
+ external?: {
+ messages: [
+ Accessor<ChatMessageWithAttachments[]>,
+ Setter<ChatMessageWithAttachments[]>,
+ ];
+ stream: [
+ Accessor<MessageStream | undefined>,
+ Setter<MessageStream | undefined>,
+ ];
+ };
+ }
+) {
+ let messages: Accessor<ChatMessageWithAttachments[]>;
+ let setMessages: Setter<ChatMessageWithAttachments[]>;
+ let stream: Accessor<MessageStream | undefined>;
+ let setStream: Setter<MessageStream | 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) {
+ } else {
const [_messages, _setMessages] = createSignal<
ChatMessageWithAttachments[]
- >(props.messages);
+ >(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);
+ const _setMessages = setMessages;
+ const addMessage = (msg: ChatMessageWithAttachments) => {
+ _setMessages((p) => [...p, msg]);
+ };
-export { ChatContextProvider };
+ return (
+ <ChatCtx.Provider
+ value={{
+ chatId: () => props.chatId,
+ messages,
+ setMessages,
+ addMessage,
+ stream,
+ setStream,
+ }}
+ >
+ {props.children}
+ </ChatCtx.Provider>
+ );
+}
-export function useChatContext(): ChatContextValue {
- const ctx = useContextInternal();
- if (ctx === undefined) {
- throw new Error(
- 'useChatContext must be used within <ChatContextProvider />'
- );
+export function useChatContext(): ChatState {
+ const ctx = useContext(ChatCtx);
+ if (!ctx) {
+ throw new Error('useChatContext must be used within <ChatProvider />');
}
return ctx;
}
-export function useChatContextOptional(): ChatContextValue | undefined {
- return useContextInternal();
+export function useChatContextOptional(): ChatState | undefined {
+ return useContext(ChatCtx);
}
diff --git a/js/app/packages/core/component/AI/context/index.ts b/js/app/packages/core/component/AI/context/index.ts
index bbc65d6661..d3ee04ddfe 100644
--- a/js/app/packages/core/component/AI/context/index.ts
+++ b/js/app/packages/core/component/AI/context/index.ts
@@ -1,7 +1,9 @@
export {
- ChatContextProvider,
+ ChatInputProvider,
+ useChatInputContext,
+ ChatProvider,
useChatContext,
useChatContextOptional,
- type ChatContextValue,
- type ChatContextProviderProps,
+ type ChatInputState,
+ type ChatState,
} from './ChatContext';