Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(hetero): pin the CLI runtime type on hetero topics instead of the chat default (#18178)

Arvin Xue917542cd7bb
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index 30ffc4b88bd..0c8d1ee2063 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -279,6 +279,30 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
expect(userCall![0].files).toEqual(['file-1', 'file-2']);
});
+ it('should pin the runtime type β€” not the agent chat model β€” on a server-created topic', async () => {
+ // regression: the topic-scoped model snapshot pinned the agent's chat
+ // model/provider, so a Gateway-created hetero topic came back from the
+ // server tagged with the default chat provider instead of the CLI runtime.
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Run the build' });
+
+ expect(topicMock.create).toHaveBeenCalledWith(
+ expect.objectContaining({ model: undefined, provider: 'claude-code' }),
+ undefined,
+ );
+ });
+
+ it('should pin the runtime type of a remote platform agent on a server-created topic', async () => {
+ heteroAgentConfig.agencyConfig = { heterogeneousProvider: { type: 'openclaw' } } as any;
+ heteroAgentConfig.provider = 'lobehub';
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Run the build' });
+
+ expect(topicMock.create).toHaveBeenCalledWith(
+ expect.objectContaining({ model: undefined, provider: 'openclaw' }),
+ undefined,
+ );
+ });
+
it('should leave files undefined when no fileIds are provided', async () => {
await service.execAgent({
agentId: 'agent-1',
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index d2f7425aeb5..e35447095a6 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1988,6 +1988,16 @@ export class AiAgentService {
: undefined;
const fallbackTitleSource = markdownToTxt(prompt);
+ // A heterogeneous agent has no chat model to snapshot: the external CLI
+ // owns model selection, so `model` here is a stale agent default and
+ // `provider` is NULL (defaulted to the platform chat provider) on every
+ // agent created before the runtime type was stamped on the agent row.
+ // Pin the runtime type and leave the model to the per-run backfill β€” the
+ // same rule the assistant placeholder below and the client's
+ // `snapshotAgentModel` follow. Detection mirrors the hetero early exit.
+ const heteroSnapshotType =
+ agentConfig.agencyConfig?.heterogeneousProvider?.type ??
+ (isHeterogeneousAgentModelId(model) ? model : undefined);
// Second argument: the id the client already rendered this topic under
// (sidebar row, message bucket). Absent β†’ the model mints one as before.
const newTopic = await this.topicModel.create(
@@ -2003,8 +2013,8 @@ export class AiAgentService {
groupId: appContext?.groupId,
metadata,
// Snapshot the effective model as the topic's pinned model (config).
- model,
- provider,
+ model: heteroSnapshotType ? undefined : model,
+ provider: heteroSnapshotType ?? provider,
title:
title !== undefined
? title
diff --git a/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.ts b/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.ts
index ce914ff358e..a2479e33f14 100644
--- a/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.ts
+++ b/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.ts
@@ -125,6 +125,36 @@ describe('HeteroSessionImporterRepo.importSessions', () => {
expect(pluginRow.apiName).toBe('Bash');
});
+ it('pins the agent heterogeneous runtime type onto the created topic', async () => {
+ const heteroAgentId = 'session-importer-hetero-agent';
+ await serverDB.insert(agents).values({
+ agencyConfig: { heterogeneousProvider: { command: 'codex', type: 'codex' } },
+ id: heteroAgentId,
+ title: 'Codex Agent',
+ userId,
+ });
+
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ const [result] = await repo.importSessions({
+ agentId: heteroAgentId,
+ sessions: [basePayload()],
+ });
+
+ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, result.topicId));
+ // an imported CLI session has no pinned model, but the runtime must be
+ // attributable β€” a NULL provider reads as "not a hetero session"
+ expect(topic.provider).toBe('codex');
+ expect(topic.model).toBeNull();
+ });
+
+ it('leaves the topic provider unset when the agent is not heterogeneous', async () => {
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ const [result] = await repo.importSessions({ agentId, sessions: [basePayload()] });
+
+ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, result.topicId));
+ expect(topic.provider).toBeNull();
+ });
+
it('is idempotent: re-importing the same payload inserts nothing', async () => {
const repo = new HeteroSessionImporterRepo(serverDB, userId);
await repo.importSessions({ agentId, sessions: [basePayload()] });
diff --git a/packages/database/src/repositories/heteroSessionImporter/index.ts b/packages/database/src/repositories/heteroSessionImporter/index.ts
index 72a575b1637..016661c1dbb 100644
--- a/packages/database/src/repositories/heteroSessionImporter/index.ts
+++ b/packages/database/src/repositories/heteroSessionImporter/index.ts
@@ -6,7 +6,7 @@ import type {
} from '@lobechat/types';
import { and, count, eq, inArray, isNotNull, like, or, sql } from 'drizzle-orm';
-import { messagePlugins, messages, threads, topics } from '../../schemas';
+import { agents, messagePlugins, messages, threads, topics } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { idGenerator } from '../../utils/idGenerator';
import { buildWorkspaceWhere } from '../../utils/workspace';
@@ -56,13 +56,29 @@ export class HeteroSessionImporterRepo {
private scopeWhere = (cols: { userId: any; workspaceId: any }) =>
buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, cols);
+ /**
+ * The agent's heterogeneous runtime type (`claude-code`, `codex`, …), pinned
+ * onto every topic this importer creates. Resolved once per batch: it is the
+ * same agent for the whole call, and every reader that attributes a topic to
+ * a CLI runtime goes through `topics.provider`.
+ */
+ private resolveHeteroType = async (agentId: string): Promise<string | null> => {
+ const [agent] = await this.db
+ .select({ agencyConfig: agents.agencyConfig })
+ .from(agents)
+ .where(eq(agents.id, agentId));
+
+ return agent?.agencyConfig?.heterogeneousProvider?.type ?? null;
+ };
+
importSessions = async (
params: ImportHeteroSessionsParams,
): Promise<HeteroSessionImportResult[]> => {
const results: HeteroSessionImportResult[] = [];
+ const heteroType = await this.resolveHeteroType(params.agentId);
// one transaction per session: a corrupt session must not roll back the batch
for (const session of params.sessions) {
- results.push(await this.importSession(session, params.agentId, params.groupId));
+ results.push(await this.importSession(session, params.agentId, params.groupId, heteroType));
}
return results;
};
@@ -71,6 +87,7 @@ export class HeteroSessionImporterRepo {
session: HeteroSessionImportPayload,
agentId: string,
groupId?: string | null,
+ heteroType?: string | null,
): Promise<HeteroSessionImportResult> =>
this.db.transaction(async (tx) => {
// the source transcript's last raw-record timestamp β€” the picker compares it
@@ -130,6 +147,11 @@ export class HeteroSessionImporterRepo {
groupId: groupId || null,
id: topicId,
metadata: { ...session.metadata, ...metadataPatch },
+ // An imported CLI session has no pinned model β€” the transcript's own
+ // records carry it per message β€” but the runtime is known, and a topic
+ // left with a NULL provider reads as "not a hetero session" to every
+ // provider-scoped query.
+ provider: heteroType ?? null,
title: session.title || 'Imported Session',
userId: this.userId,
workspaceId: this.workspaceId ?? null,
diff --git a/src/features/ConnectAgent/providers.ts b/src/features/ConnectAgent/providers.ts
index 4ae1c632c8c..3b413aeaed1 100644
--- a/src/features/ConnectAgent/providers.ts
+++ b/src/features/ConnectAgent/providers.ts
@@ -130,6 +130,10 @@ export const buildConnectAgentConfig = ({
avatar: profile?.avatar || undefined,
description: (overrides?.description ?? profile?.description)?.trim() || undefined,
name,
+ // Same stamp as the CLI branch below: readers that attribute a run by the
+ // agent's provider (topic model snapshot, agent list, message tags) must
+ // see `openclaw`/`hermes`, not the inherited default chat provider.
+ provider: provider.type,
title: profile?.title || provider.title,
};
}
diff --git a/src/features/ConnectAgent/useAgentScan.test.ts b/src/features/ConnectAgent/useAgentScan.test.ts
index 843e04f4667..46a6e73d0c7 100644
--- a/src/features/ConnectAgent/useAgentScan.test.ts
+++ b/src/features/ConnectAgent/useAgentScan.test.ts
@@ -74,4 +74,22 @@ describe('buildConnectAgentConfig', () => {
title: 'default',
});
});
+
+ it('stamps the runtime type as the agent provider for platform agents', () => {
+ expect(
+ buildConnectAgentConfig({
+ provider: getConnectableProvider('hermes')!,
+ target: { kind: 'local' },
+ }),
+ ).toMatchObject({ provider: 'hermes' });
+ });
+
+ it('stamps the runtime type as the agent provider for CLI agents', () => {
+ expect(
+ buildConnectAgentConfig({
+ provider: getConnectableProvider('claude-code')!,
+ target: { deviceId: 'device-1', kind: 'device' },
+ }),
+ ).toMatchObject({ provider: 'claude-code' });
+ });
});
diff --git a/src/store/chat/utils/snapshotAgentModel.test.ts b/src/store/chat/utils/snapshotAgentModel.test.ts
new file mode 100644
index 00000000000..b0f1c852381
--- /dev/null
+++ b/src/store/chat/utils/snapshotAgentModel.test.ts
@@ -0,0 +1,65 @@
+import { DEFAULT_PROVIDER } from '@lobechat/business-const';
+import { DEFAULT_MODEL } from '@lobechat/const';
+import { describe, expect, it, vi } from 'vitest';
+
+import { snapshotAgentModel } from './snapshotAgentModel';
+
+const agentMap: Record<string, any> = {};
+
+vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({ agentMap }) }));
+
+const seedAgent = (id: string, config: Record<string, any>) => {
+ agentMap[id] = config;
+ return id;
+};
+
+describe('snapshotAgentModel', () => {
+ it('returns nothing without an agent', () => {
+ expect(snapshotAgentModel()).toEqual({});
+ expect(snapshotAgentModel(null)).toEqual({});
+ });
+
+ it('snapshots the pinned model/provider of a regular agent', () => {
+ const id = seedAgent('regular', { model: 'gpt-5.5', provider: 'openai' });
+
+ expect(snapshotAgentModel(id)).toEqual({ model: 'gpt-5.5', provider: 'openai' });
+ });
+
+ it('snapshots the platform defaults when a regular agent pinned nothing', () => {
+ const id = seedAgent('regular-blank', {});
+
+ // the effective model IS the default here, and the topic must keep it even
+ // after the agent default later changes
+ expect(snapshotAgentModel(id)).toEqual({ model: DEFAULT_MODEL, provider: DEFAULT_PROVIDER });
+ });
+
+ it('pins the runtime type β€” not the chat defaults β€” for a heterogeneous agent', () => {
+ const id = seedAgent('hetero', {
+ agencyConfig: { heterogeneousProvider: { command: 'claude', type: 'claude-code' } },
+ });
+
+ // `model` stays unset: the CLI owns model selection and reports the real
+ // model per run. Falling back to DEFAULT_MODEL/DEFAULT_PROVIDER here is what
+ // pinned `<default provider>` onto CLI topics.
+ expect(snapshotAgentModel(id)).toEqual({ provider: 'claude-code' });
+ });
+
+ it('ignores a stale agent model when the agent is heterogeneous', () => {
+ const id = seedAgent('hetero-with-model', {
+ agencyConfig: { heterogeneousProvider: { type: 'codex' } },
+ model: DEFAULT_MODEL,
+ provider: DEFAULT_PROVIDER,
+ });
+
+ expect(snapshotAgentModel(id)).toEqual({ provider: 'codex' });
+ });
+
+ it('pins nothing when a heterogeneous config carries no type', () => {
+ const id = seedAgent('hetero-untyped', {
+ agencyConfig: { heterogeneousProvider: { command: 'claude' } },
+ provider: DEFAULT_PROVIDER,
+ });
+
+ expect(snapshotAgentModel(id)).toEqual({});
+ });
+});
diff --git a/src/store/chat/utils/snapshotAgentModel.ts b/src/store/chat/utils/snapshotAgentModel.ts
index 5419e0655a4..49e68af6a39 100644
--- a/src/store/chat/utils/snapshotAgentModel.ts
+++ b/src/store/chat/utils/snapshotAgentModel.ts
@@ -15,8 +15,27 @@ export const snapshotAgentModel = (
if (!agentId) return {};
const agentState = getAgentStoreState();
- const model = agentByIdSelectors.getAgentModelById(agentId)(agentState);
- if (!model) return {};
- return { model, provider: agentByIdSelectors.getAgentModelProviderById(agentId)(agentState) };
+ // Heterogeneous agents (Claude Code, Codex, …) delegate model selection to an
+ // external CLI, so neither agent column can be snapshotted: `model` is
+ // deliberately left unset at creation (the CLI reports the real model per run
+ // and it is backfilled onto the messages), and `provider` is NULL on every
+ // agent created before the runtime type started being stamped there. Both
+ // model/provider selectors below substitute the platform chat defaults for a
+ // blank, which would pin `<default provider>/<default model>` onto a topic
+ // that never ran either. Pin the runtime type β€” the one fact we do know β€” and
+ // leave `model` to the per-run backfill.
+ const heterogeneousProvider =
+ agentByIdSelectors.getAgencyConfigById(agentId)(agentState)?.heterogeneousProvider;
+ if (heterogeneousProvider) {
+ return heterogeneousProvider.type ? { provider: heterogeneousProvider.type } : {};
+ }
+
+ // Non-hetero: the effective model IS the agent default when nothing is pinned,
+ // so snapshotting the defaulted value is intended β€” it keeps the topic on the
+ // model it started with even after the agent default later changes.
+ return {
+ model: agentByIdSelectors.getAgentModelById(agentId)(agentState),
+ provider: agentByIdSelectors.getAgentModelProviderById(agentId)(agentState),
+ };
};