@assistant-ui/react 0.10.31 → 0.10.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/primitives/message/MessagePartsGroupedByParentId.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n type ComponentType,\n type FC,\n memo,\n PropsWithChildren,\n useMemo,\n} from \"react\";\nimport {\n TextMessagePartProvider,\n useMessagePart,\n useMessagePartRuntime,\n useToolUIs,\n} from \"../../context\";\nimport {\n useMessage,\n useMessageRuntime,\n} from \"../../context/react/MessageContext\";\nimport { MessagePartRuntimeProvider } from \"../../context/providers/MessagePartRuntimeProvider\";\nimport { MessagePartPrimitiveText } from \"../messagePart/MessagePartText\";\nimport { MessagePartPrimitiveImage } from \"../messagePart/MessagePartImage\";\nimport type {\n Unstable_AudioMessagePartComponent,\n EmptyMessagePartComponent,\n TextMessagePartComponent,\n ImageMessagePartComponent,\n SourceMessagePartComponent,\n ToolCallMessagePartComponent,\n ToolCallMessagePartProps,\n FileMessagePartComponent,\n ReasoningMessagePartComponent,\n} from \"../../types/MessagePartComponentTypes\";\nimport { MessagePartPrimitiveInProgress } from \"../messagePart/MessagePartInProgress\";\nimport { MessagePartStatus } from \"../../types/AssistantTypes\";\n\ntype MessagePartGroup = {\n parentId: string | undefined;\n indices: number[];\n};\n\n/**\n * Groups message parts by their parent ID.\n * Parts without a parent ID appear in their chronological position as individual groups.\n * Parts with the same parent ID are grouped together at the position of their first occurrence.\n */\nconst groupMessagePartsByParentId = (\n parts: readonly any[],\n): MessagePartGroup[] => {\n // Map maintains insertion order, so groups appear in order of first occurrence\n const groupMap = new Map<string, number[]>();\n \n // Process each part in order\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const parentId = part?.parentId as string | undefined;\n \n // For parts without parentId, assign a unique group ID to maintain their position\n const groupId = parentId ?? `__ungrouped_${i}`;\n \n // Get or create the indices array for this group\n const indices = groupMap.get(groupId) ?? [];\n indices.push(i);\n groupMap.set(groupId, indices);\n }\n \n // Convert map to array of groups\n const groups: MessagePartGroup[] = [];\n for (const [groupId, indices] of groupMap) {\n // Extract parentId (undefined for ungrouped parts)\n const parentId = groupId.startsWith('__ungrouped_') ? undefined : groupId;\n groups.push({ parentId, indices });\n }\n \n return groups;\n};\n\nconst useMessagePartsGroupedByParentId = (): MessagePartGroup[] => {\n const parts = useMessage((m) => m.content);\n\n return useMemo(() => {\n if (parts.length === 0) {\n return [];\n }\n return groupMessagePartsByParentId(parts);\n }, [parts]);\n};\n\nexport namespace MessagePrimitiveUnstable_PartsGroupedByParentId {\n export type Props = {\n /**\n * Component configuration for rendering different types of message content.\n *\n * You can provide custom components for each content type (text, image, file, etc.)\n * and configure tool rendering behavior. If not provided, default components will be used.\n */\n components?:\n | {\n /** Component for rendering empty messages */\n Empty?: EmptyMessagePartComponent | undefined;\n /** Component for rendering text content */\n Text?: TextMessagePartComponent | undefined;\n /** Component for rendering reasoning content (typically hidden) */\n Reasoning?: ReasoningMessagePartComponent | undefined;\n /** Component for rendering source content */\n Source?: SourceMessagePartComponent | undefined;\n /** Component for rendering image content */\n Image?: ImageMessagePartComponent | undefined;\n /** Component for rendering file content */\n File?: FileMessagePartComponent | undefined;\n /** Component for rendering audio content (experimental) */\n Unstable_Audio?: Unstable_AudioMessagePartComponent | undefined;\n /** Configuration for tool call rendering */\n tools?:\n | {\n /** Map of tool names to their specific components */\n by_name?:\n | Record<string, ToolCallMessagePartComponent | undefined>\n | undefined;\n /** Fallback component for unregistered tools */\n Fallback?: ComponentType<ToolCallMessagePartProps> | undefined;\n }\n | {\n /** Override component that handles all tool calls */\n Override: ComponentType<ToolCallMessagePartProps>;\n }\n | undefined;\n\n /**\n * Component for rendering grouped message parts with the same parent ID.\n *\n * When provided, this component will automatically wrap message parts that share\n * the same parent ID, allowing you to create collapsible sections, custom styling,\n * or other grouped presentations.\n *\n * The component receives:\n * - `parentId`: The parent ID shared by all parts in the group (or undefined for ungrouped parts)\n * - `indices`: Array of indices for the parts in this group\n * - `children`: The rendered message part components\n *\n * @example\n * ```tsx\n * // Collapsible parent ID group\n * Group: ({ parentId, indices, children }) => {\n * if (!parentId) return <>{children}</>;\n * return (\n * <details className=\"parent-group\">\n * <summary>\n * Group {parentId} ({indices.length} parts)\n * </summary>\n * <div className=\"parent-group-content\">\n * {children}\n * </div>\n * </details>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Custom styled parent ID group\n * Group: ({ parentId, indices, children }) => {\n * if (!parentId) return <>{children}</>;\n * return (\n * <div className=\"border rounded-lg p-4 my-2\">\n * <div className=\"text-sm text-gray-600 mb-2\">\n * Related content ({parentId})\n * </div>\n * <div className=\"space-y-2\">\n * {children}\n * </div>\n * </div>\n * );\n * }\n * ```\n *\n * @param parentId - The parent ID shared by all parts in this group (undefined for ungrouped parts)\n * @param indices - Array of indices for the parts in this group\n * @param children - Rendered message part components to display within the group\n */\n Group?: ComponentType<\n PropsWithChildren<{\n parentId: string | undefined;\n indices: number[];\n }>\n >;\n }\n | undefined;\n };\n}\n\nconst ToolUIDisplay = ({\n Fallback,\n ...props\n}: {\n Fallback: ToolCallMessagePartComponent | undefined;\n} & ToolCallMessagePartProps) => {\n const Render = useToolUIs((s) => s.getToolUI(props.toolName)) ?? Fallback;\n if (!Render) return null;\n return <Render {...props} />;\n};\n\nconst defaultComponents = {\n Text: () => (\n <p style={{ whiteSpace: \"pre-line\" }}>\n <MessagePartPrimitiveText />\n <MessagePartPrimitiveInProgress>\n <span style={{ fontFamily: \"revert\" }}>{\" \\u25CF\"}</span>\n </MessagePartPrimitiveInProgress>\n </p>\n ),\n Reasoning: () => null,\n Source: () => null,\n Image: () => <MessagePartPrimitiveImage />,\n File: () => null,\n Unstable_Audio: () => null,\n Group: ({ children }) => children,\n} satisfies MessagePrimitiveUnstable_PartsGroupedByParentId.Props[\"components\"];\n\ntype MessagePartComponentProps = {\n components: MessagePrimitiveUnstable_PartsGroupedByParentId.Props[\"components\"];\n};\n\nconst MessagePartComponent: FC<MessagePartComponentProps> = ({\n components: {\n Text = defaultComponents.Text,\n Reasoning = defaultComponents.Reasoning,\n Image = defaultComponents.Image,\n Source = defaultComponents.Source,\n File = defaultComponents.File,\n Unstable_Audio: Audio = defaultComponents.Unstable_Audio,\n tools = {},\n } = {},\n}) => {\n const MessagePartRuntime = useMessagePartRuntime();\n\n const part = useMessagePart();\n\n const type = part.type;\n if (type === \"tool-call\") {\n const addResult = (result: any) => MessagePartRuntime.addToolResult(result);\n if (\"Override\" in tools)\n return <tools.Override {...part} addResult={addResult} />;\n const Tool = tools.by_name?.[part.toolName] ?? tools.Fallback;\n return <ToolUIDisplay {...part} Fallback={Tool} addResult={addResult} />;\n }\n\n if (part.status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n\n switch (type) {\n case \"text\":\n return <Text {...part} />;\n\n case \"reasoning\":\n return <Reasoning {...part} />;\n\n case \"source\":\n return <Source {...part} />;\n\n case \"image\":\n // eslint-disable-next-line jsx-a11y/alt-text\n return <Image {...part} />;\n\n case \"file\":\n return <File {...part} />;\n\n case \"audio\":\n return <Audio {...part} />;\n\n default:\n const unhandledType: never = type;\n throw new Error(`Unknown message part type: ${unhandledType}`);\n }\n};\n\ntype MessagePartProps = {\n partIndex: number;\n components: MessagePrimitiveUnstable_PartsGroupedByParentId.Props[\"components\"];\n};\n\nconst MessagePartImpl: FC<MessagePartProps> = ({ partIndex, components }) => {\n const messageRuntime = useMessageRuntime();\n const runtime = useMemo(\n () => messageRuntime.getMessagePartByIndex(partIndex),\n [messageRuntime, partIndex],\n );\n\n return (\n <MessagePartRuntimeProvider runtime={runtime}>\n <MessagePartComponent components={components} />\n </MessagePartRuntimeProvider>\n );\n};\n\nconst MessagePart = memo(\n MessagePartImpl,\n (prev, next) =>\n prev.partIndex === next.partIndex &&\n prev.components?.Text === next.components?.Text &&\n prev.components?.Reasoning === next.components?.Reasoning &&\n prev.components?.Source === next.components?.Source &&\n prev.components?.Image === next.components?.Image &&\n prev.components?.File === next.components?.File &&\n prev.components?.Unstable_Audio === next.components?.Unstable_Audio &&\n prev.components?.tools === next.components?.tools &&\n prev.components?.Group === next.components?.Group,\n);\n\nconst COMPLETE_STATUS: MessagePartStatus = Object.freeze({\n type: \"complete\",\n});\n\nconst EmptyPartFallback: FC<{\n status: MessagePartStatus;\n component: TextMessagePartComponent;\n}> = ({ status, component: Component }) => {\n return (\n <TextMessagePartProvider text=\"\" isRunning={status.type === \"running\"}>\n <Component type=\"text\" text=\"\" status={status} />\n </TextMessagePartProvider>\n );\n};\n\nconst EmptyPartsImpl: FC<MessagePartComponentProps> = ({ components }) => {\n const status =\n useMessage((s) => s.status as MessagePartStatus) ?? COMPLETE_STATUS;\n\n if (components?.Empty) return <components.Empty status={status} />;\n\n return (\n <EmptyPartFallback\n status={status}\n component={components?.Text ?? defaultComponents.Text}\n />\n );\n};\n\nconst EmptyParts = memo(\n EmptyPartsImpl,\n (prev, next) =>\n prev.components?.Empty === next.components?.Empty &&\n prev.components?.Text === next.components?.Text,\n);\n\n/**\n * Renders the parts of a message grouped by their parent ID.\n *\n * This component automatically groups message parts that share the same parent ID,\n * allowing you to create hierarchical or related content presentations. Parts without\n * a parent ID appear after grouped parts and remain ungrouped.\n *\n * @example\n * ```tsx\n * <MessagePrimitive.Unstable_PartsGroupedByParentId\n * components={{\n * Text: ({ text }) => <p className=\"message-text\">{text}</p>,\n * Image: ({ image }) => <img src={image} alt=\"Message image\" />,\n * Group: ({ parentId, indices, children }) => {\n * if (!parentId) return <>{children}</>;\n * return (\n * <div className=\"parent-group border rounded p-4\">\n * <h4>Related Content</h4>\n * {children}\n * </div>\n * );\n * }\n * }}\n * />\n * ```\n */\nexport const MessagePrimitiveUnstable_PartsGroupedByParentId: FC<\n MessagePrimitiveUnstable_PartsGroupedByParentId.Props\n> = ({ components }) => {\n const contentLength = useMessage((s) => s.content.length);\n const messageGroups = useMessagePartsGroupedByParentId();\n\n const partsElements = useMemo(() => {\n if (contentLength === 0) {\n return <EmptyParts components={components} />;\n }\n\n return messageGroups.map((group, groupIndex) => {\n const GroupComponent = components?.Group ?? defaultComponents.Group;\n\n return (\n <GroupComponent\n key={`group-${groupIndex}-${group.parentId ?? \"ungrouped\"}`}\n parentId={group.parentId}\n indices={group.indices}\n >\n {group.indices.map((partIndex) => (\n <MessagePart\n key={partIndex}\n partIndex={partIndex}\n components={components}\n />\n ))}\n </GroupComponent>\n );\n });\n }, [messageGroups, components, contentLength]);\n\n return <>{partsElements}</>;\n};\n\nMessagePrimitiveUnstable_PartsGroupedByParentId.displayName =\n \"MessagePrimitive.Unstable_PartsGroupedByParentId\";\n"],"mappings":";;;AAEA;AAAA,EAGE;AAAA,EAEA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kCAAkC;AAC3C,SAAS,gCAAgC;AACzC,SAAS,iCAAiC;AAY1C,SAAS,sCAAsC;AAsKtC,SA4MA,UA5MA,KAKL,YALK;AAzJT,IAAM,8BAA8B,CAClC,UACuB;AAEvB,QAAM,WAAW,oBAAI,IAAsB;AAG3C,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,UAAM,OAAO,MAAM,CAAC;AACpB,UAAM,WAAW,MAAM;AAGvB,UAAM,UAAU,YAAY,eAAe,CAAC;AAG5C,UAAM,UAAU,SAAS,IAAI,OAAO,KAAK,CAAC;AAC1C,YAAQ,KAAK,CAAC;AACd,aAAS,IAAI,SAAS,OAAO;AAAA,EAC/B;AAGA,QAAM,SAA6B,CAAC;AACpC,aAAW,CAAC,SAAS,OAAO,KAAK,UAAU;AAEzC,UAAM,WAAW,QAAQ,WAAW,cAAc,IAAI,SAAY;AAClE,WAAO,KAAK,EAAE,UAAU,QAAQ,CAAC;AAAA,EACnC;AAEA,SAAO;AACT;AAEA,IAAM,mCAAmC,MAA0B;AACjE,QA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C;AAAA,cACA;AAAA;AAAA,YAFK;AAAA,UAGP,CACD;AAAA;AAAA,QAVI,SAAS,UAAU,IAAI,MAAM,YAAY,WAAW;AAAA,MAW3D;AAAA,IAEJ,CAAC;AAAA,EACH,GAAG,CAAC,eAAe,YAAY,aAAa,CAAC;AAE7C,SAAO,gCAAG,yBAAc;AAC1B;AAEA,gDAAgD,cAC9C;","names":[]}
1
+ {"version":3,"sources":["../../../src/primitives/message/MessagePartsGroupedByParentId.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n type ComponentType,\n type FC,\n memo,\n PropsWithChildren,\n useMemo,\n} from \"react\";\nimport {\n TextMessagePartProvider,\n useMessagePart,\n useMessagePartRuntime,\n useToolUIs,\n} from \"../../context\";\nimport {\n useMessage,\n useMessageRuntime,\n} from \"../../context/react/MessageContext\";\nimport { MessagePartRuntimeProvider } from \"../../context/providers/MessagePartRuntimeProvider\";\nimport { MessagePartPrimitiveText } from \"../messagePart/MessagePartText\";\nimport { MessagePartPrimitiveImage } from \"../messagePart/MessagePartImage\";\nimport type {\n Unstable_AudioMessagePartComponent,\n EmptyMessagePartComponent,\n TextMessagePartComponent,\n ImageMessagePartComponent,\n SourceMessagePartComponent,\n ToolCallMessagePartComponent,\n ToolCallMessagePartProps,\n FileMessagePartComponent,\n ReasoningMessagePartComponent,\n} from \"../../types/MessagePartComponentTypes\";\nimport { MessagePartPrimitiveInProgress } from \"../messagePart/MessagePartInProgress\";\nimport { MessagePartStatus } from \"../../types/AssistantTypes\";\n\ntype MessagePartGroup = {\n parentId: string | undefined;\n indices: number[];\n};\n\n/**\n * Groups message parts by their parent ID.\n * Parts without a parent ID appear in their chronological position as individual groups.\n * Parts with the same parent ID are grouped together at the position of their first occurrence.\n */\nconst groupMessagePartsByParentId = (\n parts: readonly any[],\n): MessagePartGroup[] => {\n // Map maintains insertion order, so groups appear in order of first occurrence\n const groupMap = new Map<string, number[]>();\n\n // Process each part in order\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const parentId = part?.parentId as string | undefined;\n\n // For parts without parentId, assign a unique group ID to maintain their position\n const groupId = parentId ?? `__ungrouped_${i}`;\n\n // Get or create the indices array for this group\n const indices = groupMap.get(groupId) ?? [];\n indices.push(i);\n groupMap.set(groupId, indices);\n }\n\n // Convert map to array of groups\n const groups: MessagePartGroup[] = [];\n for (const [groupId, indices] of groupMap) {\n // Extract parentId (undefined for ungrouped parts)\n const parentId = groupId.startsWith(\"__ungrouped_\") ? undefined : groupId;\n groups.push({ parentId, indices });\n }\n\n return groups;\n};\n\nconst useMessagePartsGroupedByParentId = (): MessagePartGroup[] => {\n const parts = useMessage((m) => m.content);\n\n return useMemo(() => {\n if (parts.length === 0) {\n return [];\n }\n return groupMessagePartsByParentId(parts);\n }, [parts]);\n};\n\nexport namespace MessagePrimitiveUnstable_PartsGroupedByParentId {\n export type Props = {\n /**\n * Component configuration for rendering different types of message content.\n *\n * You can provide custom components for each content type (text, image, file, etc.)\n * and configure tool rendering behavior. If not provided, default components will be used.\n */\n components?:\n | {\n /** Component for rendering empty messages */\n Empty?: EmptyMessagePartComponent | undefined;\n /** Component for rendering text content */\n Text?: TextMessagePartComponent | undefined;\n /** Component for rendering reasoning content (typically hidden) */\n Reasoning?: ReasoningMessagePartComponent | undefined;\n /** Component for rendering source content */\n Source?: SourceMessagePartComponent | undefined;\n /** Component for rendering image content */\n Image?: ImageMessagePartComponent | undefined;\n /** Component for rendering file content */\n File?: FileMessagePartComponent | undefined;\n /** Component for rendering audio content (experimental) */\n Unstable_Audio?: Unstable_AudioMessagePartComponent | undefined;\n /** Configuration for tool call rendering */\n tools?:\n | {\n /** Map of tool names to their specific components */\n by_name?:\n | Record<string, ToolCallMessagePartComponent | undefined>\n | undefined;\n /** Fallback component for unregistered tools */\n Fallback?: ComponentType<ToolCallMessagePartProps> | undefined;\n }\n | {\n /** Override component that handles all tool calls */\n Override: ComponentType<ToolCallMessagePartProps>;\n }\n | undefined;\n\n /**\n * Component for rendering grouped message parts with the same parent ID.\n *\n * When provided, this component will automatically wrap message parts that share\n * the same parent ID, allowing you to create collapsible sections, custom styling,\n * or other grouped presentations.\n *\n * The component receives:\n * - `parentId`: The parent ID shared by all parts in the group (or undefined for ungrouped parts)\n * - `indices`: Array of indices for the parts in this group\n * - `children`: The rendered message part components\n *\n * @example\n * ```tsx\n * // Collapsible parent ID group\n * Group: ({ parentId, indices, children }) => {\n * if (!parentId) return <>{children}</>;\n * return (\n * <details className=\"parent-group\">\n * <summary>\n * Group {parentId} ({indices.length} parts)\n * </summary>\n * <div className=\"parent-group-content\">\n * {children}\n * </div>\n * </details>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Custom styled parent ID group\n * Group: ({ parentId, indices, children }) => {\n * if (!parentId) return <>{children}</>;\n * return (\n * <div className=\"border rounded-lg p-4 my-2\">\n * <div className=\"text-sm text-gray-600 mb-2\">\n * Related content ({parentId})\n * </div>\n * <div className=\"space-y-2\">\n * {children}\n * </div>\n * </div>\n * );\n * }\n * ```\n *\n * @param parentId - The parent ID shared by all parts in this group (undefined for ungrouped parts)\n * @param indices - Array of indices for the parts in this group\n * @param children - Rendered message part components to display within the group\n */\n Group?: ComponentType<\n PropsWithChildren<{\n parentId: string | undefined;\n indices: number[];\n }>\n >;\n }\n | undefined;\n };\n}\n\nconst ToolUIDisplay = ({\n Fallback,\n ...props\n}: {\n Fallback: ToolCallMessagePartComponent | undefined;\n} & ToolCallMessagePartProps) => {\n const Render = useToolUIs((s) => s.getToolUI(props.toolName)) ?? Fallback;\n if (!Render) return null;\n return <Render {...props} />;\n};\n\nconst defaultComponents = {\n Text: () => (\n <p style={{ whiteSpace: \"pre-line\" }}>\n <MessagePartPrimitiveText />\n <MessagePartPrimitiveInProgress>\n <span style={{ fontFamily: \"revert\" }}>{\" \\u25CF\"}</span>\n </MessagePartPrimitiveInProgress>\n </p>\n ),\n Reasoning: () => null,\n Source: () => null,\n Image: () => <MessagePartPrimitiveImage />,\n File: () => null,\n Unstable_Audio: () => null,\n Group: ({ children }) => children,\n} satisfies MessagePrimitiveUnstable_PartsGroupedByParentId.Props[\"components\"];\n\ntype MessagePartComponentProps = {\n components: MessagePrimitiveUnstable_PartsGroupedByParentId.Props[\"components\"];\n};\n\nconst MessagePartComponent: FC<MessagePartComponentProps> = ({\n components: {\n Text = defaultComponents.Text,\n Reasoning = defaultComponents.Reasoning,\n Image = defaultComponents.Image,\n Source = defaultComponents.Source,\n File = defaultComponents.File,\n Unstable_Audio: Audio = defaultComponents.Unstable_Audio,\n tools = {},\n } = {},\n}) => {\n const MessagePartRuntime = useMessagePartRuntime();\n\n const part = useMessagePart();\n\n const type = part.type;\n if (type === \"tool-call\") {\n const addResult = (result: any) => MessagePartRuntime.addToolResult(result);\n if (\"Override\" in tools)\n return <tools.Override {...part} addResult={addResult} />;\n const Tool = tools.by_name?.[part.toolName] ?? tools.Fallback;\n return <ToolUIDisplay {...part} Fallback={Tool} addResult={addResult} />;\n }\n\n if (part.status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n\n switch (type) {\n case \"text\":\n return <Text {...part} />;\n\n case \"reasoning\":\n return <Reasoning {...part} />;\n\n case \"source\":\n return <Source {...part} />;\n\n case \"image\":\n // eslint-disable-next-line jsx-a11y/alt-text\n return <Image {...part} />;\n\n case \"file\":\n return <File {...part} />;\n\n case \"audio\":\n return <Audio {...part} />;\n\n default:\n const unhandledType: never = type;\n throw new Error(`Unknown message part type: ${unhandledType}`);\n }\n};\n\ntype MessagePartProps = {\n partIndex: number;\n components: MessagePrimitiveUnstable_PartsGroupedByParentId.Props[\"components\"];\n};\n\nconst MessagePartImpl: FC<MessagePartProps> = ({ partIndex, components }) => {\n const messageRuntime = useMessageRuntime();\n const runtime = useMemo(\n () => messageRuntime.getMessagePartByIndex(partIndex),\n [messageRuntime, partIndex],\n );\n\n return (\n <MessagePartRuntimeProvider runtime={runtime}>\n <MessagePartComponent components={components} />\n </MessagePartRuntimeProvider>\n );\n};\n\nconst MessagePart = memo(\n MessagePartImpl,\n (prev, next) =>\n prev.partIndex === next.partIndex &&\n prev.components?.Text === next.components?.Text &&\n prev.components?.Reasoning === next.components?.Reasoning &&\n prev.components?.Source === next.components?.Source &&\n prev.components?.Image === next.components?.Image &&\n prev.components?.File === next.components?.File &&\n prev.components?.Unstable_Audio === next.components?.Unstable_Audio &&\n prev.components?.tools === next.components?.tools &&\n prev.components?.Group === next.components?.Group,\n);\n\nconst COMPLETE_STATUS: MessagePartStatus = Object.freeze({\n type: \"complete\",\n});\n\nconst EmptyPartFallback: FC<{\n status: MessagePartStatus;\n component: TextMessagePartComponent;\n}> = ({ status, component: Component }) => {\n return (\n <TextMessagePartProvider text=\"\" isRunning={status.type === \"running\"}>\n <Component type=\"text\" text=\"\" status={status} />\n </TextMessagePartProvider>\n );\n};\n\nconst EmptyPartsImpl: FC<MessagePartComponentProps> = ({ components }) => {\n const status =\n useMessage((s) => s.status as MessagePartStatus) ?? COMPLETE_STATUS;\n\n if (components?.Empty) return <components.Empty status={status} />;\n\n return (\n <EmptyPartFallback\n status={status}\n component={components?.Text ?? defaultComponents.Text}\n />\n );\n};\n\nconst EmptyParts = memo(\n EmptyPartsImpl,\n (prev, next) =>\n prev.components?.Empty === next.components?.Empty &&\n prev.components?.Text === next.components?.Text,\n);\n\n/**\n * Renders the parts of a message grouped by their parent ID.\n *\n * This component automatically groups message parts that share the same parent ID,\n * allowing you to create hierarchical or related content presentations. Parts without\n * a parent ID appear after grouped parts and remain ungrouped.\n *\n * @example\n * ```tsx\n * <MessagePrimitive.Unstable_PartsGroupedByParentId\n * components={{\n * Text: ({ text }) => <p className=\"message-text\">{text}</p>,\n * Image: ({ image }) => <img src={image} alt=\"Message image\" />,\n * Group: ({ parentId, indices, children }) => {\n * if (!parentId) return <>{children}</>;\n * return (\n * <div className=\"parent-group border rounded p-4\">\n * <h4>Related Content</h4>\n * {children}\n * </div>\n * );\n * }\n * }}\n * />\n * ```\n */\nexport const MessagePrimitiveUnstable_PartsGroupedByParentId: FC<\n MessagePrimitiveUnstable_PartsGroupedByParentId.Props\n> = ({ components }) => {\n const contentLength = useMessage((s) => s.content.length);\n const messageGroups = useMessagePartsGroupedByParentId();\n\n const partsElements = useMemo(() => {\n if (contentLength === 0) {\n return <EmptyParts components={components} />;\n }\n\n return messageGroups.map((group, groupIndex) => {\n const GroupComponent = components?.Group ?? defaultComponents.Group;\n\n return (\n <GroupComponent\n key={`group-${groupIndex}-${group.parentId ?? \"ungrouped\"}`}\n parentId={group.parentId}\n indices={group.indices}\n >\n {group.indices.map((partIndex) => (\n <MessagePart\n key={partIndex}\n partIndex={partIndex}\n components={components}\n />\n ))}\n </GroupComponent>\n );\n });\n }, [messageGroups, components, contentLength]);\n\n return <>{partsElements}</>;\n};\n\nMessagePrimitiveUnstable_PartsGroupedByParentId.displayName =\n \"MessagePrimitive.Unstable_PartsGroupedByParentId\";\n"],"mappings":";;;AAEA;AAAA,EAGE;AAAA,EAEA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kCAAkC;AAC3C,SAAS,gCAAgC;AACzC,SAAS,iCAAiC;AAY1C,SAAS,sCAAsC;AAsKtC,SA4MA,UA5MA,KAKL,YALK;AAzJT,IAAM,8BAA8B,CAClC,UACuB;AAEvB,QAAM,WAAW,oBAAI,IAAsB;AAG3C,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,UAAM,OAAO,MAAM,CAAC;AACpB,UAAM,WAAW,MAAM;AAGvB,UAAM,UAAU,YAAY,eAAe,CAAC;AAG5C,UAAM,UAAU,SAAS,IAAI,OAAO,KAAK,CAAC;AAC1C,YAAQ,KAAK,CAAC;AACd,aAAS,IAAI,SAAS,OAAO;AAAA,EAC/B;AAGA,QAAM,SAA6B,CAAC;AACpC,aAAW,CAAC,SAAS,OAAO,KAAK,UAAU;AAEzC,UAAM,WAAW,QAAQ,WAAW,c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AAA;AAAA,UAEC,UAAU,MAAM;AAAA,UAChB,SAAS,MAAM;AAAA,UAEd,gBAAM,QAAQ,IAAI,CAAC,cAClB;AAAA,YAAC;AAAA;AAAA,cAEC;AAAA,cACA;AAAA;AAAA,YAFK;AAAA,UAGP,CACD;AAAA;AAAA,QAVI,SAAS,UAAU,IAAI,MAAM,YAAY,WAAW;AAAA,MAW3D;AAAA,IAEJ,CAAC;AAAA,EACH,GAAG,CAAC,eAAe,YAAY,aAAa,CAAC;AAE7C,SAAO,gCAAG,yBAAc;AAC1B;AAEA,gDAAgD,cAC9C;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"RemoteThreadListHookInstanceManager.d.ts","sourceRoot":"","sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListHookInstanceManager.tsx"],"names":[],"mappings":"AAGA,OAAO,EACL,EAAE,EAMF,iBAAiB,EACjB,aAAa,EACd,MAAM,OAAO,CAAC;AASf,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAE7C,KAAK,oBAAoB,GAAG,MAAM,gBAAgB,CAAC;AAKnD,qBAAa,mCAAoC,SAAQ,gBAAgB;IACvE,OAAO,CAAC,cAAc,CAEpB;IACF,OAAO,CAAC,SAAS,CAAmD;IACpE,OAAO,CAAC,0BAA0B,CAAsB;gBAE5C,WAAW,EAAE,oBAAoB;IAKtC,kBAAkB,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAwBnC,oBAAoB,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IASrC,iBAAiB,CAAC,QAAQ,EAAE,MAAM;IAKlC,cAAc,CAAC,cAAc,EAAE,oBAAoB;IAO1D,OAAO,CAAC,0BAA0B,CAkDhC;IAEF,OAAO,CAAC,0BAA0B,CAkB/B;IAEI,+BAA+B,EAAE,EAAE,CAAC;QACzC,QAAQ,EAAE,aAAa,CAAC,iBAAiB,CAAC,CAAC;KAC5C,CAAC,CAUA;CACH"}
1
+ {"version":3,"file":"RemoteThreadListHookInstanceManager.d.ts","sourceRoot":"","sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListHookInstanceManager.tsx"],"names":[],"mappings":"AAGA,OAAO,EACL,EAAE,EAMF,iBAAiB,EACjB,aAAa,EACd,MAAM,OAAO,CAAC;AAMf,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAE7C,KAAK,oBAAoB,GAAG,MAAM,gBAAgB,CAAC;AAKnD,qBAAa,mCAAoC,SAAQ,gBAAgB;IACvE,OAAO,CAAC,cAAc,CAEpB;IACF,OAAO,CAAC,SAAS,CAAmD;IACpE,OAAO,CAAC,0BAA0B,CAAsB;gBAE5C,WAAW,EAAE,oBAAoB;IAKtC,kBAAkB,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAwBnC,oBAAoB,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAMrC,iBAAiB,CAAC,QAAQ,EAAE,MAAM;IAKlC,cAAc,CAAC,cAAc,EAAE,oBAAoB;IAO1D,OAAO,CAAC,0BAA0B,CAmDhC;IAEF,OAAO,CAAC,0BAA0B,CAkB/B;IAEI,+BAA+B,EAAE,EAAE,CAAC;QACzC,QAAQ,EAAE,aAAa,CAAC,iBAAiB,CAAC,CAAC;KAC5C,CAAC,CAUA;CACH"}
@@ -11,10 +11,7 @@ import {
11
11
  import { create } from "zustand";
12
12
  import { useAssistantRuntime } from "../../context/index.js";
13
13
  import { ThreadListItemRuntimeProvider } from "../../context/providers/ThreadListItemRuntimeProvider.js";
14
- import {
15
- useThreadListItem,
16
- useThreadListItemRuntime
17
- } from "../../context/react/ThreadListItemContext.js";
14
+ import { useThreadListItem } from "../../context/react/ThreadListItemContext.js";
18
15
  import { BaseSubscribable } from "./BaseSubscribable.js";
19
16
  import { jsx } from "react/jsx-runtime";
20
17
  var RemoteThreadListHookInstanceManager = class extends BaseSubscribable {
@@ -49,10 +46,7 @@ var RemoteThreadListHookInstanceManager = class extends BaseSubscribable {
49
46
  }
50
47
  getThreadRuntimeCore(threadId) {
51
48
  const instance = this.instances.get(threadId);
52
- if (!instance)
53
- throw new Error(
54
- "getThreadRuntimeCore not found. This is a bug in assistant-ui."
55
- );
49
+ if (!instance) return void 0;
56
50
  return instance.runtime;
57
51
  }
58
52
  stopThreadRuntime(threadId) {
@@ -88,9 +82,9 @@ var RemoteThreadListHookInstanceManager = class extends BaseSubscribable {
88
82
  updateRuntime();
89
83
  return threadBinding.outerSubscribe(updateRuntime);
90
84
  }, [threadBinding, updateRuntime]);
91
- const threadListItemRuntime = useThreadListItemRuntime();
92
85
  useEffect(() => {
93
86
  return runtime.threads.main.unstable_on("initialize", () => {
87
+ const threadListItemRuntime = runtime.threads.getItemById(id);
94
88
  if (threadListItemRuntime.getState().status === "new") {
95
89
  threadListItemRuntime.initialize();
96
90
  const dispose = runtime.thread.unstable_on("run-end", () => {
@@ -99,7 +93,7 @@ var RemoteThreadListHookInstanceManager = class extends BaseSubscribable {
99
93
  });
100
94
  }
101
95
  });
102
- }, [runtime, threadListItemRuntime]);
96
+ }, [runtime, id]);
103
97
  return null;
104
98
  };
