Skip to content

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

Chore/gv/filters in session listing (#82)

Govinda Vashishtha18c24d2baafd
diff --git a/.codegraph/.gitignore b/.codegraph/.gitignore
deleted file mode 100644
index d20c0fe4b..000000000
--- a/.codegraph/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-# CodeGraph data files — local to each machine, not for committing.
-# Ignore everything in .codegraph/ except this file itself, so transient
-# files (the database, daemon.pid, sockets, logs) never show up in git.
-*
-!.gitignore
diff --git a/.codegraph/codegraph.db b/.codegraph/codegraph.db
deleted file mode 100644
index 09e3110e7..000000000
Binary files a/.codegraph/codegraph.db and /dev/null differ
diff --git a/eslint.config.mjs b/eslint.config.mjs
index da7422aca..dac6d94a1 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -45,6 +45,9 @@ export default defineConfig(
ignores: [
'**/node_modules/**',
'**/dist/**',
+ // Nested package ESLint config scopes `dist/**` to that package root only;
+ // example build output sits one level deeper and needs an explicit ignore.
+ 'packages/trueforge-ui-sdk/example/dist/**',
'**/coverage/**',
'**/.pnpm-store/**',
'**/.eslintcache',
diff --git a/packages/frontend/package.json b/packages/frontend/package.json
index 9d30a9d0b..34fe59b81 100644
--- a/packages/frontend/package.json
+++ b/packages/frontend/package.json
@@ -24,7 +24,7 @@
"@assistant-ui/core": "0.2.22",
"@assistant-ui/react": "^0.14.24",
"@assistant-ui/store": "0.2.21",
- "@truefoundry/assistant-ui-runtime": "^0.1.10-rc.1",
+ "@truefoundry/assistant-ui-runtime": "^0.1.10",
"@truefoundry/trueforge-ui": "workspace:*",
"monaco-editor": "^0.52.0",
"react": "^19.2.4",
diff --git a/packages/frontend/src/App.tsx b/packages/frontend/src/App.tsx
index b72265eed..a8648f799 100644
--- a/packages/frontend/src/App.tsx
+++ b/packages/frontend/src/App.tsx
@@ -128,7 +128,7 @@ export function App() {
}}
layout="sidebar"
agentConfig={{
- mode: 'AgentComposer',
+ mode: 'AgentLibraryWithComposer',
defaultAgentSpec: boot.defaultAgentSpec,
}}
overrides={overrides}
diff --git a/packages/frontend/src/harnessBuilderServer.ts b/packages/frontend/src/harnessBuilderServer.ts
index f2273b83f..8b7711e8d 100644
--- a/packages/frontend/src/harnessBuilderServer.ts
+++ b/packages/frontend/src/harnessBuilderServer.ts
@@ -1,20 +1,50 @@
/**
* AgentBuilderServer callbacks for createTrueFoundryServer.
- * Composer pickers + agent library stubs (Harness has no agent registry).
+ * Composer pickers + agent library backed by the Harness agents registry.
*/
-import type { AgentBuilderServer } from '@truefoundry/trueforge-ui';
+import type {
+ AgentBuilderServer,
+ AgentLibraryEntry,
+ ModelSelection,
+ SearchAgentsParams,
+} from '@truefoundry/trueforge-ui';
+import type { TrueForgeApi as Harness } from 'trueforge';
import { getCapabilities, listConfiguredMcpServers, listModels, listSkills } from './composerLists';
import { toUiConnector } from './connectorCatalog';
-import type { HarnessAgentSpec } from './harnessServer';
+import { createHarnessClient, harnessClient, type CreateHarnessClientOptions } from './harnessClient';
+import { agentManifest, toHarnessAgentSpec, toUiAgentSpec, type HarnessAgentSpec } from './harnessServer';
/** Harness model names are `provider/model`. */
export function providerOf(name: string): string {
return name.split('/')[0] ?? name;
}
-export function createHarnessBuilderServer(): AgentBuilderServer<HarnessAgentSpec> {
+/** Map harness model rows onto the UI picker shape (incl. reasoning-effort options). */
+export function toModelSelection(model: Harness.Model): ModelSelection {
+ const efforts = model.properties.reasoningEfforts;
return {
- getModels: async () => (await listModels()).map(model => ({ name: model.name, provider: providerOf(model.name) })),
+ name: model.name,
+ provider: providerOf(model.name),
+ ...(efforts !== undefined && efforts.length > 0 ? { reasoningEfforts: [...efforts] } : {}),
+ };
+}
+
+function toLibraryEntry(agent: Harness.Agent): AgentLibraryEntry {
+ return {
+ name: agent.name,
+ agentId: agent.id,
+ agentSpec: toUiAgentSpec(agentManifest(agent)),
+ };
+}
+
+export function createHarnessBuilderServer(
+ options: CreateHarnessClientOptions = {},
+): AgentBuilderServer<HarnessAgentSpec> {
+ const client =
+ options.baseUrl === undefined && options.fetch === undefined ? harnessClient : createHarnessClient(options);
+
+ return {
+ getModels: async () => (await listModels()).map(toModelSelection),
// Skills require a configured sandbox provider; keep the picker empty when skill capability is off.
getSkills: async () => {
const [capabilities, skills] = await Promise.all([getCapabilities(), listSkills()]);
@@ -23,7 +53,27 @@ export function createHarnessBuilderServer(): AgentBuilderServer<HarnessAgentSpe
: [];
},
getMcp: async () => (await listConfiguredMcpServers()).map(toUiConnector),
- searchAgents: () => Promise.resolve([]),
- saveAgent: () => Promise.reject(new Error('Harness has no agent registry — sessions are draft-only')),
+
+ async searchAgents(req?: SearchAgentsParams) {
+ const { data } = await client.agents.list();
+ const query = req?.query?.trim().toLowerCase();
+ const filtered =
+ query === undefined || query === '' ? data : data.filter(agent => agent.name.toLowerCase().includes(query));
+ const offset = req?.offset ?? 0;
+ const limit = req?.limit ?? 50;
+ return filtered.slice(offset, offset + limit).map(toLibraryEntry);
+ },
+
+ async saveAgent({ agentName, agentSpec }) {
+ const manifest = toHarnessAgentSpec(agentSpec);
+ const { data } = await client.agents.list();
+ const existing = data.find(agent => agent.name === agentName);
+ if (existing !== undefined) {
+ await client.agents.update(agentName, manifest);
+ return { ok: true as const, updated: true as const, agentId: existing.id };
+ }
+ const created = await client.agents.create({ name: agentName, ...manifest });
+ return { ok: true as const, updated: false as const, agentId: created.data.id };
+ },
};
}
diff --git a/packages/frontend/src/harnessServer.ts b/packages/frontend/src/harnessServer.ts
index 0d5828554..018bfc41a 100644
--- a/packages/frontend/src/harnessServer.ts
+++ b/packages/frontend/src/harnessServer.ts
@@ -9,6 +9,10 @@
*
* Skills are name refs on the wire (`SkillNameRef`); the UI SkillMount only
* needs `{ id, name }`, so id is derived as the skill name.
+ *
+ * Sessions bind either an inline draft (`agent.type === 'value'`) or a named
+ * registry ref (`agent.type === 'ref'`). The UI speaks names; the wire carries
+ * agent ids — resolve via the agents registry.
*/
import type {
AgentChatServer,
@@ -24,7 +28,7 @@ import type {
TurnInputItem,
UserMessageContent,
} from '@truefoundry/trueforge-ui';
-import type { TrueForgeApi as Harness } from 'trueforge';
+import type { TrueForgeApi as Harness, TrueForge } from 'trueforge';
import { createHarnessClient, harnessClient, type CreateHarnessClientOptions } from './harnessClient';
export type HarnessSkillMount = SkillMount;
export type HarnessMcpServerMount = McpServerMount & Harness.McpServer;
@@ -37,11 +41,6 @@ export interface HarnessAgentSpec extends AgentSpec<Harness.AgentSpecModel, Harn
variables?: Record<string, string>;
}
-export interface HarnessSession extends Session<HarnessAgentSpec> {
- agentSpec?: HarnessAgentSpec;
- isMutable: boolean;
-}
-
export type CreateHarnessServerOptions = CreateHarnessClientOptions;
/** Mount ids are derived, not stored: Harness returns MCP servers keyed by name. */
@@ -55,7 +54,7 @@ function toUiSkill(skill: Harness.SkillNameRef): HarnessSkillMount {
}
/** Strip UI-only `id` before admission; Harness skills are name refs only. */
-function toHarnessAgentSpec(spec: HarnessAgentSpec): Harness.AgentSpec {
+export function toHarnessAgentSpec(spec: HarnessAgentSpec): Harness.AgentSpec {
const { skills, mcpServers, ...rest } = spec;
return {
...rest,
@@ -72,7 +71,7 @@ function toHarnessAgentSpec(spec: HarnessAgentSpec): Harness.AgentSpec {
};
}
-function toUiAgentSpec(spec: Harness.AgentSpec): HarnessAgentSpec {
+export function toUiAgentSpec(spec: Harness.AgentSpec): HarnessAgentSpec {
const { mcpServers, skills, ...rest } = spec;
return {
...rest,
@@ -81,19 +80,46 @@ function toUiAgentSpec(spec: Harness.AgentSpec): HarnessAgentSpec {
};
}
-function toUiSession(session: Harness.Session): HarnessSession {
- // Value agents are draft/mutable; ref agents are named/immutable.
- const isMutable = session.agent.type === 'value';
+/** Drop registry identity columns so the rest is a plain AgentSpec. */
+export function agentManifest(agent: Harness.Agent): Harness.AgentSpec {
+ const { id, name, ...spec } = agent;
+ void id;
+ void name;
+ return spec;
+}
+
+/** `agentName` is caller-known (UI speaks names; the wire carries only agent ids). */
+function toUiSession(session: Harness.Session, agentName?: string): Session<HarnessAgentSpec> {
return {
id: session.id,
- isMutable,
+ isMutable: session.agent.type === 'value',
createdAt: session.createdAt,
updatedAt: session.updatedAt,
...(session.title === null ? {} : { title: session.title }),
+ // Ref sessions stay named even when the registry row is gone — stamp agentId
+ // so older runtimes that only forward custom.agentName still treat them immutable.
+ ...(session.agent.type === 'ref' ? { agentName: agentName ?? session.agent.agentId } : {}),
...(session.agent.type === 'value' ? { agentSpec: toUiAgentSpec(session.agent.agentSpec) } : {}),
};
}
+/**
+ * UI `agentId` filters may be a registry id or a display name (history filter /
+ * SingleAgent lock both pass names today).
+ */
+export async function findAgent(client: TrueForge, agentIdOrName: string): Promise<Harness.Agent | undefined> {
+ const { data } = await client.agents.list();
+ return data.find(candidate => candidate.id === agentIdOrName || candidate.name === agentIdOrName);
+}
+
+export async function resolveAgent(client: TrueForge, agentIdOrName: string): Promise<Harness.Agent> {
+ const agent = await findAgent(client, agentIdOrName);
+ if (agent === undefined) {
+ throw new Error(`Agent not found: ${agentIdOrName}`);
+ }
+ return agent;
+}
+
/** Spread drops the interface identity, which is what makes the SDK's index-signature part type accept it. */
function toUiContent(content: Harness.UserMessageContent): UserMessageContent {
return typeof content === 'string' ? content : content.map(part => ({ ...part }));
@@ -180,30 +206,76 @@ export function createHarnessChatServer(options: CreateHarnessServerOptions = {}
},
async createSession(request) {
- if (!request.agentSpec) {
- throw new Error('Harness sessions require an agentSpec');
+ if (request.agentName !== undefined && request.agentName.length > 0) {
+ const agent = await resolveAgent(client, request.agentName);
+ const created = await client.sessions.create({
+ agent: { type: 'ref', agentId: agent.id },
+ });
+ return toUiSession(created.data, agent.name);
}
- const created = await client.sessions.create({
- agent: { type: 'value', agentSpec: toHarnessAgentSpec(request.agentSpec) },
- });
- return toUiSession(created.data);
+ if (request.agentSpec !== undefined) {
+ const created = await client.sessions.create({
+ agent: { type: 'value', agentSpec: toHarnessAgentSpec(request.agentSpec) },
+ });
+ return toUiSession(created.data);
+ }
+ throw new Error('createSession requires agentName or agentSpec');
},
async listSessions(request = {}) {
+ const filterKey = request.agentId !== undefined && request.agentId.length > 0 ? request.agentId : undefined;
+ // Soft lookup: stale history filter / deleted agent / SingleAgent mismatch → empty page.
+ const agentFilter = filterKey === undefined ? undefined : await findAgent(client, filterKey);
+ if (filterKey !== undefined && agentFilter === undefined) {
+ const limit = request.limit ?? 20;
+ const data: Session<HarnessAgentSpec>[] = [];
+ const pagination = { limit };
+ const empty = (): HarnessPage<Session<HarnessAgentSpec>> => ({
+ data,
+ response: { data, pagination },
+ hasNextPage: () => false,
+ getNextPage: () => Promise.resolve(empty()),
+ });
+ return empty();
+ }
+ // Stamp ref rows with display names; registries are small (one tenant).
+ const nameById =
+ agentFilter !== undefined
+ ? new Map([[agentFilter.id, agentFilter.name]])
+ : new Map((await client.agents.list()).data.map(agent => [agent.id, agent.name]));
+
const page = await client.sessions.list({
...(request.limit === undefined ? {} : { limit: request.limit }),
...(request.order === undefined ? {} : { order: request.order }),
...(request.pageToken === undefined ? {} : { pageToken: request.pageToken }),
+ ...(agentFilter === undefined ? {} : { agentId: agentFilter.id }),
});
- return toPage(page, toUiSession);
+ return toPage(page, session =>
+ toUiSession(session, session.agent.type === 'ref' ? nameById.get(session.agent.agentId) : undefined),
+ );
},
async getSession({ sessionId }) {
const response = await client.sessions.get(sessionId);
+ const { agent } = response.data;
+ if (agent.type === 'ref') {
+ try {
+ const resolved = await resolveAgent(client, agent.agentId);
+ return toUiSession(response.data, resolved.name);
+ } catch {
+ return toUiSession(response.data);
+ }
+ }
return toUiSession(response.data);
},
async updateSession({ sessionId, agentSpec }) {
+ if (agentSpec !== undefined) {
+ const current = await client.sessions.get(sessionId);
+ if (current.data.agent.type === 'ref') {
+ throw new Error('Cannot update agent on a named session');
+ }
+ }
const response = await client.sessions.update(sessionId, {
...(agentSpec === undefined ? {} : { agent: { type: 'value', agentSpec: toHarnessAgentSpec(agentSpec) } }),
});
diff --git a/packages/frontend/tests/harnessBuilderServer.test.ts b/packages/frontend/tests/harnessBuilderServer.test.ts
index c019cd370..275a3fbc2 100644
--- a/packages/frontend/tests/harnessBuilderServer.test.ts
+++ b/packages/frontend/tests/harnessBuilderServer.test.ts
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
-import { providerOf } from '../src/harnessBuilderServer';
+import { createHarnessBuilderServer, providerOf, toModelSelection } from '../src/harnessBuilderServer';
describe('harnessBuilderServer', () => {
it('providerOf takes the segment before the first slash', () => {
@@ -11,4 +11,139 @@ describe('harnessBuilderServer', () => {
it('providerOf falls back to the full name when there is no slash', () => {
assert.equal(providerOf('gpt-4o'), 'gpt-4o');
});
+
+ it('toModelSelection forwards reasoningEfforts when present', () => {
+ assert.deepEqual(
+ toModelSelection({
+ name: 'openai/o3',
+ properties: { reasoningEfforts: ['low', 'medium', 'high'] },
+ }),
+ {
+ name: 'openai/o3',
+ provider: 'openai',
+ reasoningEfforts: ['low', 'medium', 'high'],
+ },
+ );
+ assert.deepEqual(toModelSelection({ name: 'openai/gpt-4o', properties: {} }), {
+ name: 'openai/gpt-4o',
+ provider: 'openai',
+ });
+ });
+
+ it('searchAgents maps registry rows to library entries with agentId + agentSpec', async () => {
+ const fetchMock: typeof fetch = async input => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.endsWith('/api/v1/agents')) {
+ return Response.json({
+ data: [
+ {
+ id: 'agt_1',
+ name: 'reviewer',
+ model: { name: 'test/model' },
+ instructions: 'Review carefully.',
+ skills: [{ name: 'review' }],
+ mcp_servers: [{ name: 'github', enable_tools: ['@all'] }],
+ },
+ { id: 'agt_2', name: 'writer', model: { name: 'test/model' } },
+ ],
+ });
+ }
+ return new Response(`Unexpected request: ${url}`, { status: 500 });
+ };
+
+ const builder = createHarnessBuilderServer({ fetch: fetchMock });
+ const all = await builder.searchAgents();
+ assert.equal(all.length, 2);
+ assert.deepEqual(all[0], {
+ name: 'reviewer',
+ agentId: 'agt_1',
+ agentSpec: {
+ model: { name: 'test/model' },
+ instructions: 'Review carefully.',
+ skills: [{ id: 'review', name: 'review' }],
+ mcpServers: [{ id: 'github', name: 'github', enableTools: ['@all'] }],
+ },
+ });
+
+ const filtered = await builder.searchAgents({ query: 'write' });
+ assert.deepEqual(
+ filtered.map(row => row.name),
+ ['writer'],
+ );
+ });
+
+ it('saveAgent creates when the name is new', async () => {
+ const requests: { method: string; url: string; body?: unknown }[] = [];
+ const fetchMock: typeof fetch = async (input, init) => {
+ const url = input instanceof Request ? input.url : String(input);
+ const method = init?.method ?? 'GET';
+ if (url.endsWith('/api/v1/agents') && method === 'GET') {
+ return Response.json({ data: [] });
+ }
+ if (url.endsWith('/api/v1/agents') && method === 'POST' && typeof init?.body === 'string') {
+ requests.push({ method, url, body: JSON.parse(init.body) });
+ return Response.json({
+ data: { id: 'agt_new', name: 'saved-agent', model: { name: 'test/model' } },
+ });
+ }
+ return new Response(`Unexpected request: ${method} ${url}`, { status: 500 });
+ };
+
+ const builder = createHarnessBuilderServer({ fetch: fetchMock });
+ const result = await builder.saveAgent({
+ agentName: 'saved-agent',
+ agentSpec: {
+ model: { name: 'test/model' },
+ skills: [{ id: 'review', name: 'review' }],
+ },
+ });
+
+ assert.deepEqual(result, { ok: true, updated: false, agentId: 'agt_new' });
+ assert.deepEqual(requests.at(-1)?.body, {
+ name: 'saved-agent',
+ model: { name: 'test/model' },
+ skills: [{ name: 'review' }],
+ });
+ });
+
+ it('saveAgent updates when the name already exists', async () => {
+ const requests: { method: string; url: string; body?: unknown }[] = [];
+ const fetchMock: typeof fetch = async (input, init) => {
+ const url = input instanceof Request ? input.url : String(input);
+ const method = init?.method ?? 'GET';
+ if (url.endsWith('/api/v1/agents') && method === 'GET') {
+ return Response.json({
+ data: [{ id: 'agt_1', name: 'writer', model: { name: 'test/model' } }],
+ });
+ }
+ if (url.endsWith('/api/v1/agents/writer') && method === 'PUT' && typeof init?.body === 'string') {
+ requests.push({ method, url, body: JSON.parse(init.body) });
+ return Response.json({
+ data: {
+ id: 'agt_1',
+ name: 'writer',
+ model: { name: 'test/model' },
+ instructions: 'Write release notes.',
+ },
+ });
+ }
+ return new Response(`Unexpected request: ${method} ${url}`, { status: 500 });
+ };
+
+ const builder = createHarnessBuilderServer({ fetch: fetchMock });
+ const result = await builder.saveAgent({
+ agentName: 'writer',
+ agentSpec: {
+ model: { name: 'test/model' },
+ instructions: 'Write release notes.',
+ },
+ });
+
+ assert.deepEqual(result, { ok: true, updated: true, agentId: 'agt_1' });
+ assert.equal(requests.length, 1);
+ assert.deepEqual(requests[0]?.body, {
+ model: { name: 'test/model' },
+ instructions: 'Write release notes.',
+ });
+ });
});
diff --git a/packages/frontend/tests/harnessServer.test.ts b/packages/frontend/tests/harnessServer.test.ts
index f0e88feb8..b2b46c2ba 100644
--- a/packages/frontend/tests/harnessServer.test.ts
+++ b/packages/frontend/tests/harnessServer.test.ts
@@ -38,6 +38,9 @@ const fetchMock: typeof fetch = async (input, init) => {
if (url.includes('/api/v1/sessions?') || url.endsWith('/api/v1/sessions')) {
return Response.json({ data: [session], pagination: { limit: 20, next_page_token: 'tok_2' } });
}
+ if (url.endsWith('/api/v1/agents')) {
+ return Response.json({ data: [] });
+ }
if (url.endsWith('/api/v1/sessions/ses_1/turns')) {
return new Response(
'id: 7\ndata: {"type":"model.message.delta","id":"evt_1","thread_id":"main","content":"hello"}\n\n',
@@ -133,6 +136,174 @@ describe('createHarnessChatServer', () => {
]);
});
+ it('creates a ref session from agentName and reports it immutable', async () => {
+ const requests: { url: string; body?: unknown }[] = [];
+ const fetchNamed: typeof fetch = async (input, init) => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.endsWith('/api/v1/agents')) {
+ return Response.json({
+ data: [{ id: 'agt_1', name: 'reviewer', model: { name: 'test/model' } }],
+ });
+ }
+ if (url.endsWith('/api/v1/sessions') && init?.method === 'POST' && typeof init.body === 'string') {
+ requests.push({ url, body: JSON.parse(init.body) });
+ return Response.json({ data: { ...session, agent: { type: 'ref', agent_id: 'agt_1' } } });
+ }
+ return new Response(`Unexpected request: ${url}`, { status: 500 });
+ };
+
+ const server = createHarnessChatServer({ fetch: fetchNamed });
+ const created = await server.createSession({ agentName: 'reviewer' });
+
+ assert.deepEqual(requests.at(-1)?.body, { agent: { type: 'ref', agent_id: 'agt_1' } });
+ assert.equal(created.isMutable, false);
+ assert.equal(created.agentName, 'reviewer');
+ assert.equal(created.agentSpec, undefined);
+ });
+
+ it('rejects createSession for an unknown agentName without touching sessions', async () => {
+ const fetchNamed: typeof fetch = async input => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.endsWith('/api/v1/agents')) return Response.json({ data: [] });
+ return new Response(`Unexpected request: ${url}`, { status: 500 });
+ };
+
+ const server = createHarnessChatServer({ fetch: fetchNamed });
+ await assert.rejects(() => server.createSession({ agentName: 'ghost' }), /Agent not found: ghost/);
+ });
+
+ it('filters listSessions by agentId (name) and stamps it on the ref rows', async () => {
+ let listUrl: string | undefined;
+ const fetchNamed: typeof fetch = async input => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.endsWith('/api/v1/agents')) {
+ return Response.json({
+ data: [{ id: 'agt_1', name: 'reviewer', model: { name: 'test/model' } }],
+ });
+ }
+ if (url.includes('/api/v1/sessions?')) {
+ listUrl = url;
+ return Response.json({
+ data: [{ ...session, agent: { type: 'ref', agent_id: 'agt_1' } }],
+ pagination: { limit: 20 },
+ });
+ }
+ return new Response(`Unexpected request: ${url}`, { status: 500 });
+ };
+
+ const server = createHarnessChatServer({ fetch: fetchNamed });
+ const page = await server.listSessions({ agentId: 'reviewer' });
+
+ assert.ok(listUrl !== undefined);
+ assert.equal(new URL(listUrl, 'http://test.local').searchParams.get('agent_id'), 'agt_1');
+ assert.equal(page.data[0]?.agentName, 'reviewer');
+ assert.equal(page.data[0]?.isMutable, false);
+ });
+
+ it('filters listSessions when agentId is the registry id', async () => {
+ let listUrl: string | undefined;
+ const fetchNamed: typeof fetch = async input => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.endsWith('/api/v1/agents')) {
+ return Response.json({
+ data: [{ id: 'agt_1', name: 'reviewer', model: { name: 'test/model' } }],
+ });
+ }
+ if (url.includes('/api/v1/sessions?')) {
+ listUrl = url;
+ return Response.json({
+ data: [{ ...session, agent: { type: 'ref', agent_id: 'agt_1' } }],
+ pagination: { limit: 20 },
+ });
+ }
+ return new Response(`Unexpected request: ${url}`, { status: 500 });
+ };
+
+ const server = createHarnessChatServer({ fetch: fetchNamed });
+ const page = await server.listSessions({ agentId: 'agt_1' });
+
+ assert.ok(listUrl !== undefined);
+ assert.equal(new URL(listUrl, 'http://test.local').searchParams.get('agent_id'), 'agt_1');
+ assert.equal(page.data[0]?.agentName, 'reviewer');
+ });
+
+ it('listSessions returns an empty page when agentId matches no registry agent', async () => {
+ let listedSessions = false;
+ const fetchNamed: typeof fetch = async input => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.endsWith('/api/v1/agents')) return Response.json({ data: [] });
+ if (url.includes('/api/v1/sessions')) {
+ listedSessions = true;
+ return new Response(`Unexpected request: ${url}`, { status: 500 });
+ }
+ return new Response(`Unexpected request: ${url}`, { status: 500 });
+ };
+
+ const server = createHarnessChatServer({ fetch: fetchNamed });
+ const page = await server.listSessions({ agentId: 'ghost', limit: 10 });
+
+ assert.equal(listedSessions, false);
+ assert.deepEqual(page.data, []);
+ assert.equal(page.hasNextPage(), false);
+ assert.deepEqual(page.response.pagination, { limit: 10 });
+ });
+
+ it('getSession resolves the agentName of a ref session from the registry', async () => {
+ const fetchNamed: typeof fetch = async input => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.endsWith('/api/v1/agents')) {
+ return Response.json({
+ data: [{ id: 'agt_1', name: 'reviewer', model: { name: 'test/model' } }],
+ });
+ }
+ if (url.endsWith('/api/v1/sessions/ses_1')) {
+ return Response.json({ data: { ...session, agent: { type: 'ref', agent_id: 'agt_1' } } });
+ }
+ return new Response(`Unexpected request: ${url}`, { status: 500 });
+ };
+
+ const server = createHarnessChatServer({ fetch: fetchNamed });
+ const found = await server.getSession({ sessionId: 'ses_1' });
+
+ assert.equal(found.agentName, 'reviewer');
+ assert.equal(found.isMutable, false);
+ });
+
+ it('getSession stamps agentId as agentName when the registry agent is gone', async () => {
+ const fetchNamed: typeof fetch = async input => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.endsWith('/api/v1/agents')) return Response.json({ data: [] });
+ if (url.endsWith('/api/v1/sessions/ses_1')) {
+ return Response.json({ data: { ...session, agent: { type: 'ref', agent_id: 'agt_deleted' } } });
+ }
+ return new Response(`Unexpected request: ${url}`, { status: 500 });
+ };
+
+ const server = createHarnessChatServer({ fetch: fetchNamed });
+ const found = await server.getSession({ sessionId: 'ses_1' });
+
+ assert.equal(found.isMutable, false);
+ assert.equal(found.agentName, 'agt_deleted');
+ });
+
+ it('refuses to update the agent of a ref session', async () => {
+ const fetchNamed: typeof fetch = async input => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.endsWith('/api/v1/sessions/ses_1')) {
+ return Response.json({ data: { ...session, agent: { type: 'ref', agent_id: 'agt_1' } } });
+ }
+ return new Response(`Unexpected request: ${url}`, { status: 500 });
+ };
+
+ const server = createHarnessChatServer({ fetch: fetchNamed });
+ const updateSession = server.updateSession;
+ assert.ok(updateSession);
+ await assert.rejects(
+ () => updateSession({ sessionId: 'ses_1', agentSpec: { model: { name: 'test/model' } } }),
+ /Cannot update agent on a named session/,
+ );
+ });
+
it('subscribes to a turn and forwards afterSequenceNumber', async () => {
const server = createHarnessChatServer({ fetch: fetchMock });
assert.ok(server.subscribeToTurn);
diff --git a/packages/trueforge-ui-sdk/CHANGELOG.md b/packages/trueforge-ui-sdk/CHANGELOG.md
index 5ce71771d..d5fd5071e 100644
--- a/packages/trueforge-ui-sdk/CHANGELOG.md
+++ b/packages/trueforge-ui-sdk/CHANGELOG.md
@@ -7,8 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **History row mutability** — prefer `custom.isMutable` from the session (runtime
+ stamp) over inferring from `agentName`. Orphaned named refs (deleted agent, no
+ `agentName`) open as immutable. `openHistorySession` allows `isMutable: false`
+ without an agent name.
+- **Edit-bound draft history switch** — do not reuse the mutable shell via
+ `switchToThread` when the shell still carries an Edit `agentName`/`agentId`
+ and the row is a different session. Remount through `openHistorySession` so
+ Update Agent chrome cannot overwrite the wrong library agent.
+
### Breaking
+- **`ShellMode` shape** — replaced `type: 'idle' | 'named' | 'draft'` with
+ `status: 'idle' | 'active'` plus `isMutable` on active bindings. Composer /
+ Save Agent / welcome chrome key off `isMutable`, not draft|named.
+ Hosts that inspected `mode.type` must switch to `mode.status` /
+ `mode.isMutable` (see `shellIsMutable`).
- **Renamed `TrueFoundryAssistantUI` → `TrueforgeUI`** (props type
`TrueFoundryAssistantUIProps` → `TrueforgeUIProps`). Update imports and JSX.
- **`TrueforgeUI` agent props** — replaced top-level `agentName` and
@@ -34,6 +50,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Named agent header title** — when an immutable (named) agent chat is open,
+ the thread header shows the agent name on the left (sidebar / drawer / dock /
+ widget layouts). Hidden for idle and draft/mutable chats.
+- **`AgentLibraryEntry.agentId?` / `agentSpec?`** — optional listing fields.
+ Hosts that only return `{ name }` keep working; `agentSpec` enables Edit.
+- **Agents Library Edit** — when `isComposerEnabled` and the row has
+ `agentSpec`, Edit binds a mutable session seeded from that spec
+ (`isMutable: true`). Try Agent remains immutable (`isMutable: false`).
+- **`selectLibraryAgent` / `shellIsMutable` / `libraryAgentId`** on shell
+ context. `selectAgent` / `openDraft` remain as thin wrappers.
- **Reasoning-effort selector** beside the model picker in the draft composer.
Shown only when the selected `ModelSelection` declares `reasoningEfforts`;
the effort is coerced into the spec on model change or explicit pick.
diff --git a/packages/trueforge-ui-sdk/docs/server-types.temp.ts b/packages/trueforge-ui-sdk/docs/server-types.temp.ts
index a05f94101..8f9165b5c 100644
--- a/packages/trueforge-ui-sdk/docs/server-types.temp.ts
+++ b/packages/trueforge-ui-sdk/docs/server-types.temp.ts
@@ -273,7 +273,12 @@ export interface CreateSessionRequest {
/** List filter + pagination. Hosts extend via `TList extends ListSessionsParams`. */
export interface ListSessionsParams extends PageParams {
- agentName?: string;
+ /**
+ * Host-owned agent identity filter. Hosts that key agents by name pass that name here.
+ * Unknown / deleted ids MUST return an empty page (stale history filter, SingleAgent
+ * mismatch) — do not throw and fail the whole thread list.
+ */
+ agentId?: string;
}
/**
diff --git a/packages/trueforge-ui-sdk/eslint.config.js b/packages/trueforge-ui-sdk/eslint.config.js
index 4e2db7b2a..218825190 100644
--- a/packages/trueforge-ui-sdk/eslint.config.js
+++ b/packages/trueforge-ui-sdk/eslint.config.js
@@ -5,7 +5,7 @@ import tseslint from 'typescript-eslint';
export default tseslint.config(
{
- ignores: ['dist/**', 'node_modules/**', 'coverage/**'],
+ ignores: ['dist/**', 'example/dist/**', 'example/node_modules/**', 'node_modules/**', 'coverage/**'],
},
eslint.configs.recommended,
...tseslint.configs.recommended,
diff --git a/packages/trueforge-ui-sdk/example/package.json b/packages/trueforge-ui-sdk/example/package.json
index 3c2d0a53b..37ecadd20 100644
--- a/packages/trueforge-ui-sdk/example/package.json
+++ b/packages/trueforge-ui-sdk/example/package.json
@@ -12,8 +12,8 @@
"dependencies": {
"@assistant-ui/core": "^0.2.22",
"@assistant-ui/react": "^0.14.24",
+ "@truefoundry/assistant-ui-runtime": "^0.1.10",
"@truefoundry/trueforge-ui": "link:..",
- "@truefoundry/assistant-ui-runtime": "^0.1.9",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"truefoundry-gateway-sdk": "^0.4.0-rc.5"
diff --git a/packages/trueforge-ui-sdk/example/src/App.tsx b/packages/trueforge-ui-sdk/example/src/App.tsx
index 2aa87584f..0bf28749d 100644
--- a/packages/trueforge-ui-sdk/example/src/App.tsx
+++ b/packages/trueforge-ui-sdk/example/src/App.tsx
@@ -269,6 +269,7 @@ export default function App() {
}}
agentConfig={{ mode: 'AgentLibraryWithComposer' }}
theme={{
+ preset: 'claude',
brand: {
icon: {
src: 'https://media.licdn.com/dms/image/v2/C560BAQGQ9Tfeof4MbA/company-logo_200_200/company-logo_200_200/0/1644494262340/truefoundry_logo?e=2147483647&v=beta&t=Xm6c1LGNbVPD2Ehtj21Z5OcuSCGLhYwlJ763oEYb92M',
diff --git a/packages/trueforge-ui-sdk/example/yarn.lock b/packages/trueforge-ui-sdk/example/yarn.lock
index a9db94465..023e1e633 100644
--- a/packages/trueforge-ui-sdk/example/yarn.lock
+++ b/packages/trueforge-ui-sdk/example/yarn.lock
@@ -9,7 +9,7 @@
dependencies:
zod "^3.22.4"
-"@assistant-ui/core@^0.2.19", "@assistant-ui/core@^0.2.22", "@assistant-ui/core@^0.2.23":
+"@assistant-ui/core@^0.2.22", "@assistant-ui/core@^0.2.23":
version "0.2.23"
resolved "https://registry.yarnpkg.com/@assistant-ui/core/-/core-0.2.23.tgz#24e63f885864d20af322c2261a93d46870358a18"
integrity sha512-mD/sWrdH4SF1POxWE0Wn8jrxOSnuGOJfj8j5coDuEtdtoevQT3Z8LzD5mkd2UdyXHIkwFsMb3/vIL1kH8XKyGg==
@@ -42,7 +42,7 @@
zod "^4.4.3"
zustand "^5.0.14"
-"@assistant-ui/store@^0.2.19", "@assistant-ui/store@^0.2.22":
+"@assistant-ui/store@^0.2.21", "@assistant-ui/store@^0.2.22":
version "0.2.22"
resolved "https://registry.yarnpkg.com/@assistant-ui/store/-/store-0.2.22.tgz#3eaa11b7c2fcdddac909d4b3e3e1726e9238d2a8"
integrity sha512-RdUFLOFJ3ZwIoOZYrRvps3OAODwnWoUAuNfqbROKrj5qtlQsIJRqxUNdLTjcf4AimhkjCwOaFacGHHm9lE4qBw==
@@ -1425,13 +1425,13 @@
"@tailwindcss/oxide" "4.3.3"
tailwindcss "4.3.3"
-"@truefoundry/assistant-ui-runtime@^0.1.9":
- version "0.1.9"
- resolved "https://registry.yarnpkg.com/@truefoundry/assistant-ui-runtime/-/assistant-ui-runtime-0.1.9.tgz#3234bb477f88d11e3fef4c034798f0a1bf85ddfc"
- integrity sha512-2LjsIHbWOtJI+oSF28SvgcJ8WpUUr74/LYJ84UyKfOLnFutgJZPAwFp9a3uYmIdwVahnwk9pF6FD3zFyVVDB/Q==
+"@truefoundry/assistant-ui-runtime@^0.1.10":
+ version "0.1.10"
+ resolved "https://registry.yarnpkg.com/@truefoundry/assistant-ui-runtime/-/assistant-ui-runtime-0.1.10.tgz#71fef92257ea2534c74498e3769ee259d1dbb112"
+ integrity sha512-EDIIssQt6y/WVGLRf1Vd7JdS0Ewvuzn8jWCCueiMj38L+Hfcdih3TBr6H2hhEby9C4ULxTl4xbBVG3ybmVxPSw==
dependencies:
- "@assistant-ui/core" "^0.2.19"
- "@assistant-ui/store" "^0.2.19"
+ "@assistant-ui/core" "^0.2.22"
+ "@assistant-ui/store" "^0.2.21"
"@truefoundry/trueforge-ui@link:..":
version "0.0.0"
@@ -1634,7 +1634,7 @@ assistant-cloud@^0.1.37:
dependencies:
assistant-stream "^0.3.33"
-assistant-stream@^0.3.27, assistant-stream@^0.3.28, assistant-stream@^0.3.33:
+assistant-stream@^0.3.28, assistant-stream@^0.3.33:
version "0.3.33"
resolved "https://registry.yarnpkg.com/assistant-stream/-/assistant-stream-0.3.33.tgz#8dd69031265966686ada54d9e33b0c60c351c091"
integrity sha512-ZUP5hGMtucRpg1TQWCMX3Tp7iOvhG4KWrKTJYtNUCbtDvPuMod4JbBp2JJp8ThrNALXBi3OlE4ZU1a/6W11Cog==
diff --git a/packages/trueforge-ui-sdk/package.json b/packages/trueforge-ui-sdk/package.json
index 9423fe039..00ba06fec 100644
--- a/packages/trueforge-ui-sdk/package.json
+++ b/packages/trueforge-ui-sdk/package.json
@@ -82,7 +82,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.10-rc.1",
+ "@truefoundry/assistant-ui-runtime": "^0.1.10",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
"monaco-editor": "^0.56.0",
diff --git a/packages/trueforge-ui-sdk/src/atoms/AgentHistoryFilterButton.test.tsx b/packages/trueforge-ui-sdk/src/atoms/AgentHistoryFilterButton.test.tsx
new file mode 100644
index 000000000..62860cd33
--- /dev/null
+++ b/packages/trueforge-ui-sdk/src/atoms/AgentHistoryFilterButton.test.tsx
@@ -0,0 +1,106 @@
+// @vitest-environment jsdom
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { ServerProvider } from '../server/ServerContext.js';
+import { ShellModeProvider, useShellMode } from '../server/ShellModeContext.js';
+import type { AgentUIServer } from '../server/types.js';
+import { SlotsProvider } from '../theme/SlotsProvider.js';
+import { AgentHistoryFilterButton } from './AgentHistoryFilterButton.js';
+
+HTMLDialogElement.prototype.showModal = function showModal() {
+ this.setAttribute('open', '');
+};
+HTMLDialogElement.prototype.close = function close() {
+ this.removeAttribute('open');
+ this.dispatchEvent(new Event('close'));
+};
+
+function mockServer(partial: Partial<AgentUIServer> = {}): AgentUIServer {
+ return {
+ searchAgents: vi.fn().mockResolvedValue([{ name: 'from-sdk' }, { name: 'other' }]),
+ ...partial,
+ } as AgentUIServer;
+}
+
+function FilterProbe() {
+ const shell = useShellMode();
+ return <span data-testid="filter-value">{shell.historyAgentFilter ?? 'all'}</span>;
+}
+
+function wrap({
+ agentConfig,
+ server,
+}: {
+ agentConfig?: Parameters<typeof ShellModeProvider>[0]['agentConfig'];
+ server?: AgentUIServer | null;
+}) {
+ return function Wrapper({ children }: { children: ReactNode }) {
+ const tree = (
+ <SlotsProvider>
+ <ShellModeProvider agentConfig={agentConfig}>
+ {children}
+ <FilterProbe />
+ </ShellModeProvider>
+ </SlotsProvider>
+ );
+ if (server == null) return tree;
+ return <ServerProvider server={server}>{tree}</ServerProvider>;
+ };
+}
+
+describe('AgentHistoryFilterButton', () => {
+ it('renders nothing when library is disabled', () => {
+ render(<AgentHistoryFilterButton />, {
+ wrapper: wrap({ agentConfig: { mode: 'SingleAgent', name: 'locked' }, server: mockServer() }),
+ });
+ expect(screen.queryByRole('button', { name: /Filter chat history/i })).not.toBeInTheDocument();
+ });
+
+ it('opens popover and sets history filter on agent click', async () => {
+ const server = mockServer();
+ render(<AgentHistoryFilterButton />, {
+ wrapper: wrap({ agentConfig: { mode: 'AgentLibraryWithComposer' }, server }),
+ });
+
+ expect(screen.getByTestId('filter-value')).toHaveTextContent('all');
+
+ fireEvent.click(screen.getByRole('button', { name: /Filter chat history/i }));
+ await waitFor(() => expect(screen.getByRole('menuitem', { name: /from-sdk/i })).toBeInTheDocument());
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('menuitem', { name: /from-sdk/i }));
+ });
+
+ expect(screen.getByTestId('filter-value')).toHaveTextContent('from-sdk');
+ expect(server.searchAgents).toHaveBeenCalled();
+ });
+
+ it('opens a bottom sheet on mobile', async () => {
+ const matchMedia = vi.fn().mockImplementation((query: string) => ({
+ matches: query === '(max-width: 767px)',
+ media: query,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ onchange: null,
+ }));
+ vi.stubGlobal('matchMedia', matchMedia);
+
+ const server = mockServer();
+ render(<AgentHistoryFilterButton />, {
+ wrapper: wrap({ agentConfig: { mode: 'AgentLibraryWithComposer' }, server }),
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: /Filter chat history/i }));
+ await waitFor(() => {
+ expect(screen.getByRole('dialog', { name: /Filter agents/i })).toBeInTheDocument();
+ });
+ await waitFor(() => expect(screen.getByRole('menuitem', { name: /from-sdk/i })).toBeInTheDocument());
+
+ vi.unstubAllGlobals();
+ });
+});
diff --git a/packages/trueforge-ui-sdk/src/atoms/AgentHistoryFilterButton.tsx b/packages/trueforge-ui-sdk/src/atoms/AgentHistoryFilterButton.tsx
new file mode 100644
index 000000000..4c7df6576
--- /dev/null
+++ b/packages/trueforge-ui-sdk/src/atoms/AgentHistoryFilterButton.tsx
@@ -0,0 +1,194 @@
+'use client';
+
+import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+
+import { Icon } from '../icons/Icon.js';
+import { useOptionalServer } from '../server/ServerContext.js';
+import { useOptionalShellMode } from '../server/ShellModeContext.js';
+import type { AgentLibraryEntry } from '../server/types.js';
+import { auiButtonClass } from './lib/buttonClasses.js';
+import { cn } from './lib/cn.js';
+import { useCompactLayout } from './lib/CompactLayoutContext.js';
+import { useIsMobile } from './lib/useIsMobile.js';
+import { BottomSheet } from './primitives/BottomSheet.js';
+import SearchInput from './primitives/SearchInput.js';
+
+/**
+ * Funnel popover for filtering chat history by agent id.
+ * Desktop: fixed menu to the right of the funnel. Mobile/compact: bottom sheet.
+ */
+export function AgentHistoryFilterButton() {
+ const shell = useOptionalShellMode();
+ const server = useOptionalServer();
+ const isMobile = useIsMobile();
+ const compact = useCompactLayout();
+ const useSheet = isMobile || compact;
+
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState('');
+ const [agents, setAgents] = useState<AgentLibraryEntry[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [menuPos, setMenuPos] = useState<{ top: number; left: number } | null>(null);
+ const buttonRef = useRef<HTMLButtonElement>(null);
+ const menuRef = useRef<HTMLDivElement>(null);
+ const menuId = useId();
+
+ const enabled = shell?.isLibraryEnabled === true && server != null;
+ const selected = shell?.historyAgentFilter ?? null;
+
+ useEffect(() => {
+ if (!open) {
+ setQuery('');
+ return;
+ }
+ if (!server) return;
+ let cancelled = false;
+ setLoading(true);
+ void server
+ .searchAgents({ query: query.trim() || undefined, limit: 50 })
+ .then(rows => {
+ if (!cancelled) setAgents(rows);
+ })
+ .catch(() => {
+ if (!cancelled) setAgents([]);
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, query, server]);
+
+ // Desktop only: anchor to the right of the funnel; portal escapes sidebar overflow.
+ useLayoutEffect(() => {
+ if (!open || useSheet) {
+ setMenuPos(null);
+ return;
+ }
+ const update = () => {
+ const rect = buttonRef.current?.getBoundingClientRect();
+ if (!rect) return;
+ setMenuPos({ top: rect.top, left: rect.right + 4 });
+ };
+ update();
+ window.addEventListener('resize', update);
+ window.addEventListener('scroll', update, true);
+ return () => {
+ window.removeEventListener('resize', update);
+ window.removeEventListener('scroll', update, true);
+ };
+ }, [open, useSheet]);
+
+ useEffect(() => {
+ if (!open || useSheet) return;
+ const handler = (e: MouseEvent) => {
+ const target = e.target as Node;
+ if (buttonRef.current?.contains(target) || menuRef.current?.contains(target)) return;
+ setOpen(false);
+ };
+ document.addEventListener('mousedown', handler);
+ return () => document.removeEventListener('mousedown', handler);
+ }, [open, useSheet]);
+
+ if (!enabled) return null;
+
+ const pick = (agentId: string | null) => {
+ shell?.setHistoryAgentFilter(agentId);
+ setOpen(false);
+ };
+
+ const filterBody = (
+ <>
+ <div className="p-1" onMouseDown={e => e.stopPropagation()}>
+ <SearchInput query={query} setQuery={setQuery} placeholder="Search agents" />
+ </div>
+ <div className={cn('mt-1 overflow-y-auto', useSheet ? 'min-h-0 flex-1 px-1 pb-2' : 'max-h-64')}>
+ <button
+ type="button"
+ role="menuitem"
+ className={cn(
+ 'flex w-full cursor-pointer items-center justify-between rounded-sm px-2 py-1.5 text-sm outline-none',
+ 'hover:bg-accent hover:text-accent-foreground',
+ selected == null && 'bg-accent',
+ )}
+ onClick={() => pick(null)}
+ >
+ All chats
+ {selected == null ? <Icon name="check" className="size-3.5 shrink-0" /> : null}
+ </button>
+ {loading ? (
+ <p className="px-2 py-3 text-center text-xs text-muted-foreground">Loading…</p>
+ ) : (
+ agents.map(agent => {
+ const active = selected === agent.name;
+ return (
+ <button
+ key={agent.name}
+ type="button"
+ role="menuitem"
+ className={cn(
+ 'flex w-full cursor-pointer items-center justify-between gap-2 rounded-sm px-2 py-1.5 text-left text-sm outline-none',
+ 'hover:bg-accent hover:text-accent-foreground',
+ active && 'bg-accent',
+ )}
+ onClick={() => pick(agent.name)}
+ >
+ <span className="min-w-0 truncate">{agent.name}</span>
+ {active ? <Icon name="check" className="size-3.5 shrink-0" /> : null}
+ </button>
+ );
+ })
+ )}
+ </div>
+ </>
+ );
+
+ return (
+ <div className="relative shrink-0">
+ <button
+ ref={buttonRef}
+ type="button"
+ aria-label="Filter chat history by agent"
+ aria-haspopup={useSheet ? 'dialog' : 'menu'}
+ aria-expanded={open}
+ aria-controls={open ? menuId : undefined}
+ title="Filter by agent"
+ className={auiButtonClass({
+ variant: 'ghost',
+ size: 'icon',
+ className: cn(
+ 'size-7 text-muted-foreground hover:bg-accent hover:text-foreground',
+ selected != null && 'text-foreground',
+ ),
+ })}
+ onClick={() => setOpen(v => !v)}
+ >
+ <Icon name="funnel" className="size-3.5" />
+ </button>
+ {useSheet && open ? (
+ <BottomSheet open onOpenChange={setOpen} id={menuId} aria-label="Filter agents">
+ <div className="flex min-h-0 flex-1 flex-col p-2" role="menu">
+ {filterBody}
+ </div>
+ </BottomSheet>
+ ) : null}
+ {!useSheet && open && menuPos != null
+ ? createPortal(
+ <div
+ ref={menuRef}
+ id={menuId}
+ role="menu"
+ aria-label="Filter agents"
+ style={{ top: menuPos.top, left: menuPos.left }}
+ className="fixed z-50 w-56 rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md"
+ >
+ {filterBody}
+ </div>,
+ document.body,
+ )
+ : null}
+ </div>
+ );
+}
diff --git a/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.test.tsx b/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.test.tsx
index 08187621c..830898d9f 100644
--- a/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.test.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.test.tsx
@@ -3,7 +3,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { ServerProvider } from '../server/ServerContext.js';
-import { ShellModeProvider } from '../server/ShellModeContext.js';
+import { ShellModeProvider, useShellMode } from '../server/ShellModeContext.js';
import type { AgentUIServer } from '../server/types.js';
import { SlotsProvider } from '../theme/SlotsProvider.js';
import { AgentsLibrary } from './AgentsLibrary.js';
@@ -21,7 +21,13 @@ beforeAll(() => {
};
});
-function mockServer(agents: Array<{ name: string }> = [{ name: 'alpha-agent' }]): AgentUIServer {
+function mockServer(
+ agents: Array<{
+ name: string;
+ agentId?: string;
+ agentSpec?: { model: { name: string }; skills?: Array<{ id: string; name: string }> };
+ }> = [{ name: 'alpha-agent' }],
+): AgentUIServer {
return {
searchAgents: vi.fn(async () => agents),
} as unknown as AgentUIServer;
@@ -59,7 +65,7 @@ describe('CenteredModal', () => {
});
describe('AgentsLibrary', () => {
- it('lists agents and selects a named agent', async () => {
+ it('lists agents and selects a named agent (Try = immutable)', async () => {
const server = mockServer([{ name: 'alpha-agent' }, { name: 'beta-agent' }]);
const onSelectAgent = vi.fn();
const onOpenChange = vi.fn();
@@ -83,6 +89,57 @@ describe('AgentsLibrary', () => {
expect(onOpenChange).toHaveBeenCalledWith(false);
expect(onSelectAgent).toHaveBeenCalledWith('beta-agent');
});
+
+ it('shows Edit when composer is enabled and agentSpec is present', async () => {
+ const server = mockServer([
+ {
+ name: 'writer',
+ agentId: 'writer-id',
+ agentSpec: { model: { name: 'openai-main/gpt-4.1' }, skills: [{ id: 's1', name: 'Skill' }] },
+ },
+ { name: 'try-only' },
+ ]);
+
+ render(
+ <SlotsProvider>
+ <ServerProvider server={server}>
+ <ShellModeProvider agentConfig={{ mode: 'AgentLibraryWithComposer' }}>
+ <AgentsLibrary open onOpenChange={() => undefined} />
+ </ShellModeProvider>
+ </ServerProvider>
+ </SlotsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Edit agent writer' })).toBeInTheDocument();
+ });
+ expect(screen.queryByRole('button', { name: 'Edit agent try-only' })).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Try agent try-only' })).toBeInTheDocument();
+ });
+
+ it('hides Edit when composer is disabled (AgentLibrary only)', async () => {
+ const server = mockServer([
+ {
+ name: 'writer',
+ agentSpec: { model: { name: 'openai-main/gpt-4.1' } },
+ },
+ ]);
+
+ render(
+ <SlotsProvider>
+ <ServerProvider server={server}>
+ <ShellModeProvider agentConfig={{ mode: 'AgentLibrary' }}>
+ <AgentsLibrary open onOpenChange={() => undefined} />
+ </ShellModeProvider>
+ </ServerProvider>
+ </SlotsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Try agent writer' })).toBeInTheDocument();
+ });
+ expect(screen.queryByRole('button', { name: 'Edit agent writer' })).not.toBeInTheDocument();
+ });
});
describe('AgentsLibraryButton', () => {
@@ -105,4 +162,43 @@ describe('AgentsLibraryButton', () => {
expect(screen.getByRole('button', { name: 'Try agent alpha-agent' })).toBeInTheDocument();
});
});
+
+ it('re-fetches the agent count when agentsListEpoch bumps', async () => {
+ const searchAgents = vi
+ .fn()
+ .mockResolvedValueOnce([{ name: 'alpha' }])
+ .mockResolvedValueOnce([{ name: 'alpha' }, { name: 'beta' }]);
+ const server = { searchAgents } as unknown as AgentUIServer;
+
+ function Invalidate() {
+ const shell = useShellMode();
+ return (
+ <button type="button" onClick={() => shell.invalidateAgentsList()}>
+ Invalidate
+ </button>
+ );
+ }
+
+ render(
+ <SlotsProvider>
+ <ServerProvider server={server}>
+ <ShellModeProvider>
+ <AgentsLibraryButton />
+ <Invalidate />
+ </ShellModeProvider>
+ </ServerProvider>
+ </SlotsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: /Agents Library \(1\)/ })).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Invalidate' }));
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: /Agents Library \(2\)/ })).toBeInTheDocument();
+ });
+ expect(searchAgents).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.tsx b/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.tsx
index f902396d3..858fe5b45 100644
--- a/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.tsx
@@ -4,8 +4,8 @@ import { useEffect, useState } from 'react';
import { Icon } from '../icons/Icon.js';
import { useOptionalServer } from '../server/ServerContext.js';
-import { useOptionalShellMode } from '../server/ShellModeContext.js';
-import type { AgentLibraryEntry } from '../server/types.js';
+import { libraryAgentId, useOptionalShellMode } from '../server/ShellModeContext.js';
+import type { AgentLibraryEntry, AgentSpec } from '../server/types.js';
import { auiButtonClass } from './lib/buttonClasses.js';
import { cn } from './lib/cn.js';
import { useCompactLayout } from './lib/CompactLayoutContext.js';
@@ -18,7 +18,22 @@ export type AgentsLibraryProps = {
onSelectAgent?: (agentName: string) => void;
};
-function AgentLibraryRow({ agent, onSelect }: { agent: AgentLibraryEntry; onSelect: () => void }) {
+type AgentLibraryRowProps = {
+ agent: AgentLibraryEntry;
+ showEdit: boolean;
+ onTry: () => void;
+ onEdit: () => void;
+};
+
+function rowActionClass(compact: boolean) {
+ return cn(
+ 'shrink-0 opacity-100 transition-opacity',
+ !compact && 'md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100',
+ 'focus-visible:opacity-100',
+ );
+}
+
+function AgentLibraryRow({ agent, showEdit, onTry, onEdit }: AgentLibraryRowProps) {
const compact = useCompactLayout();
return (
@@ -36,22 +51,34 @@ function AgentLibraryRow({ agent, onSelect }: { agent: AgentLibraryEntry; onSele
<span className="text-foreground min-w-0 flex-1 truncate text-left text-sm font-medium leading-tight">
{agent.name}
</span>
- <button
- type="button"
- aria-label={`Try agent ${agent.name}`}
- className={auiButtonClass({
- variant: 'outline',
- size: 'sm',
- className: cn(
- 'shrink-0 opacity-100 transition-opacity',
- !compact && 'md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100',
- 'focus-visible:opacity-100',
- ),
- })}
- onClick={onSelect}
- >
- Try Agent
- </button>
+ <span className="flex shrink-0 items-center gap-1.5">
+ {showEdit ? (
+ <button
+ type="button"
+ aria-label={`Edit agent ${agent.name}`}
+ className={auiButtonClass({
+ variant: 'ghost',
+ size: 'sm',
+ className: rowActionClass(compact),
+ })}
+ onClick={onEdit}
+ >
+ Edit
+ </button>
+ ) : null}
+ <button
+ type="button"
+ aria-label={`Try agent ${agent.name}`}
+ className={auiButtonClass({
+ variant: 'outline',
+ size: 'sm',
+ className: rowActionClass(compact),
+ })}
+ onClick={onTry}
+ >
+ Try Agent
+ </button>
+ </span>
</div>
);
}
@@ -64,6 +91,9 @@ export function AgentsLibrary({ open, onOpenChange, onSelectAgent }: AgentsLibra
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const canEdit = shell?.isComposerEnabled === true;
+ const agentsListEpoch = shell?.agentsListEpoch ?? 0;
+
useEffect(() => {
if (!open) {
setQuery('');
@@ -90,21 +120,38 @@ export function AgentsLibrary({ open, onOpenChange, onSelectAgent }: AgentsLibra
return () => {
cancelled = true;
};
- }, [open, query, server]);
+ }, [open, query, server, agentsListEpoch]);
- const handleSelect = (name: string) => {
+ const closeLibrary = () => {
onOpenChange(false);
setQuery('');
- onSelectAgent?.(name);
- shell?.selectAgent(name);
+ };
+
+ const handleTry = (agent: AgentLibraryEntry) => {
+ const id = libraryAgentId(agent);
+ closeLibrary();
+ onSelectAgent?.(agent.name);
+ shell?.selectLibraryAgent({
+ isMutable: false,
+ agentId: id,
+ agentName: agent.name,
+ });
+ };
+
+ const handleEdit = (agent: AgentLibraryEntry, agentSpec: AgentSpec) => {
+ const id = libraryAgentId(agent);
+ closeLibrary();
+ onSelectAgent?.(agent.name);
+ shell?.selectLibraryAgent({
+ isMutable: true,
+ agentId: id,
+ agentName: agent.name,
+ agentSpec,
+ });
};
return (
<CenteredModal open={open} onOpenChange={onOpenChange} title="Agents Library">
- {/*
- Single-pane layout modeled on the MCP tools modal's left column
- (search + icon rows). Detail columns need fields beyond AgentLibraryEntry.
- */}
<div className="bg-muted/40 flex min-h-0 flex-1 flex-col">
<div className="shrink-0 border-b border-border px-4 py-3">
<label className="relative block">
@@ -134,9 +181,21 @@ export function AgentsLibrary({ open, onOpenChange, onSelectAgent }: AgentsLibra
) : agents.length === 0 ? (
<p className="text-muted-foreground px-3 py-8 text-center text-sm">No agents found</p>
) : (
- agents.map(agent => (
- <AgentLibraryRow key={agent.name} agent={agent} onSelect={() => handleSelect(agent.name)} />
- ))
+ agents.map(agent => {
+ const agentSpec = agent.agentSpec;
+ const showEdit = canEdit && agentSpec != null;
+ return (
+ <AgentLibraryRow
+ key={libraryAgentId(agent)}
+ agent={agent}
+ showEdit={showEdit}
+ onTry={() => handleTry(agent)}
+ onEdit={() => {
+ if (agentSpec != null) handleEdit(agent, agentSpec);
+ }}
+ />
+ );
+ })
)}
</div>
</div>
diff --git a/packages/trueforge-ui-sdk/src/atoms/AgentsLibraryButton.tsx b/packages/trueforge-ui-sdk/src/atoms/AgentsLibraryButton.tsx
index ad12c9ec4..752b99a0b 100644
--- a/packages/trueforge-ui-sdk/src/atoms/AgentsLibraryButton.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/AgentsLibraryButton.tsx
@@ -22,6 +22,7 @@ export function AgentsLibraryButton({ className, compact = false, onSelectAgent
const [count, setCount] = useState<number | null>(null);
const enabled = shell?.isLibraryEnabled === true && server != null;
+ const agentsListEpoch = shell?.agentsListEpoch ?? 0;
useEffect(() => {
if (!enabled || !server) return;
@@ -35,7 +36,7 @@ export function AgentsLibraryButton({ className, compact = false, onSelectAgent
return () => {
cancelled = true;
};
- }, [enabled, server]);
+ }, [enabled, server, agentsListEpoch]);
if (!enabled) return null;
diff --git a/packages/trueforge-ui-sdk/src/atoms/ClearChatButton.tsx b/packages/trueforge-ui-sdk/src/atoms/ClearChatButton.tsx
index 609ff4e51..373f99fe1 100644
--- a/packages/trueforge-ui-sdk/src/atoms/ClearChatButton.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/ClearChatButton.tsx
@@ -8,17 +8,17 @@ import { auiButtonClass } from './lib/buttonClasses.js';
export function ClearChatButton() {
const shell = useOptionalShellMode();
- if (shell == null || shell.mode.type === 'idle') return null;
+ if (shell == null || shell.mode.status === 'idle') return null;
return (
<button
type="button"
- aria-label="Clear chat"
title="Clear chat"
- className={auiButtonClass({ variant: 'ghost', size: 'icon' })}
+ className={auiButtonClass({ variant: 'ghost', size: 'sm' })}
onClick={() => shell.clearChat()}
>
- <Icon name="rotate-right" />
+ <Icon name="broom" size="0.875em" />
+ Clear chat
</button>
);
}
diff --git a/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.test.tsx b/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.test.tsx
new file mode 100644
index 000000000..fc313cc7a
--- /dev/null
+++ b/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.test.tsx
@@ -0,0 +1,50 @@
+// @vitest-environment jsdom
+import { act, render, screen } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { ShellModeProvider, useShellMode } from '../server/ShellModeContext.js';
+import { NamedAgentHeaderLabel } from './NamedAgentHeaderLabel.js';
+
+function SelectNamed() {
+ const shell = useShellMode();
+ return (
+ <button type="button" onClick={() => shell.selectAgent('reviewer')}>
+ select
+ </button>
+ );
+}
+
+describe('NamedAgentHeaderLabel', () => {
+ it('shows the agent name for a named (immutable) chat', () => {
+ render(
+ <ShellModeProvider agentConfig={{ mode: 'SingleAgent', name: 'support' }}>
+ <NamedAgentHeaderLabel />
+ </ShellModeProvider>,
+ );
+ expect(screen.getByRole('heading', { name: 'support' })).toBeInTheDocument();
+ });
+
+ it('is hidden for draft / mutable chats', () => {
+ render(
+ <ShellModeProvider agentConfig={{ mode: 'AgentComposer' }}>
+ <NamedAgentHeaderLabel />
+ </ShellModeProvider>,
+ );
+ expect(screen.queryByRole('heading')).not.toBeInTheDocument();
+ });
+
+ it('is hidden while idle, then appears after selecting a named agent', () => {
+ render(
+ <ShellModeProvider agentConfig={{ mode: 'AgentLibrary' }}>
+ <SelectNamed />
+ <NamedAgentHeaderLabel />
+ </ShellModeProvider>,
+ );
+ expect(screen.queryByRole('heading')).not.toBeInTheDocument();
+
+ act(() => {
+ screen.getByRole('button', { name: 'select' }).click();
+ });
+ expect(screen.getByRole('heading', { name: 'reviewer' })).toBeInTheDocument();
+ });
+});
diff --git a/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsx b/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsx
new file mode 100644
index 000000000..02fffb309
--- /dev/null
+++ b/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsx
@@ -0,0 +1,19 @@
+'use client';
+
+import { useOptionalShellMode } from '../server/ShellModeContext.js';
+import { cn } from './lib/cn.js';
+
+/** Left-of-header title for an immutable (named) agent chat. Hidden for idle / draft. */
+export function NamedAgentHeaderLabel({ className }: { className?: string }) {
+ const shell = useOptionalShellMode();
+ if (shell == null || shell.mode.status !== 'active' || shell.mode.isMutable) return null;
+
+ const name = shell.mode.agentName ?? shell.mode.agentId;
+ if (name == null || name.length === 0) return null;
+
+ return (
+ <h1 className={cn('min-w-0 truncate px-1 text-sm font-medium text-foreground', className)} title={name}>
+ {name}
+ </h1>
+ );
+}
diff --git a/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.test.tsx b/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.test.tsx
index 5050ead55..626cea202 100644
--- a/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.test.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.test.tsx
@@ -1,9 +1,10 @@
// @vitest-environment jsdom
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { useEffect, useRef } from 'react';
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { ServerProvider } from '../server/ServerContext.js';
-import { ShellModeProvider } from '../server/ShellModeContext.js';
+import { ShellModeProvider, useShellMode } from '../server/ShellModeContext.js';
import type { AgentUIServer } from '../server/types.js';
import { SlotsProvider } from '../theme/SlotsProvider.js';
import { SaveAgentButton } from './SaveAgentButton.js';
@@ -87,6 +88,62 @@ describe('SaveAgentButton', () => {
await waitFor(() => {
expect(screen.queryByRole('dialog', { name: 'Save as agent' })).not.toBeInTheDocument();
});
+ // Bound as mutable Edit with saved identity + spec; chrome flips to Update Agent.
+ expect(screen.getByRole('button', { name: 'Update Agent' })).toBeInTheDocument();
+ });
+
+ it('binds the same draft chat as editable agent without remounting', async () => {
+ const saveAgent = vi.fn(async () => ({ ok: true }));
+ let shellSnap: ReturnType<typeof useShellMode> | undefined;
+
+ function Probe() {
+ shellSnap = useShellMode();
+ return <SaveAgentButton />;
+ }
+
+ render(
+ <SlotsProvider>
+ <ServerProvider server={mockServer(saveAgent)}>
+ <ShellModeProvider>
+ <Probe />
+ </ShellModeProvider>
+ </ServerProvider>
+ </SlotsProvider>,
+ );
+
+ expect(shellSnap).toBeDefined();
+ if (shellSnap == null) throw new Error('expected shell');
+ const epochBefore = shellSnap.agentsListEpoch;
+ const runtimeKeyBefore = shellSnap.runtimeKey;
+
+ fireEvent.click(screen.getByRole('button', { name: 'Save as agent' }));
+ const dialog = screen.getByRole('dialog', { name: 'Save as agent' });
+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'saved-agent' } });
+ fireEvent.change(screen.getByLabelText('System instructions'), {
+ target: { value: 'Be helpful.' },
+ });
+ const submit = dialog.querySelector('button[type="submit"]');
+ expect(submit).toBeInstanceOf(HTMLButtonElement);
+ if (!(submit instanceof HTMLButtonElement)) throw new Error('expected submit');
+ fireEvent.click(submit);
+
+ await waitFor(() => {
+ expect(shellSnap?.mode).toEqual({
+ status: 'active',
+ isMutable: true,
+ agentId: 'saved-agent',
+ agentName: 'saved-agent',
+ agentSpec: {
+ model: { name: 'openai-main/gpt-4.1' },
+ skills: [{ id: 's1', name: 'Skill One' }],
+ instructions: 'Be helpful.',
+ },
+ locked: false,
+ });
+ });
+ expect(shellSnap.agentsListEpoch).toBe(epochBefore + 1);
+ // Same chat continues — runtime must not remount.
+ expect(shellSnap.runtimeKey).toBe(runtimeKeyBefore);
});
it('surfaces save errors without closing', async () => {
@@ -114,4 +171,46 @@ describe('SaveAgentButton', () => {
});
expect(screen.getByRole('dialog', { name: 'Save as agent' })).toBeInTheDocument();
});
+
+ it('shows Update Agent and prefills name when editing a library agent', async () => {
+ function EditSeed() {
+ const shell = useShellMode();
+ const seeded = useRef(false);
+ useEffect(() => {
+ if (seeded.current) return;
+ seeded.current = true;
+ shell.selectLibraryAgent({
+ isMutable: true,
+ agentId: 'writer',
+ agentName: 'writer',
+ agentSpec: {
+ model: { name: 'openai-main/gpt-4.1' },
+ instructions: 'Write release notes.',
+ },
+ });
+ }, [shell]);
+ return <SaveAgentButton />;
+ }
+
+ render(
+ <SlotsProvider>
+ <ServerProvider server={mockServer()}>
+ <ShellModeProvider agentConfig={{ mode: 'AgentLibraryWithComposer' }}>
+ <EditSeed />
+ </ShellModeProvider>
+ </ServerProvider>
+ </SlotsProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Update Agent' })).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Update Agent' }));
+ expect(screen.getByRole('dialog', { name: 'Update Agent' })).toBeInTheDocument();
+ const nameInput = screen.getByLabelText('Name');
+ expect(nameInput).toHaveValue('writer');
+ expect(nameInput).toBeDisabled();
+ expect(screen.getByLabelText('System instructions')).toHaveValue('Write release notes.');
+ });
});
diff --git a/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx b/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx
index 8967f25fb..9fae011fa 100644
--- a/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx
@@ -24,9 +24,11 @@ export function SaveAgentButton() {
const nameId = useId();
const instructionsId = useId();
- if (shell?.mode.type !== 'draft' || server == null) return null;
+ if (shell?.mode.status !== 'active' || !shell.mode.isMutable || server == null) return null;
- const draftSpec = shell.mode.defaultAgentSpec;
+ const editingAgentName = shell.mode.agentName ?? shell.mode.agentId;
+ const isUpdate = editingAgentName != null && editingAgentName !== '';
+ const draftSpec = shell.mode.agentSpec ?? { model: { name: 'openai-main/gpt-4.1' } };
// Runtime AgentSpec is structurally compatible; cast across package boundary.
const specToSave: AgentSpec = (agentSpec as AgentSpec | undefined) ?? draftSpec;
@@ -39,7 +41,8 @@ export function SaveAgentButton() {
const handleOpenChange = (next: boolean) => {
if (next) {
- setInstructions(specToSave.instructions ?? '');
+ setName(editingAgentName ?? '');
+ setInstructions(specToSave.instructions ?? draftSpec.instructions ?? '');
} else {
reset();
}
@@ -54,21 +57,36 @@ export function SaveAgentButton() {
setSaving(true);
setError(null);
const trimmedInstructions = instructions.trim();
+ const savedSpec: AgentSpec = {
+ ...specToSave,
+ instructions: trimmedInstructions || undefined,
+ };
try {
await server.saveAgent({
agentName,
- agentSpec: {
- ...specToSave,
- instructions: trimmedInstructions || undefined,
- },
+ agentSpec: savedSpec,
});
+ // Same draft chat continues as editable agent — do not remount via selectLibraryAgent.
+ shell.bindMutableAgent({
+ agentId: agentName,
+ agentName,
+ agentSpec: savedSpec,
+ });
+ shell.invalidateAgentsList();
handleOpenChange(false);
} catch (err: unknown) {
- setError(err instanceof Error ? err.message : 'Failed to save agent.');
+ setError(err instanceof Error ? err.message : isUpdate ? 'Failed to update agent.' : 'Failed to save agent.');
setSaving(false);
}
};
+ const triggerLabel = isUpdate ? 'Update Agent' : 'Save as agent';
+ const modalTitle = isUpdate ? 'Update Agent' : 'Save as agent';
+ const modalDescription = isUpdate
+ ? 'Save changes to this agent in the Agents library'
+ : 'Reuse this setup later from the Agents library';
+ const submitLabel = saving ? (isUpdate ? 'Updating…' : 'Saving…') : isUpdate ? 'Update' : 'Save';
+
return (
<>
<button
@@ -76,14 +94,14 @@ export function SaveAgentButton() {
className={auiButtonClass({ variant: 'outline', size: 'sm' })}
onClick={() => handleOpenChange(true)}
>
- Save as agent
+ {triggerLabel}
</button>
<CenteredModal
open={open}
onOpenChange={handleOpenChange}
- title="Save as agent"
- description="Reuse this setup later from the Agents library"
+ title={modalTitle}
+ description={modalDescription}
contentSized
>
<form className="flex flex-col gap-4 p-5" onSubmit={e => void handleSubmit(e)}>
@@ -97,9 +115,9 @@ export function SaveAgentButton() {
value={name}
onChange={e => setName(e.target.value)}
placeholder="Release notes writer"
- autoFocus
+ autoFocus={!isUpdate}
autoComplete="off"
- disabled={saving}
+ disabled={saving || isUpdate}
className={`${inputClassName} h-9`}
/>
</div>
@@ -113,6 +131,7 @@ export function SaveAgentButton() {
onChange={e => setInstructions(e.target.value)}
placeholder="You are a release notes writer for the platform team..."
rows={4}
+ autoFocus={isUpdate}
disabled={saving}
className={`${inputClassName} min-h-24 resize-y py-2`}
/>
@@ -123,7 +142,7 @@ export function SaveAgentButton() {
disabled={saving || name.trim().length === 0}
className={auiButtonClass({ variant: 'default', className: 'w-full' })}
>
- {saving ? 'Saving…' : 'Save'}
+ {submitLabel}
</button>
</form>
</CenteredModal>
diff --git a/packages/trueforge-ui-sdk/src/atoms/SelectAgentEmptyState.tsx b/packages/trueforge-ui-sdk/src/atoms/SelectAgentEmptyState.tsx
index 1fb0de0e3..d8fc4f1c9 100644
--- a/packages/trueforge-ui-sdk/src/atoms/SelectAgentEmptyState.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/SelectAgentEmptyState.tsx
@@ -8,7 +8,7 @@ export function SelectAgentEmptyState() {
const shell = useOptionalShellMode();
const AgentsLibraryButton = useSlot('AgentsLibraryButton');
- if (shell?.mode.type !== 'idle') return null;
+ if (shell?.mode.status !== 'idle') return null;
return (
<div
diff --git a/packages/trueforge-ui-sdk/src/atoms/ThreadListMisc.tsx b/packages/trueforge-ui-sdk/src/atoms/ThreadListMisc.tsx
index 0c1cffaef..069e400ab 100644
--- a/packages/trueforge-ui-sdk/src/atoms/ThreadListMisc.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/ThreadListMisc.tsx
@@ -77,7 +77,8 @@ export function ThreadListShell({ header, children, className }: ThreadListShell
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>
- <div className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto p-2">{children}</div>
+ {/* 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-sdk/src/atoms/ThreadListRow.test.tsx b/packages/trueforge-ui-sdk/src/atoms/ThreadListRow.test.tsx
index 6f6c6496a..3b3f8cf9d 100644
--- a/packages/trueforge-ui-sdk/src/atoms/ThreadListRow.test.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/ThreadListRow.test.tsx
@@ -54,4 +54,53 @@ describe('ThreadListRow', () => {
const activeRow = container.querySelector('[data-slot="aui_thread-list-item"]');
expect(activeRow?.className).toMatch(/bg-muted/);
});
+
+ it('renders agent name and relative time when provided', () => {
+ const lastMessageAt = new Date(Date.now() - 30 * 60_000);
+ render(
+ <SlotsProvider>
+ <ThreadListRow
+ title="Hello chat"
+ active={false}
+ onSelect={() => {}}
+ agentName="from-sdk"
+ lastMessageAt={lastMessageAt}
+ />
+ </SlotsProvider>,
+ );
+ expect(screen.getByText('Hello chat')).toBeInTheDocument();
+ expect(screen.getByText('from-sdk')).toBeInTheDocument();
+ expect(screen.getByText('30m')).toBeInTheDocument();
+ });
+
+ it('keeps relative time and actions in one trailing slot that swaps on hover', () => {
+ const lastMessageAt = new Date(Date.now() - 2 * 24 * 60 * 60_000);
+ const { container } = render(
+ <SlotsProvider>
+ <ThreadListRow
+ title="Hello"
+ active={false}
+ onSelect={() => {}}
+ agentName="test-gv-yo"
+ lastMessageAt={lastMessageAt}
+ actions={
+ <button type="button" aria-label="Session actions">
+ …
+ </button>
+ }
+ />
+ </SlotsProvider>,
+ );
+ const row = container.querySelector('[data-slot="aui_thread-list-item"]');
+ expect(row?.className).toMatch(/items-center/);
+ const time = screen.getByText('2d');
+ expect(time.getAttribute('data-slot')).toBe('aui_thread-list-item-age');
+ const actionsSlot = screen.getByRole('button', { name: 'Session actions' }).parentElement;
+ expect(actionsSlot?.getAttribute('data-slot')).toBe('aui_thread-list-item-actions');
+ expect(actionsSlot?.className).toMatch(/absolute/);
+ expect(actionsSlot?.className).toMatch(/md:opacity-0/);
+ expect(actionsSlot?.className).toMatch(/md:group-hover:opacity-100/);
+ expect(time.className).toMatch(/md:opacity-100/);
+ expect(time.className).toMatch(/md:group-hover:opacity-0/);
+ });
});
diff --git a/packages/trueforge-ui-sdk/src/atoms/ThreadListRow.tsx b/packages/trueforge-ui-sdk/src/atoms/ThreadListRow.tsx
index 924ceb481..8a1241e21 100644
--- a/packages/trueforge-ui-sdk/src/atoms/ThreadListRow.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/ThreadListRow.tsx
@@ -2,19 +2,36 @@
import type { ReactNode } from 'react';
+import { Icon } from '../icons/Icon.js';
import { auiButtonClass } from './lib/buttonClasses.js';
import { cn } from './lib/cn.js';
+import { formatRelativeShort } from './lib/threadListMeta.js';
export type ThreadListRowProps = {
title: string;
active: boolean;
onSelect: () => void;
+ /** Named-agent label under the title (from session.agentName). */
+ agentName?: string;
+ /** Shown as compact relative time on the right. */
+ lastMessageAt?: Date;
/** Overflow actions (e.g. delete menu) — rendered as a sibling of the title button. */
actions?: ReactNode;
className?: string;
};
-export function ThreadListRow({ title, active, onSelect, actions, className }: ThreadListRowProps) {
+export function ThreadListRow({
+ title,
+ active,
+ onSelect,
+ agentName,
+ lastMessageAt,
+ actions,
+ className,
+}: ThreadListRowProps) {
+ const relative = lastMessageAt != null ? formatRelativeShort(lastMessageAt) : undefined;
+ const hasTrailing = relative != null || actions != null;
+
return (
<div
data-slot="aui_thread-list-item"
@@ -32,15 +49,52 @@ export function ThreadListRow({ title, active, onSelect, actions, className }: T
className={auiButtonClass({
variant: 'ghost',
className: cn(
- '!justify-start h-8 min-w-0 flex-1 overflow-hidden rounded-md px-2.5 text-left font-normal shadow-none',
+ '!justify-start h-auto min-h-8 min-w-0 flex-1 overflow-hidden rounded-md px-2.5 py-1.5 text-left font-normal shadow-none',
'bg-transparent hover:bg-transparent hover:text-inherit',
active ? 'text-foreground' : 'text-inherit',
),
})}
>
- <span className="min-w-0 flex-1 truncate">{title}</span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm font-medium text-foreground">{title}</span>
+ {agentName != null ? (
+ <span className="mt-0.5 flex min-w-0 items-center gap-1 text-xs text-muted-foreground">
+ <Icon name="robot" className="size-3 shrink-0" />
+ <span className="truncate">{agentName}</span>
+ </span>
+ ) : null}
+ </span>
</button>
- {actions != null ? <div className="shrink-0 pr-0.5">{actions}</div> : null}
+ {hasTrailing ? (
+ <div className="relative mr-1 flex size-7 shrink-0 items-center justify-center">
+ {relative != null ? (
+ <span
+ data-slot="aui_thread-list-item-age"
+ className={cn(
+ 'pointer-events-none text-xs text-muted-foreground transition-opacity',
+ // md: variants survive host Tailwind tree-shaking (same set as AgentsLibrary).
+ // Bare group-hover:opacity-* is dropped from the example CSS bundle.
+ actions != null &&
+ 'opacity-0 md:opacity-100 md:group-hover:opacity-0 md:group-focus-within:opacity-0 md:group-has-[[data-state=open]]:opacity-0',
+ )}
+ >
+ {relative}
+ </span>
+ ) : null}
+ {actions != null ? (
+ <div
+ data-slot="aui_thread-list-item-actions"
+ className={cn(
+ 'absolute inset-0 flex items-center justify-center transition-opacity',
+ relative != null &&
+ 'md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100 md:group-has-[[data-state=open]]:opacity-100',
+ )}
+ >
+ {actions}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
</div>
);
}
diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsx
index d3a165472..5ecc82099 100644
--- a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsx
+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsx
@@ -97,6 +97,14 @@ export type DraftCompositeSelectorProps = {
onAttach?: () => void;
};
+function SectionHeading({ label, count }: { label: string; count: number }) {
+ return (
+ <div className="text-muted-foreground px-3 pt-2 pb-1 text-[11px] font-medium tracking-wide uppercase">
+ {label} ({count})
+ </div>
+ );
+}
+
export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCompositeSelectorProps) {
const { skills, connectors } = useDraftCatalog();
const { agentSpec } = useTrueFoundryAgentSpec();
@@ -104,6 +112,9 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
const [open, setOpen] = useState(false);
const [tab, setTab] = useState<AttachTab>('connectors');
const [query, setQuery] = useState('');
+ // Section membership is snapped when the picker opens, so toggles don't jump rows mid-session.
+ const [pinnedMcpIds, setPinnedMcpIds] = useState<Set<string>>(() => new Set());
+ const [pinnedSkillIds, setPinnedSkillIds] = useState<Set<string>>(() => new Set());
const containerRef = useRef<HTMLDivElement>(null);
const menuId = useId();
const isMobile = useIsMobile();
@@ -152,6 +163,23 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
);
}, [skills, query]);
+ const pinnedSelectedConnectors = useMemo(
+ () => filteredConnectors.filter(c => pinnedMcpIds.has(c.id)),
+ [filteredConnectors, pinnedMcpIds],
+ );
+ const pinnedAvailableConnectors = useMemo(
+ () => filteredConnectors.filter(c => !pinnedMcpIds.has(c.id)),
+ [filteredConnectors, pinnedMcpIds],
+ );
+ const pinnedSelectedSkills = useMemo(
+ () => filteredSkills.filter(s => pinnedSkillIds.has(s.id)),
+ [filteredSkills, pinnedSkillIds],
+ );
+ const pinnedAvailableSkills = useMemo(
+ () => filteredSkills.filter(s => !pinnedSkillIds.has(s.id)),
+ [filteredSkills, pinnedSkillIds],
+ );
+
const toggleConnector = (connector: ConnectorState) => {
const next = selectedMcpIds.has(connector.id)
? selectedMcp.filter(m => m.id !== connector.id)
@@ -166,6 +194,12 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
updateAgentSpec?.({ skills: next });
};
+ const openPicker = () => {
+ setPinnedMcpIds(new Set(selectedMcp.map(m => m.id)));
+ setPinnedSkillIds(new Set(selectedSkills.map(s => s.id)));
+ setOpen(true);
+ };
+
const content = (
<>
<div className="flex shrink-0 border-b border-border">
@@ -218,29 +252,70 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
onChange={setQuery}
placeholder={tab === 'connectors' ? 'Search connectors...' : 'Search skills...'}
/>
- <div className="text-muted-foreground flex items-center justify-between px-3 pb-1 text-[11px] font-medium tracking-wide uppercase">
- <span>Available ({tab === 'connectors' ? filteredConnectors.length : filteredSkills.length})</span>
- </div>
<div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">
- {tab === 'connectors'
- ? filteredConnectors.map(c => (
- <CatalogRow
- key={c.id}
- title={c.name}
- description={c.description}
- checked={selectedMcpIds.has(c.id)}
- onToggle={() => toggleConnector(c)}
- />
- ))
- : filteredSkills.map(s => (
- <CatalogRow
- key={s.id}
- title={s.name}
- description={s.description}
- checked={selectedSkillIds.has(s.id)}
- onToggle={() => toggleSkill(s)}
- />
- ))}
+ {tab === 'connectors' ? (
+ <>
+ {pinnedSelectedConnectors.length > 0 ? (
+ <>
+ <SectionHeading label="Selected" count={pinnedSelectedConnectors.length} />
+ {pinnedSelectedConnectors.map(c => (
+ <CatalogRow
+ key={c.id}
+ title={c.name}
+ description={c.description}
+ checked={selectedMcpIds.has(c.id)}
+ onToggle={() => toggleConnector(c)}
+ />
+ ))}
+ </>
+ ) : null}
+ {pinnedAvailableConnectors.length > 0 ? (
+ <>
+ <SectionHeading label="Available" count={pinnedAvailableConnectors.length} />
+ {pinnedAvailableConnectors.map(c => (
+ <CatalogRow
+ key={c.id}
+ title={c.name}
+ description={c.description}
+ checked={selectedMcpIds.has(c.id)}
+ onToggle={() => toggleConnector(c)}
+ />
+ ))}
+ </>
+ ) : null}
+ </>
+ ) : (
+ <>
+ {pinnedSelectedSkills.length > 0 ? (
+ <>
+ <SectionHeading label="Selected" count={pinnedSelectedSkills.length} />
+ {pinnedSelectedSkills.map(s => (
+ <CatalogRow
+ key={s.id}
+ title={s.name}
+ description={s.description}
+ checked={selectedSkillIds.has(s.id)}
+ onToggle={() => toggleSkill(s)}
+ />
+ ))}
+ </>
+ ) : null}
+ {pinnedAvailableSkills.length > 0 ? (
+ <>
+ <SectionHeading label="Available" count={pinnedAvailableSkills.length} />
+ {pinnedAvailableSkills.map(s => (
+ <CatalogRow
+ key={s.id}
+ title={s.name}
+ description={s.description}
+ checked={selectedSkillIds.has(s.id)}
+ onToggle={() => toggleSkill(s)}
+ />
+ ))}
+ </>
+ ) : null}
+ </>
+ )}
</div>
</>
)}
@@ -257,7 +332,13 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
aria-expanded={open}
aria-controls={open ? menuId : undefined}
className={auiButtonClass({ variant: 'ghost', size: 'icon' })}
- onClick={() => setOpen(v => !v)}
+ onClick={() => {
+ if (open) {
+ setOpen(false);
+ return;
+ }
+ openPicker();
+ }}
>
<Icon name="plus" className="text-primary" />
</button>
diff --git a/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.test.ts b/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.test.ts
new file mode 100644
index 000000000..e7e584ef9
--- /dev/null
+++ b/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ canReuseMutableShell,
+ formatRelativeShort,
+ readThreadAgentName,
+ readThreadIsMutable,
+ threadListItemIsMutable,
+} from './threadListMeta.js';
+
+describe('formatRelativeShort', () => {
+ const now = new Date('2026-08-06T12:00:00.000Z');
+
+ it('formats minutes, hours, and days', () => {
+ expect(formatRelativeShort(new Date('2026-08-06T11:30:00.000Z'), now)).toBe('30m');
+ expect(formatRelativeShort(new Date('2026-08-05T14:00:00.000Z'), now)).toBe('22h');
+ expect(formatRelativeShort(new Date('2026-08-05T12:00:00.000Z'), now)).toBe('1d');
+ });
+});
+
+describe('readThreadAgentName', () => {
+ it('reads agentName from custom metadata', () => {
+ expect(readThreadAgentName({ agentName: 'from-sdk' })).toBe('from-sdk');
+ expect(readThreadAgentName({})).toBeUndefined();
+ expect(readThreadAgentName(null)).toBeUndefined();
+ expect(readThreadAgentName({ agentName: 1 })).toBeUndefined();
+ });
+});
+
+describe('threadListItemIsMutable', () => {
+ it('prefers custom.isMutable over agentName presence', () => {
+ expect(readThreadIsMutable({ isMutable: false })).toBe(false);
+ expect(threadListItemIsMutable({ isMutable: false })).toBe(false);
+ // Orphaned named ref: no agentName, but still immutable on the wire.
+ expect(threadListItemIsMutable({ isMutable: false })).toBe(false);
+ expect(threadListItemIsMutable({ isMutable: true, agentName: 'x' })).toBe(true);
+ });
+
+ it('falls back to agentName heuristic when isMutable is absent', () => {
+ expect(threadListItemIsMutable({ agentName: 'from-sdk' })).toBe(false);
+ expect(threadListItemIsMutable({})).toBe(true);
+ expect(threadListItemIsMutable(null)).toBe(true);
+ });
+});
+
+describe('canReuseMutableShell', () => {
+ it('allows blank drafts to share the mutable shell', () => {
+ expect(
+ canReuseMutableShell({
+ sessionMutable: true,
+ shellMutable: true,
+ remoteId: 'sess-b',
+ pendingSessionId: 'sess-a',
+ }),
+ ).toBe(true);
+ });
+
+ it('blocks Edit-bound shells from reusing chrome on a different session', () => {
+ expect(
+ canReuseMutableShell({
+ sessionMutable: true,
+ shellMutable: true,
+ shellAgentName: 'writer',
+ remoteId: 'sess-b',
+ pendingSessionId: 'sess-a',
+ }),
+ ).toBe(false);
+ });
+
+ it('allows Edit-bound shells to switchToThread for their pending session', () => {
+ expect(
+ canReuseMutableShell({
+ sessionMutable: true,
+ shellMutable: true,
+ shellAgentName: 'writer',
+ remoteId: 'sess-a',
+ pendingSessionId: 'sess-a',
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.ts b/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.ts
new file mode 100644
index 000000000..67c7edfbe
--- /dev/null
+++ b/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.ts
@@ -0,0 +1,66 @@
+/** Compact relative age for sidebar session rows (e.g. 30m, 22h, 1d). */
+export function formatRelativeShort(date: Date, now: Date = new Date()): string {
+ const diffMs = Math.max(0, now.getTime() - date.getTime());
+ const minutes = Math.floor(diffMs / 60_000);
+ if (minutes < 60) return `${Math.max(1, minutes)}m`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h`;
+ const days = Math.floor(hours / 24);
+ if (days < 7) return `${days}d`;
+ const weeks = Math.floor(days / 7);
+ if (weeks < 5) return `${weeks}w`;
+ const months = Math.floor(days / 30);
+ if (months < 12) return `${months}mo`;
+ return `${Math.floor(days / 365)}y`;
+}
+
+export function readThreadAgentName(custom: unknown): string | undefined {
+ if (custom == null || typeof custom !== 'object') return undefined;
+ if (!('agentName' in custom)) return undefined;
+ const value = Reflect.get(custom, 'agentName');
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
+}
+
+/** Session mutability from thread-list custom (runtime ≥ isMutable stamp). */
+export function readThreadIsMutable(custom: unknown): boolean | undefined {
+ if (custom == null || typeof custom !== 'object') return undefined;
+ if (!('isMutable' in custom)) return undefined;
+ const value = Reflect.get(custom, 'isMutable');
+ return typeof value === 'boolean' ? value : undefined;
+}
+
+/**
+ * Prefer `custom.isMutable`; fall back to agentName presence for older runtimes
+ * that only stamped `agentName` on named rows.
+ */
+export function threadListItemIsMutable(custom: unknown): boolean {
+ return readThreadIsMutable(custom) ?? readThreadAgentName(custom) == null;
+}
+
+/**
+ * Fast-path `switchToThread` for mutable history rows only when Edit chrome is
+ * safe to keep. Blank drafts (no agentName/agentId) may share one shell; an
+ * Edit-bound shell must remount via `openHistorySession` when leaving its
+ * pending session so Update does not keep the previous agentName over another
+ * draft's runtime spec.
+ */
+export function canReuseMutableShell({
+ sessionMutable,
+ shellMutable,
+ shellAgentName,
+ shellAgentId,
+ remoteId,
+ pendingSessionId,
+}: {
+ sessionMutable: boolean;
+ shellMutable: boolean;
+ shellAgentName?: string;
+ shellAgentId?: string;
+ remoteId?: string | null;
+ pendingSessionId?: string;
+}): boolean {
+ if (!sessionMutable || !shellMutable) return false;
+ const editBound = (shellAgentName != null && shellAgentName !== '') || (shellAgentId != null && shellAgentId !== '');
+ if (!editBound) return true;
+ return remoteId != null && remoteId === pendingSessionId;
+}
diff --git a/packages/trueforge-ui-sdk/src/containers/ComposerContainer.tsx b/packages/trueforge-ui-sdk/src/containers/ComposerContainer.tsx
index abc1eb359..0fa47c0e2 100644
--- a/packages/trueforge-ui-sdk/src/containers/ComposerContainer.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/ComposerContainer.tsx
@@ -105,7 +105,7 @@ export function ComposerContainer({
const shell = useOptionalShellMode();
const parentLeftSection = useSlot('ComposerLeftSection');
const parentRightSection = useSlot('ComposerRightSection');
- const isDraft = shell?.mode.type === 'draft';
+ const canMutateSpec = shell?.mode.status === 'active' && shell.mode.isMutable;
if (pauseView.kind === 'mcp') {
return <McpAuthContainer />;
@@ -114,7 +114,7 @@ export function ComposerContainer({
return <AskUserContainer />;
}
- if (isDraft) {
+ if (canMutateSpec) {
return (
<DraftCatalogProvider>
<SlotsProvider
diff --git a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.test.tsx b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.test.tsx
index 6d6ddb2e3..38e50a4c7 100644
--- a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.test.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.test.tsx
@@ -184,4 +184,33 @@ describe('SandboxSettings', () => {
});
expect(host.updated[0]).not.toHaveProperty('apiKey');
});
+
+ it('hides other catalog providers once one is configured', async () => {
+ const existing: SandboxProviderBase = {
+ id: 'sb-1',
+ name: 'Daytona',
+ catalogId: 'cat-daytona',
+ isConnected: true,
+ snapshotName: 'custom-snap',
+ execTimeoutMs: 60000,
+ autoStopIntervalInMinutes: 30,
+ autoArchiveIntervalInMinutes: 1440,
+ autoDeleteIntervalInMinutes: 10080,
+ };
+ const host = createFakeHost([existing]);
+ const { wrapper: Wrapper } = host;
+ render(
+ <Wrapper>
+ <SandboxSettings />
+ </Wrapper>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText('Sandbox providers')).toBeTruthy();
+ });
+ expect(screen.queryByRole('button', { name: 'Configure' })).toBeNull();
+ expect(
+ screen.getByText('A sandbox provider is already configured. Remove it to choose a different one.'),
+ ).toBeTruthy();
+ });
});
diff --git a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.tsx b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.tsx
index ac9786de5..a6cd5386e 100644
--- a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/SandboxSettings.tsx
@@ -47,7 +47,7 @@ const SandboxSettings = () => {
setProviders(listed);
setCatalog(available);
} catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to load sandboxes');
+ setError(err instanceof Error ? err.message : 'Failed to load sandbox providers');
} finally {
if (!quiet) setLoading(false);
}
@@ -59,10 +59,13 @@ const SandboxSettings = () => {
void refresh();
}, [refresh]);
+ // Tenant/UI-wide: only one sandbox provider may be configured at a time.
+ const hasConfiguredProvider = providers.length > 0;
const availableEntries = useMemo(() => {
+ if (hasConfiguredProvider) return [];
const connectedCatalogIds = new Set(providers.map(provider => provider.catalogId));
return catalog.filter(entry => !connectedCatalogIds.has(entry.id));
- }, [catalog, providers]);
+ }, [catalog, providers, hasConfiguredProvider]);
const formInitialConfig = useMemo(
() => (updateProvider ? configFrom(updateProvider) : createEntry ? configFrom(createEntry) : null),
@@ -70,7 +73,7 @@ const SandboxSettings = () => {
);
if (!sandboxCatalog) {
- return <p className="text-sm text-muted-foreground">Sandbox catalog is not available.</p>;
+ return <p className="text-sm text-muted-foreground">Sandbox provider catalog is not available.</p>;
}
const runMutation = async (fn: () => Promise<void>) => {
@@ -127,13 +130,14 @@ const SandboxSettings = () => {
? `Update ${updateProvider.name}`
: createEntry
? `Configure ${createEntry.name}`
- : 'Configure sandbox';
+ : 'Configure sandbox provider';
return (
<>
- <h3 className="text-xl font-semibold tracking-tight text-foreground">Sandbox</h3>
+ <h3 className="text-xl font-semibold tracking-tight text-foreground">Sandbox providers</h3>
<p className="mt-1 text-sm text-muted-foreground">
- A secure, isolated environment for running code, files, and shell commands.
+ Choose a provider that runs sandboxes for code, files, and shell commands. These are providers, not sandboxes
+ themselves. Only one sandbox provider can be configured for this workspace.
</p>
{error ? (
@@ -144,13 +148,13 @@ const SandboxSettings = () => {
<div className="mt-4 flex-1 overflow-y-auto">
{loading ? (
- <p className="text-sm text-muted-foreground">Loading sandboxes…</p>
+ <p className="text-sm text-muted-foreground">Loading sandbox providers…</p>
) : (
<div className="space-y-6">
{providers.length > 0 ? (
<section>
<h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
- Connected · {providers.length}
+ Configured · {providers.length}
</h4>
<div className="overflow-hidden rounded-xl border border-border bg-card">
{providers.map(provider => (
@@ -217,7 +221,11 @@ const SandboxSettings = () => {
</h4>
{availableEntries.length === 0 ? (
<p className="text-sm text-muted-foreground">
- {providers.length > 0 ? 'All catalog sandboxes are configured.' : 'No sandboxes in the catalog.'}
+ {hasConfiguredProvider
+ ? 'A sandbox provider is already configured. Remove it to choose a different one.'
+ : catalog.length > 0
+ ? 'All catalog providers are configured.'
+ : 'No sandbox providers in the catalog.'}
</p>
) : (
<div className="overflow-hidden rounded-xl border border-border bg-card">
@@ -273,8 +281,8 @@ const SandboxSettings = () => {
title={formTitle}
description={
isUpdate
- ? 'Update sandbox settings. Leave API key blank to keep the existing key.'
- : 'Managed sandbox settings. API key is never stored in the catalog.'
+ ? 'Update this sandbox provider. Leave API key blank to keep the existing key.'
+ : 'Configure this sandbox provider. API key is never stored in the catalog.'
}
initialConfig={formInitialConfig}
requireApiKey={!isUpdate}
diff --git a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/index.tsx b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/index.tsx
index d40f9e794..73477c8b0 100644
--- a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/index.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/index.tsx
@@ -65,7 +65,7 @@ const TruefoundrySettingsBuilder = () => {
baseSections.push({ id: 'skills', label: 'Skills', icon: 'lightbulb' });
}
if (hasSandbox) {
- baseSections.push({ id: 'sandbox', label: 'Sandbox', icon: 'cube' });
+ baseSections.push({ id: 'sandbox', label: 'Sandbox providers', icon: 'cube' });
}
return baseSections;
}, [hasSkills, hasSandbox]);
diff --git a/packages/trueforge-ui-sdk/src/containers/ThreadContainer.test.tsx b/packages/trueforge-ui-sdk/src/containers/ThreadContainer.test.tsx
index e718a196c..7dbcd1682 100644
--- a/packages/trueforge-ui-sdk/src/containers/ThreadContainer.test.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/ThreadContainer.test.tsx
@@ -1,21 +1,45 @@
// @vitest-environment jsdom
import type { AssistantState, ThreadMessageLike } from '@assistant-ui/react';
-import { render, screen } from '@testing-library/react';
+import { render, screen, waitFor } from '@testing-library/react';
+import { useEffect, useRef, type ReactNode } from 'react';
import { describe, expect, it } from 'vitest';
-import { ShellModeProvider } from '../server/ShellModeContext.js';
+import { ShellModeProvider, useShellMode } from '../server/ShellModeContext.js';
import { RuntimeHarness } from './RuntimeHarness.js';
import { isNewChatView, ThreadContainer } from './ThreadContainer.js';
+function EditAgentBootstrap({ children }: { children: ReactNode }) {
+ const shell = useShellMode();
+ const seeded = useRef(false);
+ useEffect(() => {
+ if (seeded.current) return;
+ seeded.current = true;
+ shell.selectLibraryAgent({
+ isMutable: true,
+ agentId: 'writer',
+ agentName: 'writer',
+ agentSpec: { model: { name: 'openai-main/gpt-4.1' } },
+ });
+ }, [shell]);
+ return children;
+}
+
function renderThread(
messages: ThreadMessageLike[],
- options?: { isLoading?: boolean; composer?: React.ReactNode; agentName?: string },
+ options?: { isLoading?: boolean; composer?: React.ReactNode; agentName?: string; editAgent?: boolean },
) {
const thread = (
<RuntimeHarness messages={messages} isLoading={options?.isLoading}>
<ThreadContainer composer={options?.composer} />
</RuntimeHarness>
);
+ if (options?.editAgent) {
+ return render(
+ <ShellModeProvider agentConfig={{ mode: 'AgentLibraryWithComposer' }}>
+ <EditAgentBootstrap>{thread}</EditAgentBootstrap>
+ </ShellModeProvider>,
+ );
+ }
return render(
options?.agentName != null ? (
<ShellModeProvider agentConfig={{ mode: 'SingleAgent', name: options.agentName }}>{thread}</ShellModeProvider>
@@ -72,6 +96,14 @@ describe('ThreadContainer', () => {
expect(screen.queryByText('How can I help you today?')).not.toBeInTheDocument();
});
+ it('shows the agent name on the empty Edit-agent welcome screen', async () => {
+ renderThread([], { editAgent: true });
+ await waitFor(() => {
+ expect(screen.getByText('writer')).toBeInTheDocument();
+ });
+ expect(screen.queryByText('How can I help you today?')).not.toBeInTheDocument();
+ });
+
it('renders the loading skeleton while thread history is loading', () => {
renderThread([], { isLoading: true });
expect(screen.getByRole('status', { name: 'Loading conversation' })).toBeInTheDocument();
diff --git a/packages/trueforge-ui-sdk/src/containers/ThreadContainer.tsx b/packages/trueforge-ui-sdk/src/containers/ThreadContainer.tsx
index 15fededcd..c10796060 100644
--- a/packages/trueforge-ui-sdk/src/containers/ThreadContainer.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/ThreadContainer.tsx
@@ -57,7 +57,7 @@ export function ThreadContainer({ composer }: ThreadContainerProps) {
const isEmpty = useAuiState(isNewChatView);
const isLoading = useAuiState(s => s.thread.isLoading);
- const welcomeHeading = shell?.mode.type === 'named' ? shell.mode.agentName : undefined;
+ const welcomeHeading = shell?.mode.status === 'active' ? shell.mode.agentName : undefined;
return (
<ComposerBusyProvider>
diff --git a/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.pagination.test.tsx b/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.pagination.test.tsx
new file mode 100644
index 000000000..ea8c955ec
--- /dev/null
+++ b/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.pagination.test.tsx
@@ -0,0 +1,124 @@
+// @vitest-environment jsdom
+import { fireEvent, render, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+const loadMore = vi.fn().mockResolvedValue(undefined);
+
+vi.mock('@assistant-ui/react', () => ({
+ useAui: () => ({
+ threads: () => ({
+ loadMore,
+ switchToThread: vi.fn(),
+ switchToNewThread: vi.fn(),
+ }),
+ }),
+ useAuiState: (selector: (s: Record<string, unknown>) => unknown) =>
+ selector({
+ threads: {
+ isLoading: false,
+ isLoadingMore: false,
+ hasMore: true,
+ threadIds: ['t1'],
+ mainThreadId: 't1',
+ },
+ threadListItem: {
+ id: 't1',
+ remoteId: 's1',
+ title: 'Session',
+ lastMessageAt: undefined,
+ custom: undefined,
+ },
+ }),
+ ThreadListPrimitive: {
+ Root: ({ children, className }: { children?: ReactNode; className?: string }) => (
+ <div className={className}>{children}</div>
+ ),
+ Items: ({ children }: { children: (args: { threadListItem: { remoteId: string } }) => ReactNode }) => (
+ <>{children({ threadListItem: { remoteId: 's1' } })}</>
+ ),
+ },
+ ThreadListItemPrimitive: {
+ Root: ({ children, className }: { children?: ReactNode; className?: string }) => (
+ <div className={className}>{children}</div>
+ ),
+ Delete: ({ children }: { children?: ReactNode }) => <button type="button">{children}</button>,
+ },
+ ThreadListItemMorePrimitive: {
+ Root: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ Trigger: ({ children }: { children?: ReactNode }) => <button type="button">{children}</button>,
+ Content: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Item: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ },
+}));
+
+vi.mock('../server/ServerContext.js', () => ({
+ useOptionalServer: () => undefined,
+}));
+
+vi.mock('../server/ShellModeContext.js', () => ({
+ useOptionalShellMode: () => ({
+ isLibraryEnabled: false,
+ isNewChatEnabled: true,
+ isComposerEnabled: false,
+ mode: { status: 'active', isMutable: false, agentName: 'agent', agentId: 'agent', locked: false },
+ setSettingsOpen: vi.fn(),
+ selectLibraryAgent: vi.fn(),
+ openDraft: vi.fn(),
+ openHistorySession: vi.fn(),
+ }),
+}));
+
+import { ThreadListContainer } from './ThreadListContainer.js';
+
+describe('ThreadListContainer pagination', () => {
+ it('does not load more pages until the history list is scrolled', async () => {
+ loadMore.mockClear();
+ const { container } = render(
+ <div style={{ height: 200 }}>
+ <ThreadListContainer />
+ </div>,
+ );
+
+ const viewport = container.querySelector('[data-slot="aui_thread-list-viewport"]');
+ expect(viewport).toBeTruthy();
+
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(loadMore).not.toHaveBeenCalled();
+
+ Object.defineProperty(viewport, 'scrollTop', { configurable: true, value: 720 });
+ Object.defineProperty(viewport, 'scrollHeight', { configurable: true, value: 800 });
+ Object.defineProperty(viewport, 'clientHeight', { configurable: true, value: 200 });
+ fireEvent.scroll(viewport!);
+
+ await waitFor(() => expect(loadMore).toHaveBeenCalledTimes(1));
+ });
+
+ it('ignores scroll when still at the top of the list', async () => {
+ loadMore.mockClear();
+ const { container } = render(<ThreadListContainer />);
+ const viewport = container.querySelector('[data-slot="aui_thread-list-viewport"]');
+
+ Object.defineProperty(viewport, 'scrollTop', { configurable: true, value: 0 });
+ Object.defineProperty(viewport, 'scrollHeight', { configurable: true, value: 800 });
+ Object.defineProperty(viewport, 'clientHeight', { configurable: true, value: 200 });
+ fireEvent.scroll(viewport!);
+
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(loadMore).not.toHaveBeenCalled();
+ });
+
+ it('ignores scroll when not near the bottom', async () => {
+ loadMore.mockClear();
+ const { container } = render(<ThreadListContainer />);
+ const viewport = container.querySelector('[data-slot="aui_thread-list-viewport"]');
+
+ Object.defineProperty(viewport, 'scrollTop', { configurable: true, value: 50 });
+ Object.defineProperty(viewport, 'scrollHeight', { configurable: true, value: 800 });
+ Object.defineProperty(viewport, 'clientHeight', { configurable: true, value: 200 });
+ fireEvent.scroll(viewport!);
+
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(loadMore).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.tsx b/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.tsx
index 9c3bd961a..2b49ed006 100644
--- a/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.tsx
@@ -7,11 +7,13 @@ import {
useAui,
useAuiState,
} from '@assistant-ui/react';
-import { useEffect, useRef, useState, type ReactNode } from 'react';
+import { useEffect, useRef, useState, type ReactNode, type Ref } from 'react';
+import { AgentHistoryFilterButton } from '../atoms/AgentHistoryFilterButton.js';
import { auiButtonClass } from '../atoms/lib/buttonClasses.js';
import { cn } from '../atoms/lib/cn.js';
import { useCompactLayout } from '../atoms/lib/CompactLayoutContext.js';
+import { canReuseMutableShell, readThreadAgentName, threadListItemIsMutable } from '../atoms/lib/threadListMeta.js';
import { useIsMobile } from '../atoms/lib/useIsMobile.js';
import { BottomSheet } from '../atoms/primitives/BottomSheet.js';
import { Icon } from '../icons/Icon.js';
@@ -43,12 +45,7 @@ function ThreadListItemDeleteMenu() {
const moreButtonClass = auiButtonClass({
variant: 'ghost',
size: 'icon',
- className: cn(
- 'size-7 shrink-0 text-muted-foreground hover:bg-transparent hover:text-foreground',
- 'opacity-100 transition-opacity',
- !compact && 'md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100',
- 'focus-visible:opacity-100 data-[state=open]:opacity-100',
- ),
+ className: 'size-7 shrink-0 text-muted-foreground hover:bg-transparent hover:text-foreground',
});
if (useSheet) {
@@ -109,17 +106,55 @@ function ThreadListItemRow({ onThreadOpen, showDelete }: { onThreadOpen?: () =>
const shell = useOptionalShellMode();
const ThreadListRow = useSlot('ThreadListRow');
const id = useAuiState(s => s.threadListItem.id);
+ const remoteId = useAuiState(s => s.threadListItem.remoteId);
const title = useAuiState(s => s.threadListItem.title);
+ const lastMessageAt = useAuiState(s => s.threadListItem.lastMessageAt);
+ const custom = useAuiState(s => s.threadListItem.custom);
const mainThreadId = useAuiState(s => s.threads.mainThreadId);
+ const agentName = readThreadAgentName(custom);
return (
<ThreadListItemPrimitive.Root className="min-w-0">
<ThreadListRow
title={title ?? 'New Chat'}
active={id === mainThreadId}
+ agentName={agentName}
+ lastMessageAt={lastMessageAt}
onSelect={() => {
onThreadOpen?.();
shell?.setSettingsOpen(false);
+
+ // Prefer custom.isMutable (session wire); agentName-only is a legacy fallback.
+ const sessionMutable = threadListItemIsMutable(custom);
+ const sameImmutable =
+ !sessionMutable &&
+ shell?.mode.status === 'active' &&
+ !shell.mode.isMutable &&
+ (agentName == null
+ ? shell.mode.agentName == null && shell.mode.agentId == null
+ : shell.mode.agentName === agentName || shell.mode.agentId === agentName);
+ const sameMutable = canReuseMutableShell({
+ sessionMutable,
+ shellMutable: shell?.mode.status === 'active' && shell.mode.isMutable,
+ ...(shell?.mode.status === 'active' && shell.mode.isMutable
+ ? { shellAgentName: shell.mode.agentName, shellAgentId: shell.mode.agentId }
+ : {}),
+ remoteId,
+ pendingSessionId: shell?.pendingSessionId,
+ });
+
+ if ((sameImmutable || sameMutable) && remoteId != null) {
+ void Promise.resolve(aui.threads().switchToThread(id)).catch(() => undefined);
+ return;
+ }
+ if (remoteId != null) {
+ shell?.openHistorySession({
+ sessionId: remoteId,
+ isMutable: sessionMutable,
+ ...(agentName != null ? { agentName } : {}),
+ });
+ return;
+ }
void Promise.resolve(aui.threads().switchToThread(id)).catch(() => undefined);
}}
actions={showDelete ? <ThreadListItemDeleteMenu /> : undefined}
@@ -128,11 +163,49 @@ function ThreadListItemRow({ onThreadOpen, showDelete }: { onThreadOpen?: () =>
);
}
+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);
+ const shell = useOptionalShellMode();
+ const showFilter = 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-muted-foreground hover:bg-accent hover:text-foreground"
+ 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>
+ {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>
+ );
+}
+
export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps = {}) {
const aui = useAui();
const server = useOptionalServer();
const isLoading = useAuiState(s => s.threads.isLoading);
- const isLoadingMore = useAuiState(s => s.threads.isLoadingMore);
const hasMore = useAuiState(s => s.threads.hasMore);
const threadIds = useAuiState(s => s.threads.threadIds);
const shell = useOptionalShellMode();
@@ -143,23 +216,50 @@ export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps =
const ThreadListRowSkeleton = useSlot('ThreadListRowSkeleton');
const ThreadListEmptyState = useSlot('ThreadListEmptyState');
- const sentinelRef = useRef<HTMLDivElement>(null);
+ const viewportRef = useRef<HTMLDivElement>(null);
+ const loadMoreInflightRef = useRef(false);
+ const hasMoreRef = useRef(hasMore);
+ const auiRef = useRef(aui);
+ hasMoreRef.current = hasMore;
+ auiRef.current = aui;
+
const showNewChat = shell?.isNewChatEnabled !== false;
- const isIdle = shell?.mode.type === 'idle';
+ const isIdle = shell?.mode.status === 'idle';
const canDeleteSession = typeof server?.deleteSession === 'function';
+ // Scroll-driven pagination only — never auto-chain pages while the sentinel
+ // is visible on mount (that drained every listSessions page).
useEffect(() => {
- const node = sentinelRef.current;
- if (!node || !hasMore || isIdle) return;
+ if (isIdle) return;
+ const viewport = viewportRef.current;
+ if (!viewport) return;
- const observer = new IntersectionObserver(entries => {
- if (entries.some(e => e.isIntersecting) && hasMore && !isLoadingMore) {
- void aui.threads().loadMore();
- }
- });
- observer.observe(node);
- return () => observer.disconnect();
- }, [aui, hasMore, isLoadingMore, isIdle]);
+ let cancelled = false;
+ let chainRaf = 0;
+
+ const tryLoadMore = () => {
+ if (cancelled || !hasMoreRef.current || loadMoreInflightRef.current) return;
+ // Require a real scroll so a short first page does not fill-drain the cursor.
+ if (viewport.scrollTop <= 0) return;
+ const remaining = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
+ if (remaining > LOAD_MORE_BOTTOM_PX) return;
+
+ loadMoreInflightRef.current = true;
+ void Promise.resolve(auiRef.current.threads().loadMore()).finally(() => {
+ loadMoreInflightRef.current = false;
+ if (cancelled) return;
+ // Still glued to the bottom after append → fetch the next page.
+ chainRaf = requestAnimationFrame(() => tryLoadMore());
+ });
+ };
+
+ viewport.addEventListener('scroll', tryLoadMore, { passive: true });
+ return () => {
+ cancelled = true;
+ cancelAnimationFrame(chainRaf);
+ viewport.removeEventListener('scroll', tryLoadMore);
+ };
+ }, [isIdle]);
const handleNewChat = () => {
onThreadOpen?.();
@@ -206,8 +306,10 @@ export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps =
</div>
}
>
- {listBody}
- {!isIdle && hasMore ? <div ref={sentinelRef} className="h-4 shrink-0" aria-hidden /> : null}
+ <ChatHistorySection viewportRef={viewportRef}>
+ {listBody}
+ {!isIdle && hasMore ? <div className="h-4 shrink-0" aria-hidden /> : null}
+ </ChatHistorySection>
</ThreadListShell>
);
}
diff --git a/packages/trueforge-ui-sdk/src/containers/TrueFoundryChatProvider.tsx b/packages/trueforge-ui-sdk/src/containers/TrueFoundryChatProvider.tsx
index 4d69f6a1a..cc542f38f 100644
--- a/packages/trueforge-ui-sdk/src/containers/TrueFoundryChatProvider.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/TrueFoundryChatProvider.tsx
@@ -24,12 +24,15 @@ export type TrueFoundryChatProviderProps = {
agent?: TrueFoundryAgentConfig;
/** Legacy named-agent shorthand. Prefer `agent: { mode: "named", agentName }`. */
agentName?: string;
+ /** Forwarded to `listSessions({ agentId })` for history filtering. */
+ listSessionsAgentId?: string;
};
function ChatRuntimeScope({
server,
agent,
agentName,
+ listSessionsAgentId,
initialSessionId,
adapters,
onError,
@@ -38,6 +41,7 @@ function ChatRuntimeScope({
server: AgentUIServer;
agent?: TrueFoundryAgentConfig;
agentName?: string;
+ listSessionsAgentId?: string;
initialSessionId?: string;
adapters?: RuntimeAdapters;
onError?: (error: unknown) => void;
@@ -50,6 +54,7 @@ function ChatRuntimeScope({
server: server as never,
agent,
agentName,
+ listSessionsAgentId,
initialSessionId,
onError: resolvedOnError,
adapters: {
@@ -58,7 +63,7 @@ function ChatRuntimeScope({
},
});
- return <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>;
+ return <AssistantRuntimeProvider runtime={runtime as never}>{children}</AssistantRuntimeProvider>;
}
/**
@@ -66,7 +71,7 @@ function ChatRuntimeScope({
* assistant-ui + error toasts.
*/
export function TrueFoundryChatProvider(props: TrueFoundryChatProviderProps) {
- const { server, initialSessionId, adapters, onError, children, agent, agentName } = props;
+ const { server, initialSessionId, adapters, onError, children, agent, agentName, listSessionsAgentId } = props;
const stableServer = useMemo(() => server, [server]);
@@ -76,6 +81,7 @@ export function TrueFoundryChatProvider(props: TrueFoundryChatProviderProps) {
server={stableServer}
agent={agent}
agentName={agentName}
+ listSessionsAgentId={listSessionsAgentId}
initialSessionId={initialSessionId}
adapters={adapters}
onError={onError}
diff --git a/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx b/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx
index a226219a3..4ee6ba7e9 100644
--- a/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx
+++ b/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx
@@ -123,29 +123,59 @@ function LayoutChildren({ layout, className }: { layout: LayoutProp; className?:
function ChatProviderFromShell({
children,
+ initialSessionId: hostInitialSessionId,
...providerRest
}: {
children: ReactNode;
-} & Omit<TrueFoundryChatProviderProps, 'agent' | 'agentName' | 'children'>) {
- const { mode, runtimeKey } = useShellMode();
+} & Omit<TrueFoundryChatProviderProps, 'agent' | 'agentName' | 'listSessionsAgentId' | 'children'>) {
+ const { mode, runtimeKey, listSessionsAgentId, pendingSessionId } = useShellMode();
+
+ // 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(() => {
+ if (mode.status === 'active' && mode.isMutable) {
+ return mode.agentSpec ?? { model: { name: 'openai-main/gpt-4.1' } };
+ }
+ return { model: { name: 'openai-main/gpt-4.1' } };
+ // runtimeKey is the remount boundary for mutable chats.
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally keyed on runtimeKey only
+ }, [runtimeKey]);
const agent: TrueFoundryAgentConfig = useMemo(() => {
- if (mode.type === 'named') {
- return { mode: 'named', agentName: mode.agentName };
- }
// idle uses a placeholder draft so layout chrome (useAui) still mounts;
// layouts render an empty CTA instead of the thread.
- if (mode.type === 'idle') {
+ if (mode.status === 'idle') {
return {
mode: 'draft',
defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
};
}
- return { mode: 'draft', defaultAgentSpec: mode.defaultAgentSpec };
- }, [mode]);
+ // Runtime still uses named|draft; shell mutability maps onto that adapter.
+ if (!mode.isMutable) {
+ const agentName = mode.agentName ?? mode.agentId ?? pendingSessionId;
+ if (agentName == null) {
+ // Active immutable without identity should not happen; keep chrome mounted.
+ return {
+ mode: 'draft',
+ defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
+ };
+ }
+ return { mode: 'named', agentName };
+ }
+ return {
+ mode: 'draft',
+ defaultAgentSpec: draftDefaultAgentSpec,
+ };
+ }, [mode, draftDefaultAgentSpec, pendingSessionId]);
return (
- <TrueFoundryChatProvider key={runtimeKey} {...providerRest} agent={agent}>
+ <TrueFoundryChatProvider
+ key={runtimeKey}
+ {...providerRest}
+ agent={agent}
+ listSessionsAgentId={listSessionsAgentId}
+ initialSessionId={pendingSessionId ?? hostInitialSessionId}
+ >
{children}
</TrueFoundryChatProvider>
);
diff --git a/packages/trueforge-ui-sdk/src/icons/IconRegistry.tsx b/packages/trueforge-ui-sdk/src/icons/IconRegistry.tsx
index 9b103bed4..52abfb677 100644
--- a/packages/trueforge-ui-sdk/src/icons/IconRegistry.tsx
+++ b/packages/trueforge-ui-sdk/src/icons/IconRegistry.tsx
@@ -7,6 +7,7 @@ import {
Bot,
Box,
Brain,
+ BrushCleaning,
Check,
ChevronDown,
ChevronLeft,
@@ -26,6 +27,7 @@ import {
History,
Lightbulb,
ListChecks,
+ ListFilter,
ListOrdered,
Loader2,
Maximize2,
@@ -84,6 +86,7 @@ const defaults: Record<string, LucideIcon> = {
check: Check,
pencil: Pencil,
'rotate-right': RotateCw,
+ broom: BrushCleaning,
ellipsis: Ellipsis,
trash: Trash2,
'box-archive': Archive,
@@ -108,6 +111,7 @@ const defaults: Record<string, LucideIcon> = {
'circle-check': CircleCheck,
'circle-xmark': CircleX,
robot: Bot,
+ funnel: ListFilter,
plug: Plug,
'list-check': ListChecks,
lightbulb: Lightbulb,
diff --git a/packages/trueforge-ui-sdk/src/index.ts b/packages/trueforge-ui-sdk/src/index.ts
index 09f1c6fe9..539e24afa 100644
--- a/packages/trueforge-ui-sdk/src/index.ts
+++ b/packages/trueforge-ui-sdk/src/index.ts
@@ -229,10 +229,12 @@ export {
export {
DEFAULT_AGENT_CONFIG,
ShellModeProvider,
+ libraryAgentId,
+ shellIsMutable,
useOptionalShellMode,
useShellMode,
} from './server/ShellModeContext.js';
-export type { AgentConfig, ShellMode } from './server/ShellModeContext.js';
+export type { AgentConfig, SelectLibraryAgentRequest, ShellMode } from './server/ShellModeContext.js';
export type {
AgentBuilderServer,
AgentChatServer,
diff --git a/packages/trueforge-ui-sdk/src/layouts/DrawerLayout.tsx b/packages/trueforge-ui-sdk/src/layouts/DrawerLayout.tsx
index 0de8cf9ed..613069bfd 100644
--- a/packages/trueforge-ui-sdk/src/layouts/DrawerLayout.tsx
+++ b/packages/trueforge-ui-sdk/src/layouts/DrawerLayout.tsx
@@ -3,6 +3,7 @@
import { useEffect, useRef, useState } from 'react';
import { useAui } from '../assistant-ui.js';
+import { NamedAgentHeaderLabel } from '../atoms/NamedAgentHeaderLabel.js';
import { SaveAgentButton } from '../atoms/SaveAgentButton.js';
import { SelectAgentEmptyState } from '../atoms/SelectAgentEmptyState.js';
import { ShellActions } from '../atoms/ShellActions.js';
@@ -24,7 +25,7 @@ export function DrawerLayout({ className }: { className?: string }) {
const dialogRef = useRef<HTMLDivElement>(null);
const mainRef = useRef<HTMLDivElement>(null);
const wasOpen = useRef(false);
- const isIdle = shell?.mode.type === 'idle';
+ const isIdle = shell?.mode.status === 'idle';
const settingsOpen = shell?.settingsOpen === true;
useEffect(() => {
@@ -64,9 +65,11 @@ export function DrawerLayout({ className }: { className?: string }) {
return (
<div className={cn('relative flex h-full min-h-0 w-full flex-col', className)}>
{!settingsOpen ? (
- <header className="flex shrink-0 items-center justify-end gap-1 border-b border-border bg-background px-2 py-1.5">
- <SaveAgentButton />
+ <header className="flex shrink-0 items-center gap-1 border-b border-border bg-background px-2 py-1.5">
+ <NamedAgentHeaderLabel />
+ <span className="min-w-0 flex-1" />
<ClearChatButton />
+ <SaveAgentButton />
<ShellActions />
{shell?.isNewChatEnabled !== false ? (
<button
diff --git a/packages/trueforge-ui-sdk/src/layouts/SidebarLayout.tsx b/packages/trueforge-ui-sdk/src/layouts/SidebarLayout.tsx
index 562f7a08c..dee8dd571 100644
--- a/packages/trueforge-ui-sdk/src/layouts/SidebarLayout.tsx
+++ b/packages/trueforge-ui-sdk/src/layouts/SidebarLayout.tsx
@@ -5,6 +5,7 @@ import { useEffect, useRef, useState } from 'react';
import { useAui } from '../assistant-ui.js';
import { auiButtonClass } from '../atoms/lib/buttonClasses.js';
import { cn } from '../atoms/lib/cn.js';
+import { NamedAgentHeaderLabel } from '../atoms/NamedAgentHeaderLabel.js';
import { SaveAgentButton } from '../atoms/SaveAgentButton.js';
import { SelectAgentEmptyState } from '../atoms/SelectAgentEmptyState.js';
import { ShellActions } from '../atoms/ShellActions.js';
@@ -39,7 +40,7 @@ export function SidebarLayout({ className }: { className?: string }) {
const dialogRef = useRef<HTMLDivElement>(null);
const mainRef = useRef<HTMLDivElement>(null);
const wasOpen = useRef(false);
- const isIdle = shell?.mode.type === 'idle';
+ const isIdle = shell?.mode.status === 'idle';
const settingsOpen = shell?.settingsOpen === true;
useEffect(() => {
@@ -155,9 +156,10 @@ export function SidebarLayout({ className }: { className?: string }) {
>
<Icon name="bars" />
</button>
+ <NamedAgentHeaderLabel />
<span className="min-w-0 flex-1" />
- <SaveAgentButton />
<ClearChatButton />
+ <SaveAgentButton />
<div className="md:hidden">
<ShellActions />
</div>
diff --git a/packages/trueforge-ui-sdk/src/layouts/StackChatPanel.tsx b/packages/trueforge-ui-sdk/src/layouts/StackChatPanel.tsx
index 7b8c90d4e..548dd1c24 100644
--- a/packages/trueforge-ui-sdk/src/layouts/StackChatPanel.tsx
+++ b/packages/trueforge-ui-sdk/src/layouts/StackChatPanel.tsx
@@ -3,6 +3,7 @@
import { useEffect, useState, type ReactNode } from 'react';
import { useAui } from '../assistant-ui.js';
+import { NamedAgentHeaderLabel } from '../atoms/NamedAgentHeaderLabel.js';
import { SaveAgentButton } from '../atoms/SaveAgentButton.js';
import { SelectAgentEmptyState } from '../atoms/SelectAgentEmptyState.js';
import { ShellActions } from '../atoms/ShellActions.js';
@@ -30,7 +31,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro
const aui = useAui();
const shell = useOptionalShellMode();
const ClearChatButton = useSlot('ClearChatButton');
- const isIdle = shell?.mode.type === 'idle';
+ const isIdle = shell?.mode.status === 'idle';
const settingsOpen = shell?.settingsOpen === true;
useEffect(() => {
@@ -69,9 +70,10 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro
>
<Icon name="clock-rotate-left" />
</button>
+ <NamedAgentHeaderLabel />
<span className="min-w-0 flex-1" />
- <SaveAgentButton />
<ClearChatButton />
+ <SaveAgentButton />
<ShellActions />
{threadHeaderEnd}
</header>
diff --git a/packages/trueforge-ui-sdk/src/server/ShellModeContext.test.tsx b/packages/trueforge-ui-sdk/src/server/ShellModeContext.test.tsx
index 7ccf5d4fb..250c83568 100644
--- a/packages/trueforge-ui-sdk/src/server/ShellModeContext.test.tsx
+++ b/packages/trueforge-ui-sdk/src/server/ShellModeContext.test.tsx
@@ -12,9 +12,9 @@ function wrap(agentConfig?: AgentConfig) {
}
describe('ShellModeProvider', () => {
- it('defaults to AgentLibraryWithComposer (draft + library)', () => {
+ it('defaults to AgentLibraryWithComposer (mutable + library)', () => {
const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });
- expect(result.current.mode.type).toBe('draft');
+ expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true, locked: false });
expect(result.current.isLibraryEnabled).toBe(true);
expect(result.current.isComposerEnabled).toBe(true);
expect(result.current.isNewChatEnabled).toBe(true);
@@ -25,7 +25,9 @@ describe('ShellModeProvider', () => {
wrapper: wrap({ mode: 'SingleAgent', name: 'locked' }),
});
expect(result.current.mode).toEqual({
- type: 'named',
+ status: 'active',
+ isMutable: false,
+ agentId: 'locked',
agentName: 'locked',
locked: true,
});
@@ -35,31 +37,36 @@ describe('ShellModeProvider', () => {
act(() => result.current.selectAgent('other'));
act(() => result.current.openDraft());
expect(result.current.mode).toEqual({
- type: 'named',
+ status: 'active',
+ isMutable: false,
+ agentId: 'locked',
agentName: 'locked',
locked: true,
});
});
- it('starts AgentLibrary idle, then selectAgent → named', () => {
+ it('starts AgentLibrary idle, then selectAgent → immutable', () => {
const { result } = renderHook(() => useShellMode(), {
wrapper: wrap({ mode: 'AgentLibrary' }),
});
- expect(result.current.mode.type).toBe('idle');
+ expect(result.current.mode.status).toBe('idle');
expect(result.current.isNewChatEnabled).toBe(false);
expect(result.current.isComposerEnabled).toBe(false);
expect(result.current.isLibraryEnabled).toBe(true);
act(() => result.current.selectAgent('alpha'));
expect(result.current.mode).toEqual({
- type: 'named',
+ status: 'active',
+ isMutable: false,
+ agentId: 'alpha',
agentName: 'alpha',
locked: false,
});
const keyBefore = result.current.runtimeKey;
act(() => result.current.clearChat());
- expect(result.current.mode.type).toBe('named');
+ expect(result.current.mode.status).toBe('active');
+ expect(result.current.mode).toMatchObject({ isMutable: false });
expect(result.current.runtimeKey).not.toBe(keyBefore);
});
@@ -73,30 +80,32 @@ describe('ShellModeProvider', () => {
act(() => result.current.selectAgent('alpha'));
expect(result.current.mode).toEqual({
- type: 'named',
+ status: 'active',
+ isMutable: false,
+ agentId: 'alpha',
agentName: 'alpha',
locked: false,
});
expect(result.current.runtimeKey).not.toBe(keyBefore);
});
- it('AgentComposer stays draft; clearChat bumps draft epoch', () => {
+ it('AgentComposer stays mutable; clearChat bumps epoch', () => {
const { result } = renderHook(() => useShellMode(), {
wrapper: wrap({
mode: 'AgentComposer',
defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
}),
});
- expect(result.current.mode.type).toBe('draft');
+ expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
expect(result.current.isLibraryEnabled).toBe(false);
expect(result.current.isComposerEnabled).toBe(true);
act(() => result.current.selectAgent('nope'));
- expect(result.current.mode.type).toBe('draft');
+ expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
const keyBefore = result.current.runtimeKey;
act(() => result.current.clearChat());
- expect(result.current.mode.type).toBe('draft');
+ expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
expect(result.current.runtimeKey).not.toBe(keyBefore);
});
@@ -107,7 +116,7 @@ describe('ShellModeProvider', () => {
const key = result.current.runtimeKey;
act(() => result.current.clearChat());
expect(result.current.runtimeKey).toBe(key);
- expect(result.current.mode.type).toBe('idle');
+ expect(result.current.mode.status).toBe('idle');
});
it('openDraft and selectAgent close Settings', () => {
@@ -120,15 +129,240 @@ describe('ShellModeProvider', () => {
act(() => result.current.openDraft());
expect(result.current.settingsOpen).toBe(false);
- expect(result.current.mode.type).toBe('draft');
+ expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
act(() => result.current.setSettingsOpen(true));
act(() => result.current.selectAgent('alpha'));
expect(result.current.settingsOpen).toBe(false);
expect(result.current.mode).toEqual({
- type: 'named',
+ status: 'active',
+ isMutable: false,
+ agentId: 'alpha',
agentName: 'alpha',
locked: false,
});
});
+
+ it('selectLibraryAgent Edit seeds mutable binding with agentSpec', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
+ });
+ const spec = {
+ model: { name: 'custom/model' },
+ skills: [{ id: 's1', name: 'Skill' }],
+ mcpServers: [{ id: 'm1', name: 'MCP' }],
+ };
+
+ act(() =>
+ result.current.selectLibraryAgent({
+ isMutable: true,
+ agentId: 'writer',
+ agentName: 'writer',
+ agentSpec: spec,
+ }),
+ );
+
+ expect(result.current.mode).toEqual({
+ status: 'active',
+ isMutable: true,
+ agentId: 'writer',
+ agentName: 'writer',
+ agentSpec: spec,
+ locked: false,
+ });
+ });
+
+ it('clearChat on Edit preserves agentName and seeded agentSpec', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
+ });
+ const spec = {
+ model: { name: 'custom/model' },
+ skills: [{ id: 's1', name: 'Skill' }],
+ };
+
+ act(() =>
+ result.current.selectLibraryAgent({
+ isMutable: true,
+ agentId: 'writer',
+ agentName: 'writer',
+ agentSpec: spec,
+ }),
+ );
+ const keyBefore = result.current.runtimeKey;
+
+ act(() => result.current.clearChat());
+
+ expect(result.current.mode).toEqual({
+ status: 'active',
+ isMutable: true,
+ agentId: 'writer',
+ agentName: 'writer',
+ agentSpec: spec,
+ locked: false,
+ });
+ expect(result.current.runtimeKey).not.toBe(keyBefore);
+ });
+
+ it('listSessionsAgentId follows history filter when library is enabled', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
+ });
+ expect(result.current.listSessionsAgentId).toBeUndefined();
+ expect(result.current.historyAgentFilter).toBeNull();
+
+ act(() => result.current.setHistoryAgentFilter('from-sdk'));
+ expect(result.current.historyAgentFilter).toBe('from-sdk');
+ expect(result.current.listSessionsAgentId).toBe('from-sdk');
+
+ act(() => result.current.setHistoryAgentFilter(null));
+ expect(result.current.listSessionsAgentId).toBeUndefined();
+ });
+
+ it('SingleAgent locks listSessionsAgentId to the agent name', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'SingleAgent', name: 'locked' }),
+ });
+ expect(result.current.listSessionsAgentId).toBe('locked');
+ act(() => result.current.setHistoryAgentFilter('ignored'));
+ expect(result.current.listSessionsAgentId).toBe('locked');
+ });
+
+ it('openHistorySession remounts into immutable binding with pendingSessionId', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
+ });
+ expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
+
+ act(() => result.current.openHistorySession({ sessionId: 'sess-1', agentName: 'from-sdk' }));
+ expect(result.current.mode).toEqual({
+ status: 'active',
+ isMutable: false,
+ agentId: 'from-sdk',
+ agentName: 'from-sdk',
+ locked: false,
+ });
+ expect(result.current.pendingSessionId).toBe('sess-1');
+ expect(result.current.runtimeKey).toContain('sess-1');
+ });
+
+ it('openHistorySession keeps immutable binding when agentName is missing', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
+ });
+
+ act(() => result.current.openHistorySession({ sessionId: 'sess-orphan', isMutable: false }));
+ expect(result.current.mode).toEqual({
+ status: 'active',
+ isMutable: false,
+ locked: false,
+ });
+ expect(result.current.pendingSessionId).toBe('sess-orphan');
+ });
+
+ it('openHistorySession into mutable clears Edit identity', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({
+ mode: 'AgentLibraryWithComposer',
+ defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
+ }),
+ });
+
+ act(() =>
+ result.current.selectLibraryAgent({
+ isMutable: true,
+ agentId: 'writer',
+ agentName: 'writer',
+ agentSpec: { model: { name: 'openai-main/gpt-4.1' }, instructions: 'Write.' },
+ }),
+ );
+ expect(result.current.mode).toMatchObject({ agentName: 'writer', isMutable: true });
+
+ act(() => result.current.openHistorySession({ sessionId: 'sess-other', isMutable: true }));
+ expect(result.current.mode).toEqual({
+ status: 'active',
+ isMutable: true,
+ agentSpec: { model: { name: 'openai-main/gpt-4.1' } },
+ locked: false,
+ });
+ expect(result.current.pendingSessionId).toBe('sess-other');
+ });
+
+ it('invalidateAgentsList bumps agentsListEpoch', () => {
+ const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });
+ expect(result.current.agentsListEpoch).toBe(0);
+ act(() => result.current.invalidateAgentsList());
+ expect(result.current.agentsListEpoch).toBe(1);
+ });
+
+ it('bindMutableAgent attaches identity without remounting', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
+ });
+ const keyBefore = result.current.runtimeKey;
+ const spec = {
+ model: { name: 'openai-main/gpt-4.1' },
+ instructions: 'Saved.',
+ };
+
+ act(() =>
+ result.current.bindMutableAgent({
+ agentId: 'saved',
+ agentName: 'saved',
+ agentSpec: spec,
+ }),
+ );
+
+ expect(result.current.mode).toEqual({
+ status: 'active',
+ isMutable: true,
+ agentId: 'saved',
+ agentName: 'saved',
+ agentSpec: spec,
+ locked: false,
+ });
+ expect(result.current.runtimeKey).toBe(keyBefore);
+ });
+
+ it('bindMutableAgent keeps runtimeKey stable even when model changes', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({
+ mode: 'AgentLibraryWithComposer',
+ defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
+ }),
+ });
+ const keyBefore = result.current.runtimeKey;
+
+ act(() =>
+ result.current.bindMutableAgent({
+ agentId: 'saved',
+ agentName: 'saved',
+ agentSpec: { model: { name: 'other/model' }, instructions: 'Saved.' },
+ }),
+ );
+
+ expect(result.current.runtimeKey).toBe(keyBefore);
+ expect(result.current.mode).toMatchObject({
+ agentId: 'saved',
+ agentName: 'saved',
+ agentSpec: { model: { name: 'other/model' } },
+ });
+ });
+
+ it('bindMutableAgent is a no-op when not on a mutable chat', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibrary' }),
+ });
+ expect(result.current.mode.status).toBe('idle');
+
+ act(() =>
+ result.current.bindMutableAgent({
+ agentId: 'x',
+ agentName: 'x',
+ agentSpec: { model: { name: 'openai-main/gpt-4.1' } },
+ }),
+ );
+
+ expect(result.current.mode.status).toBe('idle');
+ });
});
diff --git a/packages/trueforge-ui-sdk/src/server/ShellModeContext.tsx b/packages/trueforge-ui-sdk/src/server/ShellModeContext.tsx
index 73e4611ce..0a840f775 100644
--- a/packages/trueforge-ui-sdk/src/server/ShellModeContext.tsx
+++ b/packages/trueforge-ui-sdk/src/server/ShellModeContext.tsx
@@ -2,7 +2,7 @@
import { createContext, useCallback, useContext, useMemo, useRef, useState, type ReactNode } from 'react';
-import type { AgentSpec } from './types.js';
+import type { AgentLibraryEntry, AgentSpec } from './types.js';
/** Host-facing shell configuration for agent / library / composer chrome. */
export type AgentConfig =
@@ -15,10 +15,31 @@ export const DEFAULT_AGENT_CONFIG: AgentConfig = {
mode: 'AgentLibraryWithComposer',
};
+/**
+ * Active chat binding. Mutability (`isMutable`) decides composer / Save / updateSession —
+ * not a parallel draft|named shell type.
+ */
export type ShellMode =
- | { type: 'idle' }
- | { type: 'named'; agentName: string; locked: boolean }
- | { type: 'draft'; defaultAgentSpec: AgentSpec };
+ | { status: 'idle' }
+ | {
+ status: 'active';
+ isMutable: boolean;
+ /** Identity for immutable bind + history filter. */
+ agentId?: string;
+ /** Display / welcome label (often same as agentId). */
+ agentName?: string;
+ /** Seed for mutable (draft) runtime. */
+ agentSpec?: AgentSpec;
+ locked: boolean;
+ };
+
+/** Library / New Chat create intent. */
+export type SelectLibraryAgentRequest = {
+ isMutable: boolean;
+ agentId?: string;
+ agentName?: string;
+ agentSpec?: AgentSpec;
+};
type ShellModeContextValue = {
mode: ShellMode;
@@ -26,45 +47,95 @@ type ShellModeContextValue = {
agentConfigMode: AgentConfig['mode'];
/** Agents Library chrome. */
isLibraryEnabled: boolean;
- /** Draft composer / Save Agent chrome. */
+ /** Mutable composer / Save Agent chrome (host capability). */
isComposerEnabled: boolean;
/** Sidebar / list New Chat control. */
isNewChatEnabled: boolean;
settingsOpen: boolean;
setSettingsOpen: (open: boolean) => void;
+ /**
+ * Bind from the Agents Library (Try = immutable, Edit = mutable + agentSpec).
+ * Prefer this over `selectAgent` / `openDraft` when both fields are available.
+ */
+ selectLibraryAgent: (req: SelectLibraryAgentRequest) => void;
+ /**
+ * Attach identity + agentSpec to the *current* mutable chat without remounting.
+ * Used after `saveAgent` so the same draft session continues as an editable agent.
+ */
+ bindMutableAgent: (req: { agentId: string; agentName: string; agentSpec: AgentSpec }) => void;
+ /** @deprecated Prefer `selectLibraryAgent({ isMutable: false, agentName })`. */
selectAgent: (agentName: string) => void;
+ /** @deprecated Prefer `selectLibraryAgent({ isMutable: true, agentSpec })`. */
openDraft: () => void;
- /** Reset current named or draft chat; no-op when idle. */
+ /**
+ * 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.
+ */
+ openHistorySession: (req: { sessionId: string; agentName?: string; isMutable?: boolean }) => void;
+ /** Reset current chat; no-op when idle. */
clearChat: () => void;
- /** Remount key for the chat runtime when mode/agent changes. */
+ /** Remount key for the chat runtime when binding changes. */
runtimeKey: string;
+ /**
+ * History list filter forwarded as `listSessions({ agentId })`.
+ * `null` = All chats. Only meaningful when `isLibraryEnabled`.
+ */
+ historyAgentFilter: string | null;
+ 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). */
+ pendingSessionId: string | undefined;
+ /**
+ * Bumped when the Agents Library catalog may have changed (e.g. after saveAgent).
+ * Library chrome should re-fetch when this changes.
+ */
+ agentsListEpoch: number;
+ invalidateAgentsList: () => void;
};
const ShellModeContext = createContext<ShellModeContextValue | null>(null);
-const FALLBACK_DRAFT_SPEC: AgentSpec = {
+const FALLBACK_MUTABLE_SPEC: AgentSpec = {
model: { name: 'openai-main/gpt-4.1' },
};
-function draftSeedFromConfig(config: AgentConfig): AgentSpec {
+function mutableSeedFromConfig(config: AgentConfig): AgentSpec {
if (config.mode === 'AgentComposer' || config.mode === 'AgentLibraryWithComposer') {
- return config.defaultAgentSpec ?? FALLBACK_DRAFT_SPEC;
+ return config.defaultAgentSpec ?? FALLBACK_MUTABLE_SPEC;
}
- return FALLBACK_DRAFT_SPEC;
+ return FALLBACK_MUTABLE_SPEC;
}
-function initialMode(config: AgentConfig, draftSeed: AgentSpec): ShellMode {
+function initialMode(config: AgentConfig, mutableSeed: AgentSpec): ShellMode {
switch (config.mode) {
case 'SingleAgent':
- return { type: 'named', agentName: config.name, locked: true };
+ return {
+ status: 'active',
+ isMutable: false,
+ agentId: config.name,
+ agentName: config.name,
+ locked: true,
+ };
case 'AgentLibrary':
- return { type: 'idle' };
+ return { status: 'idle' };
case 'AgentComposer':
case 'AgentLibraryWithComposer':
- return { type: 'draft', defaultAgentSpec: draftSeed };
+ return {
+ status: 'active',
+ isMutable: true,
+ agentSpec: mutableSeed,
+ locked: false,
+ };
}
}
+function libraryAgentId(agent: Pick<AgentLibraryEntry, 'agentId' | 'name'>): string {
+ return agent.agentId ?? agent.name;
+}
+
export function ShellModeProvider({
agentConfig = DEFAULT_AGENT_CONFIG,
children,
@@ -72,67 +143,188 @@ export function ShellModeProvider({
agentConfig?: AgentConfig;
children: ReactNode;
}) {
- const draftSeedRef = useRef(draftSeedFromConfig(agentConfig));
+ const mutableSeedRef = useRef(mutableSeedFromConfig(agentConfig));
if (
(agentConfig.mode === 'AgentComposer' || agentConfig.mode === 'AgentLibraryWithComposer') &&
agentConfig.defaultAgentSpec != null
) {
- draftSeedRef.current = agentConfig.defaultAgentSpec;
+ mutableSeedRef.current = agentConfig.defaultAgentSpec;
}
- const draftSeed = draftSeedRef.current;
+ const mutableSeed = mutableSeedRef.current;
const isLibraryEnabled = agentConfig.mode === 'AgentLibrary' || agentConfig.mode === 'AgentLibraryWithComposer';
const isComposerEnabled = agentConfig.mode === 'AgentComposer' || agentConfig.mode === 'AgentLibraryWithComposer';
const isNewChatEnabled = agentConfig.mode !== 'AgentLibrary';
const locked = agentConfig.mode === 'SingleAgent';
- const [mode, setMode] = useState<ShellMode>(() => initialMode(agentConfig, draftSeed));
- const [draftEpoch, setDraftEpoch] = useState(0);
+ const [mode, setMode] = useState<ShellMode>(() => initialMode(agentConfig, mutableSeed));
+ const [mutableEpoch, setMutableEpoch] = useState(0);
const [clearEpoch, setClearEpoch] = useState(0);
+ const [agentsListEpoch, setAgentsListEpoch] = useState(0);
const [settingsOpen, setSettingsOpen] = useState(false);
+ const [historyAgentFilter, setHistoryAgentFilter] = useState<string | null>(null);
+ const [pendingSessionId, setPendingSessionId] = useState<string | undefined>(undefined);
+
+ const invalidateAgentsList = useCallback(() => {
+ setAgentsListEpoch(n => n + 1);
+ }, []);
const lockedAgentName = agentConfig.mode === 'SingleAgent' ? agentConfig.name : '';
- const effectiveMode: ShellMode = useMemo(
- () => (locked ? { type: 'named', agentName: lockedAgentName, locked: true } : mode),
- [locked, lockedAgentName, mode],
+ const effectiveMode: ShellMode = useMemo(() => {
+ if (!locked) return mode;
+ return {
+ status: 'active',
+ isMutable: false,
+ agentId: lockedAgentName,
+ agentName: lockedAgentName,
+ locked: true,
+ };
+ }, [locked, lockedAgentName, mode]);
+
+ const listSessionsAgentId = useMemo(() => {
+ if (locked) return lockedAgentName;
+ if (!isLibraryEnabled) return undefined;
+ return historyAgentFilter ?? undefined;
+ }, [locked, lockedAgentName, isLibraryEnabled, historyAgentFilter]);
+
+ const bumpEpoch = useCallback((isMutable: boolean) => {
+ if (isMutable) setMutableEpoch(n => n + 1);
+ else setClearEpoch(n => n + 1);
+ }, []);
+
+ const selectLibraryAgent = useCallback(
+ (req: SelectLibraryAgentRequest) => {
+ if (req.isMutable) {
+ if (!isComposerEnabled) return;
+ setSettingsOpen(false);
+ setPendingSessionId(undefined);
+ setMode({
+ status: 'active',
+ isMutable: true,
+ agentId: req.agentId,
+ agentName: req.agentName,
+ agentSpec: req.agentSpec ?? mutableSeedRef.current,
+ locked: false,
+ });
+ bumpEpoch(true);
+ return;
+ }
+ if (!isLibraryEnabled) return;
+ const agentName = req.agentName ?? req.agentId;
+ if (agentName == null) return;
+ setSettingsOpen(false);
+ setPendingSessionId(undefined);
+ setMode({
+ status: 'active',
+ isMutable: false,
+ agentId: req.agentId ?? agentName,
+ agentName,
+ locked: false,
+ });
+ bumpEpoch(false);
+ },
+ [isComposerEnabled, isLibraryEnabled, bumpEpoch],
+ );
+
+ const bindMutableAgent = useCallback(
+ (req: { agentId: string; agentName: string; agentSpec: AgentSpec }) => {
+ if (!isComposerEnabled) return;
+ setMode(prev => {
+ if (prev.status !== 'active' || !prev.isMutable) return prev;
+ return {
+ status: 'active',
+ isMutable: true,
+ agentId: req.agentId,
+ agentName: req.agentName,
+ agentSpec: req.agentSpec,
+ locked: false,
+ };
+ });
+ },
+ [isComposerEnabled],
);
const selectAgent = useCallback(
(name: string) => {
- if (!isLibraryEnabled) return;
- // Leaving Settings so the main pane shows the selected agent chat.
- setSettingsOpen(false);
- setMode({ type: 'named', agentName: name, locked: false });
- // Re-picking the current agent must still remount the runtime.
- setClearEpoch(n => n + 1);
+ selectLibraryAgent({ isMutable: false, agentId: name, agentName: name });
},
- [isLibraryEnabled],
+ [selectLibraryAgent],
);
const openDraft = useCallback(() => {
- if (!isComposerEnabled) return;
- // New Chat while Settings is open must reveal the draft composer.
- setSettingsOpen(false);
- setMode({ type: 'draft', defaultAgentSpec: draftSeedRef.current });
- setDraftEpoch(n => n + 1);
- }, [isComposerEnabled]);
+ selectLibraryAgent({ isMutable: true, agentSpec: mutableSeedRef.current });
+ }, [selectLibraryAgent]);
+
+ const openHistorySession = useCallback(
+ ({
+ sessionId,
+ agentName,
+ isMutable: isMutableOpt,
+ }: {
+ sessionId: string;
+ agentName?: string;
+ isMutable?: boolean;
+ }) => {
+ setSettingsOpen(false);
+ setPendingSessionId(sessionId);
+ const isMutable = isMutableOpt ?? agentName == null;
+ if (isMutable) {
+ if (!isComposerEnabled) return;
+ setMode({
+ status: 'active',
+ isMutable: true,
+ agentSpec: mutableSeedRef.current,
+ locked: false,
+ });
+ bumpEpoch(true);
+ return;
+ }
+ // Immutable: allow orphaned refs (deleted agent → no agentName).
+ if (locked) {
+ if (agentName == null || lockedAgentName !== agentName) return;
+ } else if (!isLibraryEnabled) {
+ return;
+ }
+ setMode({
+ status: 'active',
+ isMutable: false,
+ locked: false,
+ ...(agentName != null ? { agentId: agentName, agentName } : {}),
+ });
+ bumpEpoch(false);
+ },
+ [isLibraryEnabled, isComposerEnabled, locked, lockedAgentName, bumpEpoch],
+ );
const clearChat = useCallback(() => {
- if (effectiveMode.type === 'idle') return;
- if (effectiveMode.type === 'draft') {
- setMode({ type: 'draft', defaultAgentSpec: draftSeedRef.current });
- setDraftEpoch(n => n + 1);
+ if (effectiveMode.status === 'idle') return;
+ setPendingSessionId(undefined);
+ if (effectiveMode.isMutable) {
+ // Preserve Edit binding (name + seeded spec); blank drafts fall back to host seed.
+ setMode({
+ status: 'active',
+ isMutable: true,
+ agentId: effectiveMode.agentId,
+ agentName: effectiveMode.agentName,
+ agentSpec: effectiveMode.agentSpec ?? mutableSeedRef.current,
+ locked: false,
+ });
+ bumpEpoch(true);
return;
}
- setClearEpoch(n => n + 1);
- }, [effectiveMode]);
+ bumpEpoch(false);
+ }, [effectiveMode, bumpEpoch]);
- const runtimeKey =
- effectiveMode.type === 'idle'
- ? 'idle'
- : effectiveMode.type === 'named'
- ? `named:${effectiveMode.agentName}:${clearEpoch}`
- : `draft:${effectiveMode.defaultAgentSpec.model.name}:${draftEpoch}`;
+ // 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.
+ 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]);
const value = useMemo<ShellModeContextValue>(
() => ({
@@ -143,10 +335,19 @@ export function ShellModeProvider({
isNewChatEnabled,
settingsOpen,
setSettingsOpen,
+ selectLibraryAgent,
+ bindMutableAgent,
selectAgent,
openDraft,
+ openHistorySession,
clearChat,
runtimeKey,
+ historyAgentFilter,
+ setHistoryAgentFilter,
+ listSessionsAgentId,
+ pendingSessionId,
+ agentsListEpoch,
+ invalidateAgentsList,
}),
[
effectiveMode,
@@ -155,10 +356,18 @@ export function ShellModeProvider({
isComposerEnabled,
isNewChatEnabled,
settingsOpen,
+ selectLibraryAgent,
+ bindMutableAgent,
selectAgent,
openDraft,
+ openHistorySession,
clearChat,
runtimeKey,
+ historyAgentFilter,
+ listSessionsAgentId,
+ pendingSessionId,
+ agentsListEpoch,
+ invalidateAgentsList,
],
);
@@ -176,3 +385,10 @@ export function useShellMode(): ShellModeContextValue {
export function useOptionalShellMode(): ShellModeContextValue | null {
return useContext(ShellModeContext);
}
+
+/** True when the shell is bound to a mutable (editable) agentSpec. */
+export function shellIsMutable(mode: ShellMode): boolean {
+ return mode.status === 'active' && mode.isMutable;
+}
+
+export { libraryAgentId };
diff --git a/packages/trueforge-ui-sdk/src/server/types.ts b/packages/trueforge-ui-sdk/src/server/types.ts
index 6a91c5edf..69b794253 100644
--- a/packages/trueforge-ui-sdk/src/server/types.ts
+++ b/packages/trueforge-ui-sdk/src/server/types.ts
@@ -37,9 +37,17 @@ export interface ConnectorState {
authenticated?: boolean;
}
-/** Agents library row — UI shows name only. Host extends for metadata. */
+/**
+ * Agents library row — SDK-minimal.
+ * Hosts extend via `TAgent extends AgentLibraryEntry` for richer metadata/spec shapes.
+ * `agentSpec` enables Edit (mutable); Try Agent works with `name` alone.
+ */
export interface AgentLibraryEntry {
name: string;
+ /** Stable id when distinct from display `name`. Falls back to `name` when omitted. */
+ agentId?: string;
+ /** Published agent spec — required for Edit; optional for Try-only hosts. */
+ agentSpec?: AgentSpec;
}
export type SearchAgentsParams = {
@@ -167,7 +175,12 @@ export type PageParams = {
};
export interface ListSessionsParams extends PageParams {
- agentName?: string;
+ /**
+ * Host-owned agent identity filter. Hosts that key agents by name pass that name here.
+ * Unknown / deleted ids MUST return an empty page (stale history filter, SingleAgent
+ * mismatch) — do not throw and fail the whole thread list.
+ */
+ agentId?: string;
}
export interface ListSessionsResponse<
diff --git a/packages/trueforge-ui-sdk/src/styles.css b/packages/trueforge-ui-sdk/src/styles.css
index 09bb1b422..bcc1a370d 100644
--- a/packages/trueforge-ui-sdk/src/styles.css
+++ b/packages/trueforge-ui-sdk/src/styles.css
@@ -30,6 +30,8 @@
* :root { --background: #fff; --primary: #e11d48; }
*
* Or via the theme object: `theme={{ tokens: { primary: "#e11d48" } }}`.
+ * Scrollbar thumb: `theme={{ tokens: { scrollbarThumb: "#a1a1aa" } }}` or
+ * `--scrollbar-thumb` in host CSS. Track stays transparent; thumb is the plug.
*
* Both work because the `@layer` block below has the lowest precedence —
* any plain `:root` / `.aui-root` declaration in the consumer's CSS wins.
@@ -201,34 +203,46 @@
*/
.aui-theme-root {
--thread-list-item-radius: 0.5rem;
+ --scrollbar-thumb: var(--muted-foreground);
color: var(--foreground);
}
/* ──────────────────────────────────────────────────────────────────────
- * Slim scrollbars.
+ * Slim scrollbars — flush to the edge, transparent track. Thumb color via
+ * `--scrollbar-thumb` (theme.tokens.scrollbarThumb). Theme-root covers
+ * sidebar/chrome; aui-root covers standalone thread shells.
* ──────────────────────────────────────────────────────────────────── */
.aui-root {
color: var(--foreground);
+}
+
+.aui-theme-root,
+.aui-root {
scrollbar-width: thin;
- scrollbar-color: var(--muted-foreground) transparent;
+ scrollbar-color: var(--scrollbar-thumb, var(--muted-foreground)) transparent;
}
+.aui-theme-root ::-webkit-scrollbar,
.aui-root ::-webkit-scrollbar {
width: 8px;
height: 8px;
+ background: transparent;
}
+.aui-theme-root ::-webkit-scrollbar-track,
.aui-root ::-webkit-scrollbar-track {
background: transparent;
}
+.aui-theme-root ::-webkit-scrollbar-thumb,
.aui-root ::-webkit-scrollbar-thumb {
- background-color: var(--muted-foreground);
+ background-color: var(--scrollbar-thumb, var(--muted-foreground));
border-radius: 9999px;
border: 2px solid transparent;
background-clip: content-box;
}
+.aui-theme-root ::-webkit-scrollbar-corner,
.aui-root ::-webkit-scrollbar-corner {
background: transparent;
}
diff --git a/packages/trueforge-ui-sdk/src/theme/types.ts b/packages/trueforge-ui-sdk/src/theme/types.ts
index 4d0c2e50b..37bdc7e7f 100644
--- a/packages/trueforge-ui-sdk/src/theme/types.ts
+++ b/packages/trueforge-ui-sdk/src/theme/types.ts
@@ -32,6 +32,8 @@ export type SemanticTokens = {
userBubbleForeground?: string;
assistantBubble?: string;
assistantBubbleForeground?: string;
+ /** Scrollbar thumb (“plug”) color. Defaults to `--muted-foreground`. */
+ scrollbarThumb?: string;
};
export type IconProps = {
@@ -116,4 +118,5 @@ export const TOKEN_CSS_VARS: Record<keyof SemanticTokens, string> = {
userBubbleForeground: '--user-bubble-foreground',
assistantBubble: '--assistant-bubble',
assistantBubbleForeground: '--assistant-bubble-foreground',
+ scrollbarThumb: '--scrollbar-thumb',
};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2a05bd6ee..0de759878 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -55,8 +55,8 @@ importers:
specifier: 0.2.21
'@truefoundry/assistant-ui-runtime':
- specifier: ^0.1.10-rc.1
+ specifier: ^0.1.10
'@truefoundry/trueforge-ui':
specifier: workspace:*
version: link:../trueforge-ui-sdk
@@ -307,8 +307,8 @@ importers:
specifier: ^0.13.2
'@truefoundry/assistant-ui-runtime':
- specifier: ^0.1.10-rc.1
+ specifier: ^0.1.10
clsx:
specifier: ^2.1.1
version: 2.1.1
@@ -3212,8 +3212,8 @@ packages:
'@types/react-dom':
optional: true
- '@truefoundry/[email protected]':
- resolution: {integrity: sha512-NqX+2BV3MUA/Zre2xtJxj6yCYl+mWLuhhzIzpeD+MgMDjYp+N8gQhw99k0PQXqwG706xB9zb25KYSFWHXrFtMA==}
+ '@truefoundry/[email protected]':
+ resolution: {integrity: sha512-EDIIssQt6y/WVGLRf1Vd7JdS0Ewvuzn8jWCCueiMj38L+Hfcdih3TBr6H2hhEby9C4ULxTl4xbBVG3ybmVxPSw==}
peerDependencies:
'@types/react': '*'
react: ^18 || ^19
@@ -9833,7 +9833,7 @@ snapshots:
'@types/react': 19.2.17
'@types/react-dom': 19.2.3(@types/[email protected])
dependencies:
'@assistant-ui/store': 0.2.21(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected])