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(cli): preserve agent authorship in task comments (#20512)

AmAzing-4241061a675c
diff --git a/.agents/skills/heterogeneous-agent/SKILL.md b/.agents/skills/heterogeneous-agent/SKILL.md
index 389cd2a5f5b..0dfa5f1b935 100644
--- a/.agents/skills/heterogeneous-agent/SKILL.md
+++ b/.agents/skills/heterogeneous-agent/SKILL.md
@@ -1,6 +1,6 @@
---
name: heterogeneous-agent
-description: 'Use for Claude Code/Codex external-agent adapters, IPC, event mapping, sessions, persistence and tool-call chains.'
+description: 'Use for external-agent launchers and execution identity, Claude Code/Codex adapters, IPC, event mapping, sessions, persistence and tool-call chains.'
---
# Heterogeneous Agent Development
@@ -11,6 +11,7 @@ Use this skill when the bug or feature lives in the external CLI agent pipeline,
- Adding or changing a driver under `apps/desktop/src/main/modules/heterogeneousAgent/drivers/`
- Editing an adapter under `packages/heterogeneous-agents/src/adapters/`
+- Changing CLI/Desktop dispatch launchers, including OpenClaw/Hermes, or debugging task-comment authorship
- Debugging `heteroAgentRawLine` transport, `window.__HETERO_AGENT_TRACE`, or `executeHeterogeneousAgent`
- Fixing Claude Code stream-json bugs such as duplicate partial/full chunks, broken `message.id` boundaries, missing `tool_result`, TodoWrite state drift, or subagent thread routing
- Fixing Codex JSONL bugs such as mixed multi-tool messages, broken turn boundaries, or missing tool-result mapping
@@ -57,6 +58,25 @@ Use this skill when the bug or feature lives in the external CLI agent pipeline,
- Subagent chunks must stay in thread scope and must not be forwarded into the main assistant stream.
- Never clear the global `toolMsgIdByCallId` map at main step boundaries.
+## Dispatched Run Identity
+
+A connector or desktop process can itself run inside another Agent's conversation. Its inherited environment identifies the launcher, not the dispatched Agent.
+
+- Build child identity from the current dispatch. Clear inherited `LOBEHUB_AGENT_ID`, `LOBEHUB_ASSISTANT_MESSAGE_ID`, `LOBEHUB_TASK_ID`, and `LOBEHUB_WORKSPACE_ID`; replace `LOBEHUB_TOPIC_ID` and `LOBEHUB_OPERATION_ID` with the dispatched values. Inject optional context only when supplied by the current dispatch; absent values must not retain ancestor identity.
+- Keep authorship independent of authentication. Clearing `LOBEHUB_JWT` or falling back to user credentials must not change the executing Agent. Never infer the author from the topic owner or task assignee.
+- In `apps/cli/src/commands/task/lifecycle.ts`, `lh task comment` must refuse to post when topic or operation context exists but the Agent ID is missing or blank. Ordinary terminal comments without execution identity remain user-authored. Misattributed Agent progress can otherwise become human `<user_feedback>` in later task runs.
+
+Check all four launch surfaces when changing this contract or adding a launcher:
+
+| Surface | Entry point |
+| ----------------------- | -------------------------------------------------------------------------------------------------------------------- |
+| CLI Agent dispatch | `apps/cli/src/device/agentRun.ts` β€” `spawnHeteroAgentRun` (Agent ID forwarded by `apps/cli/src/commands/connect.ts`) |
+| CLI OpenClaw/Hermes | `apps/cli/src/tools/heteroTask.ts` β€” `runHeteroTask` |
+| Desktop Agent dispatch | `apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts` β€” `spawnLhHeteroExec` |
+| Desktop OpenClaw/Hermes | `apps/desktop/src/main/controllers/GatewayConnectionCtr.ts` β€” `runHeteroTask` |
+
+Regression coverage must include a clean environment, conflicting ancestor identity, and missing current Agent/optional context. Check both OpenClaw and Hermes on CLI and Desktop, plus task comments after JWT fallback. Mocked spawn assertions verify environment construction, not end-to-end propagation through an external runtime.
+
## Common Bug Patterns
- Claude Code duplicates text or thinking:
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index 33ce2263047..a4df7e59ed2 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -996,6 +996,7 @@ function bindGatewayClientHandlers(
const ack = await maintenance.run(() =>
spawnHeteroAgentRun(
{
+ agentId: request.agentId,
agentType: request.agentType,
assistantMessageId: request.assistantMessageId,
args: request.args,
diff --git a/apps/cli/src/commands/task/lifecycle.test.ts b/apps/cli/src/commands/task/lifecycle.test.ts
index 7dc73076ed4..aa12ca56a5b 100644
--- a/apps/cli/src/commands/task/lifecycle.test.ts
+++ b/apps/cli/src/commands/task/lifecycle.test.ts
@@ -6,12 +6,14 @@ import { registerLifecycleCommands } from './lifecycle';
const { client, streamAgentEvents } = vi.hoisted(() => ({
client: {
task: {
+ addComment: { mutate: vi.fn() },
find: { query: vi.fn() },
heartbeat: { mutate: vi.fn() },
run: { mutate: vi.fn() },
update: { mutate: vi.fn() },
updateStatus: { mutate: vi.fn() },
},
+ topic: { getTopicDetail: { query: vi.fn() } },
},
streamAgentEvents: vi.fn(),
}));
@@ -32,6 +34,85 @@ const createProgram = () => {
return program;
};
+describe('task comment attribution', () => {
+ const comment = () =>
+ createProgram().parseAsync(['node', 'test', 'task', 'comment', 'T-1', '-m', 'Sync finished']);
+
+ beforeEach(() => {
+ vi.stubEnv('LOBEHUB_AGENT_ID', '');
+ vi.stubEnv('LOBEHUB_TOPIC_ID', '');
+ vi.stubEnv('LOBEHUB_OPERATION_ID', '');
+ vi.stubEnv('LOBEHUB_JWT', '');
+ client.task.addComment.mutate.mockReset();
+ client.topic.getTopicDetail.query.mockReset();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('keeps ordinary terminal comments user-authored', async () => {
+ await comment();
+
+ expect(client.task.addComment.mutate).toHaveBeenCalledWith({
+ content: 'Sync finished',
+ id: 'T-1',
+ });
+ expect(client.topic.getTopicDetail.query).not.toHaveBeenCalled();
+ });
+
+ it('uses the executing agent, not the task assignee', async () => {
+ vi.stubEnv('LOBEHUB_AGENT_ID', 'agt_writer');
+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc_current');
+
+ await comment();
+
+ expect(client.task.addComment.mutate).toHaveBeenCalledWith({
+ authorAgentId: 'agt_writer',
+ content: 'Sync finished',
+ id: 'T-1',
+ topicId: 'tpc_current',
+ });
+ expect(client.topic.getTopicDetail.query).not.toHaveBeenCalled();
+ });
+
+ it('preserves the dispatched author after JWT is cleared even when the topic belongs to another agent', async () => {
+ vi.stubEnv('LOBEHUB_AGENT_ID', 'agt_device');
+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc_device');
+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op_device');
+ client.topic.getTopicDetail.query.mockResolvedValue({ agentId: 'agt_topic_owner' });
+
+ await comment();
+
+ expect(client.topic.getTopicDetail.query).not.toHaveBeenCalled();
+ expect(client.task.addComment.mutate).toHaveBeenCalledWith({
+ authorAgentId: 'agt_device',
+ content: 'Sync finished',
+ id: 'T-1',
+ topicId: 'tpc_device',
+ });
+ });
+
+ it.each([null, { agentId: 'agt_topic_owner' }])(
+ 'does not infer the author from a topic (%j)',
+ async (topic) => {
+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc_missing');
+ client.topic.getTopicDetail.query.mockResolvedValue(topic);
+
+ await expect(comment()).rejects.toThrow('Cannot determine the agent author');
+ expect(client.topic.getTopicDetail.query).not.toHaveBeenCalled();
+ expect(client.task.addComment.mutate).not.toHaveBeenCalled();
+ },
+ );
+
+ it('refuses an agent run missing both agent and topic context', async () => {
+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op_incomplete');
+
+ await expect(comment()).rejects.toThrow('Cannot determine the agent author');
+ expect(client.task.addComment.mutate).not.toHaveBeenCalled();
+ });
+});
+
describe('task lifecycle β€” following the agent stream', () => {
let exitSpy: ReturnType<typeof vi.spyOn>;
diff --git a/apps/cli/src/commands/task/lifecycle.ts b/apps/cli/src/commands/task/lifecycle.ts
index c7e268dd290..ce0662469d3 100644
--- a/apps/cli/src/commands/task/lifecycle.ts
+++ b/apps/cli/src/commands/task/lifecycle.ts
@@ -197,7 +197,23 @@ export function registerLifecycleCommands(task: Command) {
.requiredOption('-m, --message <text>', 'Comment content')
.action(async (id: string, options: { message: string }) => {
const client = await getTrpcClient();
- await client.task.addComment.mutate({ content: options.message, id });
+ const topicId = process.env.LOBEHUB_TOPIC_ID?.trim() || undefined;
+ const authorAgentId = process.env.LOBEHUB_AGENT_ID?.trim() || undefined;
+
+ // The executing agent can differ from the topic owner or task assignee.
+ // Use only the identity injected by the run launcher, even after JWT fallback.
+ if (!authorAgentId && (topicId || process.env.LOBEHUB_OPERATION_ID)) {
+ throw new Error(
+ 'Cannot determine the agent author for this run. Refusing to post a task comment as the user. Update and restart the connector or desktop app, then start a new run.',
+ );
+ }
+
+ await client.task.addComment.mutate({
+ authorAgentId,
+ content: options.message,
+ id,
+ topicId,
+ });
log.info('Comment added.');
});
diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.ts
index fbb38ba6cf1..0b865cbef58 100644
--- a/apps/cli/src/device/agentRun.test.ts
+++ b/apps/cli/src/device/agentRun.test.ts
@@ -128,23 +128,27 @@ describe('spawnHeteroAgentRun', () => {
expect(child.stdin.end).toHaveBeenCalledTimes(1);
});
- it('replaces the launcher conversation context with the dispatched run', async () => {
- for (const key of ['AGENT', 'TASK', 'OPERATION', 'TOPIC', 'WORKSPACE', 'ASSISTANT_MESSAGE']) {
- vi.stubEnv(`LOBEHUB_${key}_ID`, `launcher-${key}`);
- }
- const child = makeFakeChild();
- spawnMock.mockReturnValue(child);
-
- const ack = spawnHeteroAgentRun({ ...baseParams, assistantMessageId: undefined });
- const env = spawnMock.mock.calls[0][2].env;
- expect(env.LOBEHUB_OPERATION_ID).toBe('op');
- expect(env.LOBEHUB_TOPIC_ID).toBe('tpc');
- for (const key of ['AGENT', 'TASK', 'WORKSPACE', 'ASSISTANT_MESSAGE']) {
- expect(env).not.toHaveProperty(`LOBEHUB_${key}_ID`);
- }
- child.emit('spawn');
- await expect(ack).resolves.toEqual({ status: 'accepted' });
- });
+ it.each([undefined, 'agt_dispatched'])(
+ 'replaces the launcher conversation context with dispatched agent %s',
+ async (agentId) => {
+ for (const key of ['AGENT', 'TASK', 'OPERATION', 'TOPIC', 'WORKSPACE', 'ASSISTANT_MESSAGE']) {
+ vi.stubEnv(`LOBEHUB_${key}_ID`, `launcher-${key}`);
+ }
+ const child = makeFakeChild();
+ spawnMock.mockReturnValue(child);
+
+ const ack = spawnHeteroAgentRun({ ...baseParams, agentId, assistantMessageId: undefined });
+ const env = spawnMock.mock.calls[0][2].env;
+ expect(env.LOBEHUB_OPERATION_ID).toBe('op');
+ expect(env.LOBEHUB_TOPIC_ID).toBe('tpc');
+ expect(env.LOBEHUB_AGENT_ID).toBe(agentId);
+ for (const key of ['TASK', 'WORKSPACE', 'ASSISTANT_MESSAGE']) {
+ expect(env).not.toHaveProperty(`LOBEHUB_${key}_ID`);
+ }
+ child.emit('spawn');
+ await expect(ack).resolves.toEqual({ status: 'accepted' });
+ },
+ );
it('starts the wrapper from home so its inner preflight can report a missing cwd', async () => {
const missingCwd = '/missing';
diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.ts
index a9260927a9b..acaa97ec439 100644
--- a/apps/cli/src/device/agentRun.ts
+++ b/apps/cli/src/device/agentRun.ts
@@ -11,6 +11,7 @@ import { getTask, removeTask, saveTask } from '../daemon/taskRegistry';
import { registerAgentRun } from './agentRunRegistry';
export interface SpawnHeteroAgentRunParams {
+ agentId?: string;
agentType: string;
/** Resolved `lh hetero exec` wrapper args. */
args?: string[];
@@ -143,6 +144,7 @@ export function spawnHeteroAgentRun(
detached: true,
env: {
...childEnv,
+ ...(params.agentId ? { LOBEHUB_AGENT_ID: params.agentId } : {}),
...(assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: assistantMessageId } : {}),
[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV]: '1',
LOBEHUB_JWT: jwt,
diff --git a/apps/cli/src/tools/__tests__/heteroTask.test.ts b/apps/cli/src/tools/__tests__/heteroTask.test.ts
index 5d6f12cf94a..7ac7fe62088 100644
--- a/apps/cli/src/tools/__tests__/heteroTask.test.ts
+++ b/apps/cli/src/tools/__tests__/heteroTask.test.ts
@@ -119,6 +119,57 @@ function makeMockChild(pid = 9999) {
// ─── Tests ───
+describe.each(['openclaw', 'hermes'] as const)('runHeteroTask (%s) identity', (agentType) => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ for (const key of Object.keys(taskStore)) delete taskStore[key];
+ execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
+ spawnMock.mockReturnValue(makeMockChild());
+ resetTrpcClientMock();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ { agentId: 'agent-current', inherited: false, workspaceId: 'workspace-current' },
+ { agentId: 'agent-current', inherited: true, workspaceId: 'workspace-current' },
+ { agentId: undefined, inherited: true, workspaceId: undefined },
+ ])('isolates dispatched identity ($agentId, inherited=$inherited)', async (params) => {
+ for (const key of [
+ 'AGENT_ID',
+ 'TOPIC_ID',
+ 'OPERATION_ID',
+ 'ASSISTANT_MESSAGE_ID',
+ 'TASK_ID',
+ 'WORKSPACE_ID',
+ ]) {
+ vi.stubEnv(`LOBEHUB_${key}`, params.inherited ? `ancestor-${key}` : undefined);
+ }
+
+ await runHeteroTask({
+ agentId: params.agentId,
+ agentType,
+ operationId: 'operation-current',
+ prompt: 'hello',
+ taskId: 'device-task-current',
+ topicId: 'topic-current',
+ workspaceId: params.workspaceId,
+ });
+
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ const env = spawnMock.mock.calls[0][2].env;
+ expect(env.LOBEHUB_AGENT_ID).toBe(params.agentId);
+ expect(env.LOBEHUB_TOPIC_ID).toBe('topic-current');
+ expect(env.LOBEHUB_OPERATION_ID).toBe('operation-current');
+ expect(env.LOBEHUB_WORKSPACE_ID).toBe(params.workspaceId);
+ expect(env.LOBEHUB_ASSISTANT_MESSAGE_ID).toBeUndefined();
+ expect(env.LOBEHUB_TASK_ID).toBeUndefined();
+ });
+});
+
describe('runHeteroTask (openclaw)', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/apps/cli/src/tools/heteroTask.ts b/apps/cli/src/tools/heteroTask.ts
index 28946dc4364..1fb2e4009a0 100644
--- a/apps/cli/src/tools/heteroTask.ts
+++ b/apps/cli/src/tools/heteroTask.ts
@@ -206,12 +206,24 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
} = params;
const workDir = cwd || process.cwd();
const lhPath = resolveLhPath();
+ // A connector may run inside another agent's conversation. Never reuse that identity.
+ const inheritedEnv = { ...process.env };
+ for (const key of [
+ 'LOBEHUB_AGENT_ID',
+ 'LOBEHUB_ASSISTANT_MESSAGE_ID',
+ 'LOBEHUB_TASK_ID',
+ 'LOBEHUB_WORKSPACE_ID',
+ ]) {
+ delete inheritedEnv[key];
+ }
// Propagate workspace scope into the spawned child so its own `lh notify`
// invocations (and any grandchildren it shells out) inherit the same scope
// via getTrpcClient β†’ resolveWorkspaceId.
const childEnv: NodeJS.ProcessEnv = {
- ...process.env,
+ ...inheritedEnv,
+ ...(agentId && { LOBEHUB_AGENT_ID: agentId }),
LOBEHUB_OPERATION_ID: operationId,
+ LOBEHUB_TOPIC_ID: topicId,
...(workspaceId && { LOBEHUB_WORKSPACE_ID: workspaceId }),
};
const sessionKey = parentOperationId ? operationId : topicId;
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 382dbe7efa8..810dbdc2028 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -867,15 +867,28 @@ export default class GatewayConnectionCtr extends ControllerModule {
this.remoteServerConfigCtr.getAccessToken(),
]);
+ // Never inherit the launcher's conversation identity for a dispatched run.
+ const inheritedEnv = { ...process.env };
+ for (const key of [
+ 'LOBEHUB_AGENT_ID',
+ 'LOBEHUB_ASSISTANT_MESSAGE_ID',
+ 'LOBEHUB_TASK_ID',
+ 'LOBEHUB_WORKSPACE_ID',
+ ]) {
+ delete inheritedEnv[key];
+ }
+
// Inject auth + workspace scope into child env so `lh notify` can
// authenticate AND target the same workspace as the dispatched topic
// (without LOBEHUB_WORKSPACE_ID, the CLI's notify falls back to personal
// mode and the workspace topic 404s).
const childEnv: NodeJS.ProcessEnv = {
- ...process.env,
+ ...inheritedEnv,
+ ...(agentId && { LOBEHUB_AGENT_ID: agentId }),
...(accessToken && { LOBEHUB_JWT: accessToken }),
LOBEHUB_OPERATION_ID: operationId,
...(serverUrl && { LOBEHUB_SERVER: serverUrl }),
+ LOBEHUB_TOPIC_ID: topicId,
...(workspaceId && { LOBEHUB_WORKSPACE_ID: workspaceId }),
};
const sessionKey = parentOperationId ? operationId : topicId;
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 404c56dcef4..63c1e75f1f3 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -4321,12 +4321,26 @@ export default class HeterogeneousAgentCtr {
});
}
+ // Never inherit the launcher's conversation identity for a dispatched run.
+ const childEnv = { ...process.env };
+ for (const key of [
+ 'LOBEHUB_AGENT_ID',
+ 'LOBEHUB_ASSISTANT_MESSAGE_ID',
+ 'LOBEHUB_TASK_ID',
+ 'LOBEHUB_WORKSPACE_ID',
+ ]) {
+ delete childEnv[key];
+ }
+
const env = {
- ...process.env,
+ ...childEnv,
...buildProxyEnv(this.app.storeManager.get('networkProxy')),
ELECTRON_RUN_AS_NODE: '1',
[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV]: '1',
+ ...(params.agentId ? { LOBEHUB_AGENT_ID: params.agentId } : {}),
LOBEHUB_JWT: jwt,
+ LOBEHUB_OPERATION_ID: operationId,
+ LOBEHUB_TOPIC_ID: topicId,
...(assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: assistantMessageId } : {}),
LOBEHUB_SERVER: serverUrl,
// Same reason `runHeteroTask` injects this for notify: without it the
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index 09d83c35ea0..041c9116208 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -1370,6 +1370,50 @@ describe('GatewayConnectionCtr', () => {
spawnMock.mockReset();
});
+ describe.each(['openclaw', 'hermes'])('%s identity', (agentType) => {
+ it.each([
+ { agentId: 'agent-current', inherited: false, workspaceId: 'workspace-current' },
+ { agentId: 'agent-current', inherited: true, workspaceId: 'workspace-current' },
+ { agentId: undefined, inherited: true, workspaceId: undefined },
+ ])('isolates dispatched identity ($agentId, inherited=$inherited)', async (params) => {
+ for (const key of [
+ 'AGENT_ID',
+ 'TOPIC_ID',
+ 'OPERATION_ID',
+ 'ASSISTANT_MESSAGE_ID',
+ 'TASK_ID',
+ 'WORKSPACE_ID',
+ ]) {
+ vi.stubEnv(`LOBEHUB_${key}`, params.inherited ? `ancestor-${key}` : undefined);
+ }
+ spawnMock.mockReturnValue(makeMockChild());
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'runHeteroTask',
+ {
+ agentId: params.agentId,
+ agentType,
+ operationId: 'operation-current',
+ prompt: 'hello',
+ taskId: 'device-task-current',
+ topicId: 'topic-current',
+ workspaceId: params.workspaceId,
+ },
+ 'req-identity',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ const env = spawnMock.mock.calls[0][2].env;
+ expect(env.LOBEHUB_AGENT_ID).toBe(params.agentId);
+ expect(env.LOBEHUB_TOPIC_ID).toBe('topic-current');
+ expect(env.LOBEHUB_OPERATION_ID).toBe('operation-current');
+ expect(env.LOBEHUB_WORKSPACE_ID).toBe(params.workspaceId);
+ expect(env.LOBEHUB_ASSISTANT_MESSAGE_ID).toBeUndefined();
+ expect(env.LOBEHUB_TASK_ID).toBeUndefined();
+ });
+ });
+
it('always injects buildNotifyProtocol into the prompt', async () => {
const child = makeMockChild();
spawnMock.mockReturnValue(child);
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 2bfb38a2642..a15e85d5b41 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -4789,6 +4789,44 @@ describe('HeterogeneousAgentCtr', () => {
expect(proc.stdin.end).toHaveBeenCalledOnce();
});
+ it.each([undefined, 'agt_dispatched'])(
+ 'replaces launcher identity with dispatched agent %s',
+ async (agentId) => {
+ for (const key of [
+ 'AGENT',
+ 'TASK',
+ 'OPERATION',
+ 'TOPIC',
+ 'WORKSPACE',
+ 'ASSISTANT_MESSAGE',
+ ]) {
+ vi.stubEnv(`LOBEHUB_${key}_ID`, `launcher-${key}`);
+ }
+ try {
+ const proc = createGatewayCliProc();
+ nextFakeProc = proc;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+
+ const ack = ctr.spawnLhHeteroExec({ ...params, agentId, assistantMessageId: undefined });
+ proc.emit('spawn');
+ await expect(ack).resolves.toEqual({ status: 'accepted' });
+
+ const env = spawnCalls[0].options.env;
+ expect(env.LOBEHUB_AGENT_ID).toBe(agentId);
+ expect(env.LOBEHUB_OPERATION_ID).toBe(params.operationId);
+ expect(env.LOBEHUB_TOPIC_ID).toBe(params.topicId);
+ for (const key of ['TASK', 'WORKSPACE', 'ASSISTANT_MESSAGE']) {
+ expect(env).not.toHaveProperty(`LOBEHUB_${key}_ID`);
+ }
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ },
+ );
+
it('forwards the topic workspace as LOBEHUB_WORKSPACE_ID for ingest', async () => {
const proc = createGatewayCliProc();
nextFakeProc = proc;
diff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
index 9b47420f295..f010d0ac7b7 100644
--- a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
@@ -29,10 +29,15 @@
* as "clear the variable", not `env -u`: devices run Windows too, and
* `pickAuthSource` only tests `LOBEHUB_JWT` for truthiness, so an empty value
* falls through to the stored login in every shell.
- * - **`LOBEHUB_AGENT_ID`.** Only the desktop client-mode path sets it
- * (`buildLobeHubSessionEnv`); `lh hetero exec` re-exports just the operation
- * and topic ids, and the `lh connect` daemon strips any ambient agent id so a
- * dispatched run cannot inherit its launcher's identity.
+ * - **`LOBEHUB_AGENT_ID`.** Desktop client mode sets it through
+ * `buildLobeHubSessionEnv`. CLI/Desktop dispatch launchers, including
+ * OpenClaw/Hermes, clear inherited identity and inject the current dispatch's
+ * agent id when supplied; a missing id must not retain the launcher's identity.
+ * Gateway-dispatched `lh hetero exec` runs preserve that id through
+ * `spawnAgent` to the external agent. Auth fallback (clearing `LOBEHUB_JWT`)
+ * does not change authorship. The id is still not guaranteed on every path:
+ * `lh task comment` refuses topic/operation contexts with a missing or blank
+ * agent id rather than attributing Agent output to the user.
*/
export const lobeHubCliGuide = [
'## LobeHub CLI (`lh`)',