Compare commits

...

2 Commits

Author SHA1 Message Date
Gaurav Tewari
711a34e421 feat(noz): show open chats as bottom-strip tabs
Open tabs and unread replies persist in localStorage, so both survive a reload.
2026-11-13 16:41:26 +05:30
Gaurav Tewari
8e02fd808b feat(bottom-strip): add closable StripTab and StripTabs
@signozhq/ui/tabs has no close action and scrolls instead of shrinking, so the tab is two Buttons.
2026-11-13 16:41:20 +05:30
17 changed files with 704 additions and 9 deletions

View File

@@ -13,7 +13,7 @@ const config: Config.InitialOptions = {
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
modulePathIgnorePatterns: ['dist'],
moduleNameMapper: {
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$':
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff|wav)$':
'<rootDir>/__mocks__/fileMock.ts',
// The icon glob module uses `import.meta.glob` (Vite-only); jest can't parse
// it, so redirect any import of it to a stub.

Binary file not shown.

View File

@@ -1,4 +1,11 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import cx from 'classnames';
import { useAppLocation } from 'lib/router/useAppLocation';
@@ -45,6 +52,17 @@ export default function ConversationView({
const cancelStream = useAIAssistantStore((s) => s.cancelStream);
const analyticsCtx = useAIAssistantAnalyticsContext(conversationId);
const hasUnreadReply = useAIAssistantStore((s) =>
s.unreadReplyIds.includes(conversationId),
);
const markReplyRead = useAIAssistantStore((s) => s.markReplyRead);
// Layout effect: clears before paint, so the strip tab never flashes for an on-screen reply.
useLayoutEffect(() => {
if (hasUnreadReply) {
markReplyRead(conversationId);
}
}, [hasUnreadReply, conversationId, markReplyRead]);
// Auto-derived contexts come from the route the user is currently looking
// at (dashboard detail, service metrics, an explorer, …). Skip when the
// user is on the standalone AI Assistant page — there's no "underlying"

View File

@@ -528,11 +528,17 @@ function finalizeStreamingMessage(
createdAt: Date.now(),
});
conv.updatedAt = Date.now();
dropUnreadReply(s, conversationId);
s.unreadReplyIds.push(conversationId);
}
delete s.streams[conversationId];
});
}
function dropUnreadReply(s: AIAssistantStore, conversationId: string): void {
s.unreadReplyIds = s.unreadReplyIds.filter((id) => id !== conversationId);
}
function hasPendingInput(conversationId: string, get: StoreGetter): boolean {
const stream = get().streams[conversationId];
return Boolean(stream?.pendingApproval || stream?.pendingClarification);
@@ -627,6 +633,9 @@ export interface AIAssistantStore {
// Per-conversation streaming state
streams: Record<string, ConversationStreamState>;
/** Thread ids whose finished reply no open view has shown yet, oldest first; persisted. */
unreadReplyIds: string[];
/**
* Persists answered state for interactive blocks (ai-question, ai-confirm)
* so re-renders/remounts don't reset the answered UI.
@@ -636,6 +645,8 @@ export interface AIAssistantStore {
// Loading state
isLoadingThreads: boolean;
isLoadingThread: boolean;
/** True once `fetchThreads` has succeeded; a failed fetch leaves it false. */
hasLoadedThreads: boolean;
// Actions
openDrawer: () => void;
@@ -648,6 +659,7 @@ export interface AIAssistantStore {
startNewConversation: () => string;
setActiveConversation: (id: string) => void;
clearConversation: (id: string) => void;
markReplyRead: (id: string) => void;
archiveConversation: (id: string) => void;
restoreConversation: (id: string) => void;
renameConversation: (id: string, title: string) => Promise<void>;
@@ -782,8 +794,10 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
activeConversationId: null,
conversations: {},
streams: {},
unreadReplyIds: [],
isLoadingThreads: false,
isLoadingThread: false,
hasLoadedThreads: false,
answeredBlocks: {},
openDrawer: (): void => {
@@ -892,7 +906,14 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
s.conversations[thread.threadId] = mapped;
}
// Restored ids may name a deleted, archived or another user's thread.
s.unreadReplyIds = s.unreadReplyIds.filter((id) => {
const conv = s.conversations[id];
return Boolean(conv && !conv.archived);
});
s.isLoadingThreads = false;
s.hasLoadedThreads = true;
// Clear the rehydrate-time hydration flag on any entries
// the server didn't claim — those are local-only chats
@@ -1054,6 +1075,13 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
state.conversations[id].archived = false;
state.conversations[id].updatedAt = Date.now();
}
dropUnreadReply(state, id);
});
},
markReplyRead: (id: string): void => {
set((state) => {
dropUnreadReply(state, id);
});
},
@@ -1063,6 +1091,9 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
return;
}
disconnectAndCommit(id, set, get);
set((state) => {
dropUnreadReply(state, id);
});
if (conv.threadId) {
updateThread(conv.threadId, { archived: true }).catch((err) => {
console.error('[AIAssistant] archiveThread failed:', err);
@@ -1460,6 +1491,8 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
// Persist the active conversation so a page reload returns the
// user to the same thread instead of dumping them into a new one.
activeConversationId: state.activeConversationId,
// A reply needs a thread, and a chat is re-keyed to its threadId on first send.
unreadReplyIds: state.unreadReplyIds,
}),
migrate: () => ({
isDrawerOpen: false,

View File

@@ -33,6 +33,28 @@
cursor: default;
}
// Takes what the left slot leaves; `safe` overflows to the end, not over the left slot.
.right {
flex: 1 1 0;
justify-content: safe flex-end;
}
.right > * {
flex-shrink: 0;
}
// The only right-side entity that shrinks: tabs give way before Ask Noz and Support.
.chats {
display: flex;
align-items: center;
flex-shrink: 1;
min-width: 0;
&:empty {
display: none;
}
}
// separator b/w strip entities
.left > *:not(:last-child)::after,
.right > *:not(:last-child)::after {

View File

@@ -0,0 +1,7 @@
.unreadDot {
flex-shrink: 0;
width: var(--spacing-3);
height: var(--spacing-3);
border-radius: var(--radius-round);
background: var(--accent-primary);
}

View File

@@ -0,0 +1,54 @@
import { useMemo } from 'react';
import ROUTES from 'constants/routes';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { useAppLocation } from 'lib/router/useAppLocation';
import StripTabs from '../components/StripTabs/StripTabs';
import type { StripTabItem } from '../types';
import { useNozActiveChats } from './useNozActiveChats';
import { useNozReplySound } from './useNozReplySound';
import styles from './NozActiveChat.module.scss';
const UNTITLED = 'New conversation';
/** One tab per open Noz conversation; a dot marks an unseen reply. */
function NozActiveChat(): JSX.Element | null {
const { pathname } = useAppLocation();
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const { chats, openChat, closeChat } = useNozActiveChats();
useNozReplySound();
const items = useMemo(
() =>
chats.map((chat): StripTabItem => {
const title = chat.title ?? UNTITLED;
return {
id: chat.threadId,
label: title,
isActive: chat.isActive,
prefix: chat.hasUnreadReply ? (
<span className={styles.unreadDot} aria-hidden />
) : undefined,
ariaLabel: chat.hasUnreadReply ? `Noz replied in ${title}` : undefined,
};
}),
[chats],
);
// The drawer does not render on the Noz full page.
if (!isAIAssistantEnabled || pathname.startsWith(ROUTES.AI_ASSISTANT_BASE)) {
return null;
}
return (
<StripTabs
items={items}
onSelect={openChat}
onClose={closeChat}
testId="bottom-strip-noz-chats"
/>
);
}
export default NozActiveChat;

View File

@@ -0,0 +1,88 @@
import getLocalStorageKey from 'api/browser/localstorage/get';
import removeLocalStorageKey from 'api/browser/localstorage/remove';
import setLocalStorageKey from 'api/browser/localstorage/set';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
export const MAX_OPEN_CONVERSATIONS = 5;
export const NOZ_OPEN_CONVERSATIONS_STORAGE_KEY = 'nozOpenConversations';
interface NozOpenConversationsState {
/** Thread ids of the open tabs, oldest first. */
threadIds: string[];
/** Past the cap, drops the oldest tab with no unseen reply or running stream, else the oldest. */
open: (threadId: string) => void;
close: (threadId: string) => void;
prune: (staleThreadIds: readonly string[]) => void;
}
function isBusy(threadId: string): boolean {
const { conversations, unreadReplyIds, streams } =
useAIAssistantStore.getState();
const conversation = Object.values(conversations).find(
(c) => c.threadId === threadId,
);
return Boolean(
conversation &&
(unreadReplyIds.includes(conversation.id) || streams[conversation.id]),
);
}
export const useNozOpenConversationsStore = create<NozOpenConversationsState>()(
persist(
(set, get) => ({
threadIds: [],
open: (threadId): void => {
const { threadIds } = get();
// Every set() writes storage, so skip the no-op.
if (threadIds.includes(threadId)) {
return;
}
const next = [...threadIds, threadId];
if (next.length <= MAX_OPEN_CONVERSATIONS) {
set({ threadIds: next });
return;
}
const evicted =
next.find((id) => id !== threadId && !isBusy(id)) ?? next[0];
set({ threadIds: next.filter((id) => id !== evicted) });
},
close: (threadId): void => {
set({ threadIds: get().threadIds.filter((id) => id !== threadId) });
},
prune: (staleThreadIds): void => {
set({
threadIds: get().threadIds.filter((id) => !staleThreadIds.includes(id)),
});
},
}),
{
name: NOZ_OPEN_CONVERSATIONS_STORAGE_KEY,
version: 1,
// Scoped wrappers prefix the key when SigNoz is served under a base path.
storage: createJSONStorage(() => ({
getItem: getLocalStorageKey,
setItem: setLocalStorageKey,
removeItem: removeLocalStorageKey,
})),
partialize: (state) => ({ threadIds: state.threadIds }),
// Storage is user-editable: keep only string ids, newest within the cap.
merge: (persisted, current) => {
const stored = (persisted as Partial<NozOpenConversationsState> | null)
?.threadIds;
return {
...current,
threadIds: Array.isArray(stored)
? stored
.filter((id): id is string => typeof id === 'string')
.slice(-MAX_OPEN_CONVERSATIONS)
: [],
};
},
},
),
);

View File

@@ -0,0 +1,153 @@
import { useCallback, useEffect, useMemo } from 'react';
import {
openAIAssistant,
useAIAssistantStore,
} from 'container/AIAssistant/store/useAIAssistantStore';
import type { Conversation } from 'container/AIAssistant/types';
import { useNozOpenConversationsStore } from './store/useNozOpenConversationsStore';
export interface NozChatTab {
threadId: string;
title: string | undefined;
hasUnreadReply: boolean;
isActive: boolean;
}
interface UseNozActiveChatsResult {
chats: NozChatTab[];
openChat: (threadId: string) => void;
closeChat: (threadId: string) => void;
}
/**
* Open Noz conversations for the strip, kept in localStorage by thread id.
* A chat joins when it becomes active in the drawer or modal, or when a reply
* lands in it; it leaves on close, archive, clear, or once the server no
* longer lists it.
*/
export function useNozActiveChats(): UseNozActiveChatsResult {
const threadIds = useNozOpenConversationsStore((s) => s.threadIds);
const openTab = useNozOpenConversationsStore((s) => s.open);
const closeTab = useNozOpenConversationsStore((s) => s.close);
const pruneTabs = useNozOpenConversationsStore((s) => s.prune);
const conversations = useAIAssistantStore((s) => s.conversations);
const unreadReplyIds = useAIAssistantStore((s) => s.unreadReplyIds);
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const isAssistantOpen = useAIAssistantStore(
(s) => s.isDrawerOpen || s.isModalOpen,
);
const hasLoadedThreads = useAIAssistantStore((s) => s.hasLoadedThreads);
const setActiveConversation = useAIAssistantStore(
(s) => s.setActiveConversation,
);
const loadThread = useAIAssistantStore((s) => s.loadThread);
const markReplyRead = useAIAssistantStore((s) => s.markReplyRead);
// A new chat keeps its local id after the server assigns a thread id.
const conversationByThreadId = useMemo(() => {
const byThreadId = new Map<string, Conversation>();
Object.values(conversations).forEach((conversation) => {
if (conversation.threadId) {
byThreadId.set(conversation.threadId, conversation);
}
});
return byThreadId;
}, [conversations]);
const activeThreadId = activeConversationId
? conversations[activeConversationId]?.threadId
: undefined;
useEffect(() => {
if (isAssistantOpen && activeThreadId) {
openTab(activeThreadId);
}
}, [isAssistantOpen, activeThreadId, openTab]);
useEffect(() => {
unreadReplyIds.forEach((conversationId) => {
const threadId = conversations[conversationId]?.threadId;
if (threadId) {
openTab(threadId);
}
});
}, [unreadReplyIds, conversations, openTab]);
// Before the first successful fetch, a missing thread may only be unloaded.
useEffect(() => {
const staleThreadIds = threadIds.filter((threadId) => {
const conversation = conversationByThreadId.get(threadId);
return conversation ? Boolean(conversation.archived) : hasLoadedThreads;
});
if (staleThreadIds.length > 0) {
pruneTabs(staleThreadIds);
}
}, [threadIds, conversationByThreadId, hasLoadedThreads, pruneTabs]);
const chats = useMemo(
() =>
threadIds.flatMap((threadId): NozChatTab[] => {
const conversation = conversationByThreadId.get(threadId);
if (!conversation || conversation.archived) {
return [];
}
return [
{
threadId,
title: conversation.title,
hasUnreadReply: unreadReplyIds.includes(conversation.id),
isActive: isAssistantOpen && activeConversationId === conversation.id,
},
];
}),
[
threadIds,
conversationByThreadId,
unreadReplyIds,
isAssistantOpen,
activeConversationId,
],
);
const openChat = useCallback(
(threadId: string): void => {
const conversation = conversationByThreadId.get(threadId);
if (!conversation) {
return;
}
if (conversation.id !== activeConversationId) {
// After a reload only the thread list is loaded, not its messages.
if (conversation.messages.length === 0) {
void loadThread(threadId);
} else {
setActiveConversation(conversation.id);
}
}
openAIAssistant();
},
[
conversationByThreadId,
activeConversationId,
loadThread,
setActiveConversation,
],
);
// Closing dismisses the unseen reply too, or the reply would reopen the tab.
const closeChat = useCallback(
(threadId: string): void => {
closeTab(threadId);
const conversation = conversationByThreadId.get(threadId);
if (conversation && unreadReplyIds.includes(conversation.id)) {
markReplyRead(conversation.id);
}
},
[closeTab, conversationByThreadId, unreadReplyIds, markReplyRead],
);
return { chats, openChat, closeChat };
}

View File

@@ -0,0 +1,37 @@
import { useEffect, useLayoutEffect, useRef } from 'react';
import replySoundUrl from 'assets/sounds/noz-reply.wav';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
/** Chimes when a Noz reply lands in a conversation that isn't on screen. */
export function useNozReplySound(): void {
const unreadReplyIds = useAIAssistantStore((s) => s.unreadReplyIds);
const previousIdsRef = useRef(unreadReplyIds);
const latestIdsRef = useRef(unreadReplyIds);
const audioRef = useRef<HTMLAudioElement | null>(null);
useLayoutEffect(() => {
latestIdsRef.current = unreadReplyIds;
}, [unreadReplyIds]);
useEffect(() => {
const previousIds = previousIdsRef.current;
previousIdsRef.current = unreadReplyIds;
const newIds = unreadReplyIds.filter((id) => !previousIds.includes(id));
if (newIds.length === 0) {
return undefined;
}
// ConversationView clears an on-screen reply within the same task; check after it.
const timer = window.setTimeout(() => {
if (!newIds.some((id) => latestIdsRef.current.includes(id))) {
return;
}
audioRef.current ??= new Audio(replySoundUrl);
audioRef.current.currentTime = 0;
// Autoplay policy rejects play() until the user has interacted with the page.
audioRef.current.play().catch(() => undefined);
}, 0);
return (): void => window.clearTimeout(timer);
}, [unreadReplyIds]);
}

View File

@@ -0,0 +1,39 @@
// `--strip-tab-max-width` / `--strip-tab-min-width` let a container tune how far tabs grow and shrink.
.stripTab {
display: flex;
align-items: center;
flex: 0 1 var(--strip-tab-max-width, 160px);
min-width: var(--strip-tab-min-width, var(--spacing-32));
border-radius: var(--radius-1);
&:hover,
&:focus-within {
.close {
visibility: visible;
}
}
}
.isActive {
background: var(--l3-background);
.close {
visibility: visible;
}
}
.open {
display: flex;
flex: 1 1 auto;
min-width: 0;
--button-width: 100%;
--button-min-width: 0;
}
// Hidden rather than removed so the label doesn't reflow on hover.
.close {
display: flex;
flex-shrink: 0;
visibility: hidden;
}

View File

@@ -0,0 +1,72 @@
import type { ReactElement } from 'react';
import { X } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import cx from 'classnames';
import styles from './StripTab.module.scss';
interface StripTabProps {
label: string;
onClick: () => void;
onClose: () => void;
prefix?: ReactElement;
isActive?: boolean;
ariaLabel?: string;
testId?: string;
}
/** A closable tab: the label opens it, the × beside it closes it. */
function StripTab({
label,
onClick,
onClose,
prefix,
isActive,
ariaLabel,
testId,
}: StripTabProps): JSX.Element {
return (
<div
className={cx(styles.stripTab, isActive && styles.isActive)}
data-active={isActive || undefined}
data-testid={testId}
>
<span className={styles.open}>
<Button
variant="ghost"
color="secondary"
size="sm"
prefix={prefix}
onClick={onClick}
aria-label={ariaLabel}
aria-current={isActive || undefined}
testId={testId ? `${testId}-open` : undefined}
>
{label}
</Button>
</span>
<span className={styles.close}>
<Button
variant="ghost"
color="secondary"
size="sm"
icon
onClick={onClose}
aria-label={`Close ${label}`}
testId={testId ? `${testId}-close` : undefined}
>
<X size={12} />
</Button>
</span>
</div>
);
}
StripTab.defaultProps = {
prefix: undefined,
isActive: false,
ariaLabel: undefined,
testId: undefined,
};
export default StripTab;

View File

@@ -0,0 +1,8 @@
.stripTabs {
display: flex;
align-items: center;
flex: 0 1 auto;
gap: var(--spacing-1);
min-width: 0;
overflow: hidden;
}

View File

@@ -0,0 +1,45 @@
import type { StripTabItem } from '../../types';
import StripTab from '../StripTab/StripTab';
import styles from './StripTabs.module.scss';
interface StripTabsProps {
items: StripTabItem[];
onSelect: (id: string) => void;
onClose: (id: string) => void;
/** Each tab gets `${testId}-${item.id}`, with `-open` / `-close` on its buttons. */
testId?: string;
}
/** Closable tabs that shrink to share whatever width their container leaves. */
function StripTabs({
items,
onSelect,
onClose,
testId,
}: StripTabsProps): JSX.Element | null {
if (items.length === 0) {
return null;
}
return (
<div className={styles.stripTabs} data-testid={testId}>
{items.map((item) => (
<StripTab
key={item.id}
label={item.label}
prefix={item.prefix}
isActive={item.isActive}
ariaLabel={item.ariaLabel}
onClick={(): void => onSelect(item.id)}
onClose={(): void => onClose(item.id)}
testId={testId ? `${testId}-${item.id}` : undefined}
/>
))}
</div>
);
}
StripTabs.defaultProps = { testId: undefined };
export default StripTabs;

View File

@@ -2,6 +2,7 @@ import { useLayoutEffect } from 'react';
import AskNoz from './AskNoz/AskNoz';
import LeftSlot from './LeftSlot/LeftSlot';
import NozActiveChat from './NozActiveChat/NozActiveChat';
import SupportButton from './SupportButton/SupportButton';
import styles from './BottomStrip.module.scss';
@@ -31,6 +32,9 @@ function BottomStrip(): JSX.Element {
<LeftSlot />
</div>
<div className={styles.right}>
<div className={styles.chats}>
<NozActiveChat />
</div>
<AskNoz />
<SupportButton />
</div>

View File

@@ -1,4 +1,4 @@
import type { ReactNode } from 'react';
import type { ReactElement, ReactNode } from 'react';
export enum StripTone {
Default = 'default',
@@ -29,3 +29,14 @@ export type StripItem =
/** Tints the icon; the text stays neutral at every tone. */
tone?: StripTone;
};
/** One tab in `StripTabs`. */
export interface StripTabItem {
/** Stable identity, passed back to `onSelect` / `onClose`. */
id: string;
label: string;
prefix?: ReactElement;
isActive?: boolean;
/** Accessible name when the label alone doesn't say what opening does. */
ariaLabel?: string;
}

View File

@@ -1,8 +1,17 @@
import { rest } from 'msw';
import { AI_API_PATH } from 'api/AIAPIInstance';
import type { ThreadListResponse } from 'api/ai-assistant/chat';
import type {
ThreadDetailResponse,
ThreadListResponse,
ThreadSummary,
} from 'api/ai-assistant/chat';
import { MessageRoleDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import type { ConversationStreamState } from 'container/AIAssistant/types';
import {
MAX_OPEN_CONVERSATIONS,
useNozOpenConversationsStore,
} from 'container/BottomStrip/NozActiveChat/store/useNozOpenConversationsStore';
import { countControl, toggleControl } from '../controls/controls';
import { defineStoryMocks } from '../controls/defineStoryMocks';
@@ -15,8 +24,59 @@ const NOZ = 'Noz';
/** The streams this module seeds, so it only ever removes its own. */
const AWAITING_PREFIX = 'storybook-awaiting-';
/** The chats this module opens as strip tabs, so it only ever removes its own. */
const CHAT_PREFIX = 'storybook-chat-';
const CHAT_TITLES = [
'Why is checkout p99 latency spiking?',
'Top noisy log patterns in prod',
'Draft an alert for Kafka consumer lag',
'Error rate before and after the 14:05 deploy',
'Which dashboard panels load slowest?',
];
const threadsUrl = `${nozGlobalConfigResponse.data.ai_assistant_url}${AI_API_PATH}/threads`;
const noThreads: ThreadListResponse = { threads: [], hasMore: false };
const chatThreadIds = (count: number): string[] =>
CHAT_TITLES.slice(0, count).map((_, index) => `${CHAT_PREFIX}${index}`);
const chatThread = (threadId: string): ThreadSummary => {
const index = Number(threadId.slice(CHAT_PREFIX.length));
return {
threadId,
title: CHAT_TITLES[index] ?? null,
archived: false,
createdAt: '2026-11-13T09:00:00Z',
updatedAt: `2026-11-13T09:0${index}:00Z`,
};
};
const chatThreadDetail = (threadId: string): ThreadDetailResponse => {
const thread = chatThread(threadId);
return {
...thread,
messages: [
{
messageId: `${threadId}-question`,
role: MessageRoleDTO.user,
content: thread.title,
createdAt: thread.createdAt,
updatedAt: thread.createdAt,
},
{
messageId: `${threadId}-answer`,
role: MessageRoleDTO.assistant,
content:
'Here is what I found. This is a placeholder reply seeded by the Storybook Noz mocks.',
createdAt: thread.updatedAt,
updatedAt: thread.updatedAt,
},
],
};
};
const awaitingStream = (): ConversationStreamState => ({
isStreaming: false,
streamingContent: '',
@@ -47,19 +107,58 @@ export const nozMocks = defineStoryMocks({
value: 0,
max: 3,
}),
nozChats: countControl('Open chats', {
group: NOZ,
description:
'Conversations open as tabs in the bottom strip, newest beside Ask Noz. Clicking one opens it in the drawer.',
value: 0,
max: MAX_OPEN_CONVERSATIONS,
}),
nozUnread: countControl('Unseen replies', {
group: NOZ,
description:
'How many of the newest open chats carry a reply the user has not seen yet, marked with a dot.',
value: 0,
max: MAX_OPEN_CONVERSATIONS,
}),
},
handlers: ({ noz }) =>
handlers: ({ noz, nozChats }) =>
noz
? [
nozGlobalConfigHandler,
// The drawer loads the thread list on mount, while it is still closed.
rest.get(
`${nozGlobalConfigResponse.data.ai_assistant_url}${AI_API_PATH}/threads`,
(_req, res, ctx) => res(ctx.status(200), ctx.json(noThreads)),
rest.get(threadsUrl, (req, res, ctx) =>
res(
ctx.status(200),
ctx.json(
req.url.searchParams.get('archived') === 'true'
? noThreads
: {
threads: chatThreadIds(nozChats).map(chatThread),
hasMore: false,
},
),
),
),
rest.get(`${threadsUrl}/:threadId`, (req, res, ctx) =>
res(
ctx.status(200),
ctx.json(chatThreadDetail(String(req.params.threadId))),
),
),
]
: [],
effect: ({ nozAwaiting }) => {
effect: ({ nozAwaiting, nozChats, nozUnread }) => {
const threadIds = chatThreadIds(nozChats);
const unreadIds = threadIds.slice(Math.max(0, threadIds.length - nozUnread));
useNozOpenConversationsStore.setState((state) => ({
threadIds: [
...state.threadIds.filter((id) => !id.startsWith(CHAT_PREFIX)),
...threadIds,
],
}));
// The store is a singleton another story's mocks may have seeded, so
// only this module's own streams are replaced.
useAIAssistantStore.setState((state) => {
@@ -72,6 +171,11 @@ export const nozMocks = defineStoryMocks({
for (let index = 0; index < nozAwaiting; index += 1) {
state.streams[`${AWAITING_PREFIX}${index}`] = awaitingStream();
}
state.unreadReplyIds = [
...state.unreadReplyIds.filter((id) => !id.startsWith(CHAT_PREFIX)),
...unreadIds,
];
});
},
});