105
99
  _OuterActiveThreadProvider = memo(({ threadId, provider: Provider }) => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListHookInstanceManager.tsx"],"sourcesContent":["/* eslint-disable react-hooks/rules-of-hooks */\n\"use client\";\n\nimport {\n FC,\n useCallback,\n useRef,\n useEffect,\n memo,\n useMemo,\n PropsWithChildren,\n ComponentType,\n} from \"react\";\nimport { UseBoundStore, StoreApi, create } from \"zustand\";\nimport { useAssistantRuntime } from \"../../context\";\nimport { ThreadListItemRuntimeProvider } from \"../../context/providers/ThreadListItemRuntimeProvider\";\nimport {\n useThreadListItem,\n useThreadListItemRuntime,\n} from \"../../context/react/ThreadListItemContext\";\nimport { ThreadRuntimeCore, ThreadRuntimeImpl } from \"../../internal\";\nimport { BaseSubscribable } from \"./BaseSubscribable\";\nimport { AssistantRuntime } from \"../../api\";\n\ntype RemoteThreadListHook = () => AssistantRuntime;\n\ntype RemoteThreadListHookInstance = {\n runtime?: ThreadRuntimeCore;\n};\nexport class RemoteThreadListHookInstanceManager extends BaseSubscribable {\n private useRuntimeHook: UseBoundStore<\n StoreApi<{ useRuntime: RemoteThreadListHook }>\n >;\n private instances = new Map<string, RemoteThreadListHookInstance>();\n private useAliveThreadsKeysChanged = create(() => ({}));\n\n constructor(runtimeHook: RemoteThreadListHook) {\n super();\n this.useRuntimeHook = create(() => ({ useRuntime: runtimeHook }));\n }\n\n public startThreadRuntime(threadId: string) {\n if (!this.instances.has(threadId)) {\n this.instances.set(threadId, {});\n this.useAliveThreadsKeysChanged.setState({}, true);\n }\n\n return new Promise<ThreadRuntimeCore>((resolve, reject) => {\n const callback = () => {\n const instance = this.instances.get(threadId);\n if (!instance) {\n dispose();\n reject(new Error(\"Thread was deleted before runtime was started\"));\n } else if (!instance.runtime) {\n return; // misc update\n } else {\n dispose();\n resolve(instance.runtime);\n }\n };\n const dispose = this.subscribe(callback);\n callback();\n });\n }\n\n public getThreadRuntimeCore(threadId: string) {\n const instance = this.instances.get(threadId);\n if (!instance)\n throw new Error(\n \"getThreadRuntimeCore not found. This is a bug in assistant-ui.\",\n );\n return instance.runtime;\n }\n\n public stopThreadRuntime(threadId: string) {\n this.instances.delete(threadId);\n this.useAliveThreadsKeysChanged.setState({}, true);\n }\n\n public setRuntimeHook(newRuntimeHook: RemoteThreadListHook) {\n const prevRuntimeHook = this.useRuntimeHook.getState().useRuntime;\n if (prevRuntimeHook !== newRuntimeHook) {\n this.useRuntimeHook.setState({ useRuntime: newRuntimeHook }, true);\n }\n }\n\n private _InnerActiveThreadProvider: FC = () => {\n const { id } = useThreadListItem();\n\n const { useRuntime } = this.useRuntimeHook();\n const runtime = useRuntime();\n\n const threadBinding = (runtime.thread as ThreadRuntimeImpl)\n .__internal_threadBinding;\n\n const updateRuntime = useCallback(() => {\n const aliveThread = this.instances.get(id);\n if (!aliveThread)\n throw new Error(\"Thread not found. This is a bug in assistant-ui.\");\n\n aliveThread.runtime = threadBinding.getState();\n\n if (isMounted) {\n this._notifySubscribers();\n }\n }, [id, threadBinding]);\n\n const isMounted = useRef(false);\n if (!isMounted.current) {\n updateRuntime();\n }\n\n useEffect(() => {\n isMounted.current = true;\n updateRuntime();\n return threadBinding.outerSubscribe(updateRuntime);\n }, [threadBinding, updateRuntime]);\n\n // auto initialize thread\n const threadListItemRuntime = useThreadListItemRuntime();\n useEffect(() => {\n return runtime.threads.main.unstable_on(\"initialize\", () => {\n if (threadListItemRuntime.getState().status === \"new\") {\n threadListItemRuntime.initialize();\n\n // auto generate a title after first run\n const dispose = runtime.thread.unstable_on(\"run-end\", () => {\n dispose();\n\n threadListItemRuntime.generateTitle();\n });\n }\n });\n }, [runtime, threadListItemRuntime]);\n\n return null;\n };\n\n private _OuterActiveThreadProvider: FC<{\n threadId: string;\n provider: ComponentType<PropsWithChildren>;\n // eslint-disable-next-line react/display-name\n }> = memo(({ threadId, provider: Provider }) => {\n const assistantRuntime = useAssistantRuntime();\n const threadListItemRuntime = useMemo(\n () => assistantRuntime.threads.getItemById(threadId),\n [assistantRuntime, threadId],\n );\n\n return (\n <ThreadListItemRuntimeProvider runtime={threadListItemRuntime}>\n <Provider>\n <this._InnerActiveThreadProvider />\n </Provider>\n </ThreadListItemRuntimeProvider>\n );\n });\n\n public __internal_RenderThreadRuntimes: FC<{\n provider: ComponentType<PropsWithChildren>;\n }> = ({ provider }) => {\n this.useAliveThreadsKeysChanged(); // trigger re-render on alive threads change\n\n return Array.from(this.instances.keys()).map((threadId) => (\n <this._OuterActiveThreadProvider\n key={threadId}\n threadId={thre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AAEnC,WAAO;AAAA,EACT;AAAA,EAEQ,6BAIH,KAAK,CAAC,EAAE,UAAU,UAAU,SAAS,MAAM;AAC9C,UAAM,mBAAmB,oBAAoB;AAC7C,UAAM,wBAAwB;AAAA,MAC5B,MAAM,iBAAiB,QAAQ,YAAY,QAAQ;AAAA,MACnD,CAAC,kBAAkB,QAAQ;AAAA,IAC7B;AAEA,WACE,oBAAC,iCAA8B,SAAS,uBACtC,8BAAC,YACC,8BAAC,KAAK,4BAAL,EAAgC,GACnC,GACF;AAAA,EAEJ,CAAC;AAAA,EAEM,kCAEF,CAAC,EAAE,SAAS,MAAM;AACrB,SAAK,2BAA2B;AAEhC,WAAO,MAAM,KAAK,KAAK,UAAU,KAAK,CAAC,EAAE,IAAI,CAAC,aAC5C;AAAA,MAAC,KAAK;AAAA,MAAL;AAAA,QAEC;AAAA,QACA;AAAA;AAAA,MAFK;AAAA,IAGP,CACD;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListHookInstanceManager.tsx"],"sourcesContent":["/* eslint-disable react-hooks/rules-of-hooks */\n\"use client\";\n\nimport {\n FC,\n useCallback,\n useRef,\n useEffect,\n memo,\n useMemo,\n PropsWithChildren,\n ComponentType,\n} from \"react\";\nimport { UseBoundStore, StoreApi, create } from \"zustand\";\nimport { useAssistantRuntime } from \"../../context\";\nimport { ThreadListItemRuntimeProvider } from \"../../context/providers/ThreadListItemRuntimeProvider\";\nimport { useThreadListItem } from \"../../context/react/ThreadListItemContext\";\nimport { ThreadRuntimeCore, ThreadRuntimeImpl } from \"../../internal\";\nimport { BaseSubscribable } from \"./BaseSubscribable\";\nimport { AssistantRuntime } from \"../../api\";\n\ntype RemoteThreadListHook = () => AssistantRuntime;\n\ntype RemoteThreadListHookInstance = {\n runtime?: ThreadRuntimeCore;\n};\nexport class RemoteThreadListHookInstanceManager extends BaseSubscribable {\n private useRuntimeHook: UseBoundStore<\n StoreApi<{ useRuntime: RemoteThreadListHook }>\n >;\n private instances = new Map<string, RemoteThreadListHookInstance>();\n private useAliveThreadsKeysChanged = create(() => ({}));\n\n constructor(runtimeHook: RemoteThreadListHook) {\n super();\n this.useRuntimeHook = create(() => ({ useRuntime: runtimeHook }));\n }\n\n public startThreadRuntime(threadId: string) {\n if (!this.instances.has(threadId)) {\n this.instances.set(threadId, {});\n this.useAliveThreadsKeysChanged.setState({}, true);\n }\n\n return new Promise<ThreadRuntimeCore>((resolve, reject) => {\n const callback = () => {\n const instance = this.instances.get(threadId);\n if (!instance) {\n dispose();\n reject(new Error(\"Thread was deleted before runtime was started\"));\n } else if (!instance.runtime) {\n return; // misc update\n } else {\n dispose();\n resolve(instance.runtime);\n }\n };\n const dispose = this.subscribe(callback);\n callback();\n });\n }\n\n public getThreadRuntimeCore(threadId: string) {\n const instance = this.instances.get(threadId);\n if (!instance) return undefined;\n return instance.runtime;\n }\n\n public stopThreadRuntime(threadId: string) {\n this.instances.delete(threadId);\n this.useAliveThreadsKeysChanged.setState({}, true);\n }\n\n public setRuntimeHook(newRuntimeHook: RemoteThreadListHook) {\n const prevRuntimeHook = this.useRuntimeHook.getState().useRuntime;\n if (prevRuntimeHook !== newRuntimeHook) {\n this.useRuntimeHook.setState({ useRuntime: newRuntimeHook }, true);\n }\n }\n\n private _InnerActiveThreadProvider: FC = () => {\n const { id } = useThreadListItem();\n\n const { useRuntime } = this.useRuntimeHook();\n const runtime = useRuntime();\n\n const threadBinding = (runtime.thread as ThreadRuntimeImpl)\n .__internal_threadBinding;\n\n const updateRuntime = useCallback(() => {\n const aliveThread = this.instances.get(id);\n if (!aliveThread)\n throw new Error(\"Thread not found. This is a bug in assistant-ui.\");\n\n aliveThread.runtime = threadBinding.getState();\n\n if (isMounted) {\n this._notifySubscribers();\n }\n }, [id, threadBinding]);\n\n const isMounted = useRef(false);\n if (!isMounted.current) {\n updateRuntime();\n }\n\n useEffect(() => {\n isMounted.current = true;\n updateRuntime();\n return threadBinding.outerSubscribe(updateRuntime);\n }, [threadBinding, updateRuntime]);\n\n // auto initialize thread\n useEffect(() => {\n return runtime.threads.main.unstable_on(\"initialize\", () => {\n const threadListItemRuntime = runtime.threads.getItemById(id);\n\n if (threadListItemRuntime.getState().status === \"new\") {\n threadListItemRuntime.initialize();\n\n // auto generate a title after first run\n const dispose = runtime.thread.unstable_on(\"run-end\", () => {\n dispose();\n\n threadListItemRuntime.generateTitle();\n });\n }\n });\n }, [runtime, id]);\n\n return null;\n };\n\n private _OuterActiveThreadProvider: FC<{\n threadId: string;\n provider: ComponentType<PropsWithChildren>;\n // eslint-disable-next-line react/display-name\n }> = memo(({ threadId, provider: Provider }) => {\n const assistantRuntime = useAssistantRuntime();\n const threadListItemRuntime = useMemo(\n () => assistantRuntime.threads.getItemById(threadId),\n [assistantRuntime, threadId],\n );\n\n return (\n <ThreadListItemRuntimeProvider runtime={threadListItemRuntime}>\n <Provider>\n <this._InnerActiveThreadProvider />\n </Provider>\n </ThreadListItemRuntimeProvider>\n );\n });\n\n public __internal_RenderThreadRuntimes: FC<{\n provider: ComponentType<PropsWithChildren>;\n }> = ({ provider }) => {\n this.useAliveThreadsKeysChanged(); // trigger re-render on alive threads change\n\n return Array.from(this.instances.keys()).map((threadId) => (\n <this._OuterActiveThreadProvider\n key={threadId}\n threadId={threadId}\n provider={provider}\n />\n ));\n };\n}\n"],"mappings":";;;AAGA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAkC,cAAc;AAChD,SAAS,2BAA2B;AACpC,SAAS,qCAAqC;AAC9C,SAAS,yBAAyB;AAElC,SAAS,wBAAwB;AAiIvB;AAzHH,IAAM,sCAAN,cAAkD,iBAAiB;AAAA,EAChE;AAAA,EAGA,YAAY,oBAAI,IAA0C;AAAA,EAC1D,6BAA6B,OAAO,OAAO,CAAC,EAAE;AAAA,EAEtD,YAAY,aAAmC;AAC7C,UAAM;AACN,SAAK,iBAAiB,OAAO,OAAO,EAAE,Y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AAE,IAAI,CAAC,aAC5C;AAAA,MAAC,KAAK;AAAA,MAAL;AAAA,QAEC;AAAA,QACA;AAAA;AAAA,MAFK;AAAA,IAGP,CACD;AAAA,EACH;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"RemoteThreadListThreadListRuntimeCore.d.ts","sourceRoot":"","sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAEtE,OAAO,EACL,8BAA8B,EAC9B,uBAAuB,EACxB,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAGtD,OAAO,EAAE,EAAE,EAA8B,MAAM,OAAO,CAAC;AAGvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAG3D,KAAK,gBAAgB,GACjB;IACE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,CAAC;IAChC,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;CAC3B,GACD;IACE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC,8BAA8B,CAAC,CAAC;IACjE,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,CAAC;IAChC,QAAQ,CAAC,MAAM,EAAE,SAAS,GAAG,UAAU,CAAC;IACxC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC,GACD;IACE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,cAAc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AAW,CAAC,kBAAkB,EAAE,MAAM;IAIhC,cAAc,CAAC,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAmBzD,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC;IAqCxC,UAAU,GAAU,UAAU,MAAM,6CAmDzC;IAEK,aAAa,GAAU,UAAU,MAAM,mBA8B5C;IAEK,MAAM,CAAC,kBAAkB,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;YA4B5D,sBAAsB;IASvB,OAAO,CAAC,kBAAkB,EAAE,MAAM;IAkBxC,SAAS,CAAC,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAqB9C,MAAM,CAAC,kBAAkB,EAAE,MAAM;IAkBjC,MAAM,CAAC,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAU9D,OAAO,CAAC,WAAW,CAA8B;IAE1C,0BAA0B,EAAE,EAAE,CA4BnC;CACH"}
