diff --git a/src/components/chat/MrOneHookTabs.tsx b/src/components/chat/MrOneHookTabs.tsx
new file mode 100644
index 0000000..5cb09d8
--- /dev/null
+++ b/src/components/chat/MrOneHookTabs.tsx
@@ -0,0 +1,190 @@
+import { useEffect, useState } from 'react';
+import { Plus, X } from 'lucide-react';
+import { LockIcon, UNLOCK_TIER_NAME, UpgradeDialog } from '../common/LockedFeature';
+import { trackProps, UiElement, type UiElementId, type UiTrackOptions } from '../../lib/analytics/analytics';
+
+export interface MrOneHookTab {
+ /** The saved chat's id; undefined for the new, unsaved chat. */
+ sessionId?: string;
+ title: string;
+}
+
+/**
+ * Mr. OneHook chats as calm, full-width tabs that float at the top of the chat (not part of the header).
+ *
+ * A soft track holds the chats in equal widths; the active chat is a raised pill that eases in. Only the
+ * active saved chat shows its delete control, so the row stays quiet. A round + ends the row. Must sees
+ * the same row with locks; tapping explains the Super feature. Motion is skipped with reduced motion.
+ */
+export function MrOneHookTabs({
+ tabs,
+ activeId,
+ locked,
+ leavingId,
+ onSelect,
+ onDelete,
+ onAdd,
+}: {
+ tabs: MrOneHookTab[];
+ activeId?: string;
+ locked: boolean;
+ /** The tab being replaced: it shrinks away before the new chat takes its place. */
+ leavingId?: string;
+ onSelect: (sessionId: string) => void;
+ onDelete: (sessionId: string) => void;
+ onAdd: () => void;
+}) {
+ const [upsell, setUpsell] = useState(false);
+ const newTabKey = tabs.find((t) => !t.sessionId) ? 'new' : undefined;
+ // The new tab grows in softly once it appears.
+ const [newShown, setNewShown] = useState(false);
+ useEffect(() => {
+ if (!newTabKey) {
+ setNewShown(false);
+ return;
+ }
+ const id = requestAnimationFrame(() => setNewShown(true));
+ return () => cancelAnimationFrame(id);
+ }, [newTabKey]);
+
+ const track =
+ 'rounded-full bg-surface/90 backdrop-blur-sm border border-border shadow-[0_2px_8px_rgba(0,0,0,0.08)]';
+
+ return (
+
+
+ {tabs.map((tab) => {
+ const active = locked ? true : tab.sessionId === activeId || (!tab.sessionId && !activeId);
+ const leaving = tab.sessionId !== undefined && tab.sessionId === leavingId;
+ const isNew = !tab.sessionId;
+ return (
+
+ {
+ if (locked) return setUpsell(true);
+ if (tab.sessionId && !active) onSelect(tab.sessionId);
+ }}
+ {...(locked
+ ? trackProps(UiElement.CHAT_MR_ONEHOOK_UPGRADE_OPEN, { action: 'tap' })
+ : trackProps(UiElement.CHAT_MR_ONEHOOK_SESSION_RESUME))}
+ className={`w-full h-full px-3 flex items-center justify-center gap-1.5 truncate text-sm cursor-pointer rounded-full
+ ${active ? 'font-semibold text-text' : 'text-text/55 hover:text-text/80'}
+ ${active && tab.sessionId && !locked ? 'pr-7' : ''}`}
+ aria-label={locked ? `${tab.title}. Keeping several chats is part of ${UNLOCK_TIER_NAME}.` : tab.title}
+ >
+ {tab.title}
+ {locked && }
+
+ {active && tab.sessionId && !locked && (
+ onDelete(tab.sessionId!)}
+ {...trackProps(UiElement.CHAT_MR_ONEHOOK_SESSION_DELETE, { action: 'tap' })}
+ aria-label={`Delete ${tab.title}`}
+ className="absolute right-1.5 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full flex items-center justify-center text-text/40 hover:text-text/70 hover:bg-black/5 cursor-pointer"
+ >
+
+
+ )}
+
+ );
+ })}
+
+
(locked ? setUpsell(true) : onAdd())}
+ {...(locked
+ ? trackProps(UiElement.CHAT_MR_ONEHOOK_UPGRADE_OPEN, { action: 'tap' })
+ : trackProps(UiElement.CHAT_MR_ONEHOOK_SESSION_NEW))}
+ aria-label={locked ? `New chat, locked. Keeping several chats is part of ${UNLOCK_TIER_NAME}.` : 'New chat with Mr. OneHook'}
+ className={`shrink-0 w-11 h-11 flex items-center justify-center text-text cursor-pointer ${track} ${locked ? 'opacity-55' : 'hover:bg-surface'}`}
+ >
+ {locked ? : }
+
+ {upsell && (
+
setUpsell(false)}
+ />
+ )}
+
+ );
+}
+
+/** A calm confirmation (replace the least recent chat, or delete one). */
+export function MrOneHookConfirm({
+ title,
+ body,
+ confirmLabel,
+ onConfirm,
+ onCancel,
+ element,
+ confirmOptions,
+ cancelOptions,
+}: {
+ title: string;
+ body: string;
+ confirmLabel: string;
+ onConfirm: () => void;
+ onCancel: () => void;
+ /** Telemetry element for both buttons; the options tell Confirm and Cancel apart. */
+ element: UiElementId;
+ confirmOptions?: UiTrackOptions;
+ cancelOptions?: UiTrackOptions;
+}) {
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onCancel();
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [onCancel]);
+ return (
+
+
e.stopPropagation()}
+ data-track-exempt="backdrop: only stops clicks inside the dialog from closing it"
+ >
+
{title}
+
{body}
+
+
+ Cancel
+
+
+ {confirmLabel}
+
+
+
+
+ );
+}
diff --git a/src/features/chat/ChatView.tsx b/src/features/chat/ChatView.tsx
index 9dade52..bd75fec 100644
--- a/src/features/chat/ChatView.tsx
+++ b/src/features/chat/ChatView.tsx
@@ -46,7 +46,6 @@ import {
HistoryLockedBanner,
LockedMessageNotice,
} from '../../components/chat/LockedMessage';
-import { LockIcon, UpgradeDialog } from '../../components/common/LockedFeature';
import {
useChatWallpaper,
WALLPAPER_SCRIM_CLASS,
@@ -61,12 +60,14 @@ import {
getSortOption,
type SortableConversation,
} from '../../lib/chat-sort';
+import { MrOneHookConfirm, MrOneHookTabs } from '../../components/chat/MrOneHookTabs';
import {
+ leastRecentSession,
+ mrOneHookTabs,
useMrOneHookChat,
type MrOneHookMessage,
type MrOneHookScope,
type PendingExcerptReview,
- type SessionListItem,
} from '../../lib/mr-onehook';
import {
selectEphemeralExcerpts,
@@ -1551,9 +1552,10 @@ function MrOneHookConversation({
match={activeMatch}
matchName={activeMatchName}
tier={tier}
+ onOpenScope={setScope}
/>
) : (
-
+
)}
>
);
@@ -1564,15 +1566,18 @@ function MrOneHookProductScope({
currentUser,
wallpaper,
tier,
+ onOpenScope,
}: {
currentUser: UserProfile;
wallpaper: ChatWallpaper;
tier: SubscriptionTier;
+ onOpenScope: (scope: MrOneHookScope) => void;
}) {
const chat = useMrOneHookChat({
userId: currentUser.id,
scope: { type: 'product' },
tier,
+ onOpenScope,
});
return ;
}
@@ -1588,6 +1593,7 @@ function MrOneHookMatchScope({
match,
matchName,
tier,
+ onOpenScope,
}: {
key?: string;
currentUser: UserProfile;
@@ -1595,6 +1601,7 @@ function MrOneHookMatchScope({
match: HydratedMatch;
matchName: string;
tier: SubscriptionTier;
+ onOpenScope: (scope: MrOneHookScope) => void;
}) {
const { messages } = useChatMessages(match.matchId, match.peerId || undefined);
@@ -1613,6 +1620,7 @@ function MrOneHookMatchScope({
scope: { type: 'match', matchId: match.matchId },
tier,
resolveLocalExcerpts,
+ onOpenScope,
});
return (
@@ -1639,7 +1647,20 @@ function MrOneHookChatBody({
scopeType: 'product' | 'connection';
}) {
const canSaveChats = isPaidSubscriptionTier(tier);
- const [savedOpen, setSavedOpen] = useState(false);
+ const [confirm, setConfirm] = useState(null);
+ const [leavingId, setLeavingId] = useState(undefined);
+ const tabs = mrOneHookTabs(chat.sessions, chat.currentSessionId, canSaveChats, chat.replacing);
+ const MAX_CHATS = 3;
+ const addChat = () => {
+ if (chat.loading) return;
+ const oldest = leastRecentSession(chat.sessions);
+ if (chat.sessions.length >= MAX_CHATS && chat.currentSessionId && !chat.replacing && oldest) {
+ const title = tabs.find((t) => t.sessionId === oldest.sessionId)?.title ?? 'your least recent chat';
+ setConfirm({ kind: 'replace', oldest: oldest.sessionId, title });
+ return;
+ }
+ chat.clear();
+ };
const { messages, loading, mood, pendingReview, availability, send, confirmReview, cancelReview } = chat;
const [input, setInput] = useState('');
const endRef = useRef(null);
@@ -1660,21 +1681,60 @@ function MrOneHookChatBody({
return (
<>
- {!canSaveChats && }
- {canSaveChats && (
- {
- if (!savedOpen) void chat.refreshSessions();
- setSavedOpen((v) => !v);
- }}
- />
- )}
-
+ {/* The chat tabs float at the top of the conversation, on the wallpaper (not part of the header). */}
+
+
+ void chat.resumeSession(id)}
+ onDelete={(id) =>
+ setConfirm({ kind: 'delete', id, title: tabs.find((t) => t.sessionId === id)?.title ?? 'this chat' })
+ }
+ onAdd={addChat}
+ />
+
+
+ {confirm?.kind === 'replace' && (
+
setConfirm(null)}
+ onConfirm={() => {
+ const old = confirm.oldest;
+ setConfirm(null);
+ setLeavingId(old);
+ window.setTimeout(() => {
+ setLeavingId(undefined);
+ chat.startReplacingLeastRecent();
+ }, 280);
+ }}
+ />
+ )}
+ {confirm?.kind === 'delete' && (
+ setConfirm(null)}
+ onConfirm={() => {
+ const id = confirm.id;
+ setConfirm(null);
+ void chat.deleteSession(id).catch(() => undefined);
+ }}
+ />
+ )}
+
{chat.sessionLimit && (
- setOpen(true)}
- {...trackProps(UiElement.CHAT_MR_ONEHOOK_SESSIONS_OPEN)}
- aria-label="Saved chats, locked"
- className="inline-flex items-center gap-1 px-3 py-1.5 rounded-full border border-dashed border-border text-xs font-semibold text-text-muted cursor-pointer"
- >
- Saved chats
-
- {open && (
- setOpen(false)}
- />
- )}
-
- );
-}
-
-function SavedChatsBar({
- chat,
- scopeType,
- open,
- onToggle,
-}: {
- chat: ReturnType
;
- scopeType: 'product' | 'connection';
- open: boolean;
- onToggle: () => void;
-}) {
- const [busy, setBusy] = useState(null);
- const [error, setError] = useState(null);
- const list: SessionListItem[] = chat.sessionLimit?.sessions ?? chat.sessions;
-
- const remove = async (sessionId: string) => {
- setBusy(sessionId);
- setError(null);
- try {
- await chat.deleteSession(sessionId);
- } catch {
- setError("Couldn't delete that chat. Please try again.");
- } finally {
- setBusy(null);
- }
- };
-
- return (
-
-
-
- Saved chats
-
-
{
- chat.clear();
- void chat.refreshSessions();
- }}
- {...trackProps(UiElement.CHAT_MR_ONEHOOK_SESSION_NEW)}
- className="flex items-center gap-1 px-3 py-1.5 rounded-full border border-border text-xs font-semibold text-text hover:bg-surface-hover cursor-pointer"
- >
- New chat
-
-
- {open && (
-
- {list.length === 0 && No saved chats yet. }
- {list.map((s) => (
-
-
- {s.scope === 'product' ? 'OneHook chat' : 'Match chat'} ·{' '}
- {Number.isFinite(Date.parse(s.updatedAt)) ? new Date(s.updatedAt).toLocaleString() : ''} ·{' '}
- {s.messageCount} messages
-
-
- {s.scope === scopeType && scopeType === 'product' && (
- void chat.resumeSession(s.sessionId)}
- {...trackProps(UiElement.CHAT_MR_ONEHOOK_SESSION_RESUME)}
- className="px-2 py-1 rounded-md border border-border font-semibold cursor-pointer"
- >
- Open
-
- )}
- void remove(s.sessionId)}
- disabled={busy === s.sessionId}
- {...trackProps(UiElement.CHAT_MR_ONEHOOK_SESSION_DELETE)}
- className="px-2 py-1 rounded-md border border-border font-semibold text-red-500 disabled:opacity-50 cursor-pointer"
- aria-label="Delete saved chat"
- >
- {busy === s.sessionId ? 'Deleting…' : 'Delete'}
-
-
-
- ))}
-
- )}
- {error &&
{error}
}
-
- );
-}
-
/**
* The consent gate. Shows the EXACT excerpts that would be shared (speaker, time, text) and sends
* nothing until the user approves. Mirrors the privacy contract: the user sees precisely what leaves
diff --git a/src/lib/analytics/generated/telemetryCatalog.ts b/src/lib/analytics/generated/telemetryCatalog.ts
index 7429d1c..3ba6e75 100644
--- a/src/lib/analytics/generated/telemetryCatalog.ts
+++ b/src/lib/analytics/generated/telemetryCatalog.ts
@@ -1,15 +1,15 @@
// GENERATED FILE - DO NOT EDIT.
-// telemetry-integrity: sha256 eb26b79e95efdcecec8c38d7f7f4e6f5a507d7abc2ec14ba82092910fd6a3341
+// telemetry-integrity: sha256 69623fb2407fa47f0bdb55c5dffc92e06e45b4fd15d51cd50015e879720d8e8f
// Source of truth: OneHookBackend/packages/telemetry/src/catalog.ts
// Regenerate: (OneHookBackend) npm run telemetry:generate && npm run telemetry:sync
-// Catalog version 1.14.0, hash 93ffca84480c903b.
+// Catalog version 1.14.0, hash 4d228919bd9883a5.
//
// HARD RULE: every user interaction MUST emit ui_interaction with an id from THIS file, and
// ids are controlled by the backend. Read TELEMETRY_CONTRACT.txt (printed by every build).
/* eslint-disable */
export const TELEMETRY_CATALOG_VERSION = "1.14.0";
-export const TELEMETRY_CATALOG_HASH = "93ffca84480c903b";
+export const TELEMETRY_CATALOG_HASH = "4d228919bd9883a5";
/** Every signal type the ingest accepts. */
export const SignalType = {
@@ -409,6 +409,7 @@ export const UiElement = {
CHAT_MR_ONEHOOK_SESSION_DELETE: "chat.mr_onehook_session_delete",
CHAT_MR_ONEHOOK_SESSION_NEW: "chat.mr_onehook_session_new",
CHAT_MR_ONEHOOK_SESSION_LIMIT: "chat.mr_onehook_session_limit",
+ CHAT_MR_ONEHOOK_UPGRADE_OPEN: "chat.mr_onehook_upgrade_open",
CHAT_INTRO_TOUR_OPEN: "chat.intro_tour_open",
CHAT_INTRO_DISMISS: "chat.intro_dismiss",
CHAT_INTRO_GET_STARTED: "chat.intro_get_started",
@@ -672,11 +673,12 @@ export const UI_ELEMENTS: { readonly [K in UiElementId]: UiElementSpec } = {
"chat.mr_onehook_context_share": { screen: "CHAT", kind: "dialog_button", actions: ["submit", "dismiss"], values: null, platforms: ["web", "ios", "android"] },
"chat.mr_onehook_scope_open": { screen: "CHAT", kind: "button", actions: ["tap", "dismiss"], values: null, platforms: ["web"] },
"chat.mr_onehook_scope_select": { screen: "CHAT", kind: "menu_item", actions: ["tap"], values: null, platforms: ["web"] },
- "chat.mr_onehook_sessions_open": { screen: "CHAT", kind: "button", actions: ["tap", "dismiss"], values: null, platforms: ["web", "ios", "android"] },
+ "chat.mr_onehook_sessions_open": { screen: "CHAT", kind: "button", actions: ["tap", "dismiss"], values: null, platforms: ["ios"] },
"chat.mr_onehook_session_resume": { screen: "CHAT", kind: "menu_item", actions: ["tap"], values: null, platforms: ["web", "ios", "android"] },
- "chat.mr_onehook_session_delete": { screen: "CHAT", kind: "button", actions: ["tap"], values: null, platforms: ["web", "ios", "android"] },
+ "chat.mr_onehook_session_delete": { screen: "CHAT", kind: "button", actions: ["tap", "dismiss"], values: null, platforms: ["web", "ios", "android"] },
"chat.mr_onehook_session_new": { screen: "CHAT", kind: "button", actions: ["tap"], values: null, platforms: ["web", "ios", "android"] },
"chat.mr_onehook_session_limit": { screen: "CHAT", kind: "dialog_button", actions: ["tap", "dismiss"], values: ["replace_least_recent", "manage", "cancel"], platforms: ["web", "ios", "android"] },
+ "chat.mr_onehook_upgrade_open": { screen: "CHAT", kind: "button", actions: ["tap", "dismiss"], values: null, platforms: ["web", "ios", "android"] },
"chat.intro_tour_open": { screen: "CHAT", kind: "button", actions: ["tap"], values: null, platforms: ["ios"] },
"chat.intro_dismiss": { screen: "CHAT", kind: "button", actions: ["tap", "dismiss"], values: null, platforms: ["ios"] },
"chat.intro_get_started": { screen: "CHAT", kind: "button", actions: ["tap"], values: null, platforms: ["ios"] },
diff --git a/src/lib/mr-onehook.ts b/src/lib/mr-onehook.ts
index 9ca63f7..1ab7ec2 100644
--- a/src/lib/mr-onehook.ts
+++ b/src/lib/mr-onehook.ts
@@ -100,6 +100,11 @@ export interface UseMrOneHookChatOptions {
tier: SubscriptionTier;
/** Supplied for match scope so a `needsMoreContext` turn can search local history. */
resolveLocalExcerpts?: LocalExcerptResolver;
+ /**
+ * Super and above: a saved chat from another scope (a match chat while on the product chat, or the
+ * reverse) was chosen in the tabs. The host switches to that scope; the session is already remembered.
+ */
+ onOpenScope?: (scope: MrOneHookScope) => void;
}
export interface UseMrOneHookChat {
@@ -137,6 +142,50 @@ export interface UseMrOneHookChat {
sessionLimit: SessionLimit | null;
replaceLeastRecentAndSend: () => Promise;
dismissSessionLimit: () => void;
+ /** The member agreed to replace the least recent saved chat: the current chat is now a new one. */
+ replacing: boolean;
+ /** Starts a new chat that replaces the least recent saved chat when its first message is sent. */
+ startReplacingLeastRecent: () => void;
+ /** The current saved chat's id (undefined for a new, unsaved chat). */
+ currentSessionId: string | undefined;
+}
+
+/**
+ * The chat tabs. Pure, for tests.
+ * - Super+: saved chats oldest first ("Chat 1"...), plus "New chat" while the current chat is unsaved.
+ * While replacing, the least recent chat is left out (the new chat takes its place).
+ * - Must: one "Chat" tab.
+ */
+export function mrOneHookTabs(
+ sessions: SessionListItem[],
+ activeId: string | undefined,
+ paid: boolean,
+ replacing: boolean,
+): Array<{ sessionId?: string; title: string }> {
+ if (!paid) return [{ title: 'Chat' }];
+ const oldest = leastRecentSession(sessions);
+ const saved = [...sessions]
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
+ .filter((s) => !(replacing && oldest && s.sessionId === oldest.sessionId));
+ const tabs: Array<{ sessionId?: string; title: string }> = saved.map((s, i) => ({
+ sessionId: s.sessionId,
+ title: `Chat ${i + 1}`,
+ }));
+ if (!activeId || !saved.some((s) => s.sessionId === activeId)) tabs.push({ title: 'New chat' });
+ return tabs;
+}
+
+/** The saved chat the server replaces at the limit: the least recently active one. */
+export function leastRecentSession(sessions: SessionListItem[]): SessionListItem | undefined {
+ return sessions.reduce(
+ (min, s) => (!min || s.updatedAt < min.updatedAt ? s : min),
+ undefined,
+ );
+}
+
+/** Remembers which saved chat continues in a scope (used when the tabs switch scope). */
+export function rememberSessionForScope(userId: string, scope: MrOneHookScope, sessionId: string): void {
+ persistSessionId(userId, scope, sessionId);
}
export interface SessionLimit {
@@ -249,7 +298,7 @@ function toEpochMs(iso?: string): number | undefined {
}
export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHookChat {
- const { userId, scope, tier, resolveLocalExcerpts } = options;
+ const { userId, scope, tier, resolveLocalExcerpts, onOpenScope } = options;
const matchId = scope.type === 'match' ? scope.matchId : undefined;
const persistAllowed = isPaidSubscriptionTier(tier);
const key = scopeKey(scope);
@@ -264,6 +313,15 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook
const [remainingMessages, setRemainingMessages] = useState(undefined);
const [sessions, setSessions] = useState([]);
const [sessionLimit, setSessionLimit] = useState(null);
+ const [replacing, setReplacing] = useState(false);
+ /** Bumped when a reply saves a chat, so the tabs reload the list. */
+ const [sessionsVersion, setSessionsVersion] = useState(0);
+ const hydratedKeyRef = useRef(undefined);
+ const replacingRef = useRef(false);
+ replacingRef.current = replacing;
+ const [currentSessionId, setCurrentSessionId] = useState(undefined);
+ const onOpenScopeRef = useRef(onOpenScope);
+ onOpenScopeRef.current = onOpenScope;
const sessionIdRef = useRef(persistAllowed ? loadSessionId(userId, scope) : undefined);
const resolveRef = useRef(resolveLocalExcerpts);
@@ -276,6 +334,7 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook
sessionIdRef.current = persistAllowed ? loadSessionId(userId, scope) : undefined;
setSession(null);
setSessionLimit(null);
+ setReplacing(false);
setPendingReview(null);
setHasError(false);
setMood('Happy');
@@ -352,7 +411,7 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook
? {
persist: true,
...(sessionIdRef.current ? { sessionId: sessionIdRef.current } : {}),
- ...(init.replaceLeastRecent ? { replaceLeastRecent: true } : {}),
+ ...(init.replaceLeastRecent || replacingRef.current ? { replaceLeastRecent: true } : {}),
}
: {}),
});
@@ -400,6 +459,9 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook
sessionIdRef.current = result.session.sessionId;
persistSessionId(userId, scope, result.session.sessionId);
setSession(result.session);
+ setCurrentSessionId(result.session.sessionId);
+ setReplacing(false);
+ setSessionsVersion((v) => v + 1);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
},
@@ -512,6 +574,7 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook
// Start a fresh server session on the next message; the prior one lapses per its retention.
sessionIdRef.current = undefined;
persistSessionId(userId, scope, undefined);
+ setCurrentSessionId(undefined);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userId, key]);
@@ -544,7 +607,18 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook
const response = await authorizedFetch(`/sessions/${encodeURIComponent(sessionId)}`);
const detail = response.ok ? parseSessionDetail(await response.json()) : undefined;
if (!detail) throw new Error('SERVER_ERROR');
+ if ((detail.matchId ?? undefined) !== matchId) {
+ // A chat from another scope: remember it there and let the host switch.
+ const target: MrOneHookScope = detail.matchId
+ ? { type: 'match', matchId: detail.matchId }
+ : { type: 'product' };
+ persistSessionId(userId, target, detail.sessionId);
+ onOpenScopeRef.current?.(target);
+ return;
+ }
sessionIdRef.current = detail.sessionId;
+ setCurrentSessionId(detail.sessionId);
+ setReplacing(false);
persistSessionId(userId, scope, detail.sessionId);
setMessages(detail.messages.map((m) => ({ role: m.role, content: m.content })));
setPendingReview(null);
@@ -573,6 +647,7 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook
persistSessionId(userId, scope, undefined);
setSession(null);
setMessages([]);
+ setCurrentSessionId(undefined);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -599,6 +674,63 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook
const dismissSessionLimit = useCallback(() => setSessionLimit(null), []);
+ const startReplacingLeastRecent = useCallback(() => {
+ clear();
+ setReplacing(true);
+ }, [clear]);
+
+ // Super and above: load the saved chats for the tabs. The server is the source of truth for a saved
+ // chat's turns, so a remembered chat is reloaded from it; with none remembered, the most recent saved
+ // chat of this scope opens, rather than starting another.
+ useEffect(() => {
+ if (!persistAllowed || !userId) {
+ setSessions([]);
+ setCurrentSessionId(undefined);
+ return;
+ }
+ let cancelled = false;
+ void (async () => {
+ try {
+ const response = await authorizedFetch('/sessions');
+ if (!response.ok || cancelled) return;
+ const list = parseSessionList(await response.json());
+ if (cancelled) return;
+ setSessions(list);
+ const remembered = sessionIdRef.current;
+ if (remembered && !list.some((s) => s.sessionId === remembered)) {
+ // Deleted elsewhere or expired.
+ sessionIdRef.current = undefined;
+ persistSessionId(userId, scope, undefined);
+ }
+ setCurrentSessionId(sessionIdRef.current);
+ // Load a chat's turns once per scope; later runs (after a reply saved) only refresh the list.
+ const hydrateKey = `${userId}|${key}`;
+ if (hydratedKeyRef.current === hydrateKey) return;
+ hydratedKeyRef.current = hydrateKey;
+ const wanted = sessionIdRef.current
+ ?? (scope.type === 'product' && !replacingRef.current
+ ? [...list].filter((s) => s.scope === 'product').sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0]
+ ?.sessionId
+ : undefined);
+ if (!wanted) return;
+ const detailResponse = await authorizedFetch(`/sessions/${encodeURIComponent(wanted)}`);
+ const detail = detailResponse.ok ? parseSessionDetail(await detailResponse.json()) : undefined;
+ if (cancelled || !detail) return;
+ sessionIdRef.current = detail.sessionId;
+ persistSessionId(userId, scope, detail.sessionId);
+ setCurrentSessionId(detail.sessionId);
+ setMessages(detail.messages.map((m) => ({ role: m.role, content: m.content })));
+ } catch {
+ /* the tabs are a convenience; chatting still works */
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ // scope is reconstructed each render; key is its stable identity.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [userId, key, persistAllowed, authorizedFetch, sessionsVersion]);
+
return {
messages,
loading,
@@ -619,5 +751,8 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook
sessionLimit,
replaceLeastRecentAndSend,
dismissSessionLimit,
+ replacing,
+ startReplacingLeastRecent,
+ currentSessionId,
};
}
diff --git a/src/tests/mr-onehook-sessions.test.ts b/src/tests/mr-onehook-sessions.test.ts
index ec904b2..8019dba 100644
--- a/src/tests/mr-onehook-sessions.test.ts
+++ b/src/tests/mr-onehook-sessions.test.ts
@@ -45,3 +45,29 @@ describe('saved Mr. OneHook chats (Super and above)', () => {
expect(parseSessionDetail({ session: { sessionId: 'a' } })).toBeUndefined();
});
});
+
+describe('Mr. OneHook chat tabs', () => {
+ const s = (id: string, created: string, updated: string) => ({
+ sessionId: id, scope: 'product' as const, createdAt: created, updatedAt: updated, expiresAt: '', messageCount: 2,
+ });
+
+ it('Must sees one Chat tab', async () => {
+ const { mrOneHookTabs } = await import('../lib/mr-onehook');
+ expect(mrOneHookTabs([], undefined, false, false).map((t) => t.title)).toEqual(['Chat']);
+ });
+
+ it('Super sees saved chats oldest first, plus New chat while unsaved', async () => {
+ const { mrOneHookTabs } = await import('../lib/mr-onehook');
+ const saved = [s('b', '2026-11-02', '2026-11-04'), s('a', '2026-11-01', '2026-11-03')];
+ expect(mrOneHookTabs(saved, 'a', true, false).map((t) => t.title)).toEqual(['Chat 1', 'Chat 2']);
+ expect(mrOneHookTabs(saved, undefined, true, false).map((t) => t.title)).toEqual(['Chat 1', 'Chat 2', 'New chat']);
+ });
+
+ it('replacing drops the least recently used chat; never more than 3 tabs', async () => {
+ const { mrOneHookTabs, leastRecentSession } = await import('../lib/mr-onehook');
+ const saved = [s('a', '1', '9'), s('b', '2', '3'), s('c', '3', '7')];
+ expect(leastRecentSession(saved)?.sessionId).toBe('b');
+ const tabs = mrOneHookTabs(saved, undefined, true, true);
+ expect(tabs.map((t) => t.sessionId)).toEqual(['a', 'c', undefined]);
+ });
+});