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): chat state management (#2184)

Eric Hayes85fde88a7dd1
diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsx
index 82be53192d..be5510ab03 100644
--- a/js/app/packages/block-chat/component/Chat.tsx
+++ b/js/app/packages/block-chat/component/Chat.tsx
@@ -49,6 +49,7 @@ import { createEffect, createSignal, Show } from 'solid-js';
export function Chat(props: { data: ChatData }) {
const loadedState = getChatInputStoredState(props.data.chat.id);
+ const { showPaywall } = usePaywallState();
return (
<ChatInputProvider
@@ -58,6 +59,7 @@ export function Chat(props: { data: ChatData }) {
<ChatProvider
chatId={props.data.chat.id}
messages={props.data.chat.messages}
+ controllerOptions={{ onShowPaywall: showPaywall }}
>
<ChatInner data={props.data} loadedInputText={loadedState.input} />
</ChatProvider>
@@ -96,16 +98,10 @@ function ChatInner(props: {
useSnapshotForDocuments: ENABLE_SNAPSHOT_NODE,
});
- // Local stream signal for registerToolHandler
-
+ // Sync isGenerating from controller phase
createEffect(() => {
- const chatStream = chat.stream();
- if (!chatStream || chatStream.isDone()) {
- input.setIsGenerating(false);
- return;
- }
- input.setIsGenerating(true);
- if (chatStream.data().length > 0) invalidateUserQuota();
+ input.setIsGenerating(chat.isGenerating());
+ if (chat.isGenerating()) invalidateUserQuota();
});
const blockHandle = blockHandleSignal.get;
@@ -123,21 +119,23 @@ function ChatInner(props: {
if (!s) return undefined;
return { data: s.data };
});
- const { showPaywall } = usePaywallState();
const sendChatMessage = useSendChatMessage();
const renameMutation = createRenameDssEntityMutation();
const onSend = createCallback(async (request: ChatSendInput) => {
const isFirstMessage = chat.messages().length === 0;
+ const optimisticId = crypto.randomUUID();
- chat.addMessage({
- id: crypto.randomUUID(),
- content: request.content,
- role: 'user',
- attachments: request.attachments ?? [],
+ chat.dispatch({
+ type: 'send_started',
+ optimisticMessage: {
+ id: optimisticId,
+ content: request.content,
+ role: 'user',
+ attachments: request.attachments ?? [],
+ },
});
- chat.setWaitingForStream(true);
if (isFirstMessage) {
const name = deriveChatName(request.content);
@@ -154,15 +152,15 @@ function ChatInner(props: {
chatId: chat.chatId(),
});
- chat.setWaitingForStream(false);
-
if ('error' in result) {
- if (result.paymentError) showPaywall();
+ chat.dispatch({
+ type: 'send_failed',
+ paymentError: result.paymentError,
+ });
return;
}
- chat.setStream(result.stream);
- input.setIsGenerating(true);
+ chat.attachStream(result.stream);
invalidateUserQuota();
});
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 9e875546d2..c58e195d3e 100644
--- a/js/app/packages/core/component/AI/component/debug/Component.tsx
+++ b/js/app/packages/core/component/AI/component/debug/Component.tsx
@@ -232,12 +232,15 @@ function FullChatInner() {
const [debugStream, _setDebugStream] = createSignal<ChatMessageStream>();
const onSend = async (input: ChatSendInput) => {
- chat.addMessage({
- attachments: input.attachments,
- content: input.content,
- role: 'user',
- id: '',
- });
+ chat.setMessages((p) => [
+ ...p,
+ {
+ attachments: input.attachments,
+ content: input.content,
+ role: 'user',
+ id: '',
+ },
+ ]);
const response = await cognitionApiServiceClient.sendStreamChatMessage({
content: input.content,
model: input.model,
diff --git a/js/app/packages/core/component/AI/component/input/ChatInput.tsx b/js/app/packages/core/component/AI/component/input/ChatInput.tsx
index 37ccc89e45..95a7048d3e 100644
--- a/js/app/packages/core/component/AI/component/input/ChatInput.tsx
+++ b/js/app/packages/core/component/AI/component/input/ChatInput.tsx
@@ -1,12 +1,13 @@
+import { useAnalytics } from '@app/component/analytics-context';
import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';
import { useChatInputContext } from '@core/component/AI/context';
import type { Model, ToolSet } from '@core/component/AI/types';
-import type { EditorConfigBuilder } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
-import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
import { Hotkey } from '@core/component/Hotkey';
-import { Tooltip } from '@core/component/Tooltip';
+import type { EditorConfigBuilder } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
import { toast } from '@core/component/Toast/Toast';
+import { Tooltip } from '@core/component/Tooltip';
import { isMobile } from '@core/mobile/isMobile';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -22,7 +23,6 @@ import { createEffect, createSignal, Match, Show, Switch } from 'solid-js';
import { AttachmentList } from './Attachment';
import { ChatAttachMenu } from './ChatAttachMenu';
import { useAiDataConsentGate } from './useAiDataConsent';
-import { useAnalytics } from '@app/component/analytics-context';
export type ChatInputProps = {
onSend: (args: ChatSendInput) => void;
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 cbe7ebc9a9..fe879b286c 100644
--- a/js/app/packages/core/component/AI/component/message/ChatMessages.tsx
+++ b/js/app/packages/core/component/AI/component/message/ChatMessages.tsx
@@ -1,13 +1,11 @@
import { useChatContext } from '@core/component/AI/context';
import type { ChatMessageWithAttachments } from '@core/component/AI/types';
import { asChatMessage } from '@core/component/AI/util/message';
-import { toast } from '@core/component/Toast/Toast';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { aiChatTheme } from '@core/component/LexicalMarkdown/theme';
import { PulsingStar } from '@entity/components/PulsingStar';
-import type { ChatMessageStream } from '@service-connection/stream';
import { createElementSize } from '@solid-primitives/resize-observer';
-import type { Accessor, JSXElement, Setter } from 'solid-js';
+import type { Accessor, JSXElement } from 'solid-js';
import {
createEffect,
createMemo,
@@ -15,7 +13,6 @@ import {
createSignal,
For,
Match,
- on,
onMount,
Show,
Switch,
@@ -54,62 +51,11 @@ function messageContentIsEmpty(message: ChatMessageWithAttachments) {
export function ChatMessages(props: ChatMessagesProps) {
const chat = useChatContext();
- const [messages, setMessages] = [chat.messages, chat.setMessages];
- const streamTuple: [
- Accessor<ChatMessageStream | undefined>,
- Setter<ChatMessageStream | undefined>,
- ] = [chat.stream, chat.setStream];
- // const chatId = chat.chatId;
- // const additionalInstructions = useAdditionalInstructions();
-
- // const makeEdit = async (data: ChatSendInput) => {
- // const setStream = streamTuple?.[1];
- // if (!setStream) return;
-
- // setMessages((p) => {
- // const last = p.at(-1);
- // if (!last) return p;
- // if (last.role === "user") {
- // return p.slice(0, -1);
- // } else {
- // return p.slice(0, -2);
- // }
- // });
- // setMessages((p) => [
- // ...p,
- // {
- // attachments: data.attachments ?? [],
- // content: data.content,
- // role: "user",
- // model: data.model,
- // id: "todo",
- // },
- // ]);
-
- // const token = await getMacroApiToken();
- // const modelInstructions = data.model ? `\nYou are ${data.model}` : "";
- // const additional = `${additionalInstructions()}${modelInstructions}`;
- // const editStream = cognitionWebsocketServiceClient.streamEditMessage({
- // chat_id: chatId()!,
- // content: data.content,
- // model: data.model ?? DEFAULT_MODEL,
- // attachments: data.attachments ?? [],
- // token,
- // additional_instructions: additional,
- // toolset: data.toolset,
- // });
-
- // setStream({
- // data: editStream.data,
- // isDone: editStream.isDone,
- // id: () => ({
-
- // })
- // });
- // };
+ const messages = chat.messages;
+ const stream = chat.stream;
const extendedStream = createMemo(() => {
- const s = streamTuple?.[0]?.();
+ const s = stream();
if (!s) return;
return timeStream(idStream(s));
});
@@ -117,12 +63,11 @@ export function ChatMessages(props: ChatMessagesProps) {
const [messageTimingMap, setTiming] = createStore<Record<string, number>>({});
createEffect(() => {
- const stream = extendedStream();
- if (!stream) return;
- const ttft = stream.timeToFirstMessageMs();
- const id = stream.messageId();
+ const s = extendedStream();
+ if (!s) return;
+ const ttft = s.timeToFirstMessageMs();
+ const id = s.messageId();
if (id && ttft) {
- console.log('ID TTFT', id, ttft);
setTiming(id, ttft);
}
});
@@ -130,12 +75,10 @@ export function ChatMessages(props: ChatMessagesProps) {
let messagesRef: HTMLDivElement | undefined;
const generatingMessage = () => {
- const streamAccessor = streamTuple?.[0];
- if (!streamAccessor) return;
- const stream = streamAccessor();
- if (!stream) return;
- if (stream.isDone()) return;
- const parts = stream.data();
+ const s = stream();
+ if (!s) return;
+ if (s.isDone()) return;
+ const parts = s.data();
const message = asChatMessage(parts);
if (!message) return;
if (messageContentIsEmpty(message)) return;
@@ -143,92 +86,12 @@ export function ChatMessages(props: ChatMessagesProps) {
};
const isStream = () => {
- const streamSignal = streamTuple?.[0];
- if (!streamSignal) return false;
- const stream = streamSignal();
- if (!stream) return false;
- return !stream.isDone();
+ const s = stream();
+ console.log('isStream', Boolean(s));
+ if (!s) return false;
+ return !s.isDone();
};
- // const streamRequestAttachments = () => {
- // const streamable = streamTuple?.[0];
- // if (!streamable) return [];
- // const stream = streamable();
- // if (!stream) return [];
- // return stream.attachments ?? [];
- // };
-
- const streamData = () => {
- const stream = streamTuple?.[0]?.();
- if (!stream) return [];
- return stream.data();
- };
- // handle stream error
- createEffect(
- on(streamData, (data) => {
- const latest = data.at(-1);
- if (!latest) return;
- if (latest.type !== 'error') return;
-
- const error = 'stream_error' in latest ? latest.stream_error : undefined;
- if (error === 'model_context_overflow') {
- toast.failure(
- 'Too much context. Remove attachments or start a new chat'
- );
- } else {
- toast.failure('Failed to respond to message');
- }
-
- // Clear stream so the isGenerating effect in Chat.tsx resets
- chat.setStream(undefined);
- })
- );
- // when a user message arrives via stream, update optimistic ID or append
- createEffect(
- on(streamData, (data) => {
- const latest = data.at(-1);
- if (!latest) return;
- if (latest.type !== 'chat_user_message') return;
- setMessages((p) => {
- const last = p.at(-1);
- if (last?.role === 'user' && last?.content === latest.content) {
- // Patch the optimistic message with the real server ID
- if (last.id !== latest.message_id) {
- const updated = p.slice();
- updated[updated.length - 1] = { ...last, id: latest.message_id };
- return updated;
- }
- return p;
- }
- return [
- ...p,
- {
- id: latest.message_id,
- content: latest.content,
- role: 'user' as const,
- attachments: latest.attachments,
- },
- ];
- });
- })
- );
-
- // when messages finish streaming, append and scroll
- createEffect(() => {
- if (!streamTuple?.[0]) return;
- const s = streamTuple?.[0]();
- if (!s) return;
- if (s.isDone()) {
- const message = asChatMessage(s.data());
- if (message) {
- setMessages((p) => {
- if (p.find((m) => m.id === message.id)) return p;
- return [...p, message];
- });
- }
- }
- });
-
const [parentHeight, setParentHeight] = createSignal(0);
const selectScroll = () => {
@@ -356,7 +219,7 @@ export function ChatMessages(props: ChatMessagesProps) {
)}
</For>
- <Show when={isStream() || chat.waitingForStream() || lastPair()}>
+ <Show when={isStream() || chat.isWaiting() || lastPair()}>
<div
class="shrink-0"
style={{
@@ -399,7 +262,7 @@ export function ChatMessages(props: ChatMessagesProps) {
);
}}
</Show>
- <Show when={isStream() || chat.waitingForStream()}>
+ <Show when={isStream() || chat.isWaiting()}>
<OnMount
onShow={() =>
scrollToBottom(isNearBottom() ? 'instant' : 'smooth')
diff --git a/js/app/packages/core/component/AI/context/ChatContext.tsx b/js/app/packages/core/component/AI/context/ChatContext.tsx
index 4016359a19..c8c3b6577d 100644
--- a/js/app/packages/core/component/AI/context/ChatContext.tsx
+++ b/js/app/packages/core/component/AI/context/ChatContext.tsx
@@ -10,15 +10,17 @@ 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 { ChatMessageStream } from '@service-connection/stream';
-import { getEntityStreams } from '@service-connection/stream';
-import type { Accessor, ParentProps, Setter } from 'solid-js';
+import {
+ createChatController,
+ type ChatController,
+ type ChatControllerOptions,
+} from '@core/component/AI/state/createChatController';
+import type { Accessor, ParentProps } from 'solid-js';
import {
createContext,
createEffect,
createSignal,
on,
- untrack,
useContext,
} from 'solid-js';
@@ -96,16 +98,7 @@ export function useChatInputContext(): ChatInputState {
// ---- Created state (only when chat exists) ----
-export type ChatState = {
- chatId: Accessor<string>;
- messages: Accessor<ChatMessageWithAttachments[]>;
- setMessages: Setter<ChatMessageWithAttachments[]>;
- addMessage: (msg: ChatMessageWithAttachments) => void;
- stream: Accessor<ChatMessageStream | undefined>;
- setStream: Setter<ChatMessageStream | undefined>;
- waitingForStream: Accessor<boolean>;
- setWaitingForStream: Setter<boolean>;
-};
+export type ChatState = ChatController;
const ChatCtx = createContext<ChatState>();
@@ -113,95 +106,17 @@ export function ChatProvider(
props: ParentProps & {
chatId: string;
messages?: ChatMessageWithAttachments[];
- external?: {
- messages: [
- Accessor<ChatMessageWithAttachments[]>,
- Setter<ChatMessageWithAttachments[]>,
- ];
- stream: [
- Accessor<ChatMessageStream | undefined>,
- Setter<ChatMessageStream | undefined>,
- ];
- waitingForStream?: [Accessor<boolean>, Setter<boolean>];
- };
+ controllerOptions?: ChatControllerOptions;
}
) {
- let messages: Accessor<ChatMessageWithAttachments[]>;
- let setMessages: Setter<ChatMessageWithAttachments[]>;
- let stream: Accessor<ChatMessageStream | undefined>;
- let setStream: Setter<ChatMessageStream | undefined>;
- let waitingForStream: Accessor<boolean>;
- let setWaitingForStream: Setter<boolean>;
-
- if (props.external) {
- [messages, setMessages] = props.external.messages;
- [stream, setStream] = props.external.stream;
- if (props.external.waitingForStream) {
- [waitingForStream, setWaitingForStream] = props.external.waitingForStream;
- } else {
- [waitingForStream, setWaitingForStream] = createSignal(false);
- }
- } else {
- const [_messages, _setMessages] = createSignal<
- ChatMessageWithAttachments[]
- >(props.messages ?? []);
- const [_stream, _setStream] = createSignal<ChatMessageStream>();
- messages = _messages;
- setMessages = _setMessages;
- stream = _stream;
- setStream = _setStream;
- [waitingForStream, setWaitingForStream] = createSignal(false);
- }
-
- const _setMessages = setMessages;
- const addMessage = (msg: ChatMessageWithAttachments) => {
- _setMessages((p) => [...p, msg]);
- };
-
- // --- Reconnect active streams on page refresh ---
- // Reactive to props.chatId (ChatProvider may not remount on chat switch).
- // Uses untrack for stream/messages to only fire on new WS streams or chatId change.
- createEffect(() => {
- const activeStreams = getEntityStreams('chat', props.chatId)();
- const currentStream = untrack(stream);
-
- for (const s of activeStreams) {
- const sid = s.id()?.stream_id;
- if (!sid) {
- console.warn('reject chat stream: no id');
- continue;
- }
- if (currentStream?.isDone() && currentStream?.id()?.stream_id === sid) {
- console.warn('reject chat stream: duplicate stream');
- continue;
- }
-
- const isInMessages = untrack(() => messages().some((m) => m.id === sid));
- if (isInMessages) {
- console.warn('reject chat stream: already has message');
- continue;
- }
-
- setStream(s);
- break;
- }
- });
+ const controller = createChatController(
+ props.chatId,
+ props.messages ?? [],
+ props.controllerOptions
+ );
return (
- <ChatCtx.Provider
- value={{
- chatId: () => props.chatId,
- messages,
- setMessages,
- addMessage,
- stream,
- setStream,
- waitingForStream,
- setWaitingForStream,
- }}
- >
- {props.children}
- </ChatCtx.Provider>
+ <ChatCtx.Provider value={controller}>{props.children}</ChatCtx.Provider>
);
}
diff --git a/js/app/packages/core/component/AI/context/index.ts b/js/app/packages/core/component/AI/context/index.ts
index d3ee04ddfe..e3dd9acacd 100644
--- a/js/app/packages/core/component/AI/context/index.ts
+++ b/js/app/packages/core/component/AI/context/index.ts
@@ -7,3 +7,6 @@ export {
type ChatInputState,
type ChatState,
} from './ChatContext';
+
+export type { ChatPhase, ChatEvent } from '@core/component/AI/state/chatState';
+export type { ChatController } from '@core/component/AI/state/createChatController';
diff --git a/js/app/packages/core/component/AI/state/chatState.ts b/js/app/packages/core/component/AI/state/chatState.ts
new file mode 100644
index 0000000000..7331f3a97b
--- /dev/null
+++ b/js/app/packages/core/component/AI/state/chatState.ts
@@ -0,0 +1,140 @@
+import type { ChatMessageWithAttachments } from '@core/component/AI/types';
+import type { ChatAttachmentWithName } from '@service-cognition/generated/schemas';
+import { match, P } from 'ts-pattern';
+
+// --- Phases ---
+
+export type ChatPhase =
+ | { type: 'idle' }
+ | { type: 'sending'; optimisticMessageId: string }
+ | { type: 'streaming' };
+
+// --- Events ---
+
+export type ChatEvent =
+ | {
+ type: 'send_started';
+ optimisticMessage: ChatMessageWithAttachments;
+ }
+ | { type: 'send_failed'; paymentError?: boolean }
+ | { type: 'stream_connected' }
+ | {
+ type: 'stream_user_message';
+ messageId: string;
+ content: string;
+ attachments: ChatAttachmentWithName[];
+ }
+ | {
+ type: 'stream_done';
+ message: ChatMessageWithAttachments | undefined;
+ }
+ | {
+ type: 'stream_error';
+ streamError: string | undefined;
+ };
+
+export type SideEffect =
+ | { type: 'toast'; message: string }
+ | { type: 'show_paywall' };
+
+// --- Transition result ---
+
+export type TransitionResult = {
+ phase: ChatPhase;
+ messages?: (
+ prev: ChatMessageWithAttachments[]
+ ) => ChatMessageWithAttachments[];
+ effects: SideEffect[];
+};
+
+const rejected = (phase: ChatPhase, event: string): TransitionResult => {
+ console.warn(`chat transition: ${event} from ${phase.type}`);
+ return { phase, effects: [] };
+};
+
+export function transition(
+ phase: ChatPhase,
+ event: ChatEvent
+): TransitionResult {
+ return match([phase, event] as const)
+ .with([{ type: 'idle' }, { type: 'send_started' }], ([, e]) => ({
+ phase: {
+ type: 'sending' as const,
+ optimisticMessageId: e.optimisticMessage.id,
+ },
+ messages: (prev: ChatMessageWithAttachments[]) => [
+ ...prev,
+ e.optimisticMessage,
+ ],
+ effects: [],
+ }))
+
+ .with([{ type: 'sending' }, { type: 'send_failed' }], ([, e]) => ({
+ phase: { type: 'idle' as const },
+ effects: e.paymentError
+ ? ([{ type: 'show_paywall' }] as SideEffect[])
+ : [],
+ }))
+
+ .with(
+ [{ type: P.union('idle', 'sending') }, { type: 'stream_connected' }],
+ () => ({
+ phase: { type: 'streaming' as const },
+ effects: [],
+ })
+ )
+
+ .with(
+ [
+ { type: P.union('sending', 'streaming') },
+ { type: 'stream_user_message' },
+ ],
+ ([, e]) => {
+ return {
+ phase: { type: 'streaming' as const },
+ messages: (prev: ChatMessageWithAttachments[]) => {
+ if (prev.find((m) => m.role === 'user' && m.content === e.content))
+ return prev;
+ return [
+ ...prev,
+ {
+ id: e.messageId,
+ content: e.content,
+ role: 'user' as const,
+ attachments: e.attachments,
+ },
+ ];
+ },
+ effects: [],
+ };
+ }
+ )
+
+ .with([{ type: 'streaming' }, { type: 'stream_done' }], ([, e]) => ({
+ phase: { type: 'idle' as const },
+ messages: e.message
+ ? (prev: ChatMessageWithAttachments[]) => {
+ if (prev.find((m) => m.id === e.message!.id)) return prev;
+ return [...prev, e.message!];
+ }
+ : undefined,
+ effects: [],
+ }))
+
+ .with(
+ [{ type: P.union('streaming', 'sending') }, { type: 'stream_error' }],
+ ([, e]) => ({
+ phase: { type: 'idle' as const },
+ effects: [
+ {
+ type: 'toast' as const,
+ message:
+ e.streamError === 'model_context_overflow'
+ ? 'Too much context. Remove attachments or start a new chat'
+ : 'Failed to respond to message',
+ },
+ ],
+ })
+ )
+ .otherwise(([p, e]) => rejected(p, e.type));
+}
diff --git a/js/app/packages/core/component/AI/state/createChatController.ts b/js/app/packages/core/component/AI/state/createChatController.ts
new file mode 100644
index 0000000000..38eaac800e
--- /dev/null
+++ b/js/app/packages/core/component/AI/state/createChatController.ts
@@ -0,0 +1,149 @@
+import type { ChatMessageWithAttachments } from '@core/component/AI/types';
+import { asChatMessage } from '@core/component/AI/util/message';
+import { toast } from '@core/component/Toast/Toast';
+import type { ChatMessageStream } from '@service-connection/stream';
+import { getEntityStreams } from '@service-connection/stream';
+import type { Accessor, Setter } from 'solid-js';
+import { createEffect, createSignal, on, untrack } from 'solid-js';
+import { match } from 'ts-pattern';
+import {
+ type ChatEvent,
+ type ChatPhase,
+ type SideEffect,
+ transition,
+} from './chatState';
+
+export type ChatController = {
+ chatId: Accessor<string>;
+ phase: Accessor<ChatPhase>;
+ messages: Accessor<ChatMessageWithAttachments[]>;
+ setMessages: Setter<ChatMessageWithAttachments[]>;
+ stream: Accessor<ChatMessageStream | undefined>;
+ isGenerating: Accessor<boolean>;
+ isWaiting: Accessor<boolean>;
+
+ dispatch: (event: ChatEvent) => void;
+ attachStream: (stream: ChatMessageStream) => void;
+ /** Escape hatch for debug components that set stream directly */
+ setStream: Setter<ChatMessageStream | undefined>;
+};
+
+export type ChatControllerOptions = {
+ onShowPaywall?: () => void;
+};
+
+export function createChatController(
+ chatId: string,
+ initialMessages: ChatMessageWithAttachments[],
+ options?: ChatControllerOptions
+): ChatController {
+ const [phase, setPhase] = createSignal<ChatPhase>({ type: 'idle' });
+ const [messages, setMessages] =
+ createSignal<ChatMessageWithAttachments[]>(initialMessages);
+ const [stream, setStream] = createSignal<ChatMessageStream>();
+
+ function executeEffects(effects: SideEffect[]) {
+ for (const effect of effects) {
+ match(effect)
+ .with({ type: 'toast' }, (e) => toast.failure(e.message))
+ .with({ type: 'show_paywall' }, () => options?.onShowPaywall?.())
+ .exhaustive();
+ }
+ }
+
+ function dispatch(event: ChatEvent) {
+ const result = transition(untrack(phase), event);
+ setPhase(result.phase);
+ if (result.messages) {
+ setMessages(result.messages);
+ }
+ // Clear stream on transition to idle
+ if (result.phase.type === 'idle' && untrack(stream)) {
+ setStream(undefined);
+ }
+ executeEffects(result.effects);
+ }
+
+ function attachStream(newStream: ChatMessageStream) {
+ setStream(newStream);
+ dispatch({ type: 'stream_connected' });
+
+ // Watch stream data for user messages and errors
+ createEffect(
+ on(
+ () => newStream.data(),
+ (data) => {
+ const latest = data.at(-1);
+ if (!latest) return;
+
+ if (latest.type === 'error') {
+ const streamError =
+ 'stream_error' in latest ? latest.stream_error : undefined;
+ dispatch({
+ type: 'stream_error',
+ streamError: streamError as string | undefined,
+ });
+ return;
+ }
+
+ if (latest.type === 'chat_user_message') {
+ dispatch({
+ type: 'stream_user_message',
+ messageId: latest.message_id,
+ content: latest.content,
+ attachments: latest.attachments,
+ });
+ }
+ }
+ )
+ );
+
+ // Watch stream completion
+ createEffect(() => {
+ if (!newStream.isDone()) return;
+ const message = asChatMessage(newStream.data());
+ dispatch({ type: 'stream_done', message });
+ });
+ }
+
+ // Reconnect active streams on page refresh / chat switch
+ createEffect(() => {
+ const activeStreams = getEntityStreams('chat', chatId)();
+ const currentStream = untrack(stream);
+
+ for (const s of activeStreams) {
+ const sid = s.id()?.stream_id;
+ if (!sid) {
+ console.warn('reject chat stream: no id');
+ continue;
+ }
+ if (currentStream?.isDone() && currentStream?.id()?.stream_id === sid) {
+ console.warn('reject chat stream: duplicate stream');
+ continue;
+ }
+
+ const isInMessages = untrack(() => messages().some((m) => m.id === sid));
+ if (isInMessages) {
+ console.warn('reject chat stream: already has message');
+ continue;
+ }
+
+ attachStream(s);
+ break;
+ }
+ });
+
+ return {
+ chatId: () => chatId,
+ phase,
+ messages,
+ setMessages,
+ stream,
+ isGenerating: () => phase().type === 'streaming',
+ isWaiting: () => phase().type === 'sending',
+
+ dispatch,
+ attachStream,
+ setStream,
+ };
+}