Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

feat: Recent Chats in sidebar (#640)

harshil-20964cea38cf6bf8
diff --git a/.changeset/bump-assistant-ui-runtime-0-1-31.md b/.changeset/bump-assistant-ui-runtime-0-1-31.md
new file mode 100644
index 000000000..876e7cadd
--- /dev/null
+++ b/.changeset/bump-assistant-ui-runtime-0-1-31.md
@@ -0,0 +1,6 @@
+---
+"@truefoundry/trueforge-ui": patch
+"@truefoundry/trueforge": patch
+---
+
+Bump `@truefoundry/assistant-ui-runtime` to `0.1.31`.
diff --git a/.changeset/recent-draft-history.md b/.changeset/recent-draft-history.md
new file mode 100644
index 000000000..adc2e1ad4
--- /dev/null
+++ b/.changeset/recent-draft-history.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge-ui": patch
+---
+
+Show draft and named sessions in the history panel, exclude agent-builder sessions, cache session pages, and switch history sessions in place without remounting the chat runtime.
diff --git a/packages/frontend/package.json b/packages/frontend/package.json
index 8323ebd97..ac033d6ca 100644
--- a/packages/frontend/package.json
+++ b/packages/frontend/package.json
@@ -26,7 +26,7 @@
"@assistant-ui/core": "0.2.22",
"@assistant-ui/react": "0.14.27",
"@assistant-ui/store": "0.2.21",
- "@truefoundry/assistant-ui-runtime": "0.1.30",
+ "@truefoundry/assistant-ui-runtime": "0.1.31",
"@truefoundry/trueforge-sdk": "workspace:*",
"@truefoundry/trueforge-ui": "workspace:*",
"monaco-editor": "^0.52.0",
diff --git a/packages/trueforge-ui/README.md b/packages/trueforge-ui/README.md
index 93c36a15d..a2c278e0a 100644
--- a/packages/trueforge-ui/README.md
+++ b/packages/trueforge-ui/README.md
@@ -446,12 +446,12 @@ Mutable composers expose **Agent Config** for live model parameters, instruction
Built-in `layout` values:
-| Value | Description |
-| --------- | -------------------------------------------------------- |
-| `sidebar` | Left session list + main thread (ChatGPT / Claude style) |
-| `drawer` | Full-bleed thread; sessions open in a slide-over |
-| `dock` | Fixed-width right panel; list XOR thread stack |
-| `widget` | Same stack as `dock`, opened from a bottom-right FAB |
+| Value | Description |
+| --------- | ---------------------------------------------------- |
+| `sidebar` | Icon rail + recent session history + active thread |
+| `drawer` | Full-bleed thread; sessions open in a slide-over |
+| `dock` | Fixed-width right panel; list XOR thread stack |
+| `widget` | Same stack as `dock`, opened from a bottom-right FAB |
---
diff --git a/packages/trueforge-ui/package.json b/packages/trueforge-ui/package.json
index 844528fc9..9f08a8af8 100644
--- a/packages/trueforge-ui/package.json
+++ b/packages/trueforge-ui/package.json
@@ -95,7 +95,7 @@
"@openuidev/react-headless": "^0.9.4",
"@openuidev/react-lang": "^0.2.9",
"@openuidev/react-ui": "^0.13.2",
- "@truefoundry/assistant-ui-runtime": "0.1.30",
+ "@truefoundry/assistant-ui-runtime": "0.1.31",
"@truefoundry/trueforge-sdk": "workspace:*",
"chart.js": "^4.5.1",
"clsx": "^2.1.1",
diff --git a/packages/trueforge-ui/src/atoms/ThreadListMisc.tsx b/packages/trueforge-ui/src/atoms/ThreadListMisc.tsx
index 188a557f1..1ed846e50 100644
--- a/packages/trueforge-ui/src/atoms/ThreadListMisc.tsx
+++ b/packages/trueforge-ui/src/atoms/ThreadListMisc.tsx
@@ -65,7 +65,7 @@ export function ThreadListEmptyState({ message = 'No threads yet', className }:
}
export type ThreadListShellProps = {
- header: ReactNode;
+ header?: ReactNode;
children: ReactNode;
className?: string;
};
@@ -73,7 +73,7 @@ export type ThreadListShellProps = {
export function ThreadListShell({ header, children, className }: ThreadListShellProps) {
return (
<div className={cn('font-sans-flex flex h-full min-h-0 flex-1 flex-col overflow-hidden', className)}>
- <div className="shrink-0 border-b border-border px-2 py-2">{header}</div>
+ {header != null ? <div className="shrink-0 border-b border-border px-2 py-2">{header}</div> : null}
{/* History section owns overflow scroll so infinite-load IO can root on it. */}
<div className="flex min-h-0 flex-1 flex-col overflow-hidden p-2">{children}</div>
</div>
diff --git a/packages/trueforge-ui/src/containers/ThreadListContainer.tsx b/packages/trueforge-ui/src/containers/ThreadListContainer.tsx
index 82ae36059..f88191ff4 100644
--- a/packages/trueforge-ui/src/containers/ThreadListContainer.tsx
+++ b/packages/trueforge-ui/src/containers/ThreadListContainer.tsx
@@ -37,6 +37,8 @@ import { useSlot } from '../theme/SlotsProvider.js';
export type ThreadListContainerProps = {
/** Called after New chat or selecting a row — used by stack/drawer chrome. */
onThreadOpen?: () => void;
+ /** `recent-history` hides navigation and lists only persisted sessions. */
+ variant?: 'default' | 'recent-history';
};
const deleteItemClass =
@@ -187,22 +189,39 @@ function ThreadListItemRow({
);
}
-function useThreadListIndicesByRecency(): number[] {
+function useThreadListIndicesByRecency(variant: NonNullable<ThreadListContainerProps['variant']>): number[] {
const threadIds = useAuiState(s => s.threads.threadIds);
const threadItems = useAuiState(s => s.threads.threadItems);
- return useMemo(() => threadListIndicesByRecency({ threadIds, threadItems }), [threadIds, threadItems]);
+ return useMemo(() => {
+ const indices = threadListIndicesByRecency({ threadIds, threadItems });
+ if (variant === 'default') return indices;
+
+ const itemById = new Map<string, (typeof threadItems)[number]>();
+ for (const item of threadItems) {
+ itemById.set(item.id, item);
+ if (item.remoteId != null) itemById.set(item.remoteId, item);
+ }
+
+ return indices.filter(index => {
+ const id = threadIds[index];
+ if (id === undefined) return false;
+ const item = itemById.get(id);
+ return item?.remoteId != null;
+ });
+ }, [threadIds, threadItems, variant]);
}
function ThreadListItemsByRecency({
+ indices,
onThreadOpen,
canDeleteSession,
}: {
+ indices: number[];
onThreadOpen?: () => void;
canDeleteSession: boolean;
}) {
// Newest-first: remount/switchToThread can append the active session to threadIds.
- const indices = useThreadListIndicesByRecency();
const threadIds = useAuiState(s => s.threads.threadIds);
return (
@@ -223,42 +242,38 @@ const THREAD_LIST_VIEWPORT_SLOT = 'aui_thread-list-viewport';
/** How close to the bottom (px) before the next sessions page is fetched. */
const LOAD_MORE_BOTTOM_PX = 80;
-function ChatHistorySection({ children, viewportRef }: { children: ReactNode; viewportRef: Ref<HTMLDivElement> }) {
- const [expanded, setExpanded] = useState(true);
+function RecentChatsSection({
+ children,
+ viewportRef,
+ hideScrollbar,
+ showAgentFilter,
+}: {
+ children: ReactNode;
+ viewportRef: Ref<HTMLDivElement>;
+ hideScrollbar: boolean;
+ showAgentFilter: boolean;
+}) {
const shell = useOptionalShellMode();
- const showFilter = shell?.isLibraryEnabled === true;
+ const showFilter = showAgentFilter && shell?.isLibraryEnabled === true;
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex shrink-0 items-center gap-1 px-1 py-1">
- <button
- type="button"
- aria-expanded={expanded}
- className="flex min-w-0 flex-1 items-center gap-1 rounded-md px-1.5 py-1 text-left text-sm font-medium text-text-secondary hover:bg-ghost-button-hover hover:text-text-primary"
- onClick={() => setExpanded(v => !v)}
- >
- <span className="truncate">Chat History</span>
- <Icon
- name="chevron-down"
- className={cn('size-3.5 shrink-0 transition-transform', !expanded && '-rotate-90')}
- />
- </button>
+ <h2 className="min-w-0 flex-1 truncate px-1.5 py-1 text-sm font-medium text-text-secondary">My History</h2>
{showFilter ? <AgentHistoryFilterButton /> : null}
</div>
- {expanded ? (
- <div
- ref={viewportRef}
- data-slot={THREAD_LIST_VIEWPORT_SLOT}
- className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto"
- >
- {children}
- </div>
- ) : null}
+ <div
+ ref={viewportRef}
+ data-slot={THREAD_LIST_VIEWPORT_SLOT}
+ className={cn('flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto', hideScrollbar && 'aui-scrollbar-hidden')}
+ >
+ {children}
+ </div>
</div>
);
}
-export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps = {}) {
+export function ThreadListContainer({ onThreadOpen, variant = 'default' }: ThreadListContainerProps = {}) {
const aui = useAui();
const server = useOptionalServer();
const isLoading = useAuiState(s => s.threads.isLoading);
@@ -275,6 +290,7 @@ export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps =
const ThreadListRowSkeleton = useSlot('ThreadListRowSkeleton');
const ThreadListEmptyState = useSlot('ThreadListEmptyState');
+ const indices = useThreadListIndicesByRecency(variant);
const viewportRef = useRef<HTMLDivElement>(null);
const hasMoreRef = useRef(hasMore);
const auiRef = useRef(aui);
@@ -283,6 +299,7 @@ export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps =
const showNewChat = shell?.isNewChatEnabled !== false;
const isIdle = shell?.mode.status === 'idle';
+ const isRecentHistory = variant === 'recent-history';
const canDeleteSession = typeof server?.deleteSession === 'function';
// Fill an underflowing viewport; once it scrolls, paginate only near the bottom.
@@ -340,15 +357,15 @@ export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps =
let listBody: ReactNode;
if (isIdle) {
- listBody = <ThreadListEmptyState />;
+ listBody = <ThreadListEmptyState message={isRecentHistory ? 'No recent chats' : undefined} />;
} else if (isLoading) {
listBody = <ThreadListRowSkeleton />;
- } else if (threadIds.length === 0) {
- listBody = <ThreadListEmptyState />;
+ } else if (indices.length === 0) {
+ listBody = <ThreadListEmptyState message={isRecentHistory ? 'No recent chats' : undefined} />;
} else {
listBody = (
<ThreadListPrimitive.Root className="flex min-h-0 flex-col gap-0.5">
- <ThreadListItemsByRecency onThreadOpen={onThreadOpen} canDeleteSession={canDeleteSession} />
+ <ThreadListItemsByRecency indices={indices} onThreadOpen={onThreadOpen} canDeleteSession={canDeleteSession} />
</ThreadListPrimitive.Root>
);
}
@@ -356,18 +373,20 @@ export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps =
return (
<ThreadListShell
header={
- <div className="flex flex-col gap-1">
- {showNewChat ? <ThreadListNewButton onClick={handleNewChat} /> : null}
- <AgentsLibraryButton />
- <SessionsBrowserButton />
- <SchedulesButton />
- </div>
+ isRecentHistory ? null : (
+ <div className="flex flex-col gap-1">
+ {showNewChat ? <ThreadListNewButton onClick={handleNewChat} /> : null}
+ <AgentsLibraryButton />
+ <SessionsBrowserButton />
+ <SchedulesButton />
+ </div>
+ )
}
>
- <ChatHistorySection viewportRef={viewportRef}>
+ <RecentChatsSection viewportRef={viewportRef} hideScrollbar={isRecentHistory} showAgentFilter={!isRecentHistory}>
{listBody}
{!isIdle && hasMore ? <div className="h-4 shrink-0" aria-hidden /> : null}
- </ChatHistorySection>
+ </RecentChatsSection>
</ThreadListShell>
);
}
diff --git a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx
index 14c173ea0..7f9cdde83 100644
--- a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx
+++ b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx
@@ -10,12 +10,14 @@ import { cn } from '../atoms/lib/cn.js';
import { IS_CREATE_AGENT_METADATA_KEY, isCreateAgentMetadataValue } from '../atoms/lib/sessionCreateAgent.js';
import { Spinner } from '../atoms/primitives/Spinner.js';
import { WidgetVisibilityProvider } from '../layouts/WidgetVisibilityContext.js';
+import { HistorySessionSwitchBridge } from '../routing/HistorySessionSwitchBridge.js';
import { LibrarySessionShareBoot } from '../routing/LibrarySessionShareBoot.js';
import { RemoteIdRouteBridge } from '../routing/RemoteIdRouteBridge.js';
import { ResolvedRoutesProvider } from '../routing/ResolvedRoutesContext.js';
import type { ResolvedRoutes, RoutesConfig } from '../routing/types.js';
import { CustomActionRenderersProvider, type CustomActionRenderers } from '../server/CustomActionRenderersContext.js';
import { ServerProvider } from '../server/ServerContext.js';
+import { createSessionListCache, withSessionListCache } from '../server/sessionListCache.js';
import { DEFAULT_AGENT_CONFIG, ShellModeProvider, useShellMode, type AgentConfig } from '../server/ShellModeContext.js';
import type { TrueForgeServerConfig } from '../server/TrueForgeServerConfig.js';
import type { AgentUIServer, CreateSessionRequest } from '../server/types.js';
@@ -163,6 +165,9 @@ function ChatProviderFromShell({
const isCreateAgent = mode.status === 'active' && mode.isMutable && mode.isCreateAgent;
+ // Keep one isolated cache per shell, preserved across chat runtime remounts.
+ const [sessionListCache] = useState(createSessionListCache);
+
const serverWithCreateIntent = useMemo((): AgentUIServer => {
return {
...server,
@@ -181,6 +186,11 @@ function ChatProviderFromShell({
};
}, [server, isCreateAgent]);
+ const runtimeServer = useMemo(
+ () => withSessionListCache({ server: serverWithCreateIntent, cache: sessionListCache }),
+ [serverWithCreateIntent, sessionListCache],
+ );
+
// Freeze draft seed for the life of this runtimeKey so bindMutableAgent (identity /
// instructions on shell) does not push a new defaultAgentSpec into the runtime.
const draftDefaultAgentSpec = useMemo(() => {
@@ -224,13 +234,14 @@ function ChatProviderFromShell({
<TrueFoundryChatProvider
key={runtimeKey}
{...providerRest}
- server={serverWithCreateIntent}
+ server={runtimeServer}
agent={agent}
listSessionsAgentId={listSessionsAgentId}
initialSessionId={pendingSessionId ?? hostInitialSessionId}
>
<AgentConfigInstructionsProvider>
<DraftSpecPreferenceBridge />
+ <HistorySessionSwitchBridge />
{onRemoteIdChange != null ? <RemoteIdRouteBridge onRemoteIdChange={onRemoteIdChange} /> : null}
{children}
</AgentConfigInstructionsProvider>
diff --git a/packages/trueforge-ui/src/containers/TrueFoundryChatProvider.tsx b/packages/trueforge-ui/src/containers/TrueFoundryChatProvider.tsx
index 6ce9d7d4b..e985d9269 100644
--- a/packages/trueforge-ui/src/containers/TrueFoundryChatProvider.tsx
+++ b/packages/trueforge-ui/src/containers/TrueFoundryChatProvider.tsx
@@ -9,12 +9,26 @@ import {
} from '@truefoundry/assistant-ui-runtime';
import { useCallback, useMemo, type ReactNode } from 'react';
+import { sessionIsCreateAgent } from '../atoms/lib/sessionCreateAgent.js';
import { notifyComposerBusyFailure } from '../hooks/useComposerBusyState.js';
import type { AgentUIServer } from '../server/types.js';
import { ToasterProvider, useToaster } from './ToasterContainer.js';
type RuntimeAdapters = NonNullable<UseTrueFoundryAgentRuntimeOptions['adapters']>;
+function withoutCreateAgentSessions(server: AgentUIServer): AgentUIServer {
+ return {
+ ...server,
+ async listSessions(request) {
+ const result = await server.listSessions(request);
+ return {
+ ...result,
+ data: result.data.filter(session => !sessionIsCreateAgent(session)),
+ };
+ },
+ };
+}
+
export type TrueFoundryChatProviderProps = {
server: AgentUIServer;
initialSessionId?: string;
@@ -50,6 +64,7 @@ function ChatRuntimeScope({
}) {
const { showError } = useToaster();
const reportError = onError ?? showError;
+ const historyServer = useMemo(() => withoutCreateAgentSessions(server), [server]);
// composer().send() is void and swallows onNew rejections; clear optimistic
// busy when the runtime reports a pre-stream failure (e.g. createSession).
const resolvedOnError = useCallback(
@@ -61,7 +76,7 @@ function ChatRuntimeScope({
);
const runtime = useTrueFoundryAgentRuntime({
- server: server as never,
+ server: historyServer as never,
agent,
agentName,
listSessionsAgentId,
diff --git a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx
index 5c218fe79..0f7fe6b7d 100644
--- a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx
+++ b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx
@@ -21,9 +21,10 @@ import { Spinner } from '../atoms/primitives/Spinner.js';
import { ShellActions } from '../atoms/ShellActions.js';
import { AgentConfigDrawerContainer } from '../containers/AgentConfigDrawerContainer.js';
import { Thread } from '../containers/Thread.js';
+import { ThreadListContainer } from '../containers/ThreadListContainer.js';
import { useChatHeaderContentVisible } from '../hooks/useChatChromeActionsVisible.js';
import { Icon } from '../icons/Icon.js';
-import { shellIsCreateAgent, useOptionalShellMode } from '../server/ShellModeContext.js';
+import { shellIsCreateAgent, useOptionalShellMode, type ShellMode } from '../server/ShellModeContext.js';
import { resolveBrandChrome } from '../theme/brand.js';
import { useSlot } from '../theme/SlotsProvider.js';
import { useBrand } from '../theme/ThemeProvider.js';
@@ -41,6 +42,10 @@ const railActionButtonClassName = cn(sidebarRailButtonClassName, 'text-sidebar-t
const railSelectedClassName =
'bg-primary-button-bg font-medium text-primary-button-text hover:bg-primary-button-hover hover:text-primary-button-text';
+function isRecentHistoryVisible({ overlayOpen, mode }: { overlayOpen: boolean; mode?: ShellMode }): boolean {
+ return !overlayOpen && mode?.status === 'active' && !mode.isCreateAgent;
+}
+
function SidebarNav(): ReactNode {
const aui = useAui();
const shell = useOptionalShellMode();
@@ -182,6 +187,7 @@ export function SidebarLayout({ className }: { className?: string }) {
const overlayOpen = settingsOpen || libraryOpen || sessionsOpen || schedulesOpen;
const showAgentConfig =
shell != null && shellIsCreateAgent(shell.mode) && !overlayOpen && (!isMobile || shell.agentConfigOpen);
+ const showRecentHistory = isRecentHistoryVisible({ overlayOpen, mode: shell?.mode });
const hasChatHeaderContent = useChatHeaderContentVisible();
useEffect(() => {
@@ -259,50 +265,61 @@ export function SidebarLayout({ className }: { className?: string }) {
}
/>
- <div ref={mainRef} className="min-h-0 min-w-0 flex-1">
- {settingsOpen ? (
- <Suspense
- fallback={
- <div
- className="flex h-full items-center justify-center"
- role="status"
- aria-live="polite"
- aria-busy="true"
- >
- <Spinner size={28} className="text-text-primary" />
- <span className="sr-only">Loading</span>
- </div>
- }
+ <div className="flex min-h-0 min-w-0 flex-1">
+ {showRecentHistory ? (
+ <aside
+ aria-label="Recent chats"
+ className="hidden min-h-0 w-64 shrink-0 border-r border-border bg-sidebar-bg md:flex"
>
- <TruefoundrySettingsBuilder />
- </Suspense>
- ) : sessionsOpen ? (
- <SessionsPage />
- ) : libraryOpen && shell?.libraryAgentId != null ? (
- <AgentDetailsPage key={shell.libraryAgentId} agentId={shell.libraryAgentId} />
- ) : libraryOpen ? (
- <AgentsLibrary onSelectAgent={() => setMobileNavOpen(false)} />
- ) : schedulesOpen ? (
- <Suspense
- fallback={
- <div
- className="flex h-full items-center justify-center"
- role="status"
- aria-live="polite"
- aria-busy="true"
- >
- <Spinner size={28} className="text-text-primary" />
- <span className="sr-only">Loading</span>
- </div>
- }
- >
- <SchedulesPage />
- </Suspense>
- ) : isIdle ? (
- <SelectAgentEmptyState />
- ) : (
- <Thread />
- )}
+ <ThreadListContainer variant="recent-history" />
+ </aside>
+ ) : null}
+
+ <div ref={mainRef} className="min-h-0 min-w-0 flex-1">
+ {settingsOpen ? (
+ <Suspense
+ fallback={
+ <div
+ className="flex h-full items-center justify-center"
+ role="status"
+ aria-live="polite"
+ aria-busy="true"
+ >
+ <Spinner size={28} className="text-text-primary" />
+ <span className="sr-only">Loading</span>
+ </div>
+ }
+ >
+ <TruefoundrySettingsBuilder />
+ </Suspense>
+ ) : sessionsOpen ? (
+ <SessionsPage />
+ ) : libraryOpen && shell?.libraryAgentId != null ? (
+ <AgentDetailsPage key={shell.libraryAgentId} agentId={shell.libraryAgentId} />
+ ) : libraryOpen ? (
+ <AgentsLibrary onSelectAgent={() => setMobileNavOpen(false)} />
+ ) : schedulesOpen ? (
+ <Suspense
+ fallback={
+ <div
+ className="flex h-full items-center justify-center"
+ role="status"
+ aria-live="polite"
+ aria-busy="true"
+ >
+ <Spinner size={28} className="text-text-primary" />
+ <span className="sr-only">Loading</span>
+ </div>
+ }
+ >
+ <SchedulesPage />
+ </Suspense>
+ ) : isIdle ? (
+ <SelectAgentEmptyState />
+ ) : (
+ <Thread />
+ )}
+ </div>
</div>
</div>
diff --git a/packages/trueforge-ui/src/routing/HistorySessionSwitchBridge.tsx b/packages/trueforge-ui/src/routing/HistorySessionSwitchBridge.tsx
new file mode 100644
index 000000000..679d1de77
--- /dev/null
+++ b/packages/trueforge-ui/src/routing/HistorySessionSwitchBridge.tsx
@@ -0,0 +1,21 @@
+'use client';
+
+import { useEffect } from 'react';
+
+import { useAui } from '../assistant-ui.js';
+import { useOptionalShellMode } from '../server/ShellModeContext.js';
+
+/** Switches history sessions in place to preserve mounted chat state to prevent flickering */
+export function HistorySessionSwitchBridge() {
+ const shell = useOptionalShellMode();
+ const aui = useAui();
+ const pendingSessionId = shell?.pendingSessionId;
+ const pendingSessionEpoch = shell?.pendingSessionEpoch ?? 0;
+
+ useEffect(() => {
+ if (pendingSessionId == null) return;
+ void Promise.resolve(aui.threads().switchToThread(pendingSessionId)).catch(() => undefined);
+ }, [aui, pendingSessionId, pendingSessionEpoch]);
+
+ return null;
+}
diff --git a/packages/trueforge-ui/src/server/ShellModeContext.tsx b/packages/trueforge-ui/src/server/ShellModeContext.tsx
index 62c292ff7..03657e24b 100644
--- a/packages/trueforge-ui/src/server/ShellModeContext.tsx
+++ b/packages/trueforge-ui/src/server/ShellModeContext.tsx
@@ -114,11 +114,8 @@ type ShellModeContextValue = {
/** Remember plain-draft composer choices as the seed for future New Chat / New Agent. */
rememberDraftSpec: (agentSpec: AgentSpec, kind?: DraftPreferenceKind) => void;
/**
- * Open a history session, remounting when mutability/identity changes.
- * Prefer explicit `isMutable` from the session row; when omitted, agentName
- * present → immutable and agentName absent → mutable. Immutable rows may omit
- * `agentName` when the registry agent was deleted.
- * `isCreateAgent` is only applied when mutable (default false when omitted).
+ * Open a history session without remounting the runtime.
+ * Prefer explicit `isMutable`; otherwise agentName means immutable.
*/
openHistorySession: (req: {
sessionId: string;
@@ -130,7 +127,7 @@ type ShellModeContextValue = {
clearChat: () => void;
/** Return library-only mode to its idle landing; no-op in other modes. */
openLibraryHome: () => void;
- /** Remount key for the chat runtime when binding changes. */
+ /** Changes only when the chat runtime must reset. */
runtimeKey: string;
/**
* History list filter forwarded as `listSessions({ agentId })`.
@@ -140,8 +137,10 @@ type ShellModeContextValue = {
setHistoryAgentFilter: (agentId: string | null) => void;
/** Effective `listSessionsAgentId` for the runtime (SingleAgent locks to name). */
listSessionsAgentId: string | undefined;
- /** Session to open after a binding remount (history click across mutability). */
+ /** Session selected from history. */
pendingSessionId: string | undefined;
+ /** Distinguishes repeated selections of the same session. */
+ pendingSessionEpoch: number;
/**
* Bumped when the Agents catalog may have changed (e.g. after saveAgent).
* Library chrome should re-fetch when this changes.
@@ -237,6 +236,7 @@ export function ShellModeProvider({
const [schedulesOpenState, setSchedulesOpenState] = useState(false);
const [historyAgentFilter, setHistoryAgentFilter] = useState<string | null>(null);
const [pendingSessionId, setPendingSessionId] = useState<string | undefined>(undefined);
+ const [pendingSessionEpoch, setPendingSessionEpoch] = useState(0);
const settingsEnabled = isSettingsChromeEnabled({ catalog, capabilities });
const settingsOpen = settingsEnabled && settingsOpenState;
const sessionsEnabled = isSessionsChromeEnabled({ sessions: sessionsServer });
@@ -499,15 +499,23 @@ export function ShellModeProvider({
isMutable?: boolean;
isCreateAgent?: boolean;
}) => {
+ const isMutable = isMutableOpt ?? agentName == null;
+ if (isMutable) {
+ if (!isComposerEnabled) return;
+ } else if (locked) {
+ if (agentName == null || lockedAgentName !== agentName) return;
+ } else if (!isLibraryEnabled) {
+ return;
+ }
+
setSettingsOpen(false);
setLibraryOpenState(false);
setLibraryAgentId(null);
setSessionsOpen(false);
setSchedulesOpen(false);
setPendingSessionId(sessionId);
- const isMutable = isMutableOpt ?? agentName == null;
+ setPendingSessionEpoch(n => n + 1);
if (isMutable) {
- if (!isComposerEnabled) return;
const isCreateAgent = isCreateAgentOpt === true;
setMode({
status: 'active',
@@ -517,13 +525,6 @@ export function ShellModeProvider({
locked: false,
});
setAgentConfigOpenState(isCreateAgent);
- bumpEpoch(true);
- return;
- }
- // Immutable: allow orphaned refs (deleted agent → no agentName).
- if (locked) {
- if (agentName == null || lockedAgentName !== agentName) return;
- } else if (!isLibraryEnabled) {
return;
}
setAgentConfigOpenState(false);
@@ -534,18 +535,8 @@ export function ShellModeProvider({
locked: false,
...(agentName != null ? { agentId: agentName, agentName } : {}),
});
- bumpEpoch(false);
},
- [
- isLibraryEnabled,
- isComposerEnabled,
- locked,
- lockedAgentName,
- bumpEpoch,
- setSettingsOpen,
- setSessionsOpen,
- setSchedulesOpen,
- ],
+ [isLibraryEnabled, isComposerEnabled, locked, lockedAgentName, setSettingsOpen, setSessionsOpen, setSchedulesOpen],
);
const clearChat = useCallback(() => {
@@ -582,16 +573,11 @@ export function ShellModeProvider({
bumpEpoch(false);
}, [isLibraryEnabled, isComposerEnabled, setSettingsOpen, setSchedulesOpen, bumpEpoch]);
- // Mutable remounts are driven only by mutableEpoch (library Edit / New Chat / Clear).
- // Agent id and model must not be in the key — saveAgent binds those onto the same draft.
+ // Only explicit resets remount the runtime; history and identity changes happen in place.
const runtimeKey = useMemo(() => {
if (effectiveMode.status === 'idle') return 'idle';
- if (effectiveMode.isMutable) {
- return `mut:${pendingSessionId ?? ''}:${mutableEpoch}`;
- }
- const id = effectiveMode.agentId ?? effectiveMode.agentName ?? '';
- return `immut:${id}:${pendingSessionId ?? ''}:${clearEpoch}`;
- }, [effectiveMode, mutableEpoch, clearEpoch, pendingSessionId]);
+ return `chat:${mutableEpoch}:${clearEpoch}`;
+ }, [effectiveMode.status, mutableEpoch, clearEpoch]);
const value = useMemo<ShellModeContextValue>(
() => ({
@@ -629,6 +615,7 @@ export function ShellModeProvider({
setHistoryAgentFilter,
listSessionsAgentId,
pendingSessionId,
+ pendingSessionEpoch,
agentsListEpoch,
invalidateAgentsList,
}),
@@ -665,6 +652,7 @@ export function ShellModeProvider({
historyAgentFilter,
listSessionsAgentId,
pendingSessionId,
+ pendingSessionEpoch,
agentsListEpoch,
invalidateAgentsList,
],
diff --git a/packages/trueforge-ui/src/server/sessionListCache.ts b/packages/trueforge-ui/src/server/sessionListCache.ts
new file mode 100644
index 000000000..d0b0df790
--- /dev/null
+++ b/packages/trueforge-ui/src/server/sessionListCache.ts
@@ -0,0 +1,67 @@
+import type { AgentUIServer, ListSessionsParams } from './types.js';
+
+/** Cached pages go stale after this window so external session changes surface. */
+const SESSION_LIST_TTL_MS = 30_000;
+
+type SessionListPage = ReturnType<AgentUIServer['listSessions']>;
+
+type CacheEntry = { at: number; page: SessionListPage };
+
+export type SessionListCache = Map<string, CacheEntry>;
+
+export function createSessionListCache(): SessionListCache {
+ return new Map();
+}
+
+// `startTimestamp` is a rolling "now − 1 year" that differs on every call;
+// keying on it would make each request unique and defeat the cache.
+function cacheKey(request: ListSessionsParams | undefined): string {
+ const rest: ListSessionsParams = { ...request };
+ delete rest.startTimestamp;
+ return JSON.stringify(rest, Object.keys(rest).sort());
+}
+
+/** Deduplicates session pages and invalidates them after mutations or TTL expiry. */
+export function withSessionListCache({
+ server,
+ cache,
+}: {
+ server: AgentUIServer;
+ cache: SessionListCache;
+}): AgentUIServer {
+ const { deleteSession } = server;
+ return {
+ ...server,
+ listSessions(request) {
+ const key = cacheKey(request);
+ const now = Date.now();
+ const entry = cache.get(key);
+ if (entry !== undefined && now - entry.at < SESSION_LIST_TTL_MS) return entry.page;
+ const page = server.listSessions(request);
+ cache.set(key, { at: now, page });
+ // Allow failed pages to be retried.
+ void page.catch(() => {
+ if (cache.get(key)?.page === page) cache.delete(key);
+ });
+ return page;
+ },
+ async createSession(request) {
+ const result = await server.createSession(request);
+ cache.clear();
+ return result;
+ },
+ async updateSession(request) {
+ const result = await server.updateSession(request);
+ cache.clear();
+ return result;
+ },
+ ...(deleteSession != null
+ ? {
+ deleteSession: async (request: { sessionId: string }) => {
+ await deleteSession.call(server, request);
+ cache.clear();
+ },
+ }
+ : {}),
+ };
+}
diff --git a/packages/trueforge-ui/src/styles.css b/packages/trueforge-ui/src/styles.css
index 8f4701f02..15433477f 100644
--- a/packages/trueforge-ui/src/styles.css
+++ b/packages/trueforge-ui/src/styles.css
@@ -269,6 +269,16 @@
background: transparent;
}
+.aui-theme-root .aui-scrollbar-hidden,
+.aui-root .aui-scrollbar-hidden {
+ scrollbar-width: none;
+}
+
+.aui-theme-root .aui-scrollbar-hidden::-webkit-scrollbar,
+.aui-root .aui-scrollbar-hidden::-webkit-scrollbar {
+ display: none;
+}
+
/* ──────────────────────────────────────────────────────────────────────
* Tailwind v4 `@theme inline` registrations.
* ──────────────────────────────────────────────────────────────────── */
diff --git a/packages/trueforge-ui/test/containers/ThreadListContainer.pagination.test.tsx b/packages/trueforge-ui/test/containers/ThreadListContainer.pagination.test.tsx
index 05434523e..a8154f4c4 100644
--- a/packages/trueforge-ui/test/containers/ThreadListContainer.pagination.test.tsx
+++ b/packages/trueforge-ui/test/containers/ThreadListContainer.pagination.test.tsx
@@ -5,8 +5,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ThreadListContainer } from '@/containers/ThreadListContainer.js';
-const { loadMore, setSchedulesOpen, setSessionsOpen } = vi.hoisted(() => ({
+const { loadMore, runtimeState, setSchedulesOpen, setSessionsOpen } = vi.hoisted(() => ({
loadMore: vi.fn().mockResolvedValue(undefined),
+ runtimeState: {
+ threadIds: ['t1'],
+ threadItems: [{ id: 't1', remoteId: 's1', lastMessageAt: undefined, custom: { isMutable: false } }],
+ },
setSchedulesOpen: vi.fn(),
setSessionsOpen: vi.fn(),
}));
@@ -42,8 +46,8 @@ vi.mock('@assistant-ui/react', () => ({
isLoading: false,
isLoadingMore: false,
hasMore: true,
- threadIds: ['t1'],
- threadItems: [{ id: 't1', remoteId: 's1', lastMessageAt: undefined }],
+ threadIds: runtimeState.threadIds,
+ threadItems: runtimeState.threadItems,
mainThreadId: 't1',
},
threadListItem: {
@@ -121,6 +125,8 @@ function notifyViewportResize(): void {
beforeEach(() => {
resizeCallback = undefined;
+ runtimeState.threadIds = ['t1'];
+ runtimeState.threadItems = [{ id: 't1', remoteId: 's1', lastMessageAt: undefined, custom: { isMutable: false } }];
vi.stubGlobal('ResizeObserver', ResizeObserverMock);
});
@@ -183,6 +189,26 @@ describe('ThreadListContainer pagination', () => {
await waitFor(() => expect(loadMore).toHaveBeenCalledTimes(1));
});
+ it('continues loading recent history after a page adds sessions', async () => {
+ loadMore.mockClear();
+ const { container, rerender } = render(<ThreadListContainer variant="recent-history" />);
+ const viewport = getViewport(container);
+
+ Object.defineProperty(viewport, 'scrollHeight', { configurable: true, value: 200 });
+ Object.defineProperty(viewport, 'clientHeight', { configurable: true, value: 400 });
+ notifyViewportResize();
+ await waitFor(() => expect(loadMore).toHaveBeenCalledTimes(1));
+
+ runtimeState.threadIds = ['t1', 't2'];
+ runtimeState.threadItems = [
+ { id: 't1', remoteId: 's1', lastMessageAt: undefined, custom: { isMutable: false } },
+ { id: 't2', remoteId: 's2', lastMessageAt: undefined, custom: { isMutable: false } },
+ ];
+ rerender(<ThreadListContainer variant="recent-history" />);
+
+ await waitFor(() => expect(loadMore).toHaveBeenCalledTimes(2));
+ });
+
it('loads more when scrolled near the bottom', async () => {
loadMore.mockClear();
const { container } = render(<ThreadListContainer />);
diff --git a/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx b/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx
index 0406f62dc..c1b4e2527 100644
--- a/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx
+++ b/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx
@@ -11,7 +11,7 @@ import { beforeAll, describe, expect, it, vi } from 'vitest';
import type { ThreadListRowProps } from '@/atoms/ThreadListRow.js';
import { CompactLayoutProvider } from '@/atoms/lib/CompactLayoutContext.js';
-import { ThreadListContainer } from '@/containers/ThreadListContainer.js';
+import { ThreadListContainer, type ThreadListContainerProps } from '@/containers/ThreadListContainer.js';
import { ServerProvider } from '@/server/ServerContext.js';
import { ShellModeProvider, useShellMode } from '@/server/ShellModeContext.js';
import { SlotsProvider } from '@/theme/SlotsProvider.js';
@@ -59,16 +59,18 @@ function renderThreadList({
adapter,
onThreadOpen,
canDelete = false,
+ variant,
}: {
adapter: ExternalStoreThreadListAdapter;
onThreadOpen?: () => void;
canDelete?: boolean;
+ variant?: ThreadListContainerProps['variant'];
}) {
const list = (
<SlotsProvider overrides={{ ThreadListRow: ThreadListRowOverride }}>
<ThreadListRuntimeHarness threadList={adapter}>
<CompactLayoutProvider>
- <ThreadListContainer onThreadOpen={onThreadOpen} />
+ <ThreadListContainer onThreadOpen={onThreadOpen} variant={variant} />
</CompactLayoutProvider>
</ThreadListRuntimeHarness>
</SlotsProvider>
@@ -147,6 +149,104 @@ describe('ThreadListContainer', () => {
expect(onThreadOpen).toHaveBeenCalledTimes(2);
});
+ it('shows persisted draft and named sessions in recent-history mode', () => {
+ const { container } = renderThreadList({
+ adapter: {
+ threadId: 'draft-1',
+ threads: [
+ {
+ status: 'regular',
+ id: 'draft-1',
+ remoteId: 'session-draft-1',
+ title: 'Draft chat',
+ custom: { isMutable: true },
+ },
+ {
+ status: 'regular',
+ id: 'named-1',
+ remoteId: 'session-named-1',
+ title: 'Named chat',
+ custom: { isMutable: false },
+ },
+ {
+ status: 'regular',
+ id: 'local-draft',
+ title: 'Unsaved chat',
+ custom: { isMutable: true },
+ },
+ ],
+ },
+ variant: 'recent-history',
+ });
+
+ expect(screen.getByRole('button', { name: 'Draft chat' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Named chat' })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Unsaved chat' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Start new chat' })).not.toBeInTheDocument();
+ expect(screen.queryByText('New Chat')).not.toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'My History' })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'My History' })).not.toBeInTheDocument();
+ expect(container.querySelector('[data-slot="aui_thread-list-viewport"]')).toHaveClass('aui-scrollbar-hidden');
+ });
+
+ it('shows the recent-history empty state when only an unsaved session exists', () => {
+ renderThreadList({
+ adapter: {
+ threads: [
+ {
+ status: 'regular',
+ id: 'local-draft',
+ title: 'Unsaved chat',
+ custom: { isMutable: true },
+ },
+ ],
+ },
+ variant: 'recent-history',
+ });
+
+ expect(screen.getByText('No recent chats')).toBeInTheDocument();
+ });
+
+ it('loads a named history session without leaving the recent list', async () => {
+ function ActiveMode() {
+ const shell = useShellMode();
+ const name = shell.mode.status === 'active' ? shell.mode.agentName : undefined;
+ return <output aria-label="Active agent">{name ?? 'draft'}</output>;
+ }
+
+ render(
+ <SlotsProvider overrides={{ ThreadListRow: ThreadListRowOverride }}>
+ <ServerProvider server={createMockAgentUIServer()}>
+ <ShellModeProvider>
+ <ThreadListRuntimeHarness
+ threadList={{
+ threads: [
+ {
+ status: 'regular',
+ id: 'named-1',
+ remoteId: 'session-named-1',
+ title: 'Named chat',
+ custom: { isMutable: false, agentName: 'named-agent' },
+ },
+ ],
+ }}
+ >
+ <CompactLayoutProvider>
+ <ActiveMode />
+ <ThreadListContainer variant="recent-history" />
+ </CompactLayoutProvider>
+ </ThreadListRuntimeHarness>
+ </ShellModeProvider>
+ </ServerProvider>
+ </SlotsProvider>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Named chat' }));
+
+ await waitFor(() => expect(screen.getByRole('status', { name: 'Active agent' })).toHaveTextContent('named-agent'));
+ expect(screen.getByRole('heading', { name: 'My History' })).toBeInTheDocument();
+ });
+
it('exposes delete only for remote sessions and delegates deletion to the runtime', async () => {
const onDelete = vi.fn(async () => {});
diff --git a/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx b/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx
index a23c099d6..6ef256057 100644
--- a/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx
+++ b/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx
@@ -506,6 +506,50 @@ describe('SidebarLayout', () => {
expect(screen.queryByRole('button', { name: /^(Collapse|Expand) sidebar$/ })).not.toBeInTheDocument();
});
+ it('keeps recent history visible when a named chat loads in the same page', async () => {
+ function OpenNamedChatButton() {
+ const shell = useShellMode();
+ return (
+ <button type="button" onClick={() => shell.selectLibraryAgent({ isMutable: false, agentName: 'named-agent' })}>
+ Open named chat
+ </button>
+ );
+ }
+
+ render(
+ <SlotsProvider>
+ <ServerProvider server={mockServer(stubCatalog)}>
+ <ShellModeProvider>
+ <AgentConfigInstructionsProvider>
+ <RuntimeHarness messages={[]}>
+ <OpenNamedChatButton />
+ <div className="h-96">
+ <SidebarLayout />
+ </div>
+ </RuntimeHarness>
+ </AgentConfigInstructionsProvider>
+ </ShellModeProvider>
+ </ServerProvider>
+ </SlotsProvider>,
+ );
+
+ const recentChats = screen.getByRole('complementary', { name: 'Recent chats' });
+ expect(recentChats).toHaveClass('hidden', 'md:flex');
+ expect(recentChats.parentElement?.previousElementSibling?.tagName).toBe('HEADER');
+ expect(screen.getAllByText('New Chat')).toHaveLength(2);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Start new agent' }));
+ await waitFor(() => {
+ expect(screen.queryByRole('complementary', { name: 'Recent chats' })).not.toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Start new chat' }));
+ expect(await screen.findByRole('complementary', { name: 'Recent chats' })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Open named chat' }));
+ expect(await screen.findByRole('complementary', { name: 'Recent chats' })).toBeInTheDocument();
+ });
+
it('highlights New Chat, New Agent, and Settings when selected', async () => {
render(
<SlotsProvider theme={{ brand: { mode: 'icon-title', name: 'Acme' } }}>
diff --git a/packages/trueforge-ui/test/containers/TrueFoundryChatProvider.test.tsx b/packages/trueforge-ui/test/containers/TrueFoundryChatProvider.test.tsx
index afb1e588b..f41243fb4 100644
--- a/packages/trueforge-ui/test/containers/TrueFoundryChatProvider.test.tsx
+++ b/packages/trueforge-ui/test/containers/TrueFoundryChatProvider.test.tsx
@@ -46,12 +46,12 @@ describe('TrueFoundryChatProvider', () => {
expect(screen.getByText('chat-child')).toBeInTheDocument();
expect(runtimeSpy).toHaveBeenCalledWith(
expect.objectContaining({
- server,
agentName: 'my-agent',
initialSessionId: 'session-123',
adapters: { attachments: defaultAttachmentAdapter },
}),
);
+ expect(runtimeSpy.mock.calls[0]?.[0]?.server).not.toBe(server);
const forwardedOnError = runtimeSpy.mock.calls[0]?.[0]?.onError;
expect(typeof forwardedOnError).toBe('function');
expect(forwardedOnError).not.toBe(onError);
@@ -62,6 +62,44 @@ describe('TrueFoundryChatProvider', () => {
expect(onError).toHaveBeenCalledWith(expect.any(Error));
});
+ it('filters create-agent sessions from runtime history', async () => {
+ const listSessions = vi.fn(async () => ({
+ data: [
+ {
+ id: 'chat-session',
+ title: 'Chat',
+ isMutable: true,
+ createdAt: '2026-09-09T00:00:00.000Z',
+ updatedAt: '2026-09-09T00:00:00.000Z',
+ },
+ {
+ id: 'builder-session',
+ title: 'Builder',
+ isMutable: true,
+ metadata: { is_create_agent: 'true' },
+ createdAt: '2026-09-09T00:00:00.000Z',
+ updatedAt: '2026-09-09T00:00:00.000Z',
+ },
+ ],
+ nextPageToken: 'next-page',
+ }));
+
+ render(
+ <TrueFoundryChatProvider server={createMockAgentUIServer({ listSessions })} agentName="my-agent">
+ <div>chat-child</div>
+ </TrueFoundryChatProvider>,
+ );
+
+ const runtimeServer = runtimeSpy.mock.calls[0]?.[0]?.server;
+ if (runtimeServer === undefined) {
+ throw new Error('Expected runtime server');
+ }
+ const result = await runtimeServer.listSessions();
+
+ expect(result.data.map(session => session.id)).toEqual(['chat-session']);
+ expect(result.nextPageToken).toBe('next-page');
+ });
+
it('forwards a discriminated agent configuration', () => {
const agent: TrueFoundryAgentConfig = {
mode: 'named',
diff --git a/packages/trueforge-ui/test/routing/HistorySessionSwitchBridge.test.tsx b/packages/trueforge-ui/test/routing/HistorySessionSwitchBridge.test.tsx
new file mode 100644
index 000000000..3ae9645fe
--- /dev/null
+++ b/packages/trueforge-ui/test/routing/HistorySessionSwitchBridge.test.tsx
@@ -0,0 +1,60 @@
+// @vitest-environment jsdom
+import { act, render } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const switchToThread = vi.hoisted(() => vi.fn(async () => {}));
+
+vi.mock('@/assistant-ui.js', () => ({
+ useAui: () => ({ threads: () => ({ switchToThread }) }),
+}));
+
+import { HistorySessionSwitchBridge } from '@/routing/HistorySessionSwitchBridge.js';
+import { ServerProvider } from '@/server/ServerContext.js';
+import { ShellModeProvider, useShellMode } from '@/server/ShellModeContext.js';
+import { createMockAgentUIServer } from '../server/mockServer.js';
+
+type ShellRef = { current: ReturnType<typeof useShellMode> | null };
+
+function CaptureShell({ shellRef }: { shellRef: ShellRef }) {
+ shellRef.current = useShellMode();
+ return null;
+}
+
+function renderBridge(): ShellRef {
+ const shellRef: ShellRef = { current: null };
+ render(
+ <ServerProvider server={createMockAgentUIServer()}>
+ <ShellModeProvider>
+ <CaptureShell shellRef={shellRef} />
+ <HistorySessionSwitchBridge />
+ </ShellModeProvider>
+ </ServerProvider>,
+ );
+ if (shellRef.current == null) throw new Error('Shell context missing');
+ return shellRef;
+}
+
+describe('HistorySessionSwitchBridge', () => {
+ beforeEach(() => {
+ switchToThread.mockClear();
+ });
+
+ it('does nothing while no history session is pending', () => {
+ renderBridge();
+ expect(switchToThread).not.toHaveBeenCalled();
+ });
+
+ it('switches to the opened session and re-switches on repeat opens', () => {
+ const shellRef = renderBridge();
+
+ act(() => shellRef.current?.openHistorySession({ sessionId: 'sess-1', agentName: 'from-sdk' }));
+ expect(switchToThread).toHaveBeenCalledTimes(1);
+ expect(switchToThread).toHaveBeenCalledWith('sess-1');
+
+ act(() => shellRef.current?.openHistorySession({ sessionId: 'sess-1', agentName: 'from-sdk' }));
+ expect(switchToThread).toHaveBeenCalledTimes(2);
+
+ act(() => shellRef.current?.openHistorySession({ sessionId: 'sess-2', isMutable: true }));
+ expect(switchToThread).toHaveBeenLastCalledWith('sess-2');
+ });
+});
diff --git a/packages/trueforge-ui/test/server/ShellModeContext.test.tsx b/packages/trueforge-ui/test/server/ShellModeContext.test.tsx
index 3f3bb028d..2c3909020 100644
--- a/packages/trueforge-ui/test/server/ShellModeContext.test.tsx
+++ b/packages/trueforge-ui/test/server/ShellModeContext.test.tsx
@@ -421,11 +421,13 @@ describe('ShellModeProvider', () => {
expect(result.current.listSessionsAgentId).toBe('locked');
});
- it('openHistorySession remounts into immutable binding with pendingSessionId', () => {
+ it('openHistorySession rebinds immutable in place without changing runtimeKey', () => {
const { result } = renderHook(() => useShellMode(), {
wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
});
expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
+ const keyBefore = result.current.runtimeKey;
+ const epochBefore = result.current.pendingSessionEpoch;
act(() => result.current.openHistorySession({ sessionId: 'sess-1', agentName: 'from-sdk' }));
expect(result.current.mode).toEqual({
@@ -437,7 +439,63 @@ describe('ShellModeProvider', () => {
locked: false,
});
expect(result.current.pendingSessionId).toBe('sess-1');
- expect(result.current.runtimeKey).toContain('sess-1');
+ expect(result.current.runtimeKey).toBe(keyBefore);
+ expect(result.current.pendingSessionEpoch).toBe(epochBefore + 1);
+ });
+
+ it('re-opening the same history session bumps pendingSessionEpoch', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
+ });
+
+ act(() => result.current.openHistorySession({ sessionId: 'sess-1', agentName: 'from-sdk' }));
+ const epochBefore = result.current.pendingSessionEpoch;
+ const keyBefore = result.current.runtimeKey;
+
+ act(() => result.current.openHistorySession({ sessionId: 'sess-1', agentName: 'from-sdk' }));
+ expect(result.current.pendingSessionId).toBe('sess-1');
+ expect(result.current.pendingSessionEpoch).toBe(epochBefore + 1);
+ expect(result.current.runtimeKey).toBe(keyBefore);
+ });
+
+ it('history switches across mutability keep runtimeKey stable', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
+ });
+ const keyBefore = result.current.runtimeKey;
+
+ act(() => result.current.openHistorySession({ sessionId: 'sess-named', agentName: 'from-sdk' }));
+ expect(result.current.runtimeKey).toBe(keyBefore);
+
+ act(() => result.current.openHistorySession({ sessionId: 'sess-draft', isMutable: true }));
+ expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
+ expect(result.current.runtimeKey).toBe(keyBefore);
+ });
+
+ it('does not queue history sessions rejected by shell capabilities', () => {
+ const library = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibrary' }),
+ });
+ const libraryEpoch = library.result.current.pendingSessionEpoch;
+
+ act(() => library.result.current.openHistorySession({ sessionId: 'draft', isMutable: true }));
+ expect(library.result.current.pendingSessionId).toBeUndefined();
+ expect(library.result.current.pendingSessionEpoch).toBe(libraryEpoch);
+
+ const singleAgent = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'SingleAgent', name: 'locked' }),
+ });
+ const singleAgentEpoch = singleAgent.result.current.pendingSessionEpoch;
+
+ act(() =>
+ singleAgent.result.current.openHistorySession({
+ sessionId: 'other-session',
+ agentName: 'other-agent',
+ isMutable: false,
+ }),
+ );
+ expect(singleAgent.result.current.pendingSessionId).toBeUndefined();
+ expect(singleAgent.result.current.pendingSessionEpoch).toBe(singleAgentEpoch);
});
it('openHistorySession keeps immutable binding when agentName is missing', () => {
diff --git a/packages/trueforge-ui/test/server/sessionListCache.test.ts b/packages/trueforge-ui/test/server/sessionListCache.test.ts
new file mode 100644
index 000000000..5636d481e
--- /dev/null
+++ b/packages/trueforge-ui/test/server/sessionListCache.test.ts
@@ -0,0 +1,87 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createSessionListCache, withSessionListCache } from '@/server/sessionListCache.js';
+
+import { createMockAgentUIServer } from './mockServer.js';
+
+const emptyPage = { data: [] };
+
+function cachedServer(overrides: Parameters<typeof createMockAgentUIServer>[0] = {}) {
+ const cache = createSessionListCache();
+ const server = withSessionListCache({ server: createMockAgentUIServer(overrides), cache });
+ return server;
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('withSessionListCache', () => {
+ it('reuses a page when requests differ only by startTimestamp', async () => {
+ const listSessions = vi.fn().mockResolvedValue(emptyPage);
+ const server = cachedServer({ listSessions });
+
+ const first = await server.listSessions({ limit: 20, startTimestamp: '2025-09-09T00:00:00.000Z' });
+ const second = await server.listSessions({ limit: 20, startTimestamp: '2025-09-09T00:00:00.001Z' });
+
+ expect(listSessions).toHaveBeenCalledTimes(1);
+ expect(second).toBe(first);
+ });
+
+ it('fetches separately per pageToken and agentId', async () => {
+ const listSessions = vi.fn().mockResolvedValue(emptyPage);
+ const server = cachedServer({ listSessions });
+
+ await server.listSessions({ limit: 20 });
+ await server.listSessions({ limit: 20, pageToken: 'page-2' });
+ await server.listSessions({ limit: 20, agentId: 'agent-x' });
+
+ expect(listSessions).toHaveBeenCalledTimes(3);
+ });
+
+ it('clears the cache after createSession, updateSession, and deleteSession', async () => {
+ const listSessions = vi.fn().mockResolvedValue(emptyPage);
+ const session = { id: 's1' };
+ const server = cachedServer({
+ listSessions,
+ createSession: vi.fn().mockResolvedValue(session),
+ updateSession: vi.fn().mockResolvedValue(session),
+ deleteSession: vi.fn().mockResolvedValue(undefined),
+ });
+
+ await server.listSessions({ limit: 20 });
+ await server.createSession({});
+ await server.listSessions({ limit: 20 });
+ await server.updateSession({ sessionId: 's1' });
+ await server.listSessions({ limit: 20 });
+ await server.deleteSession?.({ sessionId: 's1' });
+ await server.listSessions({ limit: 20 });
+
+ expect(listSessions).toHaveBeenCalledTimes(4);
+ });
+
+ it('retries after a failed page instead of replaying the rejection', async () => {
+ const listSessions = vi.fn().mockRejectedValueOnce(new Error('boom')).mockResolvedValue(emptyPage);
+ const server = cachedServer({ listSessions });
+
+ await expect(server.listSessions({ limit: 20 })).rejects.toThrow('boom');
+ await expect(server.listSessions({ limit: 20 })).resolves.toEqual(emptyPage);
+ expect(listSessions).toHaveBeenCalledTimes(2);
+ });
+
+ it('expires entries after the TTL', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ const listSessions = vi.fn().mockResolvedValue(emptyPage);
+ const server = cachedServer({ listSessions });
+
+ await server.listSessions({ limit: 20 });
+ vi.setSystemTime(29_000);
+ await server.listSessions({ limit: 20 });
+ expect(listSessions).toHaveBeenCalledTimes(1);
+
+ vi.setSystemTime(31_000);
+ await server.listSessions({ limit: 20 });
+ expect(listSessions).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0d27d6ea0..9405b0a3f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -69,8 +69,8 @@ importers:
specifier: 0.2.21
'@truefoundry/assistant-ui-runtime':
- specifier: 0.1.30
+ specifier: 0.1.31
'@truefoundry/trueforge-sdk':
specifier: workspace:*
version: link:../trueforge-sdk
@@ -366,8 +366,8 @@ importers:
specifier: ^0.13.2
'@truefoundry/assistant-ui-runtime':
- specifier: 0.1.30
+ specifier: 0.1.31
'@truefoundry/trueforge-sdk':
specifier: workspace:*
version: link:../trueforge-sdk
@@ -3645,8 +3645,8 @@ packages:
'@types/react-dom':
optional: true
- '@truefoundry/[email protected]':
- resolution: {integrity: sha512-ugcJqpiYnLToxRj+VHHfR4q875ebxUHCCiJgRk6qL/X1hTZvH3w2jiWMNQwS2DB1Q1ZKYnUi8MxmrFP/zIBnJQ==}
+ '@truefoundry/[email protected]':
+ resolution: {integrity: sha512-siWHjK0Ddargk6zjN3NlD7j+E8xOHGQFN+mFeyncY8L5pibxK4bNQi8Pd4qtNYFxxwkb8f1QUoMeB4bZMk+Jbw==}
peerDependencies:
'@types/react': '*'
react: ^18 || ^19
@@ -10904,7 +10904,7 @@ snapshots:
'@types/react': 19.2.18
'@types/react-dom': 19.2.5(@types/[email protected])
dependencies:
'@assistant-ui/store': 0.2.21(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected])