π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(topic): parent topics, child-topic listing, and lh topic stop / archive / unarchive (#23317)
Bryan08004870b02e
diff --git a/apps/cli/src/commands/topic.ts b/apps/cli/src/commands/topic.tsindex 2d4d9413a19..39b8b9236fd 100644--- a/apps/cli/src/commands/topic.ts+++ b/apps/cli/src/commands/topic.ts@@ -8,6 +8,7 @@ import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/forimport { log } from '../utils/logger';import { resolveUrlBuilder, resourcePath, withUrls } from './resourceUrl';import { registerTopicExportCommand } from './topic/export';+import { registerTopicLifecycleCommands } from './topic/lifecycle';import { registerTopicSendCommand } from './topic/send';import { registerTopicViewCommand } from './topic/view';@@ -20,6 +21,14 @@ export function registerTopicCommand(program: Command) {.command('list').description('List topics').option('--agent-id <id>', 'Filter by agent ID')+ .option(+ '--parent-topic-id <tpc_id>',+ 'Only the topics opened from this one (its child topics), whatever their agent',+ )+ .option(+ '--opened-by-me',+ 'Only the topics this conversation opened (--parent-topic-id from LOBEHUB_TOPIC_ID)',+ ).option('-L, --limit <n>', 'Page size', '30').option('-P, --page <n>', 'Page number', '1').option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')@@ -28,12 +37,22 @@ export function registerTopicCommand(program: Command) {agentId?: string;json?: string | boolean;limit?: string;+ openedByMe?: boolean;page?: string;+ parentTopicId?: string;}) => {+ const parentTopicId =+ options.parentTopicId ?? (options.openedByMe ? process.env.LOBEHUB_TOPIC_ID : undefined);+ if (options.openedByMe && !parentTopicId) {+ log.error('--opened-by-me needs LOBEHUB_TOPIC_ID; pass --parent-topic-id instead.');+ process.exit(1);+ return;+ }const client = await getTrpcClient();const input: Record<string, any> = {};if (options.agentId) input.agentId = options.agentId;+ if (parentTopicId) input.openedByTopicId = parentTopicId;if (options.limit) input.pageSize = Number.parseInt(options.limit, 10);const page = options.page ? Number.parseInt(options.page, 10) : undefined;if (page !== undefined && page > 1) input.current = page - 1;@@ -57,6 +76,20 @@ export function registerTopicCommand(program: Command) {return;}+ // Child topics may run other agents: say which.+ if (parentTopicId) {+ printTable(+ items.map((t: any) => [+ t.id || '',+ truncate(t.title || 'Untitled', 50),+ t.agentId || '',+ t.updatedAt ? timeAgo(t.updatedAt) : '',+ ]),+ ['ID', 'TITLE', 'AGENT', 'UPDATED'],+ );+ return;+ }+const rows = items.map((t: any) => [t.id || '',truncate(t.title || 'Untitled', 50),@@ -355,4 +388,5 @@ export function registerTopicCommand(program: Command) {registerTopicExportCommand(topic);registerTopicViewCommand(topic);registerTopicSendCommand(topic);+ registerTopicLifecycleCommands(topic);}diff --git a/apps/cli/src/commands/topic/lifecycle.test.ts b/apps/cli/src/commands/topic/lifecycle.test.tsnew file mode 100644index 00000000000..382a85fabd5--- /dev/null+++ b/apps/cli/src/commands/topic/lifecycle.test.ts@@ -0,0 +1,111 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../utils/logger';+import { registerTopicCommand } from '../topic';++const { client, mockGetTrpcClient } = vi.hoisted(() => ({+ client: {+ aiAgent: { interruptTask: { mutate: vi.fn() } },+ topic: { getTopics: { query: vi.fn() }, updateTopic: { mutate: vi.fn() } },+ },+ mockGetTrpcClient: vi.fn(),+}));++vi.mock('../../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+vi.mock('../../api/workspaceRef', () => ({ resolveWorkspaceRef: vi.fn(async () => undefined) }));+vi.mock('./resourceUrl', () => ({+ resolveUrlBuilder: vi.fn(async () => undefined),+ resourcePath: { topic: vi.fn() },+ withUrls: (items: unknown[]) => items,+}));++const run = async (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerTopicCommand(program);+ await program.parseAsync(['node', 'lh', ...args]);+};++describe('topic lifecycle and child topics', () => {+ let exit: ReturnType<typeof vi.spyOn>;+ let logged: string[];++ beforeEach(() => {+ mockGetTrpcClient.mockResolvedValue(client);+ client.topic.getTopics.query.mockResolvedValue({ items: [], total: 0 });+ logged = [];+ vi.spyOn(console, 'log').mockImplementation((...parts) => {+ logged.push(parts.join(' '));+ });+ exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ });++ afterEach(() => {+ vi.mocked(log.error).mockClear();+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+ });++ it("stops the topic's runs through the existing interrupt entry", async () => {+ client.aiAgent.interruptTask.mutate.mockResolvedValue({+ running: 1,+ stopped: 1,+ success: true,+ });++ await run('topic', 'stop', 'tpc-a');++ expect(client.aiAgent.interruptTask.mutate).toHaveBeenCalledWith({ topicId: 'tpc-a' });+ expect(logged.join('\n')).toMatch(/Stopped tpc-a/);+ });++ it('fails when a run could not be confirmed stopped', async () => {+ client.aiAgent.interruptTask.mutate.mockResolvedValue({+ running: 1,+ stopped: 0,+ success: false,+ });++ await run('topic', 'stop', 'tpc-a');++ expect(vi.mocked(log.error).mock.calls[0][0]).toMatch(/could not be confirmed stopped/);+ expect(exit).toHaveBeenCalledWith(1);+ });++ it('archives and unarchives through topic.updateTopic, like the app', async () => {+ await run('topic', 'archive', 'tpc-a');+ expect(client.topic.updateTopic.mutate).toHaveBeenCalledWith({+ id: 'tpc-a',+ value: { completedAt: expect.any(Date), status: 'completed' },+ });++ await run('topic', 'unarchive', 'tpc-a');+ expect(client.topic.updateTopic.mutate).toHaveBeenLastCalledWith({+ id: 'tpc-a',+ value: { completedAt: null, status: 'active' },+ });+ });++ it('lists the child topics of a parent, or of the running conversation', async () => {+ await run('topic', 'list', '--parent-topic-id', 'tpc-parent');+ expect(client.topic.getTopics.query).toHaveBeenLastCalledWith(+ expect.objectContaining({ openedByTopicId: 'tpc-parent' }),+ );++ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc-here');+ await run('topic', 'list', '--opened-by-me');+ expect(client.topic.getTopics.query).toHaveBeenLastCalledWith(+ expect.objectContaining({ openedByTopicId: 'tpc-here' }),+ );+ });++ it('needs a conversation for --opened-by-me', async () => {+ vi.stubEnv('LOBEHUB_TOPIC_ID', '');++ await run('topic', 'list', '--opened-by-me');++ expect(exit).toHaveBeenCalledWith(1);+ expect(client.topic.getTopics.query).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/commands/topic/lifecycle.ts b/apps/cli/src/commands/topic/lifecycle.tsnew file mode 100644index 00000000000..79c9ad2cb50--- /dev/null+++ b/apps/cli/src/commands/topic/lifecycle.ts@@ -0,0 +1,83 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../api/client';+import { resolveWorkspaceRef } from '../../api/workspaceRef';+import { outputJson } from '../../utils/format';+import { log } from '../../utils/logger';++/** Print a refusal and exit 1 instead of a stack trace. */+const run = async (fn: () => Promise<void>) => {+ try {+ await fn();+ } catch (error) {+ log.error((error as Error).message);+ process.exit(1);+ }+};++const WORKSPACE_OPTION_HELP = "Workspace (overrides LOBEHUB_WORKSPACE_ID and 'workspace use')";++/**+ * A topic's lifecycle from the CLI: stop its running turn, archive it, or bring+ * it back β through the same entries the app's own buttons use+ * (`aiAgent.interruptTask`, `topic.updateTopic`).+ */+export function registerTopicLifecycleCommands(topic: Command) {+ topic+ .command('stop <topicId>')+ .description("Stop the topic's running turn (the ones you started)")+ .option('--workspace <id|slug>', WORKSPACE_OPTION_HELP)+ .option('--json', 'Output JSON')+ .action((topicId: string, options: { json?: boolean; workspace?: string }) =>+ run(async () => {+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));+ const result = (await client.aiAgent.interruptTask.mutate({ topicId })) as {+ running?: number;+ stopped?: number;+ success: boolean;+ };+ if (options.json) return outputJson(result);+ if (!result.success) {+ throw new Error(+ `${topicId}: ${(result.running ?? 0) - (result.stopped ?? 0)} run(s) could not be confirmed stopped (a device may still be running them). Try again once the device is reachable.`,+ );+ }+ console.log(+ result.stopped ? `${pc.green('β')} Stopped ${topicId}.` : `${topicId} was not running.`,+ );+ }),+ );++ topic+ .command('archive <topicId>')+ .description(+ 'Archive a topic: it leaves the agent list, and its auto-created worktree is cleaned up',+ )+ .option('--workspace <id|slug>', WORKSPACE_OPTION_HELP)+ .action((topicId: string, options: { workspace?: string }) =>+ run(async () => {+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));+ await client.topic.updateTopic.mutate({+ id: topicId,+ value: { completedAt: new Date(), status: 'completed' },+ });+ console.log(`${pc.green('β')} Archived ${topicId}.`);+ }),+ );++ topic+ .command('unarchive <topicId>')+ .description('Bring an archived topic back to the agent list')+ .option('--workspace <id|slug>', WORKSPACE_OPTION_HELP)+ .action((topicId: string, options: { workspace?: string }) =>+ run(async () => {+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));+ await client.topic.updateTopic.mutate({+ id: topicId,+ value: { completedAt: null, status: 'active' },+ });+ console.log(`${pc.green('β')} Unarchived ${topicId}.`);+ }),+ );+}diff --git a/apps/cli/src/commands/topic/send.newConversation.test.ts b/apps/cli/src/commands/topic/send.newConversation.test.tsindex 390a5af06f8..d33ec37cb76 100644--- a/apps/cli/src/commands/topic/send.newConversation.test.ts+++ b/apps/cli/src/commands/topic/send.newConversation.test.ts@@ -76,6 +76,8 @@ describe('sending into a new conversation', () => {expect(client.aiAgent.execAgent.mutate).toHaveBeenCalledWith({agentId: 'agt-self',+ // Opened from inside a conversation: it becomes the new topic's parent.+ openedByTopicId: 'tpc-here',prompt: 'Draft the release notes',sourceOperationId: 'op-sender',trigger: 'cli',@@ -92,6 +94,39 @@ describe('sending into a new conversation', () => {});});+ describe('the parent topic', () => {+ const request = () => client.aiAgent.execAgent.mutate.mock.calls[0][0];++ it('takes --parent-topic-id over the conversation running the command', async () => {+ await run('topic', 'send', '--new', '-c', 'x', '--parent-topic-id', 'tpc-other');++ expect(request().openedByTopicId).toBe('tpc-other');+ });++ it('links none with --detach', async () => {+ await run('topic', 'send', '--new', '-c', 'x', '--detach');++ expect(request()).not.toHaveProperty('openedByTopicId');+ });++ it('links none outside a conversation', async () => {+ vi.stubEnv('LOBEHUB_TOPIC_ID', '');++ await run('topic', 'send', '--new', '-c', 'x');++ expect(request()).not.toHaveProperty('openedByTopicId');+ });++ it('refuses --parent-topic-id with --detach, and both on an existing topic', async () => {+ await run('topic', 'send', '--new', '-c', 'x', '--detach', '--parent-topic-id', 'tpc-p');+ expect(errorLogged()).toMatch(/either --parent-topic-id or --detach/);++ await run('topic', 'send', 'tpc-target', '-c', 'x', '--detach');+ expect(errorLogged()).toMatch(/only apply with --new/);+ expect(client.aiAgent.execAgent.mutate).not.toHaveBeenCalled();+ });+ });+it('runs the new conversation on the named device, with the given agent and title', async () => {await run('topic',diff --git a/apps/cli/src/commands/topic/send.ts b/apps/cli/src/commands/topic/send.tsindex ecaec2e3dde..03877a7ffc8 100644--- a/apps/cli/src/commands/topic/send.ts+++ b/apps/cli/src/commands/topic/send.ts@@ -164,11 +164,23 @@ export const sendToNewConversation = async (params: {agentId?: string;content: string;+ /** Open a topic linked to no parent, even from inside a conversation. */+ detach?: boolean;device?: string;+ /** The parent topic; overrides `LOBEHUB_TOPIC_ID`. */+ parentTopicId?: string;title?: string;},): Promise<ConversationSendResult> => {const agentId = params.agentId ?? process.env.LOBEHUB_AGENT_ID;+ if (params.detach && params.parentTopicId) {+ throw new Error('Pass either --parent-topic-id or --detach, not both.');+ }+ // The parent: an explicit --parent-topic-id, else the conversation running+ // this command, else none; --detach links none.+ const parentTopicId = params.detach+ ? undefined+ : params.parentTopicId || process.env.LOBEHUB_TOPIC_ID || undefined;if (!agentId) {throw new Error('No agent to start the new conversation with: pass --agent-id (LOBEHUB_AGENT_ID is not set).',@@ -189,6 +201,9 @@ export const sendToNewConversation = async (request.requireDevice = true;}if (params.title) request.title = params.title;+ // Recorded as the new topic's `metadata.openedBy`: it lists under its parent+ // (`lh topic list --parent-topic-id`).+ if (parentTopicId) request.openedByTopicId = parentTopicId;const sourceOperationId = process.env.LOBEHUB_OPERATION_ID;if (sourceOperationId) request.sourceOperationId = sourceOperationId;@@ -271,6 +286,14 @@ export function registerTopicSendCommand(topic: Command) {.option('--agent-id <id>', `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.agentId}`).option('--device <target>', `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.device}`).option('--title <title>', `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.title}`)+ .option(+ '--parent-topic-id <tpc_id>',+ 'With --new: the parent topic the new one lists under (default: the conversation running this command, LOBEHUB_TOPIC_ID)',+ )+ .option(+ '--detach',+ 'With --new: link the new topic to no parent, even from inside a conversation',+ ).option('--workspace <id|slug>',"The workspace the topic lives in (overrides LOBEHUB_WORKSPACE_ID and 'workspace use')",@@ -282,6 +305,11 @@ export function registerTopicSendCommand(topic: Command) {Examples:lh topic send tpc_xxx -c "Iterate the verifier with these notes"lh topic send --new -c "Draft the release notes" --device local --title "Release notes"+ lh topic send --new -c "Check the flaky test" --parent-topic-id tpc_xxx++Run from inside a conversation, --new opens a topic linked to it as its parent+('lh topic list --parent-topic-id <id>' lists them); --detach opens one that+stands on its own.Run by an agent, the message is shown as written by that agent, and thereceiving agent can answer it with 'lh message reply <messageId>', which wakes@@ -293,8 +321,10 @@ after a few rounds, so a person can step in.`,topicId: string | undefined,options: NewConversationOptions & {content: string;+ detach?: boolean;json?: boolean;new?: boolean;+ parentTopicId?: string;workspace?: string;},) => {@@ -307,9 +337,15 @@ after a few rounds, so a person can step in.`,if (!topicId) {throw new Error('Pass the <topicId> to send to, or --new to open a new conversation.');}- if (options.agentId || options.device || options.title) {+ if (+ options.agentId ||+ options.device ||+ options.title ||+ options.parentTopicId ||+ options.detach+ ) {throw new Error(- '--agent-id, --device and --title only apply with --new; an existing conversation keeps its own.',+ '--agent-id, --device, --title, --parent-topic-id and --detach only apply with --new; an existing conversation keeps its own.',);}return sendToConversation(client, { content: options.content, topicId });diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTopic.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTopic.test.tsnew file mode 100644index 00000000000..86edb2b0b14--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTopic.test.ts@@ -0,0 +1,104 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { agents, topics } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { aiAgentRouter } from '../aiAgent';+import { cleanupTestUser, createTestUser } from './integration/setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return testDB;+ }),+}));++const mocks = vi.hoisted(() => ({+ findOwnLiveRuns: vi.fn(),+ interruptOperation: vi.fn(),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(function () {+ return { interruptOperation: mocks.interruptOperation };+ }),+}));+vi.mock('@/server/services/aiChat', () => ({+ AiChatService: vi.fn().mockImplementation(function () {+ return {};+ }),+}));+vi.mock('@/server/services/aiAgent/steerQueue/liveRuns', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ findOwnLiveRuns: mocks.findOwnLiveRuns,+}));++describe('aiAgentRouter.interruptTask β by topic', () => {+ let serverDB: LobeChatDatabase;+ let userId: string;+ let topicId: string;++ beforeEach(async () => {+ serverDB = await getTestDB();+ testDB = serverDB;+ userId = await createTestUser(serverDB);+ mocks.interruptOperation.mockReset();+ mocks.interruptOperation.mockResolvedValue(true);+ mocks.findOwnLiveRuns.mockReset();++ const [agent] = await serverDB.insert(agents).values({ title: 'A', userId }).returning();+ const [topic] = await serverDB+ .insert(topics)+ .values({ agentId: agent.id, title: 'T', userId })+ .returning();+ topicId = topic.id;+ });++ afterEach(async () => {+ await cleanupTestUser(serverDB, userId);+ vi.clearAllMocks();+ });++ const caller = () => aiAgentRouter.createCaller({ jwtPayload: { userId }, userId } as any);++ it("stops every live run the caller owns on the topic's main line", async () => {+ mocks.findOwnLiveRuns.mockResolvedValue(['op-a', 'op-b']);++ const result = await caller().interruptTask({ topicId });++ expect(mocks.findOwnLiveRuns).toHaveBeenCalledWith(expect.anything(), {+ threadId: null,+ topicId,+ userId,+ });+ expect(mocks.interruptOperation).toHaveBeenCalledTimes(2);+ expect(result).toMatchObject({ running: 2, stopped: 2, success: true });+ });++ it('reports nothing running as a successful no-op', async () => {+ mocks.findOwnLiveRuns.mockResolvedValue([]);++ expect(await caller().interruptTask({ topicId })).toMatchObject({+ running: 0,+ stopped: 0,+ success: true,+ });+ expect(mocks.interruptOperation).not.toHaveBeenCalled();+ });++ it('says so when a run could not be confirmed stopped', async () => {+ mocks.findOwnLiveRuns.mockResolvedValue(['op-a']);+ mocks.interruptOperation.mockResolvedValue(false);++ expect(await caller().interruptTask({ topicId })).toMatchObject({+ running: 1,+ stopped: 0,+ success: false,+ });+ });++ it('still requires one of thread, operation or topic', async () => {+ await expect(caller().interruptTask({} as any)).rejects.toThrow();+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.tsindex 50853c88608..3bcafe230d4 100644--- a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts@@ -324,6 +324,49 @@ describe('Topic Router Integration Tests', () => {});describe('getTopics', () => {+ it('lists the child topics of a parent across agents, leaving out unlinked ones', async () => {+ const caller = topicRouter.createCaller(createTestContext(userId));+ const { agents } = await import('@/database/schemas');+ const [otherAgent] = await serverDB+ .insert(agents)+ .values({ title: 'Other Agent', userId })+ .returning();+ const link = (topicId: string, extra: Record<string, unknown> = {}) => ({+ openedBy: { agentId: testAgentId, at: '2026-11-18T00:00:00.000Z', topicId, ...extra },+ });+ const [parent] = await serverDB+ .insert(topics)+ .values({ agentId: testAgentId, title: 'Parent', userId })+ .returning();+ await serverDB.insert(topics).values([+ { agentId: testAgentId, metadata: link(parent.id), title: 'Same agent', userId },+ { agentId: otherAgent.id, metadata: link(parent.id), title: 'Other agent', userId },+ {+ agentId: testAgentId,+ metadata: link(parent.id, { detachedAt: '2026-11-18T01:00:00.000Z' }),+ title: 'Unlinked',+ userId,+ },+ { agentId: testAgentId, title: 'Unrelated', userId },+ ]);++ const result = await caller.getTopics({ openedByTopicId: parent.id });++ expect(result.items.map((t: any) => t.title).sort()).toEqual(['Other agent', 'Same agent']);+ expect(result.total).toBe(2);+ // A child may run another agent: the row says which.+ expect(result.items.find((t: any) => t.title === 'Other agent')).toMatchObject({+ agentId: otherAgent.id,+ });++ // `agentId` still narrows it.+ const narrowed = await caller.getTopics({+ agentId: otherAgent.id,+ openedByTopicId: parent.id,+ });+ expect(narrowed.items.map((t: any) => t.title)).toEqual(['Other agent']);+ });+it('should get topics by agentId', async () => {const caller = topicRouter.createCaller(createTestContext(userId));diff --git a/apps/server/src/routers/lambda/aiAgent/exec.ts b/apps/server/src/routers/lambda/aiAgent/exec.tsindex 923453f0855..7d1d3121ea3 100644--- a/apps/server/src/routers/lambda/aiAgent/exec.ts+++ b/apps/server/src/routers/lambda/aiAgent/exec.ts@@ -278,6 +278,8 @@ export const execRouter = router({...(resumeApprovals ?? []).map((decision) => decision.parentMessageId),resumeToolResult?.parentMessageId,],+ // The topic this one is opened from receives its reports: authorize it too.+ openedByTopicId: input.openedByTopicId,topicId: appContext?.topicId,userId: ctx.userId,workspaceId: ctx.workspaceId,diff --git a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts b/apps/server/src/routers/lambda/aiAgent/execSchemas.tsindex 61039ed9db5..2c15b21fe18 100644--- a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts+++ b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts@@ -340,6 +340,13 @@ export const ExecAgentFieldsSchema = z.object({* or topic-less operation simply resolves to nothing.*/sourceOperationId: z.string().optional(),+ /**+ * The conversation this new topic is opened from (its parent topic;+ * `lh topic send --new` passes `--parent-topic-id` or its own+ * `LOBEHUB_TOPIC_ID`): the topic records it as `metadata.openedBy` and lists+ * under it. Needs `use` on that topic.+ */+ openedByTopicId: z.string().optional(),/*** User intervention configuration for tool approvals.* Pass `{ approvalMode: 'headless' }` from headless clients (CLI, cron, bots)diff --git a/apps/server/src/routers/lambda/aiAgent/guards.test.ts b/apps/server/src/routers/lambda/aiAgent/guards.test.tsnew file mode 100644index 00000000000..2c6c93032ce--- /dev/null+++ b/apps/server/src/routers/lambda/aiAgent/guards.test.ts@@ -0,0 +1,68 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ assertCanUseMessageTargets,+ assertCanUseTopicTargets,+} from '@/server/routers/lambda/_helpers/conversationResourceGuard';++import { assertCanUseAgentRunConversation } from './guards';++vi.mock('@/server/routers/lambda/_helpers/conversationResourceGuard', () => ({+ assertCanUseMessageTargets: vi.fn(async () => []),+ assertCanUseTopicTargets: vi.fn(async () => []),+}));++const db = {} as any;++describe('assertCanUseAgentRunConversation', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('authorizes the topic a new topic is opened from, alongside the conversation', async () => {+ await assertCanUseAgentRunConversation({+ db,+ openedByTopicId: 'tpc_opener',+ topicId: 'tpc_conversation',+ userId: 'user-1',+ workspaceId: 'ws-1',+ });++ expect(assertCanUseTopicTargets).toHaveBeenCalledWith(+ { db, userId: 'user-1', workspaceId: 'ws-1' },+ ['tpc_conversation', 'tpc_opener'],+ );+ });++ it('authorizes the opener of a brand-new topic on its own', async () => {+ await assertCanUseAgentRunConversation({+ db,+ openedByTopicId: 'tpc_opener',+ userId: 'user-1',+ workspaceId: 'ws-1',+ });++ expect(assertCanUseTopicTargets).toHaveBeenCalledWith(expect.anything(), ['tpc_opener']);+ });++ it('refuses when the caller may not use the opener', async () => {+ vi.mocked(assertCanUseTopicTargets).mockRejectedValueOnce(new Error('FORBIDDEN'));++ await expect(+ assertCanUseAgentRunConversation({+ db,+ openedByTopicId: 'tpc_view_only',+ userId: 'user-1',+ workspaceId: 'ws-1',+ }),+ ).rejects.toThrow('FORBIDDEN');+ });++ it('checks nothing outside a workspace, where every topic is the caller own', async () => {+ await assertCanUseAgentRunConversation({ db, openedByTopicId: 'tpc_opener', userId: 'user-1' });++ expect(assertCanUseTopicTargets).not.toHaveBeenCalled();+ expect(assertCanUseMessageTargets).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/aiAgent/guards.ts b/apps/server/src/routers/lambda/aiAgent/guards.tsindex 9b7af639b47..a4f76012cc7 100644--- a/apps/server/src/routers/lambda/aiAgent/guards.ts+++ b/apps/server/src/routers/lambda/aiAgent/guards.ts@@ -121,18 +121,25 @@ export const assertCanUseOperationAgent = async (params: {export const assertCanUseAgentRunConversation = async (params: {db: LobeChatDatabase;messageIds?: Array<string | null | undefined>;+ /**+ * The topic a new topic is opened from (`openedByTopicId`): it receives the+ * new topic's reports and is woken by them, so it needs `use` like the+ * conversation itself.+ */+ openedByTopicId?: string | null;topicId?: string | null;userId: string;workspaceId?: string | null;}) => {- const { db, messageIds = [], topicId, userId, workspaceId } = params;+ const { db, messageIds = [], openedByTopicId, topicId, userId, workspaceId } = params;if (!workspaceId) return;const uniqueMessageIds = [...new Set(messageIds.filter(Boolean) as string[])];- // Fixed two-call tuple, not a per-id fan-out: `assertCanUseMessageTargets`- // resolves every message id in one batched `inArray` query.+ const topicIds = [...new Set([topicId, openedByTopicId].filter(Boolean) as string[])];+ // Fixed two-call tuple, not a per-id fan-out: both guards resolve their ids+ // in one batched `inArray` query.await Promise.all([- assertCanUseTopicTargets({ db, userId, workspaceId }, topicId ? [topicId] : []),+ assertCanUseTopicTargets({ db, userId, workspaceId }, topicIds),assertCanUseMessageTargets({ db, userId, workspaceId }, uniqueMessageIds),]);};diff --git a/apps/server/src/routers/lambda/aiAgent/runControl.ts b/apps/server/src/routers/lambda/aiAgent/runControl.tsindex 319fe64e199..f24b8826fe1 100644--- a/apps/server/src/routers/lambda/aiAgent/runControl.ts+++ b/apps/server/src/routers/lambda/aiAgent/runControl.ts@@ -3,12 +3,25 @@ import debug from 'debug';import { z } from 'zod';import { router } from '@/libs/trpc/lambda';+import { findOwnLiveRuns } from '@/server/services/aiAgent/steerQueue/liveRuns';-import { assertCanUseOperationAgent } from './guards';+import { assertCanUseAgentRunConversation, assertCanUseOperationAgent } from './guards';import { aiAgentWriteProcedure } from './procedures';const log = debug('lobe-server:ai-agent-router');+/** What `interruptTask` answers; `running` / `stopped` are set when it stopped a whole topic. */+type InterruptTaskResult = {+ deviceCancellationConfirmed?: boolean;+ operationId?: string;+ /** Live runs found on the topic (topic-only stop). */+ running?: number;+ /** Of those, the ones confirmed stopped. */+ stopped?: number;+ success: boolean;+ threadId?: string;+};+/*** Schema for interruptTask - interrupt a running task*/@@ -22,11 +35,13 @@ const InterruptTaskSchema = z* Topic ID β used to cancel device-backed heterogeneous agent tasks.* When provided and the topic's runningOperation has a deviceId, the server* will dispatch a cancelHeteroTask tool call to kill the device process.+ * On its own (no operation or thread), stops every live run the caller+ * owns on the topic's main line (`lh topic stop`).*/topicId: z.string().optional(),})- .refine((data) => data.threadId || data.operationId, {- message: 'Either threadId or operationId must be provided',+ .refine((data) => data.threadId || data.operationId || data.topicId, {+ message: 'Either threadId, operationId or topicId must be provided',});/**@@ -48,11 +63,38 @@ const StartExecutionSchema = z.object({export const runControlRouter = router({interruptTask: aiAgentWriteProcedure.input(InterruptTaskSchema)- .mutation(async ({ input, ctx }) => {+ .mutation(async ({ input, ctx }): Promise<InterruptTaskResult> => {const { threadId, operationId, topicId } = input;log('interruptTask: threadId=%s, operationId=%s, topicId=%s', threadId, operationId, topicId);+ // A topic alone: stop the caller's own live runs on its main line.+ if (!operationId && !threadId && topicId) {+ await assertCanUseAgentRunConversation({+ db: ctx.serverDB,+ topicId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ const runIds = await findOwnLiveRuns(+ { db: ctx.serverDB, workspaceId: ctx.workspaceId ?? undefined },+ { threadId: null, topicId, userId: ctx.userId },+ );+ let stopped = 0;+ for (const runId of runIds) {+ const result = await ctx.aiAgentService.interruptTask({ operationId: runId, topicId });+ if (result.success) stopped += 1;+ }+ // `success: false` when a run could not be confirmed stopped (a device+ // process that did not answer): it stays live so the stop can be retried.+ return {+ operationId: runIds[0],+ running: runIds.length,+ stopped,+ success: stopped === runIds.length,+ };+ }+try {return await ctx.aiAgentService.interruptTask({ operationId, threadId, topicId });} catch (error: any) {diff --git a/apps/server/src/routers/lambda/topic/queries.ts b/apps/server/src/routers/lambda/topic/queries.tsindex 3f5e56b7c04..8cc6911d764 100644--- a/apps/server/src/routers/lambda/topic/queries.ts+++ b/apps/server/src/routers/lambda/topic/queries.ts@@ -17,11 +17,36 @@ import { router } from '@/libs/trpc/lambda';import { TopicReferenceService } from '@/server/services/topicReference';import { after } from '@/server/utils/scheduleAfterResponse';-import { assertCanUseConversationTargets } from '../_helpers/conversationResourceGuard';+import {+ assertCanUseConversationTargets,+ assertCanViewConversationTargets,+ assertCanViewTopicTargets,+} from '../_helpers/conversationResourceGuard';import { batchResolveAgentIdFromSessions, resolveContext } from '../_helpers/resolveContext';import { guardCtx, topicProcedure, topicSearchProcedure } from './procedures';import { readTopicTranscript, topicTranscriptInput } from './transcript';+/**+ * Child topics may run any agent of the workspace: the ones among `agentIds`+ * the caller may view (another member's private agent stays hidden).+ */+const viewableAgentIds = async (+ ctx: Parameters<typeof guardCtx>[0],+ agentIds: string[],+): Promise<string[]> => {+ const viewable: string[] = [];+ // A topic's children run few distinct agents; each check is a lookup.+ for (const agentId of agentIds) {+ try {+ await assertCanViewConversationTargets(guardCtx(ctx), [{ agentId }]);+ viewable.push(agentId);+ } catch {+ // Not viewable: left out.+ }+ }+ return viewable;+};+export const queryRouter = router({getTopicDetail: topicProcedure.input(z.object({ id: z.string() }))@@ -103,6 +128,12 @@ export const queryRouter = router({isInbox: z.boolean().optional(),/** Only topics the caller created β the workspace "only mine" filter. */onlyMine: z.boolean().optional(),+ /**+ * Only the topics opened from this one (its child topics), whatever+ * their agent. Needs `view` on that topic; children whose agent the+ * caller may not view are left out.+ */+ openedByTopicId: z.string().nullish(),pageSize: z.number().max(100).optional(),sessionId: z.string().nullish(),/**@@ -128,9 +159,33 @@ export const queryRouter = router({excludeTriggers,includeTriggers,triggers,+ openedByTopicId,...rest} = input;+ // Child topics of one topic: authorized on the parent, then per child agent.+ if (openedByTopicId) {+ await assertCanViewTopicTargets(guardCtx(ctx), [openedByTopicId]);+ // Decide which child agents the caller may view first, so paging and+ // the total only ever count what can be shown.+ const openedByAgentIds = ctx.workspaceId+ ? await viewableAgentIds(+ ctx,+ await ctx.topicModel.listChildTopicAgentIds(openedByTopicId),+ )+ : undefined;+ const result = await ctx.topicModel.query({+ excludeStatuses,+ excludeTriggers,+ includeTriggers,+ openedByAgentIds,+ openedByTopicId,+ triggers,+ ...rest,+ });+ return { items: result.items, total: result.total };+ }+// If groupId is provided, query by groupId directlyif (groupId) {const result = await ctx.topicModel.query({diff --git a/apps/server/src/services/aiAgent/composerRun.ts b/apps/server/src/services/aiAgent/composerRun.tsindex a0f76669d4b..a67a5251acd 100644--- a/apps/server/src/services/aiAgent/composerRun.ts+++ b/apps/server/src/services/aiAgent/composerRun.ts@@ -30,6 +30,7 @@ export type ComposerRunRequest = Pick<| 'llmExecutor'| 'localDeviceId'| 'mentionedAgents'+ | 'openedByTopicId'| 'parentMessageId'| 'prompt'| 'queuedSuccessor'@@ -158,6 +159,7 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerR}),fileIds: input.fileIds,mentionedAgents: input.mentionedAgents,+ openedByTopicId: input.openedByTopicId,parentMessageId,prompt: input.prompt,queuedSuccessor: input.queuedSuccessor,diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.tsindex 45ca96aba7d..57ed4e44ea4 100644--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts@@ -139,6 +139,7 @@ export const execAgentTurn = async (trigger,cronJobId,webhookThread,+ openedByTopicId,taskId,evalContext,evalRuntime,@@ -453,6 +454,7 @@ export const execAgentTurn = async (externalOrigin,cronJobId,webhookThread,+ openedByTopicId,files,modelOverride,operationTaskId,diff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.tsindex a71c9994252..71e33ce2de6 100644--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts@@ -1,7 +1,7 @@// @vitest-environment node-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-import { buildNewTopicMetadata } from './newTopicMetadata';+import { buildNewTopicMetadata, resolveTopicOpenedBy } from './newTopicMetadata';const worktree = '/Users/me/.lobehub/worktrees/lobehub-0000beef/quiet-hill';const prepared = {@@ -75,6 +75,35 @@ describe('buildNewTopicMetadata β project directory', () => {});});+describe('sub-topic link (metadata.openedBy)', () => {+ it('records the opener read through the caller scope', async () => {+ const findById = vi.fn().mockResolvedValue({ agentId: 'agt_parent', id: 'tpc_parent' });++ const openedBy = await resolveTopicOpenedBy({ findById } as any, 'tpc_parent');++ expect(findById).toHaveBeenCalledWith('tpc_parent');+ expect(openedBy).toEqual({+ agentId: 'agt_parent',+ at: expect.any(String),+ topicId: 'tpc_parent',+ });+ expect(buildNewTopicMetadata({ openedBy })).toEqual(expect.objectContaining({ openedBy }));+ });++ it('records nothing for an unknown or unreadable opener', async () => {+ expect(+ await resolveTopicOpenedBy({ findById: vi.fn().mockResolvedValue(undefined) } as any, 'x'),+ ).toBeUndefined();+ expect(+ await resolveTopicOpenedBy(+ { findById: vi.fn().mockRejectedValue(new Error('no')) } as any,+ 'x',+ ),+ ).toBeUndefined();+ expect(await resolveTopicOpenedBy({ findById: vi.fn() } as any, undefined)).toBeUndefined();+ });+});+// A draft's first send in a project: the composer's placement and whether it// was picked must both reach `withProjectSandbox`, which decides from them// whether the project's environment applies.diff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.tsindex dffe7290abc..9a3e03dedc4 100644--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts@@ -1,6 +1,8 @@-import type { WorkingDirConfig } from '@lobechat/types';+import type { TopicOpenedBy, WorkingDirConfig } from '@lobechat/types';import { normalizeDirectoryPath } from '@lobechat/types';+import type { TopicModel } from '@/database/models/topic';+import type { InternalExecAgentParams } from '../types';import { pickSandboxPlacement } from './sandboxPlacement';@@ -11,6 +13,8 @@ export interface NewTopicMetadataInput {/** The bound device was chosen explicitly for this conversation, not auto-picked. */deviceBindingPinned?: boolean;editingAgentId?: string;+ /** The topic this one was opened from (a sub-topic); see `resolveTopicOpenedBy`. */+ openedBy?: TopicOpenedBy;/** Working directory the topic is born in; overrides the client-supplied one. */projectDirectory?: { path: string };taskId?: string;@@ -49,6 +53,7 @@ export const buildNewTopicMetadata = ({cronJobId,deviceBindingPinned,editingAgentId,+ openedBy,projectDirectory,taskId,topicBoundDeviceId,@@ -84,6 +89,7 @@ export const buildNewTopicMetadata = ({!initialTopicMeta &&!editingGroupId &&!editingAgentId &&+ !openedBy &&!webhookThread)return;@@ -95,6 +101,7 @@ export const buildNewTopicMetadata = ({...(deviceBindingPinned && { deviceBindingPinned }),...(editingAgentId && { editingAgentId }),...(editingGroupId && { editingGroupId }),+ ...(openedBy && { openedBy }),taskId,...(webhookThread && { webhook: webhookThread }),...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),@@ -107,3 +114,24 @@ export const buildNewTopicMetadata = ({}),};};++/**+ * The `metadata.openedBy` link of a topic opened from `openerTopicId`. The+ * opener is read through the caller's own topic scope, so a stale, foreign or+ * mistyped id (an env var a long-lived shell kept) records no link rather than+ * failing a run that is otherwise valid.+ */+export const resolveTopicOpenedBy = async (+ topicModel: Pick<TopicModel, 'findById'>,+ openerTopicId: string | undefined,+): Promise<TopicOpenedBy | undefined> => {+ if (!openerTopicId) return;+ const opener = await topicModel.findById(openerTopicId).catch(() => undefined);+ if (!opener) return;++ return {+ agentId: opener.agentId ?? undefined,+ at: new Date().toISOString(),+ topicId: opener.id,+ };+};diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex 2d2df554a8d..578f8e081a6 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -43,7 +43,7 @@ import { ingestAttachment } from '../ingestAttachment';import type { AgentShareGate } from '../shareGate';import { reserveShareVisitorTopic, reserveShareVisitorTurn } from '../shareVisitorAbuseGuards';import type { InternalExecAgentParams } from '../types';-import { buildNewTopicMetadata } from './newTopicMetadata';+import { buildNewTopicMetadata, resolveTopicOpenedBy } from './newTopicMetadata';import { createUserTurnAnchor } from './resolveUserMessageParentId';import { createStageTracer, openStageMark } from './sendTracing';import { assertShareHeteroAllowed } from './shareHeteroGate';@@ -357,6 +357,8 @@ export interface TurnSetupInput {externalOrigin?: InternalExecAgentParams['externalOrigin'];files?: InternalExecAgentParams['files'];modelOverride?: string;+ /** See `ExecAgentParams.openedByTopicId`. */+ openedByTopicId?: string;operationTaskId?: string;parentMessageId?: string;persistedUserMessageId?: string;@@ -469,6 +471,7 @@ export const setupTurn = async (externalOrigin,cronJobId,webhookThread,+ openedByTopicId,files,modelOverride,operationTaskId,@@ -636,12 +639,14 @@ export const setupTurn = async (await routeToProjectDirectory(projectDirectory);}+ const openedBy = await resolveTopicOpenedBy(deps.topicModel, openedByTopicId);const metadata = buildNewTopicMetadata({appContext,botContext,cronJobId,deviceBindingPinned: Boolean(effectiveRequestedDeviceId),editingAgentId,+ openedBy,projectDirectory,taskId: operationTaskId,topicBoundDeviceId,diff --git a/packages/builtin-skills/src/lobehub/references/topic.ts b/packages/builtin-skills/src/lobehub/references/topic.tsindex a77d20b9f46..15f52c92e29 100644--- a/packages/builtin-skills/src/lobehub/references/topic.ts+++ b/packages/builtin-skills/src/lobehub/references/topic.ts@@ -4,12 +4,15 @@ Manage conversation topics (chat sessions).## Subcommands-- \`lh topic list [--agent-id <id>] [-L <limit>] [--page <n>]\` - List topics with pagination+- \`lh topic list [--agent-id <id>] [--parent-topic-id <id> | --opened-by-me] [-L <limit>] [--page <n>]\` - List topics with pagination; with \`--parent-topic-id\` only the topics opened from that one (any agent), \`--opened-by-me\` for the conversation you run in- \`lh topic view <id> [-L <limit>] [--from <n>] [--to <n>] [--no-messages]\` - View topic details and its messages- \`lh topic search <keywords> [--agent-id <id>]\` - Search topics by keywords- \`lh topic create -t <title> [--agent-id <id>] [--favorite]\` - Create a topic- \`lh topic edit <id> [-t <title>] [--favorite] [--no-favorite]\` - Update topic- \`lh topic delete <ids...> [--yes]\` - Delete one or more topics+- \`lh topic stop <id>\` - Stop the topic's running turn (the runs you started)+- \`lh topic archive <id>\` / \`lh topic unarchive <id>\` - Archive a topic (it leaves the agent list; an auto-created worktree is cleaned up) or bring it back+- \`lh topic send --new -c <text> [--parent-topic-id <id> | --detach]\` - Open a new topic; run inside a conversation it is linked to that conversation as its parent unless \`--detach\`- \`lh topic recent [-L <limit>]\` - List recently accessed topics## Threadsdiff --git a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts b/packages/database/src/models/__tests__/topics/topic.characterization.test.tsindex e8073cf3f40..2e50ef709bb 100644--- a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.characterization.test.ts@@ -77,6 +77,7 @@ const PUBLIC_METHODS = ['findWaitingCleanupTopicsUnder','getCronTopicsGroupedByCronJob','isRunningOperationAlive',+ 'listChildTopicAgentIds','listTopicsForMemoryExtractor','markRead','patchRunningOperation',diff --git a/packages/database/src/models/__tests__/topics/topic.children.test.ts b/packages/database/src/models/__tests__/topics/topic.children.test.tsnew file mode 100644index 00000000000..4936618121c--- /dev/null+++ b/packages/database/src/models/__tests__/topics/topic.children.test.ts@@ -0,0 +1,86 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents, topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { TopicModel } from '../../topic';++const userId = 'topic-children-user';+const serverDB: LobeChatDatabase = await getTestDB();+const topicModel = new TopicModel(serverDB, userId);++const childOf = (topicId: string, extra: Record<string, unknown> = {}) => ({+ openedBy: { at: '2026-11-18T00:00:00.000Z', topicId, ...extra },+});++describe('TopicModel - child topics (metadata.openedBy)', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values([+ { id: 'agent-mine', userId },+ { id: 'agent-hidden', userId },+ ]);+ await serverDB.insert(topics).values([+ { agentId: 'agent-mine', id: 'parent', userId },+ // The newest children run the agent the caller may not see.+ ...[1, 2, 3].map((n) => ({+ agentId: 'agent-hidden',+ id: `hidden-${n}`,+ metadata: childOf('parent'),+ updatedAt: new Date(`2026-11-18T0${n + 3}:00:00.000Z`),+ userId,+ })),+ ...[1, 2].map((n) => ({+ agentId: 'agent-mine',+ id: `mine-${n}`,+ metadata: childOf('parent'),+ updatedAt: new Date(`2026-11-18T0${n}:00:00.000Z`),+ userId,+ })),+ {+ agentId: 'agent-mine',+ id: 'unlinked',+ metadata: childOf('parent', { detachedAt: '2026-11-18T05:00:00.000Z' }),+ userId,+ },+ ]);+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ it("names the agents a topic's children run, without unlinked ones", async () => {+ expect((await topicModel.listChildTopicAgentIds('parent')).sort()).toEqual([+ 'agent-hidden',+ 'agent-mine',+ ]);+ });++ it('pages and counts only the children of the allowed agents', async () => {+ const firstPage = await topicModel.query({+ openedByAgentIds: ['agent-mine'],+ openedByTopicId: 'parent',+ pageSize: 1,+ });++ // The hidden agent's newer children neither fill the page nor the total.+ expect(firstPage.items.map((item: any) => item.id)).toEqual(['mine-2']);+ expect(firstPage.total).toBe(2);++ const secondPage = await topicModel.query({+ current: 1,+ openedByAgentIds: ['agent-mine'],+ openedByTopicId: 'parent',+ pageSize: 1,+ });+ expect(secondPage.items.map((item: any) => item.id)).toEqual(['mine-1']);+ });++ it('lists every child when no agent restriction is given', async () => {+ const all = await topicModel.query({ openedByTopicId: 'parent' });++ expect(all.total).toBe(5);+ });+});diff --git a/packages/database/src/models/topic/index.ts b/packages/database/src/models/topic/index.tsindex 2708596d4de..a0fb28ab350 100644--- a/packages/database/src/models/topic/index.ts+++ b/packages/database/src/models/topic/index.ts@@ -121,6 +121,7 @@ export class TopicModel {query = this.withContext(list.query);queryTopics = this.withContext(list.queryTopics);+ listChildTopicAgentIds = this.withContext(list.listChildTopicAgentIds);// **************** Read *************** //diff --git a/packages/database/src/models/topic/list.ts b/packages/database/src/models/topic/list.tsindex 53e024ffa85..43fc8526950 100644--- a/packages/database/src/models/topic/list.ts+++ b/packages/database/src/models/topic/list.ts@@ -64,6 +64,36 @@ export const buildTopicOrderBy = (topicActivityAt: SQL, sortBy?: TopicQuerySortB? [desc(topics.favorite), asc(STATUS_SORT_RANK), desc(topicActivityAt)]: [desc(topics.favorite), desc(topicActivityAt)];+/** The condition a topic's child rows match (see `QueryTopicParams.openedByTopicId`). */+const childOfCondition = (openedByTopicId: string) =>+ and(+ sql`${topics.metadata} -> 'openedBy' ->> 'topicId' = ${openedByTopicId}`,+ // Never a jsonb null test in a qual β see the note on `TopicModel`.+ sql`COALESCE(${topics.metadata} -> 'openedBy' ->> 'detachedAt', '') = ''`,+ );++/**+ * The distinct agents a topic's child topics run, so a caller can decide which+ * it may show before paging through them.+ */+export const listChildTopicAgentIds = async (+ ctx: TopicModelContext,+ openedByTopicId: string,+): Promise<string[]> => {+ const rows = await ctx.db+ .selectDistinct({ agentId: topics.agentId })+ .from(topics)+ .where(+ and(+ ctx.ownership(),+ ctx.notShareVisitor(),+ notChannelTopic(),+ childOfCondition(openedByTopicId),+ ),+ );+ return rows.map((row) => row.agentId).filter(Boolean) as string[];+};+export const query = async (ctx: TopicModelContext,{@@ -80,6 +110,8 @@ export const query = async (isInbox,legacySessionId,onlyMine,+ openedByAgentIds,+ openedByTopicId,sortBy,timing,triggers,@@ -177,6 +209,79 @@ export const query = async (editingGroupId ? sql`${topics.metadata}->>'editingGroupId' = ${editingGroupId}` : undefined,);+ // Child topics of one topic, across agents. `ownership()` (the user /+ // workspace index) narrows the rows before the unindexed jsonb comparison.+ // Never a jsonb null test in a qual β see the note on `TopicModel`.+ if (openedByTopicId) {+ const childWhere = and(+ ctx.ownership(),+ ctx.notShareVisitor(),+ notChannelTopic(),+ childOfCondition(openedByTopicId),+ agentId ? eq(topics.agentId, agentId) : undefined,+ openedByAgentIds+ ? or(+ isNull(topics.agentId),+ openedByAgentIds.length > 0 ? inArray(topics.agentId, openedByAgentIds) : undefined,+ )+ : undefined,+ includeTriggerCondition,+ excludeTriggerCondition,+ triggerCondition,+ excludeStatusCondition,+ onlyMineCondition,+ );++ const [items, totalResult] = await Promise.all([+ runTimedStage(+ timing,+ 'db.topic.query.children.items.select',+ () =>+ ctx.db+ // See note on the group-branch select above re: `as any` cast.+ .select({+ // A child may run another agent: callers need to know which.+ agentId: topics.agentId,+ completedAt: topics.completedAt,+ createdAt: topics.createdAt,+ favorite: topics.favorite,+ historySummary: topics.historySummary,+ id: topics.id,+ metadata: topicMetadataWithCreator(ctx.db, ctx.messageOwnership()),+ model: topics.model,+ provider: topics.provider,+ runStartedAt: runStartedAtColumn,+ sortUpdatedAt: topicActivityAt,+ status: topics.status,+ title: topics.title,+ trigger: topics.trigger,+ updatedAt: topics.updatedAt,+ userId: topics.userId,+ ...detailColumns,+ } as any)+ .from(topics)+ .where(childWhere)+ .orderBy(...orderBy)+ .limit(pageSize)+ .offset(offset),+ { current, pageSize },+ ),+ runTimedStage(timing, 'db.topic.query.children.count.select', () =>+ ctx.db+ .select({ count: count(topics.id) })+ .from(topics)+ .where(childWhere),+ ),+ ]);++ logTiming(timing, 'db.topic.query:done', {+ itemCount: items.length,+ stageMs: getDurationMs(queryStartedAt),+ total: totalResult[0].count,+ });+ return { items, total: totalResult[0].count };+ }+if (groupId) {const whereCondition = and(ctx.ownership(),diff --git a/packages/database/src/models/topic/types.ts b/packages/database/src/models/topic/types.tsindex d4859dfac31..5b312a42138 100644--- a/packages/database/src/models/topic/types.ts+++ b/packages/database/src/models/topic/types.ts@@ -168,6 +168,18 @@ export interface QueryTopicParams {* workspace, where the list otherwise shows every member's topics.*/onlyMine?: boolean;+ /**+ * With `openedByTopicId`: only children of these agents (plus agent-less+ * ones) β the agents the caller may view, applied before paging and counting.+ */+ openedByAgentIds?: string[];+ /**+ * Only the topics opened from this one (its child topics:+ * `metadata.openedBy.topicId`, not unlinked), whatever their agent. Takes+ * precedence over the agent / group / container scopes; `agentId` still+ * narrows it when given.+ */+ openedByTopicId?: string | null;pageSize?: number;/*** Server-side ordering. Defaults to `updatedAt`. `status` orders by statusdiff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.tsindex 5a9faab698c..aabba54a9a2 100644--- a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts@@ -87,7 +87,7 @@ const lobeHubCliGuideBody = ['- **When to use it:** only when the user asks for something that lives in LobeHub rather than in this working directory β saving a document, recalling an earlier conversation, generating an image, or changing your own agent configuration. A request about local files, code or another tool does not need `lh`. Say what you did and where it landed.',"- **You already know where you are.** `LOBEHUB_TOPIC_ID` (this conversation) and `LOBEHUB_OPERATION_ID` (this run) are in your environment, and `LOBEHUB_AGENT_ID` (you) and `LOBEHUB_WORKSPACE_ID` (the workspace this conversation belongs to, which scopes every `lh` call) are too whenever the run carries them. They are ordinary environment variables, so every sub-shell, script or tool you spawn inherits them. Pass them straight to commands rather than listing agents or topics to find yourself; if the one you need is empty, say so instead of guessing an id. LobeHub topic ids start with `tpc_` β an id in the user's message without that prefix belongs to something else.",'- **Earlier conversations:** read one with `lh topic view <id>`. This run can always read its own conversation and the ones the user names in it (a `tpc_β¦` id or a `<refer_topic>` tag); for any other, ask the user to name it here.',- '- **Talking to another conversation:** `lh topic send <tpc_id> -c "β¦"` delivers a message to that conversation and has its agent act on it (queued behind its current turn if it is busy). To hand work to a fresh conversation instead, `lh topic send --new -c "β¦"` opens one for you (or `--agent-id` another agent), optionally on a given machine with `--device <id|local>` and named with `--title`; `lh message send -c "β¦"` is the same thing spelled message-first: without `--topic-id` it opens a new conversation, with `--topic-id <tpc_id>` it sends to that one. Prefer these over `lh agent run` for handing off work. `lh message create` only writes a row β nobody sees or answers it. A message another agent sent you starts with an `<agent_sender>` header; answer it with `lh message reply <message_id> -c "β¦"`, which wakes the sender\'s conversation. Your ordinary response is not delivered to that agent.',+ '- **Talking to another conversation:** `lh topic send <tpc_id> -c "β¦"` delivers a message to that conversation and has its agent act on it (queued behind its current turn if it is busy). To hand work to a fresh conversation instead, `lh topic send --new -c "β¦"` opens one for you (or `--agent-id` another agent), optionally on a given machine with `--device <id|local>` and named with `--title`; it is linked to this conversation as its parent (`--parent-topic-id <tpc_id>` names another, `--detach` links none), and `lh topic list --opened-by-me` lists the ones you opened; `lh topic stop <tpc_id>` stops a topic\'s running turn and `lh topic archive <tpc_id>` archives it; `lh message send -c "β¦"` is the same thing spelled message-first: without `--topic-id` it opens a new conversation, with `--topic-id <tpc_id>` it sends to that one. Prefer these over `lh agent run` for handing off work. `lh message create` only writes a row β nobody sees or answers it. A message another agent sent you starts with an `<agent_sender>` header; answer it with `lh message reply <message_id> -c "β¦"`, which wakes the sender\'s conversation. Your ordinary response is not delivered to that agent.','- **If `lh` is too old** β `lh man` lacks a command you expect, or `lh` reports an unknown command or option β the shell may have found a stale global install first. When `LOBEHUB_CLI` is set it is the path of the CLI this app ships β run that path instead of `lh` for the rest of the session. Otherwise, or if that one is too old as well, run the latest CLI once without installing it: `pnpm --package @lobehub/cli@latest dlx lh β¦` (or `npx -y -p @lobehub/cli@latest lh β¦`). It reads the same environment and saved login as `lh`. If the user asks you to run `lh` this way, do so.','- **Look commands up, do not guess them.** `lh man` lists every command, and `lh man <command>` (e.g. `lh man doc create`) prints the manual for the CLI actually installed here, including exactly which flags that command takes. Many commands offer `--json` for structured output, but not all of them β the manual is what says so, and an invented flag just fails the call.','- **What it reaches:** `lh kb` knowledge bases Β· `lh doc` documents Β· `lh file` files Β· `lh artifact` artifacts Β· `lh topic` / `lh message` past conversations Β· `lh agent` agents Β· `lh task` / `lh project` work Β· `lh widget` / `lh dashboard` monitoring widgets and dashboards Β· `lh search` local resources and the web Β· `lh recall` past messages, topics, goals and pages in a time window Β· `lh gen` text/image/video/TTS/ASR generation Β· `lh memory` user memory Β· `lh notify` notifications to the user Β· `lh model` / `lh provider` / `lh legacy-plugin` / `lh skill` platform configuration Β· `lh bot` chat-platform bots.',diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex e08974ade16..ed1e3fbfdf7 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -371,6 +371,13 @@ export interface ExecAgentParams {localDeviceId?: string;/** Override the agent's default model */model?: string;+ /**+ * The conversation this NEW topic is opened from β its parent topic+ * (`metadata.openedBy`). Resolved through the caller's own topic scope: an+ * unknown or foreign topic records no link. Ignored when the run continues+ * an existing topic.+ */+ openedByTopicId?: string;/*** Parent operation ID when this run is a sub-agent invocation. Forwarded* to `agent_operations.parent_operation_id` so analytics can join thediff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 4226d56188d..e930cc85d8f 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -139,6 +139,25 @@ export interface OnboardingSessionSnapshot {version: number;}+/**+ * Provenance of a topic opened from another one (its parent topic): the topic+ * and agent it was opened from.+ *+ * A link only β the topic keeps its own agent, working directory and+ * lifecycle. While `detachedAt` is unset it lists under its parent+ * (`topic.getTopics({ openedByTopicId })`, `lh topic list --parent-topic-id`);+ * a detached one keeps the link as its origin.+ */+export interface TopicOpenedBy {+ /** The opener topic's agent, so a reader never has to load the opener. */+ agentId?: string;+ /** ISO time the link was written. */+ at: string;+ /** ISO time the topic was unlinked from its parent; it no longer lists under it. */+ detachedAt?: string;+ topicId: string;+}+export interface ChatTopicMetadata {/** Watermark written by the background topic-summary workflow. */autoSummary?: {@@ -303,6 +322,13 @@ export interface ChatTopicMetadata {*/onboardingFeedback?: OnboardingFeedbackEntry;onboardingSession?: OnboardingSessionSnapshot;+ /**+ * The topic this one was opened from (its parent topic). Server-owned+ * (absent from the client-writable metadata schema), written once when the+ * topic is created with `execAgent({ openedByTopicId })` β e.g.+ * `lh topic send --new` run inside a conversation. See {@link TopicOpenedBy}.+ */+ openedBy?: TopicOpenedBy;/*** Worktrees the app created for this topic, and where their automatic* cleanup stands. Server-owned: claimed whenever metadata is written with