@@ -303,7 +303,9 @@ var RemoteThreadListThreadListRuntimeCore = class extends BaseSubscribable {
303
303
  if (!data) throw new Error("Thread not found");
304
304
  if (data.status === "new") throw new Error("Thread is not yet initialized");
305
305
  const { remoteId } = await data.initializeTask;
306
- const messages = this.getThreadRuntimeCore(threadId).messages;
306
+ const runtimeCore = this._hookManager.getThreadRuntimeCore(data.threadId);
307
+ if (!runtimeCore) return;
308
+ const messages = runtimeCore.messages;
307
309
  const stream = await this._options.adapter.generateTitle(
308
310
  remoteId,
309
311
  messages
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.tsx"],"sourcesContent":["\"use client\";\n\nimport { ThreadListRuntimeCore } from \"../core/ThreadListRuntimeCore\";\nimport { generateId } from \"../../internal\";\nimport {\n RemoteThreadInitializeResponse,\n RemoteThreadListOptions,\n} from \"./types\";\nimport { RemoteThreadListHookInstanceManager } from \"./RemoteThreadListHookInstanceManager\";\nimport { BaseSubscribable } from \"./BaseSubscribable\";\nimport { EMPTY_THREAD_CORE } from \"./EMPTY_THREAD_CORE\";\nimport { OptimisticState } from \"./OptimisticState\";\nimport { FC, Fragment, useEffect, useId } from \"react\";\nimport { create } from \"zustand\";\nimport { AssistantMessageStream } from \"assistant-stream\";\nimport { ModelContextProvider } from \"../../model-context\";\nimport { RuntimeAdapterProvider } from \"../adapters/RuntimeAdapterProvider\";\n\ntype RemoteThreadData =\n | {\n readonly threadId: string;\n readonly remoteId?: undefined;\n readonly externalId?: undefined;\n readonly status: \"new\";\n readonly title: undefined;\n }\n | {\n readonly threadId: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId?: undefined;\n readonly externalId?: undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n }\n | {\n readonly threadId: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId: string;\n readonly externalId: string | undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n };\n\ntype THREAD_MAPPING_ID = string & { __brand: \"THREAD_MAPPING_ID\" };\nfunction createThreadMappingId(id: string): THREAD_MAPPING_ID {\n return id as THREAD_MAPPING_ID;\n}\n\ntype RemoteThreadState = {\n readonly isLoading: boolean;\n readonly newThreadId: string | undefined;\n readonly threadIds: readonly string[];\n readonly archivedThreadIds: readonly string[];\n readonly threadIdMap: Readonly<Record<string, THREAD_MAPPING_ID>>;\n readonly threadData: Readonly<Record<THREAD_MAPPING_ID, RemoteThreadData>>;\n};\n\nconst getThreadData = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n) => {\n const idx = state.threadIdMap[threadIdOrRemoteId];\n if (idx === undefined) return undefined;\n return state.threadData[idx];\n};\n\nconst updateStatusReducer = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n newStatus: \"regular\" | \"archived\" | \"deleted\",\n) => {\n const data = getThreadData(state, threadIdOrRemoteId);\n if (!data) return state;\n\n const { threadId, remoteId, status: lastStatus } = data;\n if (lastStatus === newStatus) return state;\n\n const newState = { ...state };\n\n // lastStatus\n switch (lastStatus) {\n case \"new\":\n newState.newThreadId = undefined;\n break;\n case \"regular\":\n newState.threadIds = newState.threadIds.filter((t) => t !== threadId);\n break;\n case \"archived\":\n newState.archivedThreadIds = newState.archivedThreadIds.filter(\n (t) => t !== threadId,\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = lastStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n // newStatus\n switch (newStatus) {\n case \"regular\":\n newState.threadIds = [threadId, ...newState.threadIds];\n break;\n\n case \"archived\":\n newState.archivedThreadIds = [threadId, ...newState.archivedThreadIds];\n break;\n\n case \"deleted\":\n newState.threadData = Object.fromEntries(\n Object.entries(newState.threadData).filter(([key]) => key !== threadId),\n );\n newState.threadIdMap = Object.fromEntries(\n Object.entries(newState.threadIdMap).filter(\n ([key]) => key !== threadId && key !== remoteId,\n ),\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = newStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n if (newStatus !== \"deleted\") {\n newState.threadData = {\n ...newState.threadData,\n [threadId]: {\n ...data,\n status: newStatus,\n },\n };\n }\n\n return newState;\n};\n\nexport class RemoteThreadListThreadListRuntimeCore\n extends BaseSubscribable\n implements ThreadListRuntimeCore\n{\n private _options!: RemoteThreadListOptions;\n private readonly _hookManager: RemoteThreadListHookInstanceManager;\n\n private _loadThreadsPromise: Promise<void> | undefined;\n\n private _mainThreadId!: string;\n private readonly _state = new OptimisticState<RemoteThreadState>({\n isLoading: false,\n newThreadId: undefined,\n threadIds: [],\n archivedThreadIds: [],\n threadIdMap: {},\n threadData: {},\n });\n\n public getLoadThreadsPromise() {\n // TODO this needs to be cached in case this promise is loaded during suspense\n if (!this._loadThreadsPromise) {\n this._loadThreadsPromise = this._state\n .optimisticUpdate({\n execute: () => this._options.adapter.list(),\n loading: (state) => {\n return {\n ...state,\n isLoading: true,\n };\n },\n then: (state, l) => {\n const newThreadIds = [];\n const newArchivedThreadIds = [];\n const newThreadIdMap = {} as Record<string, THREAD_MAPPING_ID>;\n const newThreadData = {} as Record<\n THREAD_MAPPING_ID,\n RemoteThreadData\n >;\n\n for (const thread of l.threads) {\n switch (thread.status) {\n case \"regular\":\n newThreadIds.push(thread.remoteId);\n break;\n case \"archived\":\n newArchivedThreadIds.push(thread.remoteId);\n break;\n default: {\n const _exhaustiveCheck: never = thread.status;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n const mappingId = createThreadMappingId(thread.remoteId);\n newThreadIdMap[thread.remoteId] = mappingId;\n newThreadData[mappingId] = {\n threadId: thread.remoteId,\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n status: thread.status,\n title: thread.title,\n initializeTask: Promise.resolve({\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n }),\n };\n }\n\n return {\n ...state,\n threadIds: newThreadIds,\n archivedThreadIds: newArchivedThreadIds,\n threadIdMap: {\n ...state.threadIdMap,\n ...newThreadIdMap,\n },\n threadData: {\n ...state.threadData,\n ...newThreadData,\n },\n };\n },\n })\n .then(() => {});\n }\n\n return this._loadThreadsPromise;\n }\n\n constructor(\n options: RemoteThreadListOptions,\n private readonly contextProvider: ModelContextProvider,\n ) {\n super();\n\n this._state.subscribe(() => this._notifySubscribers());\n this._hookManager = new RemoteThreadListHookInstanceManager(\n options.runtimeHook,\n );\n this.useProvider = create(() => ({\n Provider: options.adapter.unstable_Provider ?? Fragment,\n }));\n this.__internal_setOptions(options);\n\n this.switchToNewThread();\n }\n\n private useProvider;\n\n public __internal_setOptions(options: RemoteThreadListOptions) {\n if (this._options === options) return;\n\n this._options = options;\n\n const Provider = options.adapter.unstable_Provider ?? Fragment;\n if (Provider !== this.useProvider.getState().Provider) {\n this.useProvider.setState({ Provider }, true);\n }\n\n this._hookManager.setRuntimeHook(options.runtimeHook);\n }\n\n public __internal_load() {\n this.getLoadThreadsPromise(); // begin loading on initial bind\n }\n\n public get isLoading() {\n return this._state.value.isLoading;\n }\n\n public get threadIds() {\n return this._state.value.threadIds;\n }\n\n public get archivedThreadIds() {\n return this._state.value.archivedThreadIds;\n }\n\n public get newThreadId() {\n return this._state.value.newThreadId;\n }\n\n public get mainThreadId(): string {\n return this._mainThreadId;\n }\n\n public getMainThreadRuntimeCore() {\n const result = this._hookManager.getThreadRuntimeCore(this._mainThreadId);\n if (!result) return EMPTY_THREAD_CORE;\n return result;\n }\n\n public getThreadRuntimeCore(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n\n const result = this._hookManager.getThreadRuntimeCore(data.threadId);\n if (!result) throw new Error(\"Thread not found\");\n return result;\n }\n\n public getItemById(threadIdOrRemoteId: string) {\n return getThreadData(this._state.value, threadIdOrRemoteId);\n }\n\n public async switchToThread(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n\n if (this._mainThreadId === data.threadId) return;\n\n const task = this._hookManager.startThreadRuntime(data.threadId);\n if (this.mainThreadId !== undefined) {\n await task;\n } else {\n task.then(() => this._notifySubscribers());\n }\n\n if (data.status === \"archived\") await this.unarchive(data.threadId);\n this._mainThreadId = data.threadId;\n\n this._notifySubscribers();\n }\n\n public async switchToNewThread(): Promise<void> {\n // an initialization transaction is in progress, wait for it to settle\n while (\n this._state.baseValue.newThreadId !== undefined &&\n this._state.value.newThreadId === undefined\n ) {\n await this._state.waitForUpdate();\n }\n\n const state = this._state.value;\n let threadId: string | undefined = this._state.value.newThreadId;\n if (threadId === undefined) {\n do {\n threadId = `__LOCALID_${generateId()}`;\n } while (state.threadIdMap[threadId]);\n\n const mappingId = createThreadMappingId(threadId);\n this._state.update({\n ...state,\n newThreadId: threadId,\n threadIdMap: {\n ...state.threadIdMap,\n [threadId]: mappingId,\n },\n threadData: {\n ...state.threadData,\n [threadId]: {\n status: \"new\",\n threadId,\n },\n },\n });\n }\n\n return this.switchToThread(threadId);\n }\n\n public initialize = async (threadId: string) => {\n if (this._state.value.newThreadId !== threadId) {\n const data = this.getItemById(threadId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Unexpected new state\");\n return data.initializeTask;\n }\n\n return this._state.optimisticUpdate({\n execute: () => {\n return this._options.adapter.initialize(threadId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, threadId, \"regular\");\n },\n loading: (state, task) => {\n const mappingId = createThreadMappingId(threadId);\n return {\n ...state,\n threadData: {\n ...state.threadData,\n [mappingId]: {\n ...state.threadData[mappingId],\n initializeTask: task,\n },\n },\n };\n },\n then: (state, { remoteId, externalId }) => {\n const data = getThreadData(state, threadId);\n if (!data) return state;\n\n const mappingId = createThreadMappingId(threadId);\n return {\n ...state,\n threadIdMap: {\n ...state.threadIdMap,\n [remoteId]: mappingId,\n },\n threadData: {\n ...state.threadData,\n [mappingId]: {\n ...data,\n initializeTask: Promise.resolve({ remoteId, externalId }),\n remoteId,\n externalId,\n },\n },\n };\n },\n });\n };\n\n public generateTitle = async (threadId: string) => {\n const data = this.getItemById(threadId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Thread is not yet initialized\");\n\n const { remoteId } = await data.initializeTask;\n const messages = this.getThreadRuntimeCore(threadId).messages;\n const stream = await this._options.adapter.generateTitle(\n remoteId,\n messages,\n );\n const messageStream = AssistantMessageStream.fromAssistantStream(stream);\n for await (const result of messageStream) {\n const newTitle = result.parts.filter((c) => c.type === \"text\")[0]?.text;\n const state = this._state.baseValue;\n this._state.update({\n ...state,\n threadData: {\n ...state.threadData,\n [data.threadId]: {\n ...data,\n title: newTitle,\n },\n },\n });\n }\n };\n\n public rename(threadIdOrRemoteId: string, newTitle: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Thread is not yet initialized\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n const { remoteId } = await data.initializeTask;\n return this._options.adapter.rename(remoteId, newTitle);\n },\n optimistic: (state) => {\n const data = getThreadData(state, threadIdOrRemoteId);\n if (!data) return state;\n\n return {\n ...state,\n threadData: {\n ...state.threadData,\n [data.threadId]: {\n ...data,\n title: newTitle,\n },\n },\n };\n },\n });\n }\n\n private async _ensureThreadIsNotMain(threadId: string) {\n if (threadId === this.newThreadId)\n throw new Error(\"Cannot ensure new thread is not main\");\n\n if (threadId === this._mainThreadId) {\n await this.switchToNewThread();\n }\n }\n\n public async archive(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\")\n throw new Error(\"Thread is not yet initialized or already archived\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n await this._ensureThreadIsNotMain(data.threadId);\n const { remoteId } = await data.initializeTask;\n return this._options.adapter.archive(remoteId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"archived\");\n },\n });\n }\n\n public unarchive(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"archived\") throw new Error(\"Thread is not archived\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n try {\n const { remoteId } = await data.initializeTask;\n return await this._options.adapter.unarchive(remoteId);\n } catch (error) {\n await this._ensureThreadIsNotMain(data.threadId);\n throw error;\n }\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"regular\");\n },\n });\n }\n\n public async delete(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\" && data.status !== \"archived\")\n throw new Error(\"Thread is not yet initialized\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n await this._ensureThreadIsNotMain(data.threadId);\n const { remoteId } = await data.initializeTask;\n return await this._options.adapter.delete(remoteId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"deleted\");\n },\n });\n }\n\n public async detach(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\" && data.status !== \"archived\")\n throw new Error(\"Thread is not yet initialized\");\n\n await this._ensureThreadIsNotMain(data.threadId);\n this._hookManager.stopThreadRuntime(data.threadId);\n }\n\n private useBoundIds = create<string[]>(() => []);\n\n public __internal_RenderComponent: FC = () => {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const id = useId();\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useEffect(() => {\n this.useBoundIds.setState((s) => [...s, id], true);\n return () => {\n this.useBoundIds.setState((s) => s.filter((i) => i !== id), true);\n };\n }, [id]);\n\n const boundIds = this.useBoundIds();\n const { Provider } = this.useProvider();\n\n const adapters = {\n modelContext: this.contextProvider,\n };\n\n return (\n (boundIds.length === 0 || boundIds[0] === id) && (\n // only render if the component is the first one mounted\n <RuntimeAdapterProvider adapters={adapters}>\n <this._hookManager.__internal_RenderThreadRuntimes\n provider={Provider}\n />\n </RuntimeAdapterProvider>\n )\n );\n };\n}\n"],"mappings":";;;AAGA,SAAS,kBAAkB;AAK3B,SAAS,2CAA2C;AACpD,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAa,UAAU,WAAW,aAAa;AAC/C,SAAS,cAAc;AACvB,SAAS,8BAA8B;AAEvC,SAAS,8BAA8B;AA0iB7B;AA9gBV,SAAS,sBAAsB,IAA+B;AAC5D,SAAO;AACT;AAWA,IAAM,gBAAgB,CACpB,OACA,uBACG;AACH,QAAM,MAAM,MAAM,YAAY,kBAAkB;AAChD,MAAI,QAAQ,OAAW,QAAO;AAC9B,SAAO,MAAM,WAAW,GAAG;AAC7B;AAEA,IAAM,sBAAsB,CAC1B,OACA,oBACA,cACG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AY,kBAAkB;AAChD,QAAI,CAAC,KAAM,OAAM,IAAI,MAAM,kBAAkB;AAC7C,QAAI,KAAK,WAAW,aAAa,KAAK,WAAW;AAC/C,YAAM,IAAI,MAAM,+BAA+B;AAEjD,UAAM,KAAK,uBAAuB,KAAK,QAAQ;AAC/C,SAAK,aAAa,kBAAkB,KAAK,QAAQ;AAAA,EACnD;AAAA,EAEQ,cAAc,OAAiB,MAAM,CAAC,CAAC;AAAA,EAExC,6BAAiC,MAAM;AAE5C,UAAM,KAAK,MAAM;AAEjB,cAAU,MAAM;AACd,WAAK,YAAY,SAAS,CAAC,MAAM,CAAC,GAAG,GAAG,EAAE,GAAG,IAAI;AACjD,aAAO,MAAM;AACX,aAAK,YAAY,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,MAAM,EAAE,GAAG,IAAI;AAAA,MAClE;AAAA,IACF,GAAG,CAAC,EAAE,CAAC;AAEP,UAAM,WAAW,KAAK,YAAY;AAClC,UAAM,EAAE,SAAS,IAAI,KAAK,YAAY;AAEtC,UAAM,WAAW;AAAA,MACf,cAAc,KAAK;AAAA,IACrB;AAEA,YACG,SAAS,WAAW,KAAK,SAAS,CAAC,MAAM;AAAA,IAExC,oBAAC,0BAAuB,UACtB;AAAA,MAAC,KAAK,aAAa;AAAA,MAAlB;AAAA,QACC,UAAU;AAAA;AAAA,IACZ,GACF;AAAA,EAGN;AACF;","names":["data"]}
1
+ {"version":3,"sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.tsx"],"sourcesContent":["\"use client\";\n\nimport { ThreadListRuntimeCore } from \"../core/ThreadListRuntimeCore\";\nimport { generateId } from \"../../internal\";\nimport {\n RemoteThreadInitializeResponse,\n RemoteThreadListOptions,\n} from \"./types\";\nimport { RemoteThreadListHookInstanceManager } from \"./RemoteThreadListHookInstanceManager\";\nimport { BaseSubscribable } from \"./BaseSubscribable\";\nimport { EMPTY_THREAD_CORE } from \"./EMPTY_THREAD_CORE\";\nimport { OptimisticState } from \"./OptimisticState\";\nimport { FC, Fragment, useEffect, useId } from \"react\";\nimport { create } from \"zustand\";\nimport { AssistantMessageStream } from \"assistant-stream\";\nimport { ModelContextProvider } from \"../../model-context\";\nimport { RuntimeAdapterProvider } from \"../adapters/RuntimeAdapterProvider\";\n\ntype RemoteThreadData =\n | {\n readonly threadId: string;\n readonly remoteId?: undefined;\n readonly externalId?: undefined;\n readonly status: \"new\";\n readonly title: undefined;\n }\n | {\n readonly threadId: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId?: undefined;\n readonly externalId?: undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n }\n | {\n readonly threadId: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId: string;\n readonly externalId: string | undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n };\n\ntype THREAD_MAPPING_ID = string & { __brand: \"THREAD_MAPPING_ID\" };\nfunction createThreadMappingId(id: string): THREAD_MAPPING_ID {\n return id as THREAD_MAPPING_ID;\n}\n\ntype RemoteThreadState = {\n readonly isLoading: boolean;\n readonly newThreadId: string | undefined;\n readonly threadIds: readonly string[];\n readonly archivedThreadIds: readonly string[];\n readonly threadIdMap: Readonly<Record<string, THREAD_MAPPING_ID>>;\n readonly threadData: Readonly<Record<THREAD_MAPPING_ID, RemoteThreadData>>;\n};\n\nconst getThreadData = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n) => {\n const idx = state.threadIdMap[threadIdOrRemoteId];\n if (idx === undefined) return undefined;\n return state.threadData[idx];\n};\n\nconst updateStatusReducer = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n newStatus: \"regular\" | \"archived\" | \"deleted\",\n) => {\n const data = getThreadData(state, threadIdOrRemoteId);\n if (!data) return state;\n\n const { threadId, remoteId, status: lastStatus } = data;\n if (lastStatus === newStatus) return state;\n\n const newState = { ...state };\n\n // lastStatus\n switch (lastStatus) {\n case \"new\":\n newState.newThreadId = undefined;\n break;\n case \"regular\":\n newState.threadIds = newState.threadIds.filter((t) => t !== threadId);\n break;\n case \"archived\":\n newState.archivedThreadIds = newState.archivedThreadIds.filter(\n (t) => t !== threadId,\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = lastStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n // newStatus\n switch (newStatus) {\n case \"regular\":\n newState.threadIds = [threadId, ...newState.threadIds];\n break;\n\n case \"archived\":\n newState.archivedThreadIds = [threadId, ...newState.archivedThreadIds];\n break;\n\n case \"deleted\":\n newState.threadData = Object.fromEntries(\n Object.entries(newState.threadData).filter(([key]) => key !== threadId),\n );\n newState.threadIdMap = Object.fromEntries(\n Object.entries(newState.threadIdMap).filter(\n ([key]) => key !== threadId && key !== remoteId,\n ),\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = newStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n if (newStatus !== \"deleted\") {\n newState.threadData = {\n ...newState.threadData,\n [threadId]: {\n ...data,\n status: newStatus,\n },\n };\n }\n\n return newState;\n};\n\nexport class RemoteThreadListThreadListRuntimeCore\n extends BaseSubscribable\n implements ThreadListRuntimeCore\n{\n private _options!: RemoteThreadListOptions;\n private readonly _hookManager: RemoteThreadListHookInstanceManager;\n\n private _loadThreadsPromise: Promise<void> | undefined;\n\n private _mainThreadId!: string;\n private readonly _state = new OptimisticState<RemoteThreadState>({\n isLoading: false,\n newThreadId: undefined,\n threadIds: [],\n archivedThreadIds: [],\n threadIdMap: {},\n threadData: {},\n });\n\n public getLoadThreadsPromise() {\n // TODO this needs to be cached in case this promise is loaded during suspense\n if (!this._loadThreadsPromise) {\n this._loadThreadsPromise = this._state\n .optimisticUpdate({\n execute: () => this._options.adapter.list(),\n loading: (state) => {\n return {\n ...state,\n isLoading: true,\n };\n },\n then: (state, l) => {\n const newThreadIds = [];\n const newArchivedThreadIds = [];\n const newThreadIdMap = {} as Record<string, THREAD_MAPPING_ID>;\n const newThreadData = {} as Record<\n THREAD_MAPPING_ID,\n RemoteThreadData\n >;\n\n for (const thread of l.threads) {\n switch (thread.status) {\n case \"regular\":\n newThreadIds.push(thread.remoteId);\n break;\n case \"archived\":\n newArchivedThreadIds.push(thread.remoteId);\n break;\n default: {\n const _exhaustiveCheck: never = thread.status;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n const mappingId = createThreadMappingId(thread.remoteId);\n newThreadIdMap[thread.remoteId] = mappingId;\n newThreadData[mappingId] = {\n threadId: thread.remoteId,\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n status: thread.status,\n title: thread.title,\n initializeTask: Promise.resolve({\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n }),\n };\n }\n\n return {\n ...state,\n threadIds: newThreadIds,\n archivedThreadIds: newArchivedThreadIds,\n threadIdMap: {\n ...state.threadIdMap,\n ...newThreadIdMap,\n },\n threadData: {\n ...state.threadData,\n ...newThreadData,\n },\n };\n },\n })\n .then(() => {});\n }\n\n return this._loadThreadsPromise;\n }\n\n constructor(\n options: RemoteThreadListOptions,\n private readonly contextProvider: ModelContextProvider,\n ) {\n super();\n\n this._state.subscribe(() => this._notifySubscribers());\n this._hookManager = new RemoteThreadListHookInstanceManager(\n options.runtimeHook,\n );\n this.useProvider = create(() => ({\n Provider: options.adapter.unstable_Provider ?? Fragment,\n }));\n this.__internal_setOptions(options);\n\n this.switchToNewThread();\n }\n\n private useProvider;\n\n public __internal_setOptions(options: RemoteThreadListOptions) {\n if (this._options === options) return;\n\n this._options = options;\n\n const Provider = options.adapter.unstable_Provider ?? Fragment;\n if (Provider !== this.useProvider.getState().Provider) {\n this.useProvider.setState({ Provider }, true);\n }\n\n this._hookManager.setRuntimeHook(options.runtimeHook);\n }\n\n public __internal_load() {\n this.getLoadThreadsPromise(); // begin loading on initial bind\n }\n\n public get isLoading() {\n return this._state.value.isLoading;\n }\n\n public get threadIds() {\n return this._state.value.threadIds;\n }\n\n public get archivedThreadIds() {\n return this._state.value.archivedThreadIds;\n }\n\n public get newThreadId() {\n return this._state.value.newThreadId;\n }\n\n public get mainThreadId(): string {\n return this._mainThreadId;\n }\n\n public getMainThreadRuntimeCore() {\n const result = this._hookManager.getThreadRuntimeCore(this._mainThreadId);\n if (!result) return EMPTY_THREAD_CORE;\n return result;\n }\n\n public getThreadRuntimeCore(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n\n const result = this._hookManager.getThreadRuntimeCore(data.threadId);\n if (!result) throw new Error(\"Thread not found\");\n return result;\n }\n\n public getItemById(threadIdOrRemoteId: string) {\n return getThreadData(this._state.value, threadIdOrRemoteId);\n }\n\n public async switchToThread(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n\n if (this._mainThreadId === data.threadId) return;\n\n const task = this._hookManager.startThreadRuntime(data.threadId);\n if (this.mainThreadId !== undefined) {\n await task;\n } else {\n task.then(() => this._notifySubscribers());\n }\n\n if (data.status === \"archived\") await this.unarchive(data.threadId);\n this._mainThreadId = data.threadId;\n\n this._notifySubscribers();\n }\n\n public async switchToNewThread(): Promise<void> {\n // an initialization transaction is in progress, wait for it to settle\n while (\n this._state.baseValue.newThreadId !== undefined &&\n this._state.value.newThreadId === undefined\n ) {\n await this._state.waitForUpdate();\n }\n\n const state = this._state.value;\n let threadId: string | undefined = this._state.value.newThreadId;\n if (threadId === undefined) {\n do {\n threadId = `__LOCALID_${generateId()}`;\n } while (state.threadIdMap[threadId]);\n\n const mappingId = createThreadMappingId(threadId);\n this._state.update({\n ...state,\n newThreadId: threadId,\n threadIdMap: {\n ...state.threadIdMap,\n [threadId]: mappingId,\n },\n threadData: {\n ...state.threadData,\n [threadId]: {\n status: \"new\",\n threadId,\n },\n },\n });\n }\n\n return this.switchToThread(threadId);\n }\n\n public initialize = async (threadId: string) => {\n if (this._state.value.newThreadId !== threadId) {\n const data = this.getItemById(threadId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Unexpected new state\");\n return data.initializeTask;\n }\n\n return this._state.optimisticUpdate({\n execute: () => {\n return this._options.adapter.initialize(threadId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, threadId, \"regular\");\n },\n loading: (state, task) => {\n const mappingId = createThreadMappingId(threadId);\n return {\n ...state,\n threadData: {\n ...state.threadData,\n [mappingId]: {\n ...state.threadData[mappingId],\n initializeTask: task,\n },\n },\n };\n },\n then: (state, { remoteId, externalId }) => {\n const data = getThreadData(state, threadId);\n if (!data) return state;\n\n const mappingId = createThreadMappingId(threadId);\n return {\n ...state,\n threadIdMap: {\n ...state.threadIdMap,\n [remoteId]: mappingId,\n },\n threadData: {\n ...state.threadData,\n [mappingId]: {\n ...data,\n initializeTask: Promise.resolve({ remoteId, externalId }),\n remoteId,\n externalId,\n },\n },\n };\n },\n });\n };\n\n public generateTitle = async (threadId: string) => {\n const data = this.getItemById(threadId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Thread is not yet initialized\");\n\n const { remoteId } = await data.initializeTask;\n\n const runtimeCore = this._hookManager.getThreadRuntimeCore(data.threadId);\n if (!runtimeCore) return; // thread is no longer running\n\n const messages = runtimeCore.messages;\n const stream = await this._options.adapter.generateTitle(\n remoteId,\n messages,\n );\n const messageStream = AssistantMessageStream.fromAssistantStream(stream);\n for await (const result of messageStream) {\n const newTitle = result.parts.filter((c) => c.type === \"text\")[0]?.text;\n const state = this._state.baseValue;\n this._state.update({\n ...state,\n threadData: {\n ...state.threadData,\n [data.threadId]: {\n ...data,\n title: newTitle,\n },\n },\n });\n }\n };\n\n public rename(threadIdOrRemoteId: string, newTitle: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Thread is not yet initialized\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n const { remoteId } = await data.initializeTask;\n return this._options.adapter.rename(remoteId, newTitle);\n },\n optimistic: (state) => {\n const data = getThreadData(state, threadIdOrRemoteId);\n if (!data) return state;\n\n return {\n ...state,\n threadData: {\n ...state.threadData,\n [data.threadId]: {\n ...data,\n title: newTitle,\n },\n },\n };\n },\n });\n }\n\n private async _ensureThreadIsNotMain(threadId: string) {\n if (threadId === this.newThreadId)\n throw new Error(\"Cannot ensure new thread is not main\");\n\n if (threadId === this._mainThreadId) {\n await this.switchToNewThread();\n }\n }\n\n public async archive(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\")\n throw new Error(\"Thread is not yet initialized or already archived\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n await this._ensureThreadIsNotMain(data.threadId);\n const { remoteId } = await data.initializeTask;\n return this._options.adapter.archive(remoteId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"archived\");\n },\n });\n }\n\n public unarchive(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"archived\") throw new Error(\"Thread is not archived\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n try {\n const { remoteId } = await data.initializeTask;\n return await this._options.adapter.unarchive(remoteId);\n } catch (error) {\n await this._ensureThreadIsNotMain(data.threadId);\n throw error;\n }\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"regular\");\n },\n });\n }\n\n public async delete(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\" && data.status !== \"archived\")\n throw new Error(\"Thread is not yet initialized\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n await this._ensureThreadIsNotMain(data.threadId);\n const { remoteId } = await data.initializeTask;\n return await this._options.adapter.delete(remoteId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"deleted\");\n },\n });\n }\n\n public async detach(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\" && data.status !== \"archived\")\n throw new Error(\"Thread is not yet initialized\");\n\n await this._ensureThreadIsNotMain(data.threadId);\n this._hookManager.stopThreadRuntime(data.threadId);\n }\n\n private useBoundIds = create<string[]>(() => []);\n\n public __internal_RenderComponent: FC = () => {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const id = useId();\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useEffect(() => {\n this.useBoundIds.setState((s) => [...s, id], true);\n return () => {\n this.useBoundIds.setState((s) => s.filter((i) => i !== id), true);\n };\n }, [id]);\n\n const boundIds = this.useBoundIds();\n const { Provider } = this.useProvider();\n\n const adapters = {\n modelContext: this.contextProvider,\n };\n\n return (\n (boundIds.length === 0 || boundIds[0] === id) && (\n // only render if the component is the first one mounted\n <RuntimeAdapterProvider adapters={adapters}>\n <this._hookManager.__internal_RenderThreadRuntimes\n provider={Provider}\n />\n </RuntimeAdapterProvider>\n )\n );\n };\n}\n"],"mappings":";;;AAGA,SAAS,kBAAkB;AAK3B,SAAS,2CAA2C;AACpD,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAa,UAAU,WAAW,aAAa;AAC/C,SAAS,cAAc;AACvB,SAAS,8BAA8B;AAEvC,SAAS,8BAA8B;AA8iB7B;AAlhBV,SAAS,sBAAsB,IAA+B;AAC5D,SAAO;AACT;AAWA,IAAM,gBAAgB,CACpB,OACA,uBACG;AACH,QAAM,MAAM,MAAM,YAAY,kBAAkB;AAChD,MAAI,QAAQ,OAAW,QAAO;AAC9B,SAAO,MAAM,WAAW,GAAG;AAC7B;AAEA,IAAM,sBAAsB,CAC1B,OACA,oBACA,cACG;AACH,QAAM,OAAO,cAAc,OAAO,kBAAkB;AACp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OAAO,KAAK,YAAY,kBAAkB;AAChD,QAAI,CAAC,KAAM,OAAM,IAAI,MAAM,kBAAkB;AAC7C,QAAI,KAAK,WAAW,aAAa,KAAK,WAAW;AAC/C,YAAM,IAAI,MAAM,+BAA+B;AAEjD,UAAM,KAAK,uBAAuB,KAAK,QAAQ;AAC/C,SAAK,aAAa,kBAAkB,KAAK,QAAQ;AAAA,EACnD;AAAA,EAEQ,cAAc,OAAiB,MAAM,CAAC,CAAC;AAAA,EAExC,6BAAiC,MAAM;AAE5C,UAAM,KAAK,MAAM;AAEjB,cAAU,MAAM;AACd,WAAK,YAAY,SAAS,CAAC,MAAM,CAAC,GAAG,GAAG,EAAE,GAAG,IAAI;AACjD,aAAO,MAAM;AACX,aAAK,YAAY,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,MAAM,EAAE,GAAG,IAAI;AAAA,MAClE;AAAA,IACF,GAAG,CAAC,EAAE,CAAC;AAEP,UAAM,WAAW,KAAK,YAAY;AAClC,UAAM,EAAE,SAAS,IAAI,KAAK,YAAY;AAEtC,UAAM,WAAW;AAAA,MACf,cAAc,KAAK;AAAA,IACrB;AAEA,YACG,SAAS,WAAW,KAAK,SAAS,CAAC,MAAM;AAAA,IAExC,oBAAC,0BAAuB,UACtB;AAAA,MAAC,KAAK,aAAa;AAAA,MAAlB;AAAA,QACC,UAAU;AAAA;AAAA,IACZ,GACF;AAAA,EAGN;AACF;","names":["data"]}
package/package.json CHANGED
@@ -28,7 +28,7 @@
28
28
  "conversational-ui",
