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.

✨ feat(goal): create and supervise a goal from a hetero agent conversation with /goal (#19588)

Arvin Xu394ba3a54fef
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index d0d71f45fb3..0fa6b1c8568 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -163,6 +163,25 @@ function printTick(result: GoalTickResult) {
if (result.nodeId) console.log(` ${pc.dim(`node: ${result.nodeId}`)}`);
}
+/**
+ * Whether this process runs with a server-minted operation token (device and
+ * gateway runs) rather than the user's own login. Operation tokens are refused
+ * on ordinary routes, so commands that act for the running conversation pick
+ * the operation-authenticated endpoint instead.
+ */
+const hasOperationToken = () => {
+ const injectedJwt = process.env.LOBEHUB_JWT;
+ if (!injectedJwt) return false;
+ try {
+ return (
+ JSON.parse(Buffer.from(injectedJwt.split('.')[1], 'base64url').toString()).purpose ===
+ 'hetero-operation'
+ );
+ } catch {
+ return false;
+ }
+};
+
export function registerGoalCommand(program: Command) {
const goal = program.command('goal').description('Run long-horizon Goal Graphs');
goal
@@ -183,12 +202,7 @@ export function registerGoalCommand(program: Command) {
const operationId = options.operation ?? process.env.LOBEHUB_OPERATION_ID;
if (!operationId) throw new Error('Current manager operation ID required');
const client = await getTrpcClient();
- const injectedJwt = process.env.LOBEHUB_JWT;
- const isOperationToken =
- injectedJwt &&
- JSON.parse(Buffer.from(injectedJwt.split('.')[1], 'base64url').toString()).purpose ===
- 'hetero-operation';
- const endpoint = isOperationToken
+ const endpoint = hasOperationToken()
? client.goal.submitOperationPlan
: client.goal.submitPlan;
const result = await endpoint.mutate({
@@ -245,16 +259,25 @@ export function registerGoalCommand(program: Command) {
'--operation-lease-timeout-ms <n>',
'Reclaim a Task operation after this idle time (minimum: 60000)',
)
+ .option(
+ '--conversation',
+ 'Create the goal from the current conversation run (/goal): this agent supervises it from this conversation, and the output carries a turnToken for the first plan',
+ )
+ .option('--criterion <text...>', 'Acceptance criterion (repeatable)')
.option('--json [fields]', 'Output JSON')
.action(async (title: string, options) => {
if (options.maxExperiments && !options.explore) {
throw new Error('--max-experiments requires --explore');
}
+ const operationId = process.env.LOBEHUB_OPERATION_ID;
+ if (options.conversation && !operationId) {
+ throw new Error(
+ '--conversation must run inside an agent conversation (LOBEHUB_OPERATION_ID)',
+ );
+ }
const client = await getTrpcClient();
const buildUrl = await resolveAppUrlBuilder(client);
- const result = await client.goal.create.mutate({
- agentId: options.agent ?? process.env.LOBEHUB_AGENT_ID,
- createdByAgentId: process.env.LOBEHUB_AGENT_ID,
+ const goalInput = {
config:
options.maxManagerTurns ||
options.explore ||
@@ -299,6 +322,9 @@ export function registerGoalCommand(program: Command) {
},
}
: undefined,
+ criteria: (options.criterion as string[] | undefined)?.map((criterion) => ({
+ title: criterion,
+ })),
maxRounds: options.maxRounds ? Number.parseInt(options.maxRounds, 10) : undefined,
maxTotalCost: options.maxCost ? Number.parseFloat(options.maxCost) : undefined,
problemDescription: options.instruction,
@@ -306,14 +332,43 @@ export function registerGoalCommand(program: Command) {
requirement: options.requirement,
title,
tasks: options.task,
- });
+ };
+ // A conversation goal takes its agent and conversation from the running
+ // operation on the server; the CLI only names the run. Device and gateway
+ // runs hold an operation token, which only the operation endpoint accepts.
+ // A local desktop run keeps its operation client-side, so it also names
+ // its conversation and agent for the server to check.
+ const result = options.conversation
+ ? hasOperationToken()
+ ? await client.goal.createConversationGoal.mutate({
+ ...goalInput,
+ operationId: operationId!,
+ })
+ : await client.goal.create.mutate({
+ ...goalInput,
+ agentId: process.env.LOBEHUB_AGENT_ID,
+ conversationOperationId: operationId,
+ conversationTopicId: process.env.LOBEHUB_TOPIC_ID,
+ })
+ : await client.goal.create.mutate({
+ ...goalInput,
+ agentId: options.agent ?? process.env.LOBEHUB_AGENT_ID,
+ createdByAgentId: process.env.LOBEHUB_AGENT_ID,
+ });
+ const turnToken = 'turnToken' in result ? result.turnToken : undefined;
// `goal.create` returns the whole graph snapshot, so the id is on its
// goal — `result.data.id` is undefined, and the CLI cannot resolve the
// router's types to catch that, which is how it reached a printed URL.
- const url = buildUrl(`/goal/${encodeURIComponent(result.data.goal.id)}`);
- if (options.json !== undefined) return outputJson({ ...result.data, url }, options.json);
- printGraph(result.data);
+ const url = buildUrl(`/goal/${encodeURIComponent(result.data!.goal.id)}`);
+ if (options.json !== undefined)
+ return outputJson({ ...result.data, turnToken, url }, options.json);
+ printGraph(result.data!);
console.log(`${pc.bold('goal')}: ${url}`);
+ if (turnToken) {
+ console.log(
+ `${pc.bold('planning turn')}: lh goal plan ${result.data!.goal.id} --token ${turnToken} --file <plan.json>`,
+ );
+ }
});
goal
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index d4ac7244ded..3b20023cee5 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -433,6 +433,39 @@ describe('hetero exec command', () => {
expect(call.includePartialMessages).toBe(true);
});
+ it("echoes the run's operation and conversation into a server-ingest agent's env", async () => {
+ mockSpawnAgent.mockReturnValue(createFakeHandle());
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'claude-code',
+ '--prompt',
+ '/goal ship the report',
+ '--topic',
+ 'tpc_conversation',
+ '--operation-id',
+ 'op_conversation_run',
+ ]);
+
+ // `lh goal create --conversation` inside the agent's shell reads these.
+ expect(mockSpawnAgent.mock.calls[0][0].env).toMatchObject({
+ LOBEHUB_OPERATION_ID: 'op_conversation_run',
+ LOBEHUB_TOPIC_ID: 'tpc_conversation',
+ });
+ });
+
+ it('gives a standalone run no conversation identity', async () => {
+ mockSpawnAgent.mockReturnValue(createFakeHandle());
+
+ await runCmd(['hetero', 'exec', '--type', 'claude-code', '--prompt', 'hi']);
+
+ const env = mockSpawnAgent.mock.calls[0][0].env ?? {};
+ expect(env).not.toHaveProperty('LOBEHUB_OPERATION_ID');
+ expect(env).not.toHaveProperty('LOBEHUB_TOPIC_ID');
+ });
+
it('does not request Claude partial-message framing for other heterogeneous agents', async () => {
mockSpawnAgent.mockReturnValue(createFakeHandle());
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 0b426eaf836..0d3eec4e79e 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -40,6 +40,33 @@ import { createLocalTraceStore } from '../utils/traceStore';
import { TrpcIngestSink } from '../utils/TrpcIngestSink';
export const SUPPORTED_AGENT_TYPES = new Set<string>(LOCAL_HETEROGENEOUS_AGENT_TYPES);
+
+/**
+ * Extra env for the spawned agent process.
+ *
+ * In server-ingest mode the run's operation and conversation arrive as CLI
+ * arguments, not env, so the agent's own shell could not name them. Commands it
+ * runs on behalf of this conversation — `lh goal create --conversation` for
+ * `/goal`, evidence ingests — read `LOBEHUB_OPERATION_ID` / `LOBEHUB_TOPIC_ID`,
+ * so they are echoed into the child. A standalone run has no server identity
+ * and passes none.
+ */
+export const buildAgentProcessEnv = ({
+ operationId,
+ pathEnv,
+ topicId,
+}: {
+ operationId?: string;
+ pathEnv?: string;
+ topicId?: string;
+}): Record<string, string> | undefined => {
+ const env: Record<string, string> = {
+ ...(pathEnv ? { PATH: pathEnv } : {}),
+ ...(operationId ? { LOBEHUB_OPERATION_ID: operationId } : {}),
+ ...(topicId ? { LOBEHUB_TOPIC_ID: topicId } : {}),
+ };
+ return Object.keys(env).length > 0 ? env : undefined;
+};
const SUPPORTED_AGENT_TITLES = HETEROGENEOUS_AGENT_CONFIGS.map(({ title }) => title).join(' / ');
const SUPPORTED_AGENT_COMMANDS = HETEROGENEOUS_AGENT_CONFIGS.map(
({ defaultCommand }) => `\`${defaultCommand}\``,
@@ -897,7 +924,11 @@ const exec = async (options: ExecOptions): Promise<void> => {
// a broken `codex` shim shadows PATH — so sandbox/terminal runs no longer
// ENOENT on a stale global install. Custom commands are used verbatim.
const resolvedCommand = await resolveHeteroSpawnCommand(agentType, options.command);
- const commandEnv = resolvedCommand.pathEnv ? { PATH: resolvedCommand.pathEnv } : undefined;
+ const commandEnv = buildAgentProcessEnv({
+ operationId: serverIngest ? operationId : undefined,
+ pathEnv: resolvedCommand.pathEnv,
+ topicId: options.topic,
+ });
// Devin ACP's `--permission-mode` is a global flag; default to bypass so
// headless connected-device runs do not block on permission prompts. The mode
// response must not overwrite the model selected by `initialModel`.
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 0e71fad5b99..bd171216c1a 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -38,6 +38,97 @@ const goalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
const goalWriteProcedure = goalProcedure.use(withScopedPermission('agent:update'));
const idInput = z.object({ id: z.string() });
+/** Everything a goal is created from except who owns it. */
+const conversationGoalInput = z.object({
+ config: z
+ .object({
+ acceptance: z
+ .object({
+ /** Numeric clauses gating acceptance; keyed by a series on this goal. */
+ metrics: z
+ .array(
+ z.object({
+ key: z.string().min(1).max(255),
+ op: z.enum(['gte', 'lte', 'gt', 'lt', 'eq']).optional(),
+ target: z.number(),
+ title: z.string().max(255).optional(),
+ }),
+ )
+ .max(MAX_GOAL_METRIC_CRITERIA)
+ .optional(),
+ })
+ .optional(),
+ // Bounds mirror `resolveMaxConcurrentTasks`, so a rejected value and
+ // a clamped one cannot disagree about what the cap may be.
+ exploration: z
+ .object({
+ instruction: z.string().min(1).max(8000),
+ maxExperiments: z.number().int().min(1).max(200),
+ })
+ .optional(),
+ manager: z
+ .object({
+ instruction: z.string().max(8000).optional(),
+ maxTurns: z.number().int().min(1).max(100).optional(),
+ })
+ .optional(),
+ maxConcurrentTasks: z.number().int().min(1).max(10).nullable().optional(),
+ supervision: z
+ .object({
+ enabled: z.boolean(),
+ maxIncidents: z.number().int().min(1).max(100).optional(),
+ })
+ .optional(),
+ /** Dedicated executor for the goal's Tasks; the goal agent supervises. */
+ taskAgentId: z.string().min(1).optional(),
+ recovery: z
+ .object({
+ maxAttemptsPerTask: z.number().int().positive().optional(),
+ maxStepsPerRun: z.number().int().positive().nullable().optional(),
+ operationLeaseTimeoutMs: z.number().int().min(60_000).optional(),
+ })
+ .optional(),
+ schedule: z
+ .object({
+ /** ISO-8601 instant; past it the coordinator stops dispatching. */
+ deadline: z.string().datetime().nullable().optional(),
+ })
+ .optional(),
+ })
+ .optional(),
+ maxRounds: z.number().int().positive().optional(),
+ maxTotalCost: z.number().positive().optional(),
+ /** Structured acceptance criteria — persisted rows that gate the terminal acceptance. */
+ criteria: z
+ .array(
+ z.object({
+ description: z.string().optional(),
+ instruction: z.string().optional(),
+ title: z.string().min(1),
+ }),
+ )
+ .optional(),
+ problemDescription: z.string().optional(),
+ projectId: z.string().optional(),
+ requirement: z.string().optional(),
+ title: z.string().min(1),
+ /** Seed task nodes, in dependency-free order. */
+ tasks: z
+ .array(
+ z.union([
+ z.string().min(1),
+ z.object({ description: z.string().optional(), title: z.string().min(1) }),
+ ]),
+ )
+ .optional(),
+});
+
+const createGoalInput = conversationGoalInput.extend({
+ agentId: z.string().optional(),
+ /** Set by the `/goal` tool so the seeded graph is authored by the agent. */
+ createdByAgentId: z.string().optional(),
+});
+
function mapGoalError(error: unknown, operation: string): never {
if (error instanceof TRPCError) throw error;
console.error(`[goal:${operation}]`, error);
@@ -173,112 +264,109 @@ export const goalRouter = router({
}
}),
- create: goalWriteProcedure
- .input(
- z.object({
- agentId: z.string().optional(),
- /** Set by the `/goal` tool so the seeded graph is authored by the agent. */
- createdByAgentId: z.string().optional(),
- config: z
- .object({
- acceptance: z
- .object({
- /** Numeric clauses gating acceptance; keyed by a series on this goal. */
- metrics: z
- .array(
- z.object({
- key: z.string().min(1).max(255),
- op: z.enum(['gte', 'lte', 'gt', 'lt', 'eq']).optional(),
- target: z.number(),
- title: z.string().max(255).optional(),
- }),
- )
- .max(MAX_GOAL_METRIC_CRITERIA)
- .optional(),
- })
- .optional(),
- // Bounds mirror `resolveMaxConcurrentTasks`, so a rejected value and
- // a clamped one cannot disagree about what the cap may be.
- exploration: z
- .object({
- instruction: z.string().min(1).max(8000),
- maxExperiments: z.number().int().min(1).max(200),
- })
- .optional(),
- manager: z
- .object({
- instruction: z.string().max(8000).optional(),
- maxTurns: z.number().int().min(1).max(100).optional(),
- })
- .optional(),
- maxConcurrentTasks: z.number().int().min(1).max(10).nullable().optional(),
- supervision: z
- .object({
- enabled: z.boolean(),
- maxIncidents: z.number().int().min(1).max(100).optional(),
- })
- .optional(),
- /** Dedicated executor for the goal's Tasks; the goal agent supervises. */
- taskAgentId: z.string().min(1).optional(),
- recovery: z
- .object({
- maxAttemptsPerTask: z.number().int().positive().optional(),
- maxStepsPerRun: z.number().int().positive().nullable().optional(),
- operationLeaseTimeoutMs: z.number().int().min(60_000).optional(),
- })
- .optional(),
- schedule: z
- .object({
- /** ISO-8601 instant; past it the coordinator stops dispatching. */
- deadline: z.string().datetime().nullable().optional(),
- })
- .optional(),
- })
- .optional(),
- maxRounds: z.number().int().positive().optional(),
- maxTotalCost: z.number().positive().optional(),
- /** Structured acceptance criteria — persisted rows that gate the terminal acceptance. */
- criteria: z
- .array(
- z.object({
- description: z.string().optional(),
- instruction: z.string().optional(),
- title: z.string().min(1),
- }),
- )
- .optional(),
- problemDescription: z.string().optional(),
- projectId: z.string().optional(),
- requirement: z.string().optional(),
- title: z.string().min(1),
- /** Seed task nodes, in dependency-free order. */
- tasks: z
- .array(
- z.union([
- z.string().min(1),
- z.object({ description: z.string().optional(), title: z.string().min(1) }),
- ]),
- )
- .optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
+ /**
+ * `/goal` from a conversation run authenticated by its operation token (device
+ * and gateway runs). The agent and conversation come from the operation, and
+ * the returned `turnToken` lets that run plan the goal immediately.
+ */
+ createConversationGoal: heteroAuthedProcedure
+ .use(serverDatabase)
+ .input(conversationGoalInput.extend({ operationId: z.string().min(1) }))
+ .mutation(async ({ ctx, input: { operationId, ...input } }) => {
+ if (ctx.heteroAuthKind !== 'operation' || !ctx.heteroOperation) {
+ throw new TRPCError({
+ code: 'UNAUTHORIZED',
+ message: 'An operation-bound token is required',
+ });
+ }
+ let principal;
+ try {
+ principal = await resolveActiveHeteroOperationPrincipal({
+ capability: 'goal:manage',
+ claims: ctx.heteroOperation,
+ db: ctx.serverDB,
+ operationId,
+ });
+ } catch (error) {
+ if (!(error instanceof HeteroOperationPrincipalError)) throw error;
+ throw new TRPCError({
+ cause: error,
+ code:
+ error.status === 401 ? 'UNAUTHORIZED' : error.status === 409 ? 'CONFLICT' : 'FORBIDDEN',
+ message: error.message,
+ });
+ }
try {
- const data = await ctx.goalService.create(input);
- // A goal is not a document — creating one means starting it. The
- // coordinator takes it from here without a client holding a loop open.
+ const { graph, turnToken } = await new GoalService(
+ ctx.serverDB,
+ principal.userId,
+ principal.workspaceId,
+ ).createFromConversation(operationId, input);
await scheduleGoalAdvance({
- goalId: data.goal.id,
+ goalId: graph.goal.id,
trigger: 'create',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId ?? undefined,
+ userId: principal.userId,
+ workspaceId: principal.workspaceId,
});
- return { data, message: 'Goal created', success: true };
+ return { data: graph, message: 'Goal created', success: true, turnToken };
} catch (error) {
mapGoalError(error, 'create');
}
}),
+ create: goalWriteProcedure
+ .input(
+ createGoalInput.extend({
+ /**
+ * Create the goal from the conversation run with this id (`/goal` on a
+ * desktop run signed in as the user). Agent and conversation come from
+ * the operation, so `agentId` / `createdByAgentId` are ignored.
+ */
+ conversationOperationId: z.string().min(1).optional(),
+ /**
+ * A local desktop run's operation lives only on the client, so it also
+ * names its conversation; the server checks the topic belongs to the
+ * caller and to this agent before accepting it.
+ */
+ conversationTopicId: z.string().min(1).optional(),
+ }),
+ )
+ .mutation(
+ async ({ ctx, input: { conversationOperationId, conversationTopicId, ...input } }) => {
+ try {
+ if (conversationOperationId) {
+ const { agentId, createdByAgentId: _createdBy, ...goalInput } = input;
+ const { graph, turnToken } = await ctx.goalService.createFromConversation(
+ conversationOperationId,
+ goalInput,
+ conversationTopicId && agentId
+ ? { agentId, topicId: conversationTopicId }
+ : undefined,
+ );
+ await scheduleGoalAdvance({
+ goalId: graph.goal.id,
+ trigger: 'create',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return { data: graph, message: 'Goal created', success: true, turnToken };
+ }
+ const data = await ctx.goalService.create(input);
+ // A goal is not a document — creating one means starting it. The
+ // coordinator takes it from here without a client holding a loop open.
+ await scheduleGoalAdvance({
+ goalId: data.goal.id,
+ trigger: 'create',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return { data, message: 'Goal created', success: true };
+ } catch (error) {
+ mapGoalError(error, 'create');
+ }
+ },
+ ),
+
decide: goalWriteProcedure
.input(
idInput.extend({
@@ -449,6 +537,8 @@ export const goalRouter = router({
offset: z.number().optional(),
projectId: z.string().optional(),
statuses: z.array(z.enum(goalStatuses)).optional(),
+ /** Goals created from this conversation. */
+ topicId: z.string().optional(),
}),
)
.query(async ({ input, ctx }) => ctx.goalModel.list(input)),
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
index c6ae43f1a89..b3260635b8f 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
@@ -1,3 +1,4 @@
+import { stripGoalCommand, withConversationGoalPrompt } from '@lobechat/builtin-tool-goal';
import { LOADING_FLAT } from '@lobechat/const';
import type { LobeChatDatabase } from '@lobechat/database';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
@@ -53,6 +54,7 @@ import {
} from '../helpers/heteroErrors';
import { resolveDeviceWorkingDirectoryConfig } from '../resolveDeviceWorkingDirectory';
import type { ExecRunContext } from '../types';
+import { heteroOperationCapabilities } from './heteroOperationCapabilities';
const log = debug('lobe-server:ai-agent-service');
@@ -374,7 +376,10 @@ export const dispatchHeteroAgent = async (
let operationJwt: string;
try {
operationJwt = await signHeteroOperationJWT({
- capabilities: ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read'],
+ // A `/goal` run also gets `goal:manage` so it can create the goal the agent
+ // supervises; the server still derives the agent and topic from this
+ // operation, never from the CLI.
+ capabilities: heteroOperationCapabilities(prompt),
operationId,
userId: deps.userId,
workspaceId: deps.workspaceId,
@@ -451,8 +456,14 @@ export const dispatchHeteroAgent = async (
// Build the primary context without conversation history. If native resume
// fails, the CLI switches to the complete fallback prompt on its fresh
// retry; successful same-session runs never consume the duplicate history.
+ // `/goal` reaches a hetero agent as instructions, not a tool: it creates and
+ // plans the goal through `lh` in this same run.
+ const agentSystemContext = withConversationGoalPrompt(
+ agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
+ prompt,
+ );
const systemContext = buildCloudHeteroContext({
- agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
+ agentSystemContext,
conversationHistory: resumeSessionId ? undefined : conversationHistory,
githubToken,
repos: topicRepos,
@@ -460,7 +471,7 @@ export const dispatchHeteroAgent = async (
const resumeFallbackSystemContext =
resumeSessionId && conversationHistory
? buildCloudHeteroContext({
- agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
+ agentSystemContext,
conversationHistory,
githubToken,
repos: topicRepos,
@@ -493,7 +504,9 @@ export const dispatchHeteroAgent = async (
imageList: heteroImageList,
jwt: operationJwt,
operationId,
- prompt,
+ // The CLI receives only the request: `/goal` is already in the system
+ // context, and Claude Code's own `/goal` command would otherwise take it.
+ prompt: stripGoalCommand(prompt),
repos: topicRepos,
resumeFallbackSystemContext,
resumeSessionId,
@@ -961,13 +974,13 @@ export const dispatchHeteroAgent = async (
// (which describes an ephemeral /workspace + pre-cloned repos and would mislead
// the agent). The spawned CLI already receives deviceCwd as its actual cwd.
const deviceSystemContext = buildRemoteDeviceHeteroContext({
- agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
+ agentSystemContext,
conversationHistory: resumeSessionId ? undefined : conversationHistory,
});
const deviceResumeFallbackSystemContext =
resumeSessionId && conversationHistory
? buildRemoteDeviceHeteroContext({
- agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
+ agentSystemContext,
conversationHistory,
})
: undefined;
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts
new file mode 100644
index 00000000000..10190677906
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { heteroOperationCapabilities } from './heteroOperationCapabilities';
+
+describe('heteroOperationCapabilities', () => {
+ it('grants goal management to a /goal run', () => {
+ expect(heteroOperationCapabilities('/goal ship the report')).toContain('goal:manage');
+ });
+
+ it('keeps goal management out of an ordinary run', () => {
+ // Every hetero run used to carry it, so text met during a normal coding run
+ // could drive `lh goal create --conversation` and start uncapped work.
+ expect(heteroOperationCapabilities('fix the build')).toEqual([
+ 'hetero:ingest',
+ 'hetero:finish',
+ 'hetero:intervention:read',
+ ]);
+ expect(heteroOperationCapabilities(undefined)).not.toContain('goal:manage');
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts
new file mode 100644
index 00000000000..096abd3ce2f
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts
@@ -0,0 +1,20 @@
+import { isGoalPrompt } from '@lobechat/builtin-tool-goal';
+
+import type { HeteroOperationCapability } from '@/libs/trpc/utils/internalJwt';
+
+/**
+ * What a heterogeneous run's operation token may do.
+ *
+ * `goal:manage` lets the CLI create a goal the agent supervises from this
+ * conversation (`lh goal create --conversation`). The token is exposed to the
+ * always-installed CLI, so it is granted only when the user asked for a goal
+ * with `/goal`: an ordinary coding run that meets instructions telling it to
+ * run that command must not be able to launch persistent follow-on work.
+ * Renewal copies the minted claims, so a run never gains it later.
+ */
+export const heteroOperationCapabilities = (prompt: unknown): HeteroOperationCapability[] => [
+ 'hetero:ingest',
+ 'hetero:finish',
+ 'hetero:intervention:read',
+ ...(isGoalPrompt(prompt) ? (['goal:manage'] as const) : []),
+];
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 2e3e3311ef7..e4480ff9f20 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -32,6 +32,7 @@ import { MetricModel } from '@/database/models/metric';
import { ProjectModel } from '@/database/models/project';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
+import { TopicModel } from '@/database/models/topic';
import { WorkModel } from '@/database/models/work';
import type { LobeChatDatabase } from '@/database/type';
import { assertAgentUsableBy } from '@/database/utils/agent-access';
@@ -124,6 +125,11 @@ export interface CreateGoalGraphInput {
*/
tasks?: Array<CreateGoalTaskInput | string>;
title: string;
+ /**
+ * The conversation this goal was created from. Recorded as the goal's
+ * `topic` subject so the conversation can find and show it.
+ */
+ topicId?: string;
}
export interface CreateGoalNodeInput {
@@ -194,6 +200,80 @@ export class GoalService {
? new GoalGraphModel(this.db, this.userId, this.workspaceId, { id: agentId, type: 'agent' })
: this.graphModel;
+ /**
+ * `/goal` in a conversation: the agent running there creates the goal and
+ * supervises it from that conversation.
+ *
+ * Identity comes from the running operation, never from the caller: the goal
+ * agent is the operation's agent, the conversation is its topic, and that very
+ * run becomes the first planning turn, so the agent can plan straight away with
+ * the returned token instead of waiting for a dispatched turn.
+ */
+ createFromConversation = async (
+ operationId: string,
+ input: Omit<CreateGoalGraphInput, 'agentId' | 'createdByAgentId' | 'topicId'>,
+ /**
+ * A local desktop run keeps its operation client-side, so no server row
+ * exists for `operationId`. Its conversation env names the topic and agent
+ * instead; they are accepted only when the topic is the caller's and belongs
+ * to that agent. Never used for operation-token callers.
+ */
+ localRun?: { agentId: string; topicId: string },
+ ): Promise<{ graph: GoalGraphSnapshot; turnToken: string }> => {
+ const operation = await new AgentOperationModel(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).findOwnOperationById(operationId);
+ let agentId: string;
+ let topicId: string;
+ if (operation) {
+ if (operation.status !== 'running')
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'The conversation run has already ended',
+ });
+ if (!operation.agentId || !operation.topicId)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Only a conversation run with an agent can create a goal it supervises',
+ });
+ agentId = operation.agentId;
+ topicId = operation.topicId;
+ } else {
+ const topic = localRun
+ ? await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(
+ localRun.topicId,
+ )
+ : undefined;
+ if (!localRun || !topic || topic.agentId !== localRun.agentId)
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Conversation run not found' });
+ agentId = localRun.agentId;
+ topicId = topic.id;
+ }
+
+ const created = await this.create({
+ ...input,
+ agentId,
+ config: { ...input.config, manager: input.config?.manager ?? {} },
+ createdByAgentId: agentId,
+ topicId,
+ });
+ try {
+ const state = await new GoalManagerService(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).adoptConversationTurn(created.goal.id, { operationId, topicId });
+ return { graph: (await this.graphModel.getGraph(created.goal.id))!, turnToken: state.token };
+ } catch (error) {
+ // A goal nobody can plan is worse than no goal: the agent would report it
+ // created while its supervisor never gets a turn.
+ await this.goalModel.delete(created.goal.id).catch(() => {});
+ throw error;
+ }
+ };
+
create = async (input: CreateGoalGraphInput): Promise<GoalGraphSnapshot> => {
if (input.agentId ?? input.createdByAgentId) {
await assertAgentUsableBy(this.db, (input.agentId ?? input.createdByAgentId)!, {
@@ -306,7 +386,9 @@ export class GoalService {
maxTotalCost: input.maxTotalCost,
projectId: input.projectId,
requirement,
- subjectType: 'standalone',
+ ...(input.topicId
+ ? { subjectId: input.topicId, subjectType: 'topic' as const }
+ : { subjectType: 'standalone' as const }),
title: input.title,
});
// `/goal` is an agent making the call. Seeding through the user-attributed
diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.ts
index e6b6e52713e..e6e3c243ecd 100644
--- a/apps/server/src/services/goal/manager.test.ts
+++ b/apps/server/src/services/goal/manager.test.ts
@@ -276,6 +276,182 @@ describe('CLI main Agent planning', () => {
expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);
});
+ describe('/goal from a conversation run', () => {
+ const conversationTopicId = 'tpc_goal_conversation';
+ const conversationOpId = 'op_goal_conversation';
+
+ const startConversationRun = async () => {
+ await db.insert(topics).values({ agentId, id: conversationTopicId, userId });
+ await ops().recordStart({
+ agentId,
+ appContext: { sourceMessageId: 'msg_user_goal_request' },
+ operationId: conversationOpId,
+ topicId: conversationTopicId,
+ });
+ };
+
+ it('supervises from the conversation and plans in the same run', async () => {
+ await startConversationRun();
+
+ const { graph, turnToken } = await service().createFromConversation(conversationOpId, {
+ criteria: [{ title: 'Report delivered' }],
+ title: 'Ship the report',
+ });
+
+ expect(graph.goal).toMatchObject({
+ agentId,
+ subjectId: conversationTopicId,
+ subjectType: 'topic',
+ });
+ const state = (await model().findById(graph.goal.id))!.config!.managerState!;
+ expect(state).toMatchObject({
+ adopted: true,
+ operationId: conversationOpId,
+ token: turnToken,
+ topicId: conversationTopicId,
+ turns: 1,
+ });
+
+ // The creating run plans with the returned token, no dispatched turn needed.
+ expect(await manager().submit(graph.goal.id, turnToken, conversationOpId, taskPlan)).toEqual({
+ action: 'tasks',
+ recorded: true,
+ });
+ expect((await service().tick(graph.goal.id)).outcome).toBe('waiting_external');
+ await ops().recordCompletion(conversationOpId, { status: 'done' });
+ expect((await service().tick(graph.goal.id)).outcome).toBe('advanced');
+ expect((await service().tick(graph.goal.id)).taskId).toBeTruthy();
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).not.toHaveBeenCalled();
+ expect(
+ (await model().list({ topicId: conversationTopicId })).goals.map((item) => item.goal.id),
+ ).toEqual([graph.goal.id]);
+ });
+
+ it('counts only planning turns, not the rest of the conversation, as management spend', async () => {
+ await startConversationRun();
+ await ops().recordStart({
+ agentId,
+ appContext: { sourceMessageId: 'msg_user_unrelated_chat' },
+ operationId: 'op_goal_conversation_chat',
+ topicId: conversationTopicId,
+ });
+ await db
+ .update(agentOperations)
+ .set({ totalCost: 2 })
+ .where(eq(agentOperations.id, conversationOpId));
+ await db
+ .update(agentOperations)
+ .set({ totalCost: 5 })
+ .where(eq(agentOperations.id, 'op_goal_conversation_chat'));
+
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ title: 'Budgeted goal',
+ });
+ const state = (await model().findById(graph.goal.id))!.config!.managerState!;
+
+ expect((await manager().usage(state)).totalCost).toBe(2);
+ });
+
+ it('keeps the adopted run in management spend after a later turn replaces the receipt', async () => {
+ await startConversationRun();
+ await db
+ .update(agentOperations)
+ .set({ totalCost: 2 })
+ .where(eq(agentOperations.id, conversationOpId));
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ title: 'Two-turn goal',
+ });
+ const adopted = (await model().findById(graph.goal.id))!.config!.managerState!;
+ expect(adopted.adoptedOperationId).toBe(conversationOpId);
+
+ // What `startTurn` writes for turn two: a fresh receipt with no `adopted`
+ // flag and no operation yet. The first run's spend used to vanish here,
+ // so both the displayed usage and the budget check under-counted.
+ const laterTurn = {
+ adoptedOperationId: adopted.adoptedOperationId,
+ snapshot: adopted.snapshot,
+ startedAt: new Date().toISOString(),
+ token: 'turn-two',
+ topicId: conversationTopicId,
+ turns: 2,
+ };
+
+ expect((await manager().usage(laterTurn)).totalCost).toBe(2);
+ // After a handoff the later turn lives on another topic; the run still counts.
+ expect(
+ (await manager().usage({ ...laterTurn, topicId: 'tpc_other_supervisor' })).totalCost,
+ ).toBe(2);
+ });
+
+ it('plans a local desktop run that has no server operation row', async () => {
+ await db.insert(topics).values({ agentId, id: conversationTopicId, userId });
+ const localRun = { agentId, topicId: conversationTopicId };
+
+ const { graph, turnToken } = await service().createFromConversation(
+ 'op_client_only_local_run',
+ { title: 'Local goal' },
+ localRun,
+ );
+ expect(graph.goal).toMatchObject({ agentId, subjectId: conversationTopicId });
+
+ expect(
+ await manager().submit(graph.goal.id, turnToken, 'op_client_only_local_run', taskPlan),
+ ).toEqual({ action: 'tasks', recorded: true });
+ // No run to watch exit: the submitted plan settles the turn.
+ expect((await service().tick(graph.goal.id)).outcome).toBe('advanced');
+ expect((await service().tick(graph.goal.id)).taskId).toBeTruthy();
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).not.toHaveBeenCalled();
+
+ await expect(
+ manager().submit(graph.goal.id, turnToken, 'op_some_other_run', taskPlan),
+ ).rejects.toThrow();
+ });
+
+ it("refuses a local run whose conversation is not the agent's", async () => {
+ await db.insert(agents).values({ id: 'other-local-agent', userId });
+ await db.insert(topics).values({
+ agentId: 'other-local-agent',
+ id: conversationTopicId,
+ userId,
+ });
+
+ await expect(
+ service().createFromConversation(
+ 'op_client_only_local_run',
+ { title: 'Borrowed conversation' },
+ { agentId, topicId: conversationTopicId },
+ ),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('refuses a conversation run that has already ended', async () => {
+ await startConversationRun();
+ await ops().recordCompletion(conversationOpId, { status: 'done' });
+
+ await expect(
+ service().createFromConversation(conversationOpId, { title: 'Too late' }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it('lets an operation token create the goal only with the goal capability', async () => {
+ await startConversationRun();
+
+ await expect(
+ operationCaller(conversationOpId).createConversationGoal({
+ operationId: conversationOpId,
+ title: 'No capability',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ const result = await operationCaller(conversationOpId, {
+ capabilities: ['hetero:ingest', 'goal:manage'],
+ }).createConversationGoal({ operationId: conversationOpId, title: 'From device' });
+
+ expect(result.turnToken).toBeTruthy();
+ expect(result.data?.goal).toMatchObject({ agentId, subjectType: 'topic' });
+ });
+ });
+
it('does not dispatch the previous supervisor when a handoff lands before the claim', async () => {
const { id, op } = await start();
await ops().recordCompletion(op.id, { status: 'done' });
diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.ts
index 16eda98fe08..5527dc158b0 100644
--- a/apps/server/src/services/goal/manager.ts
+++ b/apps/server/src/services/goal/manager.ts
@@ -54,6 +54,8 @@ const activeStatuses = new Set(['planning', 'running']);
const terminalOperations = new Set(['done', 'error', 'interrupted']);
const terminalNodes = new Set(['resolved', 'retired', 'rejected']);
const TIMEOUT_MS = 20 * 60_000;
+/** Source message id prefix of a dispatched planning turn; the suffix is its token. */
+const MANAGER_SOURCE_MESSAGE_PREFIX = 'msg_goal_manager_';
/** Excludes only the manager's own receipt. Concurrent policy/graph changes invalidate its plan. */
export const managerSnapshot = (graph: GoalGraphSnapshot) => {
@@ -108,18 +110,89 @@ export class GoalManagerService {
) {}
usage = async (state?: GoalManagerState) => {
- const operations = state
- ? await new AgentOperationModel(this.db, this.userId, this.workspaceId).listByTopic(
- state.topicId,
- 100,
- )
- : [];
+ // The planning topic can be the user's own conversation (`/goal`), so only
+ // manager turns count as management spend: the dispatched ones by their
+ // server-minted source message, the adopted one by its operation id. The
+ // rest of that conversation is the user's chat, not the goal's budget.
+ if (!state) return { totalCost: 0, totalTokens: 0 };
+ const model = new AgentOperationModel(this.db, this.userId, this.workspaceId);
+ // Later receipts replace `adopted` / `operationId`, so the adopted run is
+ // read from the id every receipt carries forward.
+ const adoptedId = state.adoptedOperationId ?? (state.adopted ? state.operationId : undefined);
+ const operations = (await model.listByTopic(state.topicId, 100)).filter(
+ (op) =>
+ op.appContext?.sourceMessageId?.startsWith(MANAGER_SOURCE_MESSAGE_PREFIX) ||
+ op.id === adoptedId,
+ );
+ // A handoff moves later turns to the new agent's topic; the adopted run
+ // stays on the original conversation and still counts.
+ if (adoptedId && !operations.some((op) => op.id === adoptedId)) {
+ const adoptedRun = await model.findById(adoptedId);
+ if (adoptedRun) operations.push(adoptedRun);
+ }
return {
totalCost: operations.reduce((sum, op) => sum + (Number(op.totalCost) || 0), 0),
totalTokens: operations.reduce((sum, op) => sum + (op.totalTokens ?? 0), 0),
};
};
+ /**
+ * The operation that is the current planning turn. A dispatched turn is found
+ * by the source message the manager minted for it; an adopted turn — the
+ * conversation run that created the goal — never had one, so it is the
+ * operation recorded at adoption.
+ */
+ private turnOperation = async (operations: AgentOperationModel, state: GoalManagerState) =>
+ state.adopted
+ ? state.operationId
+ ? ((await operations.findById(state.operationId)) ?? undefined)
+ : undefined
+ : operations.findByTopicSourceMessage(
+ state.topicId,
+ `${MANAGER_SOURCE_MESSAGE_PREFIX}${state.token}`,
+ );
+
+ /**
+ * Make the conversation run that created this goal its first planning turn.
+ *
+ * `/goal` in a conversation asks the agent already running there to supervise:
+ * it creates the goal and plans it in the same run, so the user watches both
+ * happen in their conversation. Dispatching a separate first turn would wait on
+ * that very run to release the topic. The receipt carries the same snapshot and
+ * review hash a dispatched turn would, so `submit` validates the plan the same
+ * way; only the operation lookup differs (`adopted`).
+ */
+ adoptConversationTurn = async (goalId: string, run: { operationId: string; topicId: string }) =>
+ this.db.transaction(async (db) => {
+ const model = new GoalModel(db, this.userId, this.workspaceId);
+ const goal = await model.lockById(goalId);
+ if (!goal?.config?.manager) throw new Error('Goal has no main Agent policy to adopt a turn');
+ if (goal.config.managerState) throw new Error('Goal already has a planning turn');
+ // A local desktop run has no server operation row; the caller already
+ // matched its conversation to the goal agent. A recorded run must match too.
+ const operation = await new AgentOperationModel(db, this.userId, this.workspaceId).findById(
+ run.operationId,
+ );
+ if (operation && (operation.topicId !== run.topicId || operation.agentId !== goal.agentId))
+ throw new Error('The adopted run does not belong to the goal agent');
+ const graph = await this.graph(db).getGraph(goalId);
+ if (!graph) throw new Error('Goal not found');
+ const state: GoalManagerState = {
+ adopted: true,
+ adoptedOperationId: run.operationId,
+ operationId: run.operationId,
+ reviewSnapshot: (await this.reviews(graph, db)).hash,
+ snapshot: managerSnapshot(graph),
+ startedAt: new Date().toISOString(),
+ token: randomUUID(),
+ topicId: run.topicId,
+ turns: 1,
+ };
+ await this.save(db, goalId, state);
+ if (goal.status === 'planning') await model.updateStatus(goalId, 'running');
+ return state;
+ });
+
private save = async (db: LobeChatDatabase, id: string, state: GoalManagerState) => {
// Caller holds the owned Goal row lock. Do not overwrite concurrent policy namespaces.
await db
@@ -287,12 +360,14 @@ export class GoalManagerService {
const { goal } = graph;
const state = goal.config?.managerState;
if (state && !state.consumed) {
- const operation = await new AgentOperationModel(
- this.db,
- this.userId,
- this.workspaceId,
- ).findByTopicSourceMessage(state.topicId, `msg_goal_manager_${state.token}`);
- if (!operation || !terminalOperations.has(operation.status)) {
+ const operation = await this.turnOperation(
+ new AgentOperationModel(this.db, this.userId, this.workspaceId),
+ state,
+ );
+ // An adopted local desktop run has no server operation to watch exit; its
+ // submitted plan is the only settlement the server can observe.
+ const settledLocally = !!state.adopted && !operation && !!state.submitted;
+ if (!settledLocally && (!operation || !terminalOperations.has(operation.status))) {
if (operation?.status === 'waiting_for_human') {
await this.wait(goal.id, 'Main Agent is waiting for a human decision');
return {
@@ -317,7 +392,7 @@ export class GoalManagerService {
) {
await this.save(db, goal.id, {
...fresh.config.managerState,
- operationId: operation.id,
+ operationId: operation?.id ?? state.operationId,
consumed: true,
});
}
@@ -442,6 +517,7 @@ export class GoalManagerService {
...(problem.taskId && { problemTaskId: problem.taskId }),
}
: {}),
+ ...(state?.adoptedOperationId && { adoptedOperationId: state.adoptedOperationId }),
reviewSnapshot: reviews.hash,
topicId,
turns: (state?.turns ?? 0) + 1,
@@ -502,15 +578,17 @@ export class GoalManagerService {
code: 'FORBIDDEN',
message: 'This planning turn does not own the Goal',
});
- const op = await new AgentOperationModel(
- db,
- this.userId,
- this.workspaceId,
- ).findByTopicSourceMessage(state.topicId, `msg_goal_manager_${token}`);
+ const op = await this.turnOperation(
+ new AgentOperationModel(db, this.userId, this.workspaceId),
+ state,
+ );
// Bound to the goal agent as it is NOW: a turn dispatched before a handoff
// no longer speaks for the goal.
const agentId = goal.agentId;
- if (op?.id !== operationId || op.agentId !== agentId)
+ // An adopted local desktop run has no server operation row; it is the run
+ // whose id the conversation environment carried when the goal was created.
+ const localAdoptedRun = !!state.adopted && !op && operationId === state.operationId;
+ if (!localAdoptedRun && (op?.id !== operationId || op.agentId !== agentId))
throw new TRPCError({ code: 'FORBIDDEN', message: 'Unrelated main Agent operation' });
const graph = await this.graph(db).getGraph(goalId);
if (
@@ -523,7 +601,11 @@ export class GoalManagerService {
message: 'Goal stopped or awaiting human decision',
});
if (state.submitted) return { duplicate: true, plan: state.submitted };
- if (state.consumed || op.status !== 'running' || managerSnapshot(graph) !== state.snapshot)
+ if (
+ state.consumed ||
+ (op && op.status !== 'running') ||
+ managerSnapshot(graph) !== state.snapshot
+ )
throw new TRPCError({ code: 'CONFLICT', message: 'Stale planning input; no plan applied' });
if (state.reviewSnapshot && (await this.reviews(graph, db)).hash !== state.reviewSnapshot)
throw new TRPCError({
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index bc40c4740fb..0f890191723 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -637,6 +637,7 @@
"goalProcess.kind.finding": "Finding",
"goalProcess.kind.problem": "Question",
"goalProcess.kind.task": "Task",
+ "goalProcess.linked.open": "Open goal progress",
"goalProcess.manager.pending": "Waiting for the first run",
"goalProcess.manager.title": "Main agent",
"goalProcess.manager.turns": "Planning rounds: {{count}}",
@@ -727,6 +728,8 @@
"goalProcess.paused": "Paused — no new work will start",
"goalProcess.planning.description": "The coordinator is breaking the goal into executable tasks — they will appear here shortly.",
"goalProcess.planning.title": "Planning the exploration",
+ "goalProcess.portal.openPage": "Open goal page",
+ "goalProcess.portal.title": "Goal",
"goalProcess.requirementPlaceholder": "Describe what counts as done…",
"goalProcess.requirementSaveFailed": "Failed to save the requirement — it will retry on your next edit",
"goalProcess.resume": "Resume",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 62628dc8ccf..8b27c8892ba 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -637,6 +637,7 @@
"goalProcess.kind.finding": "结论",
"goalProcess.kind.problem": "问题",
"goalProcess.kind.task": "任务",
+ "goalProcess.linked.open": "查看目标进度",
"goalProcess.manager.pending": "等待首次执行",
"goalProcess.manager.title": "主 Agent",
"goalProcess.manager.turns": "已发起 {{count}} 轮规划",
@@ -727,6 +728,8 @@
"goalProcess.paused": "已暂停,不会再开始新的任务",
"goalProcess.planning.description": "协调器正在把目标拆解为可执行任务,节点稍后会陆续出现",
"goalProcess.planning.title": "正在规划探索方向",
+ "goalProcess.portal.openPage": "打开目标页",
+ "goalProcess.portal.title": "目标",
"goalProcess.requirementPlaceholder": "描述怎样才算达成这个目标…",
"goalProcess.requirementSaveFailed": "验收要求保存失败,下次编辑时会自动重试",
"goalProcess.resume": "继续",
diff --git a/packages/builtin-tool-goal/src/conversationGoalPrompt.test.ts b/packages/builtin-tool-goal/src/conversationGoalPrompt.test.ts
new file mode 100644
index 00000000000..e32fc01ae20
--- /dev/null
+++ b/packages/builtin-tool-goal/src/conversationGoalPrompt.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+
+import { conversationGoalPrompt, withConversationGoalPrompt } from './conversationGoalPrompt';
+import { stripGoalCommand } from './goalPrompt';
+
+describe('stripGoalCommand', () => {
+ it("sends a CLI agent the request without /goal, so Claude Code's own /goal does not take it", () => {
+ expect(stripGoalCommand('/goal ship the report')).toBe('ship the report');
+ expect(stripGoalCommand(' /GOAL\nship the report')).toBe('ship the report');
+ });
+
+ it('leaves every other prompt untouched', () => {
+ expect(stripGoalCommand('fix the build')).toBe('fix the build');
+ expect(stripGoalCommand('/goals are nice')).toBe('/goals are nice');
+ expect(stripGoalCommand(undefined)).toBeUndefined();
+ });
+});
+
+describe('withConversationGoalPrompt', () => {
+ it('leaves an ordinary message context untouched', () => {
+ expect(withConversationGoalPrompt('Repo rules', 'fix the build')).toBe('Repo rules');
+ expect(withConversationGoalPrompt(undefined, 'fix the build')).toBeUndefined();
+ });
+
+ it('appends the /goal instructions after the agent context', () => {
+ expect(withConversationGoalPrompt('Repo rules', '/goal ship the report')).toBe(
+ `Repo rules\n\n${conversationGoalPrompt}`,
+ );
+ });
+
+ it('injects the instructions alone when the agent has no context', () => {
+ expect(withConversationGoalPrompt(' ', '/goal ship the report')).toBe(conversationGoalPrompt);
+ });
+
+ it('tells the agent to create the goal from this conversation and plan it in the same run', () => {
+ expect(conversationGoalPrompt).toContain('lh goal create');
+ expect(conversationGoalPrompt).toContain('--conversation');
+ expect(conversationGoalPrompt).toContain('lh goal plan <goalId> --token <turnToken>');
+ });
+
+ it('plans from the create output instead of reading the goal back', () => {
+ // A device run holds an operation token, which the goal read endpoint
+ // refuses; telling the agent to run `lh goal show` made its first command
+ // after create fail and pushed it to work around its own credentials.
+ expect(conversationGoalPrompt).not.toContain('Run lh goal show');
+ expect(conversationGoalPrompt).toContain('do not run lh goal show');
+ });
+});
diff --git a/packages/builtin-tool-goal/src/conversationGoalPrompt.ts b/packages/builtin-tool-goal/src/conversationGoalPrompt.ts
new file mode 100644
index 00000000000..f3a4a52f83b
--- /dev/null
+++ b/packages/builtin-tool-goal/src/conversationGoalPrompt.ts
@@ -0,0 +1,38 @@
+import { isGoalPrompt } from './goalPrompt';
+
+/**
+ * Instructions injected into a heterogeneous agent's context (Claude Code,
+ * Codex, Kimi…) when the user's message starts with `/goal`.
+ *
+ * Those agents never receive the builtin goal tool: they run the `lh` CLI in
+ * their own shell. So `/goal` is delivered as instructions rather than a tool —
+ * create the goal bound to this conversation, then plan it in the same run,
+ * which the server adopts as the goal's first planning turn.
+ */
+export const conversationGoalPrompt = `The user sent this request with LobeHub's /goal command (the prefix was removed before it reached you; it is not your own /goal command). They are asking you to turn the request into a long-running LobeHub Goal that you supervise from this conversation, not to do the work yourself in this run.
+
+1. Draft the goal from the user's request, in the user's language: a short title, the requirement, and one concrete, checkable acceptance criterion per explicit requirement. Do not add requirements the user did not ask for.
+2. Create it bound to this conversation (the LOBEHUB_* environment already identifies you and this conversation):
+ lh goal create "<title>" --conversation -r "<requirement>" -i "<the user's ask in their words>" --criterion "<criterion>" --criterion "<criterion>" --json
+ The output contains goal.id and turnToken. You are now the goal's supervising agent, and this run is its first planning turn.
+3. Plan it now from the goal graph already printed by lh goal create (do not run lh goal show or other lh goal commands: this run's credentials only allow creating this goal and submitting its plan). Write a JSON plan file and submit it once:
+ lh goal plan <goalId> --token <turnToken> --file <path> --json
+ Plan schema: {"action":"tasks","reason":"evidence-based rationale","tasks":[{"title":"specific task","description":"self-contained contract: inputs, output and acceptance"}]}
+ Plan bounded, independent tasks; the goal's coordinator dispatches and runs them under the goal budget.
+4. Then end the run with one or two sentences in the user's language: the goal is running, and what the first tasks are.
+
+Do not execute, preview or self-check the tasks, mark them complete, change budgets, or claim the goal is achieved. Later planning turns continue in this conversation once tasks deliver.`;
+
+/**
+ * The agent-level context with the `/goal` instructions appended when the
+ * prompt asks for a goal; unchanged otherwise.
+ */
+export const withConversationGoalPrompt = (
+ agentSystemContext: string | undefined,
+ prompt: unknown,
+): string | undefined => {
+ if (!isGoalPrompt(prompt)) return agentSystemContext;
+ return agentSystemContext?.trim()
+ ? `${agentSystemContext.trim()}\n\n${conversationGoalPrompt}`
+ : conversationGoalPrompt;
+};
diff --git a/packages/builtin-tool-goal/src/goalPrompt.ts b/packages/builtin-tool-goal/src/goalPrompt.ts
index 0f2917d4e88..04a75fdd096 100644
--- a/packages/builtin-tool-goal/src/goalPrompt.ts
+++ b/packages/builtin-tool-goal/src/goalPrompt.ts
@@ -3,3 +3,19 @@ const GOAL_COMMAND_PATTERN = /^\s*\/goal(?:\s|$)/i;
/** Whether a user prompt explicitly requests the canonical goal workflow. */
export const isGoalPrompt = (prompt: unknown): boolean =>
typeof prompt === 'string' && GOAL_COMMAND_PATTERN.test(prompt);
+
+/**
+ * The prompt a heterogeneous CLI agent receives for a `/goal` message: the
+ * request without its leading `/goal`.
+ *
+ * Claude Code ships its own `/goal` slash command. Sent verbatim, the user's
+ * message is taken over by it — it pins a session goal and installs a stop
+ * hook that refuses to end the run until the work is done, while LobeHub's goal
+ * waits for that same run to end before dispatching the work. The LobeHub
+ * instructions travel in the system context; the prompt only carries the ask.
+ * Other prompts pass through unchanged.
+ */
+export const stripGoalCommand = <T>(prompt: T): T =>
+ typeof prompt === 'string' && GOAL_COMMAND_PATTERN.test(prompt)
+ ? (prompt.replace(GOAL_COMMAND_PATTERN, '').trimStart() as T)
+ : prompt;
diff --git a/packages/builtin-tool-goal/src/index.ts b/packages/builtin-tool-goal/src/index.ts
index 86b08627472..35d2a379a88 100644
--- a/packages/builtin-tool-goal/src/index.ts
+++ b/packages/builtin-tool-goal/src/index.ts
@@ -1,10 +1,11 @@
+export { conversationGoalPrompt, withConversationGoalPrompt } from './conversationGoalPrompt';
export {
buildGoalRequirement,
type GoalCriterionInput,
resolveGoalAttemptBudget,
resolveGoalScheduleConfig,
} from './createGoalInput';
-export { isGoalPrompt } from './goalPrompt';
+export { isGoalPrompt, stripGoalCommand } from './goalPrompt';
export { GoalIdentifier, GoalManifest } from './manifest';
export * from './supervisor';
export { systemPrompt } from './systemRole';
diff --git a/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx b/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx
index c9233995d62..6ca02512852 100644
--- a/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx
@@ -20,7 +20,7 @@ import {
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useChatStore } from '@/store/chat';
import { goalSelectors, useGoalStore } from '@/store/goal';
import type { CreateGoalParams, CreateGoalState } from '../../../types';
@@ -125,7 +125,7 @@ const resolvePhase = (status: GoalStatus | undefined, pendingDecisions: number):
const CreateGoalRender = memo<BuiltinRenderProps<CreateGoalParams, CreateGoalState>>(
({ args, pluginState }) => {
const { t } = useTranslation('plugin');
- const navigate = useWorkspaceAwareNavigate();
+ const openGoalPortal = useChatStore((s) => s.openGoal);
const goalId = pluginState?.goalId;
const [now, setNow] = useState(() => Date.now());
@@ -150,8 +150,9 @@ const CreateGoalRender = memo<BuiltinRenderProps<CreateGoalParams, CreateGoalSta
if (!pluginState?.success || !goalId) return null;
- const agentId = snapshot?.goal.agentId;
- const openGoal = agentId ? () => navigate(`/agent/${agentId}/goal/${goalId}`) : undefined;
+ // The goal's progress opens beside the conversation that created it; the
+ // portal view links on to the full goal page.
+ const openGoal = () => openGoalPortal(goalId);
return (
<TaskResultCard
@@ -163,7 +164,7 @@ const CreateGoalRender = memo<BuiltinRenderProps<CreateGoalParams, CreateGoalSta
horizontal
align={'center'}
gap={8}
- style={openGoal ? { cursor: 'pointer' } : undefined}
+ style={{ cursor: 'pointer' }}
onClick={openGoal}
>
<Icon
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index 3c6588c626d..a5fbe18d19e 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -528,6 +528,7 @@ export class AgentOperationModel {
return this.db
.select({
agentId: agentOperations.agentId,
+ appContext: agentOperations.appContext,
createdAt: agentOperations.createdAt,
id: agentOperations.id,
model: agentOperations.model,
diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.ts
index f9128feea4a..fe2a27f9608 100644
--- a/packages/database/src/models/goal.ts
+++ b/packages/database/src/models/goal.ts
@@ -341,9 +341,11 @@ export class GoalModel {
offset?: number;
projectId?: string;
statuses?: GoalStatus[];
+ /** Goals created from this conversation (`subject_type = 'topic'`). */
+ topicId?: string;
} = {},
): Promise<{ goals: GoalListItem[]; total: number }> => {
- const { agentId, limit = 50, offset = 0, projectId, statuses } = options;
+ const { agentId, limit = 50, offset = 0, projectId, statuses, topicId } = options;
// Only goals that actually have a graph. Rows created by the earlier
// task-carried flow have no `goal_nodes`, so they would render as a
@@ -353,6 +355,7 @@ export class GoalModel {
if (agentId) conditions.push(eq(goals.agentId, agentId));
if (projectId) conditions.push(eq(goals.projectId, projectId));
if (statuses && statuses.length > 0) conditions.push(inArray(goals.status, statuses));
+ if (topicId) conditions.push(eq(goals.subjectType, 'topic'), eq(goals.subjectId, topicId));
const [countRow] = await this.db
.select({ count: sql<number>`count(*)` })
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 0a3464acba2..a9f765d137f 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2038,6 +2038,9 @@ export default {
'goalProcess.graph.view.all': 'Full map',
'goalProcess.graph.fullscreen': 'Fullscreen',
'goalProcess.graph.exitFullscreen': 'Exit fullscreen',
+ 'goalProcess.linked.open': 'Open goal progress',
+ 'goalProcess.portal.openPage': 'Open goal page',
+ 'goalProcess.portal.title': 'Goal',
'goalProcess.graph.legend.hide': 'Hide this kind on the map',
'goalProcess.graph.legend.show': 'Show this kind on the map',
'goalProcess.edge.investigates': 'investigates',
diff --git a/packages/trpc/src/utils/__tests__/internalJwt.test.ts b/packages/trpc/src/utils/__tests__/internalJwt.test.ts
index dd29079a806..bfcb5ef08da 100644
--- a/packages/trpc/src/utils/__tests__/internalJwt.test.ts
+++ b/packages/trpc/src/utils/__tests__/internalJwt.test.ts
@@ -219,6 +219,22 @@ describe('internalJwt', () => {
expect(validateHeteroOperationClaims(validClaims)).toEqual(validClaims);
});
+ it('accepts the goal capability dispatched runs carry for /goal', async () => {
+ const { validateHeteroOperationClaims } = await import('../internalJwt');
+ const claims = {
+ ...validClaims,
+ capabilities: ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read', 'goal:manage'],
+ };
+ expect(validateHeteroOperationClaims(claims)).toEqual(claims);
+ });
+
+ it('rejects a capability it does not know', async () => {
+ const { validateHeteroOperationClaims } = await import('../internalJwt');
+ expect(
+ validateHeteroOperationClaims({ ...validClaims, capabilities: ['goal:delete'] }),
+ ).toBeNull();
+ });
+
it.each(['aud', 'iss', 'purpose', 'operation_id', 'capabilities'])(
'rejects invalid %s',
async (field) => {
diff --git a/packages/trpc/src/utils/internalJwt.ts b/packages/trpc/src/utils/internalJwt.ts
index 90856fecacb..b9dda6a9ec7 100644
--- a/packages/trpc/src/utils/internalJwt.ts
+++ b/packages/trpc/src/utils/internalJwt.ts
@@ -13,7 +13,7 @@ export const HETERO_OPERATION_JWT_AUDIENCE = 'urn:lobehub:hetero-operation';
export const HETERO_OPERATION_JWT_PURPOSE = 'hetero-operation';
export type HeteroOperationCapability =
- 'hetero:finish' | 'hetero:ingest' | 'hetero:intervention:read' | 'model:invoke';
+ 'goal:manage' | 'hetero:finish' | 'hetero:ingest' | 'hetero:intervention:read' | 'model:invoke';
export interface HeteroOperationJwtClaims {
aud: typeof HETERO_OPERATION_JWT_AUDIENCE;
@@ -185,9 +185,13 @@ export const validateHeteroOperationClaims = (
typeof payload.exp !== 'number' ||
!Array.isArray(capabilities) ||
!capabilities.every((capability) =>
- ['model:invoke', 'hetero:ingest', 'hetero:finish', 'hetero:intervention:read'].includes(
- capability as string,
- ),
+ [
+ 'goal:manage',
+ 'model:invoke',
+ 'hetero:ingest',
+ 'hetero:finish',
+ 'hetero:intervention:read',
+ ].includes(capability as string),
) ||
(payload.model !== undefined && typeof payload.model !== 'string') ||
(payload.provider_id !== undefined && typeof payload.provider_id !== 'string') ||
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 96440fa8f31..b99ff878420 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -221,6 +221,20 @@ export interface GoalManagerPolicy {
/** Server-owned dispatch receipt, retained across backend restarts. */
export interface GoalManagerState {
+ /**
+ * The turn was not dispatched by the manager: it is the conversation run that
+ * created the goal (`/goal` → `lh goal create --conversation`), adopted as the
+ * first planning turn. The turn is keyed by `operationId` instead of the
+ * server-minted `msg_goal_manager_<token>` source message.
+ */
+ adopted?: boolean;
+ /**
+ * The conversation run adopted as the first planning turn, kept on every later
+ * receipt. `adopted` / `operationId` describe the current turn and are replaced
+ * when the next one starts; without this the first run's spend would drop out
+ * of the goal's management usage and budget.
+ */
+ adoptedOperationId?: string;
consumed?: boolean;
operationId?: string;
/**
diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsx
index 9573e378516..1fafcb25e13 100644
--- a/src/features/AgentGoals/GoalDetailPage.tsx
+++ b/src/features/AgentGoals/GoalDetailPage.tsx
@@ -2,9 +2,9 @@
import { Flexbox } from '@lobehub/ui';
import { Button, Text } from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar } from 'antd-style';
+import { createStaticStyles } from 'antd-style';
import { EyeIcon, PauseIcon, PlayIcon } from 'lucide-react';
-import { memo, type ReactNode, useEffect, useMemo, useRef, useState } from 'react';
+import { memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router';
@@ -19,26 +19,18 @@ import { usePortalPanelWidth } from '@/features/Portal/usePortalPanelWidth';
import RightPanel from '@/features/RightPanel';
import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';
import WideScreenContainer from '@/features/WideScreenContainer';
-import { useActivityTime } from '@/hooks/useActivityTime';
import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
-import { type GoalMetricKind } from '@/store/chat/slices/portal/initialState';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { goalSelectors, useGoalStore } from '@/store/goal';
import GoalChat from './GoalChat';
import GoalDetailActions from './GoalDetailActions';
-import {
- formatSpan,
- formatUsd,
- goalManagerConversation,
- goalStatusKey,
- summarizeGoalBudget,
-} from './goalPresentation';
+import GoalHeaderMetrics from './GoalHeaderMetrics';
+import { goalManagerConversation } from './goalPresentation';
import GoalRequirement from './GoalRequirement';
-import GoalStatusGlyph from './GoalStatusGlyph';
import { GoalSupervision } from './GoalSupervision';
import NorthStarMetrics from './NorthStarMetrics';
import ProcessControl from './ProcessControl';
@@ -58,58 +50,8 @@ const styles = createStaticStyles(({ css }) => ({
header: css`
padding-block: 8px 4px;
`,
- metric: css`
- cursor: pointer;
-
- min-width: 112px;
- padding-block: 4px;
- padding-inline: 10px;
- border-radius: ${cssVar.borderRadius};
-
- transition: background 0.15s;
-
- &:hover {
- background: ${cssVar.colorFillQuaternary};
- }
- `,
- metrics: css`
- /* Negative inline offset keeps the metric text aligned with the title while
- the hover background still gets breathing room. */
- margin-inline-start: -10px;
- `,
}));
-const Metric = memo<{
- label: string;
- onClick: () => void;
- value: ReactNode;
-}>(({ label, onClick, value }) => (
- <Flexbox className={styles.metric} gap={2} onClick={onClick}>
- <Flexbox horizontal align={'center'} gap={7} style={{ minHeight: 26 }}>
- {value}
- </Flexbox>
- <Text fontSize={12} type={'secondary'}>
- {label}
- </Text>
- </Flexbox>
-));
-
-Metric.displayName = 'GoalHeaderMetric';
-
-/** Relative "last activity" readout; isolated so its refresh never re-renders the page.
- * Plain text on purpose: the status control already carries the "running"
- * animation, and a second spinner here said the same thing twice. */
-const LivenessValue = memo<{ latest?: Date }>(({ latest }) => {
- const { text } = useActivityTime(latest);
- return (
- <Text fontSize={16} weight={600}>
- {text || '—'}
- </Text>
- );
-});
-
-LivenessValue.displayName = 'GoalLivenessValue';
-
interface GoalDetailPageProps {
/** Absent for a goal with no responsible agent — e.g. one created from a project. */
agentId?: string;
@@ -130,7 +72,6 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
const showPortal = useChatStore(chatPortalSelectors.showPortal);
const currentViewType = useChatStore(chatPortalSelectors.currentViewType);
const chat = useGoalChatPanel(goalId, agentId);
- const openGoalMetric = useChatStore((s) => s.openGoalMetric);
const clearPortalStack = useChatStore((s) => s.clearPortalStack);
// While the exploration map runs fullscreen its overlay carries the portal
@@ -189,15 +130,6 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
// page (or switching goals) must not leak it into the conversation surface.
useEffect(() => () => clearPortalStack(), [clearPortalStack, goalId]);
- const liveness = useMemo(() => {
- if (!snapshot) return { latest: undefined };
- let latest: Date | undefined;
- for (const node of snapshot.nodes) {
- if (!latest || node.updatedAt > latest) latest = node.updatedAt;
- }
- return { latest };
- }, [snapshot]);
-
if (error && !snapshot) return <AsyncError error={error} variant={'page'} onRetry={mutate} />;
if (!snapshot)
return isLoading ? (
@@ -208,9 +140,6 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
const { goal, nodes } = snapshot;
const managerConversation = goalManagerConversation(goal);
- const tasks = nodes.filter((node) => node.kind === 'task').length;
- const findings = nodes.filter((node) => node.kind === 'finding').length;
- const open = (metric: GoalMetricKind) => () => openGoalMetric(goalId, metric);
// The panel hosts the goal conversation only when the goal has a
// responsible agent; without one it is drill-down-only.
@@ -226,29 +155,6 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
nodes.length > 0 &&
['paused', 'planning', 'running', 'verifying'].includes(goal.status);
- const durationText = goal.startedAt
- ? formatSpan((goal.completedAt ?? new Date()).getTime() - goal.startedAt.getTime())
- : '—';
- // Spend is the metric; the cap is the context it is read against — see
- // `summarizeGoalBudget`. The label names only the number in the lead, and the
- // cap trails it at secondary weight rather than sharing top billing.
- const budget = summarizeGoalBudget(goal, snapshot.spend);
- const budgetLabel = t(
- budget.kind === 'rounds' ? 'goalProcess.metrics.rounds' : 'goalProcess.metrics.spend',
- );
- const budgetLead =
- budget.kind === 'cost'
- ? formatUsd(budget.spent)
- : budget.kind === 'rounds'
- ? String(budget.runs)
- : formatUsd(budget.spent);
- const budgetTrail =
- budget.kind === 'cost'
- ? `/ ${formatUsd(budget.cap)}`
- : budget.kind === 'rounds'
- ? `/ ${t('goalProcess.metrics.roundsValue', { count: budget.cap })}`
- : t('goalProcess.metrics.uncapped');
-
return (
<Flexbox horizontal flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
<Flexbox flex={1} height={'100%'} style={{ minWidth: 0 }}>
@@ -305,66 +211,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
<Text as={'h1'} fontSize={22} weight={600}>
{goal.title}
</Text>
- <Flexbox horizontal className={styles.metrics} gap={8} wrap={'wrap'}>
- <Metric
- label={t('goalProcess.metrics.status')}
- value={
- <>
- <GoalStatusGlyph size={16} status={goal.status} />
- <Text fontSize={16} weight={600}>
- {t(goalStatusKey(goal.status))}
- </Text>
- </>
- }
- onClick={open('lifecycle')}
- />
- <Metric
- label={t('goalProcess.metrics.tasks')}
- value={
- <Text fontSize={16} weight={600}>
- {tasks}
- </Text>
- }
- onClick={open('tasks')}
- />
- <Metric
- label={t('goalProcess.metrics.findings')}
- value={
- <Text fontSize={16} weight={600}>
- {findings}
- </Text>
- }
- onClick={open('findings')}
- />
- <Metric
- label={budgetLabel}
- value={
- <>
- <Text fontSize={16} weight={600}>
- {budgetLead}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {budgetTrail}
- </Text>
- </>
- }
- onClick={open('budget')}
- />
- <Metric
- label={t('goalProcess.metrics.duration')}
- value={
- <Text fontSize={16} weight={600}>
- {durationText}
- </Text>
- }
- onClick={open('duration')}
- />
- <Metric
- label={t('goalProcess.metrics.liveness')}
- value={<LivenessValue latest={liveness.latest} />}
- onClick={open('liveness')}
- />
- </Flexbox>
+ <GoalHeaderMetrics goalId={goalId} />
{/* Pause/resume above the requirement document — its reviewed
home. The status glyph keeps the "running" animation; this
button is only the control. */}
diff --git a/src/features/AgentGoals/GoalHeaderMetrics.tsx b/src/features/AgentGoals/GoalHeaderMetrics.tsx
new file mode 100644
index 00000000000..168937e171f
--- /dev/null
+++ b/src/features/AgentGoals/GoalHeaderMetrics.tsx
@@ -0,0 +1,186 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, type ReactNode, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActivityTime } from '@/hooks/useActivityTime';
+import { useChatStore } from '@/store/chat';
+import { type GoalMetricKind } from '@/store/chat/slices/portal/initialState';
+import { goalSelectors, useGoalStore } from '@/store/goal';
+
+import { formatSpan, formatUsd, goalStatusKey, summarizeGoalBudget } from './goalPresentation';
+import GoalStatusGlyph from './GoalStatusGlyph';
+
+/**
+ * The goal's header metrics row — status, tasks, findings, spend, runtime and
+ * last activity. Every metric is a drill-down entry into the Portal's metric
+ * view. Reads the graph snapshot itself, so any host that has fetched the goal
+ * graph (the goal page, the conversation portal) can mount it by id.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ metric: css`
+ cursor: pointer;
+
+ min-width: 112px;
+ padding-block: 4px;
+ padding-inline: 10px;
+ border-radius: ${cssVar.borderRadius};
+
+ transition: background 0.15s;
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ metrics: css`
+ /* Negative inline offset keeps the metric text aligned with the title while
+ the hover background still gets breathing room. */
+ margin-inline-start: -10px;
+ `,
+}));
+
+const Metric = memo<{
+ label: string;
+ onClick: () => void;
+ value: ReactNode;
+}>(({ label, onClick, value }) => (
+ <Flexbox className={styles.metric} gap={2} onClick={onClick}>
+ <Flexbox horizontal align={'center'} gap={7} style={{ minHeight: 26 }}>
+ {value}
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {label}
+ </Text>
+ </Flexbox>
+));
+
+Metric.displayName = 'GoalHeaderMetric';
+
+/** Relative "last activity" readout; isolated so its refresh never re-renders the row.
+ * Plain text on purpose: the status control already carries the "running"
+ * animation, and a second spinner here said the same thing twice. */
+const LivenessValue = memo<{ latest?: Date }>(({ latest }) => {
+ const { text } = useActivityTime(latest);
+ return (
+ <Text fontSize={16} weight={600}>
+ {text || '—'}
+ </Text>
+ );
+});
+
+LivenessValue.displayName = 'GoalLivenessValue';
+
+const GoalHeaderMetrics = memo<{ goalId: string }>(({ goalId }) => {
+ const { t } = useTranslation('chat');
+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
+ const openGoalMetric = useChatStore((s) => s.openGoalMetric);
+
+ const latest = useMemo(() => {
+ let value: Date | undefined;
+ for (const node of snapshot?.nodes ?? []) {
+ if (!value || node.updatedAt > value) value = node.updatedAt;
+ }
+ return value;
+ }, [snapshot]);
+
+ if (!snapshot) return null;
+
+ const { goal, nodes } = snapshot;
+ const tasks = nodes.filter((node) => node.kind === 'task').length;
+ const findings = nodes.filter((node) => node.kind === 'finding').length;
+ const open = (metric: GoalMetricKind) => () => openGoalMetric(goalId, metric);
+
+ const durationText = goal.startedAt
+ ? formatSpan((goal.completedAt ?? new Date()).getTime() - goal.startedAt.getTime())
+ : '—';
+ // Spend is the metric; the cap is the context it is read against — see
+ // `summarizeGoalBudget`. The label names only the number in the lead, and the
+ // cap trails it at secondary weight rather than sharing top billing.
+ const budget = summarizeGoalBudget(goal, snapshot.spend);
+ const budgetLabel = t(
+ budget.kind === 'rounds' ? 'goalProcess.metrics.rounds' : 'goalProcess.metrics.spend',
+ );
+ const budgetLead =
+ budget.kind === 'cost'
+ ? formatUsd(budget.spent)
+ : budget.kind === 'rounds'
+ ? String(budget.runs)
+ : formatUsd(budget.spent);
+ const budgetTrail =
+ budget.kind === 'cost'
+ ? `/ ${formatUsd(budget.cap)}`
+ : budget.kind === 'rounds'
+ ? `/ ${t('goalProcess.metrics.roundsValue', { count: budget.cap })}`
+ : t('goalProcess.metrics.uncapped');
+
+ return (
+ <Flexbox horizontal className={styles.metrics} gap={8} wrap={'wrap'}>
+ <Metric
+ label={t('goalProcess.metrics.status')}
+ value={
+ <>
+ <GoalStatusGlyph size={16} status={goal.status} />
+ <Text fontSize={16} weight={600}>
+ {t(goalStatusKey(goal.status))}
+ </Text>
+ </>
+ }
+ onClick={open('lifecycle')}
+ />
+ <Metric
+ label={t('goalProcess.metrics.tasks')}
+ value={
+ <Text fontSize={16} weight={600}>
+ {tasks}
+ </Text>
+ }
+ onClick={open('tasks')}
+ />
+ <Metric
+ label={t('goalProcess.metrics.findings')}
+ value={
+ <Text fontSize={16} weight={600}>
+ {findings}
+ </Text>
+ }
+ onClick={open('findings')}
+ />
+ <Metric
+ label={budgetLabel}
+ value={
+ <>
+ <Text fontSize={16} weight={600}>
+ {budgetLead}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {budgetTrail}
+ </Text>
+ </>
+ }
+ onClick={open('budget')}
+ />
+ <Metric
+ label={t('goalProcess.metrics.duration')}
+ value={
+ <Text fontSize={16} weight={600}>
+ {durationText}
+ </Text>
+ }
+ onClick={open('duration')}
+ />
+ <Metric
+ label={t('goalProcess.metrics.liveness')}
+ value={<LivenessValue latest={latest} />}
+ onClick={open('liveness')}
+ />
+ </Flexbox>
+ );
+});
+
+GoalHeaderMetrics.displayName = 'GoalHeaderMetrics';
+
+export default GoalHeaderMetrics;
diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
index f9a3ee46384..364c2714130 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
@@ -183,14 +183,17 @@ const styles = createStaticStyles(({ css }) => ({
type GraphViewMode = 'stage' | 'all';
interface GraphProps {
+ /** Header actions after the legend — e.g. a host without fullscreen links out to the goal page. */
+ extra?: ReactNode;
/**
* Fullscreen is owned by the page: the overlay replaces the page's Portal
* panel with its own, and only the owner can keep exactly one of the two
- * mounted at a time.
+ * mounted at a time. A host that cannot give up its panel (the Portal itself)
+ * omits `onFullscreenChange`, and the map stays inline.
*/
- fullscreen: boolean;
+ fullscreen?: boolean;
graph: GoalGraphView;
- onFullscreenChange: (fullscreen: boolean) => void;
+ onFullscreenChange?: (fullscreen: boolean) => void;
onSelect: (nodeId: string) => void;
/** The coordinator is still decomposing: show ghost task cards under the problem. */
planning?: boolean;
@@ -691,7 +694,7 @@ const Canvas = memo<
Canvas.displayName = 'GoalGraphCanvas';
-const Graph = memo<GraphProps>(({ fullscreen, onFullscreenChange, ...props }) => {
+const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange, ...props }) => {
const { t } = useTranslation('chat');
const navigation = useExplorationNavigation(props.graph.goal.id, {
nodes: props.graph.nodes.map((item) => item.node),
@@ -835,7 +838,7 @@ const Graph = memo<GraphProps>(({ fullscreen, onFullscreenChange, ...props }) =>
})}
</Flexbox>
);
- const toggle = (
+ const toggle = onFullscreenChange && (
<ActionIcon
icon={fullscreen ? X : Maximize2}
size={'small'}
@@ -912,6 +915,7 @@ const Graph = memo<GraphProps>(({ fullscreen, onFullscreenChange, ...props }) =>
</Flexbox>
<Flexbox horizontal align={'center'} gap={12}>
{legend}
+ {extra}
{toggle}
</Flexbox>
</Flexbox>
diff --git a/src/features/AgentGoals/ProcessControl/index.tsx b/src/features/AgentGoals/ProcessControl/index.tsx
index 2fd85e490ec..69de1de3835 100644
--- a/src/features/AgentGoals/ProcessControl/index.tsx
+++ b/src/features/AgentGoals/ProcessControl/index.tsx
@@ -1,6 +1,5 @@
'use client';
-import { experimentOwner } from '@lobechat/utils/goalGraph';
import { Flexbox } from '@lobehub/ui';
import { Accordion, type AccordionItemType, Tag, Text } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
@@ -8,19 +7,23 @@ import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
-import { goalService } from '@/services/goal';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { goalSelectors, useGoalStore } from '@/store/goal';
-import { isExperiment } from '../Experiments/model';
import GoalAcceptanceCriteria from '../GoalAcceptanceCriteria';
import Activity from './Activity';
import Deliverables from './Deliverables';
import Findings from './Findings';
-import Frontier, { type FrontierActions } from './Frontier';
-import { buildGoalGraphView, opensOnResultSurface } from './goalGraphViewModel';
+import Frontier from './Frontier';
+import { buildGoalGraphView } from './goalGraphViewModel';
import Graph from './Graph';
+import {
+ isGoalClosed,
+ isGoalPlanning,
+ useFrontierActions,
+ useGoalNodeSelect,
+} from './useGoalProcessActions';
/**
* The process-control band of the goal detail page: what can move now
@@ -52,79 +55,41 @@ const ProcessControl = memo<ProcessControlProps>(
const selectedId = nodePortal?.goalId === goalId ? nodePortal.nodeId : lastSelectedId;
const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
- const decideGoal = useGoalStore((s) => s.decideGoal);
- const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);
- const openTaskResult = useChatStore((s) => s.openTaskResult);
- const openTaskDetail = useChatStore((s) => s.openTaskDetail);
- const openGoalNode = useChatStore((s) => s.openGoalNode);
useFetchGoalGraph(goalId);
const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);
- const actions: FrontierActions = useMemo(
- () => ({
- addTask: async (title: string, description?: string) => {
- await goalService.addNode({ description, id: goalId, kind: 'task', title });
- await refreshGoalGraph(goalId);
- },
- decide: (decisionId, optionId, resolution) =>
- void decideGoal(goalId, { decisionId, optionId, resolution }),
- }),
- [decideGoal, goalId, refreshGoalGraph],
- );
+ const actions = useFrontierActions(goalId);
+ const openNode = useGoalNodeSelect(goalId, graph);
// Every click funnels here: keep the map highlight (spatial continuity) and
- // open the drill-down. A Task with a delivery to read, or a healthy run in
- // flight, lands on its result surface — the live run while it works, the
- // report once it settles. A Task waiting or in trouble opens the original
- // Task detail, where configuration and failure context live.
+ // open the drill-down (see `useGoalNodeSelect` for where each node lands).
const select = useCallback(
(nodeId: string) => {
setSelectedId(nodeId);
- const view = graph?.byId[nodeId];
- const taskId = view?.node.taskId;
- if (!taskId || (graph && view && isExperiment(graph, view))) {
- openGoalNode(goalId, nodeId);
- return;
- }
- if (
- graph &&
- experimentOwner(
- { nodes: graph.nodes.map((item) => item.node), edges: graph.edges },
- nodeId,
- )
- )
- openTaskDetail(taskId);
- else if (view && opensOnResultSurface(view)) openTaskResult(taskId);
- else openTaskDetail(taskId);
+ openNode(nodeId);
},
- [goalId, graph, openGoalNode, openTaskDetail, openTaskResult],
+ [openNode],
);
// Task-carried goals share the `goals` table but never grow a graph. Nothing
// to control here, so the page keeps its original shape.
if (!graph || graph.nodes.length === 0) return null;
- // The coordinator is decomposing the problem into tasks. `running` with zero
- // Task counts too: the decomposition claim flips the status before the
- // planner returns, and a re-plan after all Tasks were removed is the same
- // state. The surfaces below promise the incoming structure instead of
- // reading as an empty goal — the graph poll fills them in as nodes land.
- const planning =
- ['planning', 'running'].includes(graph.goal.status) &&
- !graph.nodes.some((view) => view.node.kind === 'task');
+ // While the coordinator decomposes the problem, the surfaces below promise
+ // the incoming structure instead of reading as an empty goal — the graph
+ // poll fills them in as nodes land.
+ const planning = isGoalPlanning(graph);
// Presence of the acceptance block (not a non-empty list) keeps the section
// mounted: removing the last criterion must leave the add control reachable,
// while legacy prose-only goals (no acceptance config at all) show nothing.
const acceptanceConfig = graph.goal.config?.acceptance;
const criteriaIds = acceptanceConfig?.criteriaIds ?? [];
- // A closed goal cannot move: the coordinator returns immediately for these,
- // and a Task added here would sit `proposed` forever. Stop offering actions
- // that cannot land. The goal otherwise advances entirely on its own — the
- // only legitimate human control over its pace is pause/resume.
- const closed = ['achieved', 'canceled', 'failed'].includes(graph.goal.status);
- const canAct = canEdit && !closed;
+ // Stop offering actions that cannot land on a closed goal. The goal otherwise
+ // advances entirely on its own — the only legitimate human control over its
+ // pace is pause/resume.
+ const canAct = canEdit && !isGoalClosed(graph);
const hasExperiments = graph.nodes.some((view) => view.node.kind === 'experiment');
const map = (
diff --git a/src/features/AgentGoals/ProcessControl/useGoalProcessActions.ts b/src/features/AgentGoals/ProcessControl/useGoalProcessActions.ts
new file mode 100644
index 00000000000..b49ae878a51
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/useGoalProcessActions.ts
@@ -0,0 +1,77 @@
+import { experimentOwner } from '@lobechat/utils/goalGraph';
+import { useCallback, useMemo } from 'react';
+
+import { goalService } from '@/services/goal';
+import { useChatStore } from '@/store/chat';
+import { useGoalStore } from '@/store/goal';
+
+import { isExperiment } from '../Experiments/model';
+import type { FrontierActions } from './Frontier';
+import { type GoalGraphView, opensOnResultSurface } from './goalGraphViewModel';
+
+/**
+ * Where a click on a goal graph node lands, shared by every host of the
+ * process-control sections (goal page, conversation portal). A Task with a
+ * delivery to read, or a healthy run in flight, lands on its result surface —
+ * the live run while it works, the report once it settles. A Task waiting or in
+ * trouble opens the original Task detail, where configuration and failure
+ * context live. Everything else opens the node drill-down.
+ */
+export const useGoalNodeSelect = (goalId: string, graph?: GoalGraphView) => {
+ const openTaskResult = useChatStore((s) => s.openTaskResult);
+ const openTaskDetail = useChatStore((s) => s.openTaskDetail);
+ const openGoalNode = useChatStore((s) => s.openGoalNode);
+
+ return useCallback(
+ (nodeId: string) => {
+ const view = graph?.byId[nodeId];
+ const taskId = view?.node.taskId;
+ if (!taskId || (graph && view && isExperiment(graph, view))) {
+ openGoalNode(goalId, nodeId);
+ return;
+ }
+ if (
+ graph &&
+ experimentOwner({ nodes: graph.nodes.map((item) => item.node), edges: graph.edges }, nodeId)
+ )
+ openTaskDetail(taskId);
+ else if (view && opensOnResultSurface(view)) openTaskResult(taskId);
+ else openTaskDetail(taskId);
+ },
+ [goalId, graph, openGoalNode, openTaskDetail, openTaskResult],
+ );
+};
+
+/** The frontier's write actions — add a Task, resolve a decision gate. */
+export const useFrontierActions = (goalId: string): FrontierActions => {
+ const decideGoal = useGoalStore((s) => s.decideGoal);
+ const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);
+
+ return useMemo(
+ () => ({
+ addTask: async (title: string, description?: string) => {
+ await goalService.addNode({ description, id: goalId, kind: 'task', title });
+ await refreshGoalGraph(goalId);
+ },
+ decide: (decisionId, optionId, resolution) =>
+ void decideGoal(goalId, { decisionId, optionId, resolution }),
+ }),
+ [decideGoal, goalId, refreshGoalGraph],
+ );
+};
+
+/**
+ * The coordinator is decomposing the problem into tasks. `running` with zero
+ * Task counts too: the decomposition claim flips the status before the planner
+ * returns, and a re-plan after all Tasks were removed is the same state.
+ */
+export const isGoalPlanning = (graph: GoalGraphView): boolean =>
+ ['planning', 'running'].includes(graph.goal.status) &&
+ !graph.nodes.some((view) => view.node.kind === 'task');
+
+/**
+ * A closed goal cannot move: the coordinator returns immediately for these, and
+ * a Task added here would sit `proposed` forever.
+ */
+export const isGoalClosed = (graph: GoalGraphView): boolean =>
+ ['achieved', 'canceled', 'failed'].includes(graph.goal.status);
diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx b/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx
new file mode 100644
index 00000000000..185bdbb9db0
--- /dev/null
+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx
@@ -0,0 +1,143 @@
+'use client';
+
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { ChevronRight } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { goalStatusKey } from '@/features/AgentGoals/goalPresentation';
+import GoalStatusGlyph from '@/features/AgentGoals/GoalStatusGlyph';
+import type { GoalListItem } from '@/services/goal';
+import { useChatStore } from '@/store/chat';
+import { useGoalStore } from '@/store/goal';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
+import { isGoalRequestGenerating, selectLinkedGoals } from './linkedGoals';
+
+const styles = createStaticStyles(({ css }) => ({
+ container: css`
+ border: 1px solid ${cssVar.colorFillSecondary};
+ border-block-end: none;
+ border-start-start-radius: 12px;
+ border-start-end-radius: 12px;
+
+ background: ${cssVar.colorBgElevated};
+ `,
+ containerTopAttached: css`
+ border-start-start-radius: 0;
+ border-start-end-radius: 0;
+ `,
+ row: css`
+ cursor: pointer;
+ padding-block: 6px;
+ padding-inline: 12px;
+
+ & + & {
+ border-block-start: 1px solid ${cssVar.colorFillTertiary};
+ }
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+}));
+
+const LinkedGoalRow = memo<{ item: GoalListItem }>(({ item }) => {
+ const { t } = useTranslation('chat');
+ const openGoal = useChatStore((s) => s.openGoal);
+ const { goal, pendingDecisions, taskDone, taskTotal } = item;
+ const open = () => openGoal(goal.id);
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ aria-label={t('goalProcess.linked.open')}
+ className={styles.row}
+ gap={8}
+ role={'button'}
+ tabIndex={0}
+ onClick={open}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ open();
+ }}
+ >
+ <GoalStatusGlyph size={14} status={goal.status} />
+ <Text ellipsis fontSize={12} style={{ flex: 1, minWidth: 0 }} weight={500}>
+ {goal.title}
+ </Text>
+ {/* Something blocked on the user outranks progress — it is the reason to click. */}
+ {pendingDecisions > 0 ? (
+ <Text fontSize={12} style={{ color: cssVar.colorWarning, flexShrink: 0 }}>
+ {t('goalList.needsYou', { count: pendingDecisions })}
+ </Text>
+ ) : (
+ taskTotal > 0 && (
+ <Text fontSize={12} style={{ flexShrink: 0 }} type={'secondary'}>
+ {t('goalList.taskProgress', { done: taskDone, total: taskTotal })}
+ </Text>
+ )
+ )}
+ <Text fontSize={12} style={{ flexShrink: 0 }} type={'secondary'}>
+ {t(goalStatusKey(goal.status))}
+ </Text>
+ <Icon color={cssVar.colorTextQuaternary} icon={ChevronRight} size={14} />
+ </Flexbox>
+ );
+});
+
+LinkedGoalRow.displayName = 'LinkedGoalRow';
+
+interface LinkedGoalTrayProps {
+ topAttached?: boolean;
+}
+
+/**
+ * The goals this conversation planned, floating above the composer with their
+ * live status (behind the `enableTopicAcceptance` lab). The conversation is the
+ * goal's planning conversation, so its progress belongs here — clicking a row
+ * opens the whole goal in the Portal, beside the chat that shaped it.
+ *
+ * Not the topic checklist (`VerifyTray/GoalTray`): that is a sentence and
+ * tracking checks stored on the topic; this points at real `goals` rows.
+ */
+const LinkedGoalTray = memo<LinkedGoalTrayProps>(({ topAttached }) => {
+ const enabled = useUserStore(labPreferSelectors.enableTopicAcceptance);
+ const topicId = useConversationStore((s) => s.context.topicId);
+ const displayMessages = useConversationStore(dataSelectors.displayMessages);
+ const useFetchTopicGoals = useGoalStore((s) => s.useFetchTopicGoals);
+ // Discovery polling is for the run that may create a goal — a `/goal` request —
+ // not every generation; goals already found keep polling on their own status.
+ const goalRequestGenerating = useConversationStore((s) =>
+ isGoalRequestGenerating(
+ dataSelectors.displayMessages(s),
+ messageStateSelectors.isAIGenerating(s),
+ ),
+ );
+ const { data } = useFetchTopicGoals(enabled ? topicId : undefined, goalRequestGenerating);
+
+ const goals = useMemo(
+ () => selectLinkedGoals(data?.goals, displayMessages),
+ [data, displayMessages],
+ );
+
+ if (!enabled || !topicId || goals.length === 0) return null;
+
+ return (
+ <Flexbox className={cx(styles.container, topAttached && styles.containerTopAttached)}>
+ {goals.map((item) => (
+ <LinkedGoalRow item={item} key={item.goal.id} />
+ ))}
+ </Flexbox>
+ );
+});
+
+LinkedGoalTray.displayName = 'LinkedGoalTray';
+
+export default LinkedGoalTray;
diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.ts b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.ts
new file mode 100644
index 00000000000..3969c651d2e
--- /dev/null
+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.ts
@@ -0,0 +1,78 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import type { GoalListItem } from '@/services/goal';
+
+import { isGoalRequestGenerating, MAX_LINKED_GOALS, selectLinkedGoals } from './linkedGoals';
+
+const goal = (id: string) => ({ goal: { id } }) as unknown as GoalListItem;
+
+const createGoalTurn = (goalId: string) =>
+ ({
+ children: [
+ {
+ content: '',
+ id: `block-${goalId}`,
+ tools: [
+ {
+ apiName: 'createGoal',
+ arguments: '{}',
+ id: `call-${goalId}`,
+ identifier: 'lobe-goal',
+ result: { content: 'started', id: 'tool-1', state: { goalId, success: true } },
+ type: 'builtin',
+ },
+ ],
+ },
+ ],
+ content: '',
+ createdAt: 0,
+ id: `msg-${goalId}`,
+ role: 'assistantGroup',
+ }) as unknown as UIChatMessage;
+
+describe('selectLinkedGoals', () => {
+ it('keeps goals that have no createGoal card in the conversation', () => {
+ const result = selectLinkedGoals(
+ [goal('goal-cli'), goal('goal-tool')],
+ [createGoalTurn('goal-tool')],
+ );
+
+ expect(result.map((item) => item.goal.id)).toEqual(['goal-cli']);
+ });
+
+ it('caps the tray at a few goals', () => {
+ const goals = Array.from({ length: MAX_LINKED_GOALS + 2 }, (_, i) => goal(`goal-${i}`));
+
+ expect(selectLinkedGoals(goals, [])).toHaveLength(MAX_LINKED_GOALS);
+ });
+
+ it('is empty before the list loads', () => {
+ expect(selectLinkedGoals(undefined, [createGoalTurn('goal-tool')])).toEqual([]);
+ });
+});
+
+const userMessage = (content: string) =>
+ ({ content, createdAt: 0, id: `msg-${content}`, role: 'user' }) as unknown as UIChatMessage;
+
+describe('isGoalRequestGenerating', () => {
+ it('is on while a /goal request is generating', () => {
+ expect(isGoalRequestGenerating([userMessage('/goal ship the report')], true)).toBe(true);
+ });
+
+ it('stays off for an ordinary generation', () => {
+ // Polling on every generation hit the goal list every five seconds for
+ // conversations that never asked for a goal.
+ expect(isGoalRequestGenerating([userMessage('fix the build')], true)).toBe(false);
+ expect(
+ isGoalRequestGenerating(
+ [userMessage('/goal ship the report'), createGoalTurn('goal-1'), userMessage('thanks')],
+ true,
+ ),
+ ).toBe(false);
+ });
+
+ it('stays off once nothing is generating', () => {
+ expect(isGoalRequestGenerating([userMessage('/goal ship the report')], false)).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts
new file mode 100644
index 00000000000..bfa187b741d
--- /dev/null
+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts
@@ -0,0 +1,42 @@
+import { isGoalPrompt } from '@lobechat/builtin-tool-goal';
+import type { UIChatMessage } from '@lobechat/types';
+
+import type { GoalListItem } from '@/services/goal';
+
+import { deriveOperationGoals } from '../../Messages/GoalTaskCard/deriveOperationGoals';
+
+/** The tray is a pointer, not a list — past this the goal page's list is the right surface. */
+export const MAX_LINKED_GOALS = 3;
+
+/**
+ * Goals linked to the topic that still need a surface in this conversation.
+ *
+ * A goal created by the builtin `createGoal` tool already renders as a live card
+ * inside its assistant turn, so the tray skips it; what remains are goals the
+ * conversation planned some other way — a CLI agent's `lh goal create
+ * --conversation` leaves only Bash output behind.
+ */
+export const selectLinkedGoals = (
+ goals: GoalListItem[] = [],
+ messages: UIChatMessage[] = [],
+): GoalListItem[] => {
+ const carded = new Set(
+ messages.flatMap((message) =>
+ deriveOperationGoals(message.children ?? []).map(({ goalId }) => goalId),
+ ),
+ );
+
+ return goals.filter(({ goal }) => !carded.has(goal.id)).slice(0, MAX_LINKED_GOALS);
+};
+
+/**
+ * Whether the run in flight can be the one creating a goal: something is
+ * generating and the latest user message is a `/goal` request. Polling for new
+ * goals on every generation would hit the goal list every few seconds for
+ * conversations that never asked for one.
+ */
+export const isGoalRequestGenerating = (
+ messages: UIChatMessage[] = [],
+ generating: boolean,
+): boolean =>
+ generating && isGoalPrompt(messages.findLast((message) => message.role === 'user')?.content);
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index f7bd22021c2..71d813c32a4 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -38,6 +38,7 @@ import {
} from '../store';
import TodoProgress from '../TodoProgress';
import InputCompletionErrorAlert from './InputCompletionErrorAlert';
+import LinkedGoalTray from './LinkedGoalTray';
import OpStatusTray from './OpStatusTray';
import QueueTray from './QueueTray';
import { sendVoiceMessage } from './sendVoiceMessage';
@@ -467,6 +468,10 @@ const ChatInput = memo<ChatInputProps>(
<GoalTray
topAttached={(!disableQueue && hasQueuedMessages) || hasTodos || hasOpStatus}
/>
+ {/* Goals this conversation planned; sits last so it rides flush on the input. */}
+ <LinkedGoalTray
+ topAttached={(!disableQueue && hasQueuedMessages) || hasTodos || hasOpStatus}
+ />
</Flexbox>
{/* Append the armed-goal chip to every composer's action bar. While armed,
the next message becomes the goal and the placeholder explains that state. */}
diff --git a/src/features/Conversation/Messages/GoalTaskCard/index.tsx b/src/features/Conversation/Messages/GoalTaskCard/index.tsx
index 65bc9098366..ad85e4bf81c 100644
--- a/src/features/Conversation/Messages/GoalTaskCard/index.tsx
+++ b/src/features/Conversation/Messages/GoalTaskCard/index.tsx
@@ -7,7 +7,7 @@ import { ChevronRightIcon, TargetIcon } from 'lucide-react';
import { memo } from 'react';
import RingLoadingIcon from '@/components/RingLoading';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useChatStore } from '@/store/chat';
import type { OperationGoal } from './deriveOperationGoals';
import GoalElapsedTime from './GoalElapsedTime';
@@ -56,15 +56,14 @@ const styles = createStaticStyles(({ css }) => ({
}));
const GoalCard = memo<{ goal: OperationGoal }>(({ goal }) => {
- const navigate = useWorkspaceAwareNavigate();
- const { agentId, progress, startedAt, title } = useGoalTaskStatus({
+ const openGoalPortal = useChatStore((s) => s.openGoal);
+ const { progress, startedAt, title } = useGoalTaskStatus({
criteriaCount: goal.criteriaCount,
goalId: goal.goalId,
});
const isActive = ACTIVE_PHASES.has(progress.phase);
- const openGoal = () => {
- if (agentId) navigate(`/agent/${agentId}/goal/${goal.goalId}`);
- };
+ // Same destination as the tool card: the goal's progress beside the chat.
+ const openGoal = () => openGoalPortal(goal.goalId);
return (
<Flexbox
diff --git a/src/features/Portal/Goal/Body.tsx b/src/features/Portal/Goal/Body.tsx
new file mode 100644
index 00000000000..c880fa9ef94
--- /dev/null
+++ b/src/features/Portal/Goal/Body.tsx
@@ -0,0 +1,175 @@
+import { Flexbox } from '@lobehub/ui';
+import { Accordion, ActionIcon, Skeleton, Tag, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { Maximize2 } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NotFound from '@/components/404';
+import AsyncError from '@/components/AsyncError';
+import GoalHeaderMetrics from '@/features/AgentGoals/GoalHeaderMetrics';
+import Activity from '@/features/AgentGoals/ProcessControl/Activity';
+import Deliverables from '@/features/AgentGoals/ProcessControl/Deliverables';
+import Findings from '@/features/AgentGoals/ProcessControl/Findings';
+import Frontier from '@/features/AgentGoals/ProcessControl/Frontier';
+import { buildGoalGraphView } from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';
+import Graph from '@/features/AgentGoals/ProcessControl/Graph';
+import {
+ isGoalClosed,
+ isGoalPlanning,
+ useFrontierActions,
+ useGoalNodeSelect,
+} from '@/features/AgentGoals/ProcessControl/useGoalProcessActions';
+import { usePermission } from '@/hooks/usePermission';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { goalSelectors, useGoalStore } from '@/store/goal';
+
+import { useOpenGoalPage } from './useOpenGoalPage';
+
+/**
+ * The whole goal beside the conversation that planned it: header metrics, what
+ * can move now, the exploration map, then what it produced, concluded and did.
+ * Fetches the graph itself (polling while the server advances it), so it works
+ * on any surface that hosts the Portal. Every click drills further down the same
+ * view stack — node → task → topic — and Back returns here.
+ *
+ * The map runs inline only: its fullscreen overlay carries a second Portal
+ * panel, which cannot nest inside this one, so the expand action leaves for the
+ * goal page instead.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ section: css`
+ padding-block: 8px;
+ `,
+}));
+
+const Body = memo(() => {
+ const { t } = useTranslation('chat');
+ const { allowed: canEdit } = usePermission('create_content');
+ const goalId = useChatStore(chatPortalSelectors.goalPortalId);
+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
+ const { error, isLoading, mutate } = useFetchGoalGraph(goalId);
+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
+ const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);
+ const select = useGoalNodeSelect(goalId ?? '', graph);
+ const actions = useFrontierActions(goalId ?? '');
+ const openGoalPage = useOpenGoalPage(goalId);
+
+ if (!goalId) return null;
+
+ if (error && !snapshot)
+ return (
+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflowY: 'auto' }}>
+ <AsyncError error={error} variant={'page'} onRetry={() => void mutate()} />
+ </Flexbox>
+ );
+
+ if (!snapshot || !graph)
+ return isLoading ? (
+ <Flexbox gap={16} padding={16}>
+ <Skeleton height={56} radius={8} />
+ <Skeleton height={160} radius={8} />
+ <Skeleton height={320} radius={8} />
+ </Flexbox>
+ ) : (
+ <NotFound desc={t('goalDetail.notFoundDescription')} title={t('goalDetail.notFoundTitle')} />
+ );
+
+ const hasGraph = graph.nodes.length > 0;
+ const planning = isGoalPlanning(graph);
+
+ return (
+ <Flexbox flex={1} gap={20} padding={16} style={{ minHeight: 0, overflowY: 'auto' }}>
+ <GoalHeaderMetrics goalId={goalId} />
+ {hasGraph && (
+ <>
+ <Frontier
+ actions={actions}
+ canEdit={canEdit && !isGoalClosed(graph)}
+ graph={graph}
+ planning={planning}
+ onSelect={select}
+ />
+ <Graph
+ graph={graph}
+ key={goalId}
+ planning={planning}
+ extra={
+ openGoalPage && (
+ <ActionIcon
+ aria-label={t('goalProcess.portal.openPage')}
+ icon={Maximize2}
+ size={'small'}
+ title={t('goalProcess.portal.openPage')}
+ onClick={openGoalPage}
+ />
+ )
+ }
+ onSelect={select}
+ />
+ <Accordion
+ defaultValue={['deliverables', 'findings', 'activity']}
+ gap={0}
+ indicatorPlacement="inline"
+ styles={{ header: { paddingBlock: 6, paddingInline: 0 } }}
+ items={[
+ {
+ children: (
+ <Flexbox className={styles.section}>
+ <Deliverables graph={graph} />
+ </Flexbox>
+ ),
+ key: 'deliverables',
+ title: (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={14} weight={600}>
+ {t('goalProcess.deliverables.title')}
+ </Text>
+ {graph.artifacts.length > 0 && (
+ <Tag size={'small'}>{graph.artifacts.length}</Tag>
+ )}
+ </Flexbox>
+ ),
+ },
+ {
+ children: (
+ <Flexbox className={styles.section}>
+ <Findings graph={graph} onSelect={select} />
+ </Flexbox>
+ ),
+ key: 'findings',
+ title: (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={14} weight={600}>
+ {t('goalProcess.findings.title')}
+ </Text>
+ {graph.findings.length > 0 && <Tag size={'small'}>{graph.findings.length}</Tag>}
+ </Flexbox>
+ ),
+ },
+ {
+ children: (
+ <Flexbox className={styles.section}>
+ <Activity graph={graph} onSelect={select} />
+ </Flexbox>
+ ),
+ key: 'activity',
+ title: (
+ <Text fontSize={14} weight={600}>
+ {t('goalProcess.activity.title')}
+ </Text>
+ ),
+ },
+ ]}
+ />
+ </>
+ )}
+ </Flexbox>
+ );
+});
+
+Body.displayName = 'GoalPortalBody';
+
+export default Body;
diff --git a/src/features/Portal/Goal/Title.tsx b/src/features/Portal/Goal/Title.tsx
new file mode 100644
index 00000000000..3c3a8715eda
--- /dev/null
+++ b/src/features/Portal/Goal/Title.tsx
@@ -0,0 +1,43 @@
+import { Flexbox } from '@lobehub/ui';
+import { ActionIcon, Text } from '@lobehub/ui/base-ui';
+import { SquareArrowOutUpRight } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import GoalStatusGlyph from '@/features/AgentGoals/GoalStatusGlyph';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { goalSelectors, useGoalStore } from '@/store/goal';
+import { oneLineEllipsis } from '@/styles';
+
+import { useOpenGoalPage } from './useOpenGoalPage';
+
+const Title = memo(() => {
+ const { t } = useTranslation('chat');
+ const goalId = useChatStore(chatPortalSelectors.goalPortalId);
+ const goal = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal);
+ const openGoalPage = useOpenGoalPage(goalId);
+
+ return (
+ <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
+ {goal && <GoalStatusGlyph size={14} status={goal.status} />}
+ <Text className={oneLineEllipsis} style={{ flex: '0 1 auto', fontSize: 14, minWidth: 0 }}>
+ {goal?.title ?? t('goalProcess.portal.title')}
+ </Text>
+ {openGoalPage && (
+ <ActionIcon
+ aria-label={t('goalProcess.portal.openPage')}
+ icon={SquareArrowOutUpRight}
+ size={'small'}
+ style={{ flexShrink: 0 }}
+ title={t('goalProcess.portal.openPage')}
+ onClick={openGoalPage}
+ />
+ )}
+ </Flexbox>
+ );
+});
+
+Title.displayName = 'GoalPortalTitle';
+
+export default Title;
diff --git a/src/features/Portal/Goal/index.ts b/src/features/Portal/Goal/index.ts
new file mode 100644
index 00000000000..03af5f2f56d
--- /dev/null
+++ b/src/features/Portal/Goal/index.ts
@@ -0,0 +1,5 @@
+import { type PortalImpl } from '../type';
+import Body from './Body';
+import Title from './Title';
+
+export const Goal: PortalImpl = { Body, Title };
diff --git a/src/features/Portal/Goal/useOpenGoalPage.ts b/src/features/Portal/Goal/useOpenGoalPage.ts
new file mode 100644
index 00000000000..0549f07cf1b
--- /dev/null
+++ b/src/features/Portal/Goal/useOpenGoalPage.ts
@@ -0,0 +1,23 @@
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useChatStore } from '@/store/chat';
+import { useGoalStore } from '@/store/goal';
+
+/**
+ * Leave the conversation for the goal's own page. The portal stack is this
+ * conversation's inspection session, so it is cleared on the way out — the goal
+ * page would otherwise open its panel on the same goal it already shows.
+ */
+export const useOpenGoalPage = (goalId?: string) => {
+ const navigate = useWorkspaceAwareNavigate();
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
+ const agentId = useGoalStore((s) =>
+ goalId ? (s.goalGraphById[goalId]?.goal.agentId ?? undefined) : undefined,
+ );
+
+ if (!goalId) return undefined;
+
+ return () => {
+ clearPortalStack();
+ navigate(agentId ? `/agent/${agentId}/goal/${goalId}` : `/goal/${goalId}`);
+ };
+};
diff --git a/src/features/Portal/GoalMetric/Body.tsx b/src/features/Portal/GoalMetric/Body.tsx
index e45386ef390..9643f5cdcf6 100644
--- a/src/features/Portal/GoalMetric/Body.tsx
+++ b/src/features/Portal/GoalMetric/Body.tsx
@@ -520,6 +520,9 @@ Liveness.displayName = 'GoalMetricLiveness';
const Body = memo(() => {
const view = useChatStore(chatPortalSelectors.goalMetricView);
+ // Fetched here so the metric drill-down also works outside the goal page.
+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
+ useFetchGoalGraph(view?.goalId);
const snapshot = useGoalStore(goalSelectors.goalGraph(view?.goalId ?? ''));
const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);
diff --git a/src/features/Portal/GoalNode/Body.tsx b/src/features/Portal/GoalNode/Body.tsx
index 570d2b663e9..93ab3487934 100644
--- a/src/features/Portal/GoalNode/Body.tsx
+++ b/src/features/Portal/GoalNode/Body.tsx
@@ -24,7 +24,7 @@ import { goalSelectors, useGoalStore } from '@/store/goal';
/**
* Drill-down for one Goal Graph node. Everything rendered here is derived from
- * the same `goal.graph` snapshot the page already holds — no extra fetch. A
+ * the `goal.graph` snapshot — shared by SWR key with whichever host opened it. A
* Work node links onward to its Task detail (the deep half of the chain:
* node → task → topic conversation).
*/
@@ -138,6 +138,10 @@ const Body = memo(() => {
const view = useChatStore(chatPortalSelectors.goalNodeView);
const openTaskDetail = useChatStore((s) => s.openTaskDetail);
const openGoalNode = useChatStore((s) => s.openGoalNode);
+ // Fetched here, not assumed from the goal page: the drill-down also opens
+ // from the conversation portal, where nothing else holds the snapshot.
+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
+ useFetchGoalGraph(view?.goalId);
const snapshot = useGoalStore(goalSelectors.goalGraph(view?.goalId ?? ''));
const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);
diff --git a/src/features/Portal/portalWidth.test.ts b/src/features/Portal/portalWidth.test.ts
index 4d7836392c1..1fd8fd3a05b 100644
--- a/src/features/Portal/portalWidth.test.ts
+++ b/src/features/Portal/portalWidth.test.ts
@@ -24,6 +24,7 @@ describe('getPortalViewMinWidth', () => {
PortalViewType.AcceptanceCheck,
PortalViewType.AgentDetail,
PortalViewType.Artifact,
+ PortalViewType.Goal,
PortalViewType.GoalMetric,
PortalViewType.GoalNode,
PortalViewType.TaskDetail,
diff --git a/src/features/Portal/portalWidth.ts b/src/features/Portal/portalWidth.ts
index c500a33d11e..64412ba2499 100644
--- a/src/features/Portal/portalWidth.ts
+++ b/src/features/Portal/portalWidth.ts
@@ -33,6 +33,7 @@ const VIEW_MIN_WIDTH: PortalWidths = {
[PortalViewType.AcceptanceCheck]: CHAT_PORTAL_TOOL_UI_WIDTH,
[PortalViewType.AgentDetail]: CHAT_PORTAL_TOOL_UI_WIDTH,
[PortalViewType.Artifact]: CHAT_PORTAL_TOOL_UI_WIDTH,
+ [PortalViewType.Goal]: CHAT_PORTAL_TOOL_UI_WIDTH,
[PortalViewType.GoalMetric]: CHAT_PORTAL_TOOL_UI_WIDTH,
[PortalViewType.GoalNode]: CHAT_PORTAL_TOOL_UI_WIDTH,
[PortalViewType.TaskDetail]: CHAT_PORTAL_TOOL_UI_WIDTH,
@@ -50,6 +51,9 @@ const VIEW_MIN_WIDTH: PortalWidths = {
const VIEW_DEFAULT_WIDTH: PortalWidths = {
[PortalViewType.Acceptance]: CHAT_PORTAL_WIDE_WIDTH,
[PortalViewType.AcceptanceCheck]: CHAT_PORTAL_WIDE_WIDTH,
+ // The goal overview carries the exploration map and the header metrics row,
+ // both of which only read at the wide width.
+ [PortalViewType.Goal]: CHAT_PORTAL_WIDE_WIDTH,
// Task / goal-node detail pack status, instruction, sub-tasks and the
// activity feed into one column — wider than the reading column, but the
// full document width crowds the page it sits next to.
diff --git a/src/features/Portal/router.tsx b/src/features/Portal/router.tsx
index 18c66861e59..0748106975f 100644
--- a/src/features/Portal/router.tsx
+++ b/src/features/Portal/router.tsx
@@ -13,6 +13,7 @@ import { Artifacts } from './Artifacts';
import Header from './components/Header';
import { Document } from './Document';
import { FilePreview } from './FilePreview';
+import { Goal } from './Goal';
import { GoalMetric } from './GoalMetric';
import { GoalNode } from './GoalNode';
import { GroupThread } from './GroupThread';
@@ -43,6 +44,7 @@ const VIEW_COMPONENTS: Record<PortalViewType, PortalImpl> = {
[PortalViewType.Document]: Document,
[PortalViewType.Notebook]: Notebook,
[PortalViewType.FilePreview]: FilePreview,
+ [PortalViewType.Goal]: Goal,
[PortalViewType.GoalMetric]: GoalMetric,
[PortalViewType.GoalNode]: GoalNode,
[PortalViewType.LocalFile]: LocalFile,
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index a6fde08cf58..672cda40032 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -356,6 +356,8 @@ export const isMyTaskListKey = (key: unknown): boolean =>
export const goalKeys = {
graph: def('goal:graph', (goalId: string) => ['goal:graph', goalId]),
metricSeries: def('goal:metricSeries', (goalId: string) => ['goal:metricSeries', goalId]),
+ /** Goals whose planning conversation is this topic (`subject_type = 'topic'`). */
+ topicGoals: def('goal:topicGoals', (topicId: string) => ['goal:topicGoals', topicId]),
};
export const taskKeys = {
diff --git a/src/services/goal.ts b/src/services/goal.ts
index de96267d51b..b6900b7ff2f 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -15,6 +15,8 @@ export interface GoalListParams {
offset?: number;
projectId?: string;
statuses?: GoalStatus[];
+ /** Goals created from this conversation. */
+ topicId?: string;
}
/** Every graph method takes the `goals` row id. */
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index a23a6a3e952..ac50d9f642c 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -3,6 +3,7 @@ import type {
AgentInterventionResponseData,
AgentStreamEvent,
} from '@lobechat/agent-gateway-client';
+import { stripGoalCommand, withConversationGoalPrompt } from '@lobechat/builtin-tool-goal';
import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
import {
@@ -2460,7 +2461,9 @@ export const executeHeterogeneousAgent = async (
});
const systemContext = buildLocalHeterogeneousSystemContext({
- agentSystemContext: heterogeneousProvider.systemContext,
+ // `/goal` reaches a hetero agent as instructions, not a tool: it creates
+ // and plans the goal through `lh` in this same run.
+ agentSystemContext: withConversationGoalPrompt(heterogeneousProvider.systemContext, message),
contextSelections,
pageSelections,
});
@@ -2483,7 +2486,9 @@ export const executeHeterogeneousAgent = async (
agentId: context.agentId,
imageList,
operationId,
- prompt: message,
+ // `/goal` travels as system-context instructions; the CLI gets only the
+ // request so its own `/goal` command does not take the message over.
+ prompt: stripGoalCommand(message),
...(resumeReplayMessages?.length ? { resumeReplayMessages } : {}),
sessionId: ipcRunSessionId,
systemContext: systemContext || undefined,
diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.ts
index 2840e616ec7..46b32faf906 100644
--- a/src/store/chat/slices/portal/action.test.ts
+++ b/src/store/chat/slices/portal/action.test.ts
@@ -401,6 +401,25 @@ describe('chatDockSlice', () => {
expect(chatPortalSelectors.goalNodeView(result.current)?.nodeId).toBe('third');
});
+ it('openGoal pushes a Goal view and a node drill-down returns to it on Back', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.openGoal('goal_1');
+ });
+
+ expect(result.current.portalStack).toEqual([{ goalId: 'goal_1', type: PortalViewType.Goal }]);
+ expect(result.current.showPortal).toBe(true);
+ expect(chatPortalSelectors.goalPortalId(result.current)).toBe('goal_1');
+
+ act(() => {
+ result.current.openGoalNode('goal_1', 'node_1');
+ result.current.goBack();
+ });
+
+ expect(chatPortalSelectors.goalPortalId(result.current)).toBe('goal_1');
+ });
+
it('openGoalNode pushes a GoalNode view and exposes it via selector', () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.ts
index d169eec0715..92c9e5edc43 100644
--- a/src/store/chat/slices/portal/action.ts
+++ b/src/store/chat/slices/portal/action.ts
@@ -638,6 +638,11 @@ export class ChatPortalActionImpl {
this.#get().pushPortalView({ taskId, type: PortalViewType.TaskResult });
};
+ /** The whole goal's progress, opened beside the conversation that planned it. */
+ openGoal = (goalId: string): void => {
+ this.#get().pushPortalView({ goalId, type: PortalViewType.Goal });
+ };
+
openGoalNode = (goalId: string, nodeId: string): void => {
this.#get().pushPortalView({ goalId, nodeId, type: PortalViewType.GoalNode });
};
diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.ts
index dc81380f575..677936f738a 100644
--- a/src/store/chat/slices/portal/initialState.ts
+++ b/src/store/chat/slices/portal/initialState.ts
@@ -16,6 +16,7 @@ export enum PortalViewType {
Artifact = 'artifact',
Document = 'document',
FilePreview = 'filePreview',
+ Goal = 'goal',
GoalMetric = 'goalMetric',
GoalNode = 'goalNode',
GroupThread = 'groupThread',
@@ -68,6 +69,7 @@ export type GoalMetricKind =
export type PortalViewData =
| { type: PortalViewType.Home }
+ | { goalId: string; type: PortalViewType.Goal }
| { goalId: string; metric: GoalMetricKind; type: PortalViewType.GoalMetric }
| { goalId: string; nodeId: string; type: PortalViewType.GoalNode }
| { acceptanceId: string; type: PortalViewType.Acceptance }
diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.ts
index 203f9a7f34d..9311cec98b4 100644
--- a/src/store/chat/slices/portal/selectors.ts
+++ b/src/store/chat/slices/portal/selectors.ts
@@ -255,6 +255,8 @@ const taskResultId = (s: ChatStoreState): string | undefined => {
};
// Goal detail drill-down selectors
+const goalPortalId = (s: ChatStoreState): string | undefined =>
+ getViewData(s, PortalViewType.Goal)?.goalId;
const goalNodeView = (s: ChatStoreState) => getViewData(s, PortalViewType.GoalNode);
const goalMetricView = (s: ChatStoreState) => getViewData(s, PortalViewType.GoalMetric);
@@ -341,6 +343,7 @@ export const chatPortalSelectors = {
// Goal drill-down data
goalMetricView,
goalNodeView,
+ goalPortalId,
// Local file data
activeLocalFileId,
diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.ts
index 18313cdb4cc..1d2ee3edc46 100644
--- a/src/store/goal/action.test.ts
+++ b/src/store/goal/action.test.ts
@@ -61,6 +61,49 @@ describe('GoalAction', () => {
});
});
+ describe('useFetchTopicGoals', () => {
+ it('reads the goals created from the topic under a topic-scoped key', () => {
+ useGoalStore.getState().useFetchTopicGoals('tpc-1');
+ const [key, fetcher] = vi.mocked(useClientDataSWR).mock.calls[0];
+
+ expect(key).toEqual(['goal:topicGoals', 'tpc-1']);
+ void (fetcher as () => unknown)();
+ expect(goalService.list).toHaveBeenCalledWith({ limit: 20, topicId: 'tpc-1' });
+ });
+
+ it('does not fetch without a topic', () => {
+ useGoalStore.getState().useFetchTopicGoals(undefined);
+
+ expect(vi.mocked(useClientDataSWR).mock.calls[0][0]).toBeNull();
+ });
+
+ it('polls only while one of the goals is still advancing on the server', () => {
+ useGoalStore.getState().useFetchTopicGoals('tpc-1');
+ const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {
+ refreshInterval: (result?: { goals: Array<{ goal: { status: string } }> }) => number;
+ };
+ const withStatuses = (...statuses: string[]) => ({
+ goals: statuses.map((status) => ({ goal: { status } })),
+ });
+
+ expect(options.refreshInterval(withStatuses('achieved', 'running'))).toBeGreaterThan(0);
+ expect(options.refreshInterval(withStatuses('review', 'paused'))).toBe(0);
+ expect(options.refreshInterval(undefined)).toBe(0);
+ });
+
+ it('polls while the conversation is generating, before any goal exists', () => {
+ // A CLI agent's /goal run creates the goal mid-run: the first read finds
+ // nothing, and without polling the tray stayed empty until a page reload.
+ useGoalStore.getState().useFetchTopicGoals('tpc-1', true);
+ const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {
+ refreshInterval: (result?: { goals: Array<{ goal: { status: string } }> }) => number;
+ };
+
+ expect(options.refreshInterval(undefined)).toBeGreaterThan(0);
+ expect(options.refreshInterval({ goals: [] })).toBeGreaterThan(0);
+ });
+ });
+
it('stores goal lists independently for each agent', () => {
useGoalStore.getState().useFetchGoals('agent-1');
const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index 8a3295a50e6..f972e6ba470 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -43,6 +43,17 @@ const SERVER_ADVANCING_STATUSES = new Set<GoalStatus>(['planning', 'running', 'v
/** Kept coarse on purpose — this is liveness, not a progress bar. */
const GOAL_GRAPH_POLL_INTERVAL = 5000;
+/** A conversation rarely plans more than one goal; this only bounds a runaway topic. */
+const TOPIC_GOAL_FETCH_LIMIT = 20;
+
+const topicGoalsRefreshInterval = (
+ result: { goals: { goal: { status: GoalStatus } }[] } | undefined,
+ generating?: boolean,
+) =>
+ generating || result?.goals.some(({ goal }) => SERVER_ADVANCING_STATUSES.has(goal.status))
+ ? GOAL_GRAPH_POLL_INTERVAL
+ : 0;
+
export type GoalStore = GoalState & GoalAction;
type Setter = StoreSetter<GoalStore>;
@@ -163,6 +174,25 @@ export class GoalActionImpl {
revalidateOnFocus: true,
});
+ /**
+ * Goals created from one conversation. A goal a CLI agent creates through
+ * `lh goal create --conversation` leaves no tool result to derive a card from,
+ * so the conversation reads the link from the goal rows instead. Polls on the
+ * graph's cadence while any of them is still advancing on the server, and
+ * while a `/goal` request is generating (`generating`, decided by the caller)
+ * — that run is the one that creates the goal, so nothing on screen would
+ * otherwise ask for it.
+ */
+ useFetchTopicGoals = (topicId?: string | null, generating?: boolean) =>
+ useClientDataSWR(
+ topicId ? goalKeys.topicGoals(topicId) : null,
+ () => goalService.list({ limit: TOPIC_GOAL_FETCH_LIMIT, topicId: topicId! }),
+ {
+ refreshInterval: (result) => topicGoalsRefreshInterval(result, generating),
+ revalidateOnFocus: true,
+ },
+ );
+
/**
* North-star data of the goal detail header. Polls on the same cadence logic
* as the graph: while the server is advancing, a probe Work or an agent