29
29
  "conversational-ai"
30
30
  ],
31
- "version": "0.10.31",
31
+ "version": "0.10.33",
32
32
  "license": "MIT",
33
33
  "type": "module",
34
34
  "exports": {
@@ -49,29 +49,29 @@ const groupMessagePartsByParentId = (
49
49
  ): MessagePartGroup[] => {
50
50
  // Map maintains insertion order, so groups appear in order of first occurrence
51
51
  const groupMap = new Map<string, number[]>();
52
-
52
+
53
53
  // Process each part in order
54
54
  for (let i = 0; i < parts.length; i++) {
55
55
  const part = parts[i];
56
56
  const parentId = part?.parentId as string | undefined;
57
-
57
+
58
58
  // For parts without parentId, assign a unique group ID to maintain their position
59
59
  const groupId = parentId ?? `__ungrouped_${i}`;
60
-
60
+
61
61
  // Get or create the indices array for this group
62
62
  const indices = groupMap.get(groupId) ?? [];
63
63
  indices.push(i);
64
64
  groupMap.set(groupId, indices);
65
65
  }
66
-
66
+
67
67
  // Convert map to array of groups
68
68
  const groups: MessagePartGroup[] = [];
69
69
  for (const [groupId, indices] of groupMap) {
70
70
  // Extract parentId (undefined for ungrouped parts)
71
- const parentId = groupId.startsWith('__ungrouped_') ? undefined : groupId;
71
+ const parentId = groupId.startsWith("__ungrouped_") ? undefined : groupId;
72
72
  groups.push({ parentId, indices });
73
73
  }
74
-
74
+
75
75
  return groups;
76
76
  };
77
77
 
@@ -14,10 +14,7 @@ import {
14
14
  import { UseBoundStore, StoreApi, create } from "zustand";
15
15
  import { useAssistantRuntime } from "../../context";
16
16
  import { ThreadListItemRuntimeProvider } from "../../context/providers/ThreadListItemRuntimeProvider";
17
- import {
18
- useThreadListItem,
19
- useThreadListItemRuntime,
20
- } from "../../context/react/ThreadListItemContext";
17
+ import { useThreadListItem } from "../../context/react/ThreadListItemContext";
21
18
  import { ThreadRuntimeCore, ThreadRuntimeImpl } from "../../internal";
22
19
  import { BaseSubscribable } from "./BaseSubscribable";
23
20
  import { AssistantRuntime } from "../../api";
@@ -65,10 +62,7 @@ export class RemoteThreadListHookInstanceManager extends BaseSubscribable {
65
62
 
66
63
  public getThreadRuntimeCore(threadId: string) {
67
64
  const instance = this.instances.get(threadId);
68
- if (!instance)
69
- throw new Error(
70
- "getThreadRuntimeCore not found. This is a bug in assistant-ui.",
71
- );
65
+ if (!instance) return undefined;
72
66
  return instance.runtime;
73
67
  }
74
68
 
@@ -117,9 +111,10 @@ export class RemoteThreadListHookInstanceManager extends BaseSubscribable {
117
111
  }, [threadBinding, updateRuntime]);
118
112
 
119
113
  // auto initialize thread
120
- const threadListItemRuntime = useThreadListItemRuntime();
121
114
  useEffect(() => {
122
115
  return runtime.threads.main.unstable_on("initialize", () => {
116
+ const threadListItemRuntime = runtime.threads.getItemById(id);
117
+
123
118
  if (threadListItemRuntime.getState().status === "new") {
124
119
  threadListItemRuntime.initialize();
125
120
 
@@ -131,7 +126,7 @@ export class RemoteThreadListHookInstanceManager extends BaseSubscribable {
131
126
  });
132
127
  }
133
128
  });
134
- }, [runtime, threadListItemRuntime]);
129
+ }, [runtime, id]);
135
130
 
136
131
  return null;
137
132
  };
@@ -418,7 +418,11 @@ export class RemoteThreadListThreadListRuntimeCore
418
418
  if (data.status === "new") throw new Error("Thread is not yet initialized");
419
419
 
420
420
  const { remoteId } = await data.initializeTask;
421
- const messages = this.getThreadRuntimeCore(threadId).messages;
421
+
422
+ const runtimeCore = this._hookManager.getThreadRuntimeCore(data.threadId);
423
+ if (!runtimeCore) return; // thread is no longer running
424
+
425
+ const messages = runtimeCore.messages;
422
426
  const stream = await this._options.adapter.generateTitle(
423
427
  remoteId,
424
428
  messages,