🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): make recovery supervision a creation invariant (#20286)
Arvin Xu8266bdb37124
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.tsindex 38a6ec298ff..15428489e7d 100644--- a/apps/cli/src/commands/goal.test.ts+++ b/apps/cli/src/commands/goal.test.ts@@ -540,7 +540,6 @@ describe('goal create command', () => {'Repair','--max-attempts-per-task','4',- '--supervise','--max-supervision-incidents','6',]);@@ -555,6 +554,30 @@ describe('goal create command', () => {}),);});++ it('sends supervision even when no incident cap is given', async () => {+ mockClient.goal.create.mutate.mockResolvedValue({+ data: {+ decisions: [],+ edges: [],+ events: [],+ goal: { id: 'goal-1', requirement: null, status: 'planning', title: 'Fix bugs' },+ nodes: [],+ workVersions: [],+ },+ });++ await createProgram().parseAsync(['node', 'test', 'goal', 'create', 'Fix bugs']);++ // An independently distributed CLI can be pointed at a server that predates+ // the creation invariant, so supervision must not depend on the server+ // filling it in — nor on the user remembering to pass an incident cap.+ expect(mockClient.goal.create.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ config: expect.objectContaining({ supervision: { enabled: true } }),+ }),+ );+ });});describe('goal supervision command', () => {diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.tsindex eb1dc4208dd..bca8a8d06c2 100644--- a/apps/cli/src/commands/goal.ts+++ b/apps/cli/src/commands/goal.ts@@ -275,10 +275,9 @@ export function registerGoalCommand(program: Command) {.option('--project <id>', 'Project ID').option('--explore <instruction>', 'Explore alternatives using completed experiment results').option('--max-experiments <n>', 'Maximum experiment nodes (requires --explore, default 10)')- .option('--supervise', 'Enable bounded recovery supervision in an independent topic').option('--max-supervision-incidents <n>',- 'Maximum supervised interruptions (default 10, maximum 100)',+ 'Maximum supervised interruptions (supervision is always on; default 10, maximum 100)',).option('--max-rounds <n>', 'Maximum goal rounds').option('--max-cost <usd>', 'Maximum total cost in USD')@@ -312,50 +311,42 @@ export function registerGoalCommand(program: Command) {const client = await getTrpcClient();const buildUrl = await resolveAppUrlBuilder(client);const goalInput = {- config:- options.maxManagerTurns ||- options.explore ||- options.supervise ||- options.maxAttemptsPerTask ||- options.maxStepsPerRun ||- options.operationLeaseTimeoutMs ||- options.maxConcurrentTasks ||- options.taskAgent+ // Supervision is stated by the client, not left to the server: this CLI+ // ships on its own and can be pointed at a server that predates the+ // creation invariant, where nothing else would turn supervision on now+ // that `--supervise` is gone.+ config: {+ exploration: options.explore? {- taskAgentId: options.taskAgent,- manager: options.maxManagerTurns- ? { maxTurns: Number(options.maxManagerTurns) }- : undefined,- exploration: options.explore- ? {- instruction: options.explore,- maxExperiments: Number(options.maxExperiments ?? 10),- }- : undefined,- supervision: options.supervise- ? {- enabled: true,- maxIncidents: options.maxSupervisionIncidents- ? Number.parseInt(options.maxSupervisionIncidents, 10)- : undefined,- }- : undefined,- maxConcurrentTasks: options.maxConcurrentTasks- ? Number.parseInt(options.maxConcurrentTasks, 10)- : undefined,- recovery: {- maxAttemptsPerTask: options.maxAttemptsPerTask- ? Number.parseInt(options.maxAttemptsPerTask, 10)- : undefined,- maxStepsPerRun: options.maxStepsPerRun- ? Number.parseInt(options.maxStepsPerRun, 10)- : undefined,- operationLeaseTimeoutMs: options.operationLeaseTimeoutMs- ? Number.parseInt(options.operationLeaseTimeoutMs, 10)- : undefined,- },+ instruction: options.explore,+ maxExperiments: Number(options.maxExperiments ?? 10),}: undefined,+ manager: options.maxManagerTurns+ ? { maxTurns: Number(options.maxManagerTurns) }+ : undefined,+ maxConcurrentTasks: options.maxConcurrentTasks+ ? Number.parseInt(options.maxConcurrentTasks, 10)+ : undefined,+ recovery: {+ maxAttemptsPerTask: options.maxAttemptsPerTask+ ? Number.parseInt(options.maxAttemptsPerTask, 10)+ : undefined,+ maxStepsPerRun: options.maxStepsPerRun+ ? Number.parseInt(options.maxStepsPerRun, 10)+ : undefined,+ operationLeaseTimeoutMs: options.operationLeaseTimeoutMs+ ? Number.parseInt(options.operationLeaseTimeoutMs, 10)+ : undefined,+ },+ supervision: {+ enabled: true,+ ...(options.maxSupervisionIncidents+ ? { maxIncidents: Number.parseInt(options.maxSupervisionIncidents, 10) }+ : {}),+ },+ taskAgentId: options.taskAgent,+ },criteria: (options.criterion as string[] | undefined)?.map((criterion) => ({title: criterion,})),diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex 4f51b4f8e91..3874feeceda 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -79,6 +79,28 @@ afterEach(async () => {});describe('GoalService', () => {+ it('supervises every Goal it creates, even when the caller omits the policy', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Supervised by default' });+ expect(graph.goal.config?.supervision).toMatchObject({ enabled: true });+ });++ it('keeps the caller incident cap while forcing supervision on', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { supervision: { enabled: true, maxIncidents: 4 } },+ title: 'Capped supervision',+ });+ expect(graph.goal.config?.supervision).toEqual({ enabled: true, maxIncidents: 4 });+ });++ it('rejects a caller that tries to create an unsupervised Goal', async () => {+ const service = new GoalService(serverDB, userId);+ await expect(+ service.create({ config: { supervision: { enabled: false } }, title: 'No supervision' }),+ ).rejects.toThrow('Supervision is required for every goal and cannot be disabled');+ });+it('explores after result settlement and dispatches the new graph node through the ordinary Task path', async () => {const service = new GoalService(serverDB, userId);const graph = await service.create({diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex bbdc257ad94..080c638b7a9 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -369,6 +369,28 @@ export class GoalService {manager: { instruction: managerOptions?.instruction, maxTurns: managerOptions?.maxTurns },};}+ // Supervision is a creation invariant, not a creation option: every Goal+ // recovers its own dropped dispatches, so a caller may tune the incident cap+ // but never opt out. This is the single choke point — the CLI, the `/goal`+ // tool, tRPC and REST all land here — so no client can create an+ // unsupervised Goal. A legacy `enabled: false` is rejected rather than+ // silently rewritten: the caller asked for the opposite of what it would+ // get, and hiding that would make the surprise surface later, mid-run.+ const requestedSupervision = config?.supervision;+ if (requestedSupervision?.enabled === false)+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Supervision is required for every goal and cannot be disabled',+ });+ config = {+ ...config,+ supervision: {+ enabled: true,+ ...(requestedSupervision?.maxIncidents === undefined+ ? {}+ : { maxIncidents: requestedSupervision.maxIncidents }),+ },+ };// A supplied requirement is the user-reviewed goal document. Criteria live// separately; only synthesize a document when the caller omitted one.const requirement =diff --git a/apps/server/src/services/goal/manager.README.md b/apps/server/src/services/goal/manager.README.mdindex 2e67f246468..291b6109264 100644--- a/apps/server/src/services/goal/manager.README.md+++ b/apps/server/src/services/goal/manager.README.md@@ -139,7 +139,9 @@ which checks the live operation principal and then the Goal turn binding. Normaluser credentials retain the existing scoped endpoint. Prompt instructions are not ashell sandbox. Do not install a broad personal credential in an untrusted runtime.-Legacy `--supervise` Goals retain their existing behavior and cancellation fixes.+Supervision is now a creation invariant — every new Goal gets it — so a Goal+created before that change keeps its original behavior, and `--supervise` no+longer exists as a flag.Each new planning turn includes up to 20 recent Task comments (2,000 charactersper comment); the main Agent can read full comments through `lh task view`. Adiff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.tsindex 331caea09b6..c58b518a70f 100644--- a/apps/server/src/services/goal/manager.test.ts+++ b/apps/server/src/services/goal/manager.test.ts@@ -108,6 +108,15 @@ async function start(maxTurns = 4) {createdByAgentId: agentId,config: { manager: { maxTurns } },});+ // A manager-mode Goal predates the mandatory-supervision invariant, and the+ // server now writes supervision onto every Goal it creates. Clear it so this+ // file keeps covering the manager's own recovery path: with supervision on, an+ // eligible transport failure is handled by the supervisor instead (see the+ // `failure_decision` ordering in GoalService).+ await db+ .update(goals)+ .set({ config: { manager: { maxTurns } } })+ .where(eq(goals.id, graph.goal.id));expect((await service().tick(graph.goal.id)).outcome).toBe('waiting_external');const state = (await model().findById(graph.goal.id))!.config!.managerState!;const op = await ops().findByTopicSourceMessage(state.topicId, `msg_goal_manager_${state.token}`);diff --git a/apps/server/src/services/goal/supervisor/README.md b/apps/server/src/services/goal/supervisor/README.mdindex 0eafec0ca2f..dd079f2041d 100644--- a/apps/server/src/services/goal/supervisor/README.md+++ b/apps/server/src/services/goal/supervisor/README.md@@ -1,9 +1,12 @@# Goal supervision (experimental)-Enable on a new Goal with `lh goal create <title> --supervise` or-`config.supervision.enabled = true` on `goal.create`. Inspect the independent-Topic, incidents, operation links and metrics with `lh goal supervision <id>`.-Existing Goals keep their original behavior unless explicitly enabled at creation.+Every new Goal is supervised: the server writes `config.supervision.enabled = true`+at creation, so there is no unsupervised Goal to create and no opt-out to pass.+`lh goal create <title>` and the `/goal` tool both get it; tune the incident cap+with `--max-supervision-incidents` (default 10, maximum 100). Inspect the+independent Topic, incidents, operation links and metrics with+`lh goal supervision <id>`. Goals created before supervision became mandatory keep+their original behavior.The first version covers confirmed transport failures of a failed Task's latesterror operation. It does not automatically resolve an existing human Gate,diff --git a/apps/server/src/services/goal/supervisor/index.test.ts b/apps/server/src/services/goal/supervisor/index.test.tsindex 1c246a236fa..5b7c676997d 100644--- a/apps/server/src/services/goal/supervisor/index.test.ts+++ b/apps/server/src/services/goal/supervisor/index.test.ts@@ -93,12 +93,24 @@ afterEach(async () => {await db.delete(users);});+/**+ * A Goal whose Task failed with a transport error.+ *+ * `enabled: false` stands for the legacy Goal the creation invariant deliberately+ * does not backfill. The server now rejects that flag on create, so the row is+ * cleared directly — which is precisely the config shape a pre-invariant Goal has.+ */const failedGoal = async (enabled = true, error = 'fetch failed: ECONNRESET') => {const graph = await service().create({- config: { supervision: { enabled } },+ config: { supervision: { enabled: true } },tasks: ['Finish existing report'],title: 'Interrupted delivery',});+ if (!enabled)+ await db+ .update(goals)+ .set({ config: { supervision: { enabled: false } } })+ .where(eq(goals.id, graph.goal.id));const created = await service().tick(graph.goal.id);const taskId = created.taskId!;const topicId = `topic-failed-${++sequence}`;@@ -566,7 +578,7 @@ describe('Goal Supervisor integration', () => {expect(move.outcome).not.toBe('waiting_external');});- it('without supervision the same transport failure opens a human Gate', async () => {+ it('a Goal created before supervision was mandatory opens a human Gate instead', async () => {const { goalId } = await failedGoal(false);expect((await service().tick(goalId)).outcome).toBe('waiting_human');expect((await service().graph(goalId)).decisions[0].authority).toBe('user');diff --git a/e2e/src/steps/home/layout.steps.ts b/e2e/src/steps/home/layout.steps.tsindex 7db14b3bb74..320a30b5286 100644--- a/e2e/src/steps/home/layout.steps.ts+++ b/e2e/src/steps/home/layout.steps.ts@@ -144,7 +144,14 @@ Then('Home 滚动应同时带动主列与右栏', async function (this: CustomWo// Wheel over the main column, not the rail: the point is that a gesture// anywhere in the dashboard moves the whole dashboard.- await main.hover({ position: { x: 40, y: 40 } });+ //+ // Place the pointer from the measured box instead of `main.hover()`: hover+ // waits for the element to be stable and to receive events, and this dashboard+ // keeps micro-updating while the other parallel scenarios are running, so that+ // wait can burn the whole step budget and surface as a bare 30s timeout with+ // no result. A pointer move is always delivered; whether the gesture actually+ // scrolled the dashboard is what the assertions below decide.+ await this.page.mouse.move(mainBefore!.x + 40, mainBefore!.y + 40);await this.page.mouse.wheel(0, 200);await settleBox(this, main);diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 3b1620c3a6e..a8210f31a55 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -138,7 +138,15 @@ export interface GoalExplorationConfig {maxExperiments: number;}-/** Opt-in recovery supervision. It cannot grant new permissions or expand budgets. */+/**+ * Recovery supervision. It cannot grant new permissions or expand budgets.+ *+ * Every newly created Goal carries this with `enabled: true` — the server writes+ * it at creation and rejecting the opposite is what makes "no Goal without a+ * supervisor" hold. `enabled` is kept (rather than dropped) because Goals created+ * before supervision became mandatory still read it to decide whether the+ * supervisor runs.+ */export interface GoalSupervisionPolicy {enabled: boolean;/** Bounded incident ledger and paid diagnostic runs per Goal (default 10, maximum 100). */diff --git a/src/features/AgentGoals/GoalDetailPage.test.tsx b/src/features/AgentGoals/GoalDetailPage.test.tsxindex a07dfb1d81c..5dc1f9c2536 100644--- a/src/features/AgentGoals/GoalDetailPage.test.tsx+++ b/src/features/AgentGoals/GoalDetailPage.test.tsx@@ -9,25 +9,27 @@ import { WorkspaceSidePanelProvider } from '@/features/RightPanel/WorkspaceSidePimport GoalDetailPage from './GoalDetailPage';-const mocks = vi.hoisted(() => ({ showPortal: false }));--const snapshot = {- goal: {- agentId: 'agt_manager',- config: { manager: true, managerState: { topicId: 'tpc_manager' } },- id: 'goal_1',- projectId: null,- requirement: null,- status: 'review',- title: 'Ship it',- },- nodes: [],-};+const mocks = vi.hoisted(() => ({ hasSupervision: true, showPortal: false }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));vi.mock('@/store/goal', () => ({- goalSelectors: { goalGraph: () => () => snapshot },+ goalSelectors: {+ goalGraph: () => () => ({+ goal: {+ agentId: 'agt_manager',+ config: mocks.hasSupervision+ ? { manager: true, managerState: { topicId: 'tpc_manager' } }+ : {},+ id: 'goal_1',+ projectId: null,+ requirement: null,+ status: 'review',+ title: 'Ship it',+ },+ nodes: [],+ }),+ },useGoalStore: (selector: (s: any) => unknown) =>selector({pauseGoal: vi.fn(),@@ -69,7 +71,16 @@ vi.mock('@/features/RightPanel', () => ({),}));-vi.mock('@/features/RightPanel/ToggleRightPanelButton', () => ({ default: () => null }));+// The toggle itself is store-backed (agent display meta); its own contract is+// that a press reaches `onToggle`, so the page tests drive the press, not the avatar.+vi.mock('./GoalSupervisorToggle', () => ({+ default: ({ label, onToggle }: { label: string; onToggle: () => void }) => (+ <button data-testid="goal-supervisor-toggle" onClick={onToggle}>+ {label}+ </button>+ ),+}));+vi.mock('@/features/Portal/router', () => ({PortalContent: () => <div data-testid="goal-portal-content" />,}));@@ -88,38 +99,84 @@ vi.mock('@/features/AgentBreadcrumb/useAgentRoutePath', () => ({vi.mock('@/features/WideScreenContainer', () => ({default: ({ children }: { children: ReactNode }) => <div>{children}</div>,}));-vi.mock('./GoalChat', () => ({ default: () => <div data-testid="goal-chat" /> }));+vi.mock('./GoalChat', () => ({+ default: ({ agentId }: { agentId: string }) => (+ <div data-agent-id={agentId} data-testid="goal-chat" />+ ),+}));vi.mock('./GoalDetailActions', () => ({ default: () => null }));vi.mock('./GoalHeaderMetrics', () => ({ default: () => null }));vi.mock('./GoalRequirement', () => ({ default: () => null }));vi.mock('./NorthStarMetrics', () => ({ default: () => null }));vi.mock('./ProcessControl', () => ({ default: () => null }));vi.mock('./GoalSupervision', () => ({- GoalSupervision: ({ topicId }: { topicId: string }) => (- <div data-testid="goal-supervision">{topicId}</div>+ GoalSupervision: ({ onOpenChat, topicId }: { onOpenChat?: () => void; topicId: string }) => (+ <div data-testid="goal-supervision">+ {topicId}+ {onOpenChat && (+ <button data-testid="goal-supervision-open-chat" onClick={onOpenChat}>+ open chat+ </button>+ )}+ </div>),}));describe('GoalDetailPage', () => {beforeEach(() => {+ mocks.hasSupervision = true;mocks.showPortal = false;});// On the agent-less route the task workspace owns the portal host, but the- // supervision trace has no other home: "View trace" must still open it.- it('opens the supervision trace on the agent-less workspace route', () => {+ // supervision record has no other home: the supervising agent's avatar must+ // still open it, and must name it as the supervision record to open.+ it('opens the supervision record from the supervising agent avatar on the agent-less route', () => {render(<WorkspaceSidePanelProvider><GoalDetailPage goalId={'goal_1'} /></WorkspaceSidePanelProvider>,);- fireEvent.click(screen.getByText('goalProcess.manager.viewTrace'));+ expect(screen.getByTestId('goal-supervisor-toggle')).toHaveTextContent(+ 'goalProcess.manager.viewTrace',+ );+ fireEvent.click(screen.getByTestId('goal-supervisor-toggle'));expect(screen.getByTestId('goal-supervision')).toHaveTextContent('tpc_manager');expect(screen.getByTestId('goal-right-panel')).toHaveAttribute('data-expand', 'true');});+ // The fallback has to resolve on the agent-less route too: there the route+ // names no agent and an unmanaged goal has no record, so the goal row's own+ // agent is the only thing that can say whose conversation this is.+ it('falls back to the goal agent’s conversation without a route agent or a record', () => {+ mocks.hasSupervision = false;+ render(<GoalDetailPage goalId={'goal_1'} />);++ expect(screen.getByTestId('goal-supervisor-toggle')).toHaveTextContent('goalChat.title');+ fireEvent.click(screen.getByTestId('goal-supervisor-toggle'));++ expect(screen.getByTestId('goal-chat')).toHaveAttribute('data-agent-id', 'agt_manager');+ expect(screen.getByTestId('goal-right-panel')).toHaveAttribute('data-expand', 'true');+ });++ // The record is read-only, so a goal that has one must keep a route back to the+ // editable conversation — otherwise consolidating the header's two controls+ // would have removed the only way to ask the goal's agent anything.+ it('hands a managed goal back to its editable conversation from the record', () => {+ render(<GoalDetailPage agentId={'agt_manager'} goalId={'goal_1'} />);++ fireEvent.click(screen.getByTestId('goal-supervisor-toggle'));+ expect(screen.getByTestId('goal-supervision')).toBeInTheDocument();++ fireEvent.click(screen.getByTestId('goal-supervision-open-chat'));++ expect(screen.queryByTestId('goal-supervision')).not.toBeInTheDocument();+ expect(screen.getByTestId('goal-chat')).toHaveAttribute('data-agent-id', 'agt_manager');+ expect(screen.getByTestId('goal-right-panel')).toHaveAttribute('data-expand', 'true');+ });+it('leaves drill-downs to the workspace portal host on the agent-less route', () => {mocks.showPortal = true;render(diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxindex e6edf1b6675..a3d401514f8 100644--- a/src/features/AgentGoals/GoalDetailPage.tsx+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -3,7 +3,7 @@import { Flexbox } from '@lobehub/ui';import { Button, Text } from '@lobehub/ui/base-ui';import { createStaticStyles } from 'antd-style';-import { EyeIcon, PauseIcon, PlayIcon } from 'lucide-react';+import { PauseIcon, PlayIcon } from 'lucide-react';import { memo, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Link } from 'react-router';@@ -17,7 +17,6 @@ import NavHeader from '@/features/NavHeader';import { PortalContent } from '@/features/Portal/router';import { usePortalPanelWidth } from '@/features/Portal/usePortalPanelWidth';import RightPanel from '@/features/RightPanel';-import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';import { useWorkspaceSidePanel } from '@/features/RightPanel/WorkspaceSidePanel';import WideScreenContainer from '@/features/WideScreenContainer';import { usePermission } from '@/hooks/usePermission';@@ -33,6 +32,7 @@ import GoalHeaderMetrics from './GoalHeaderMetrics';import { goalManagerConversation } from './goalPresentation';import GoalRequirement from './GoalRequirement';import { GoalSupervision } from './GoalSupervision';+import GoalSupervisorToggle from './GoalSupervisorToggle';import NorthStarMetrics from './NorthStarMetrics';import ProcessControl from './ProcessControl';import { useGoalChatPanel } from './useGoalChatPanel';@@ -145,11 +145,35 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {const { goal, nodes } = snapshot;const managerConversation = goalManagerConversation(goal);- // The panel hosts the goal conversation only when the goal has a- // responsible agent; without one it is drill-down-only.- const panelExpandable = !!chat.agentId;+ // Who supervises this page: the agent the route names, the agent behind the+ // supervision record, or the goal's own agent. That last fallback is what keeps+ // the agent-less `/goal/:goalId` route working — there the route names no agent+ // and an unmanaged goal has no record, but the goal still knows whose+ // conversation this is.+ const supervisingAgentId =+ chat.agentId ?? managerConversation?.agentId ?? goal.agentId ?? undefined;+ const panelExpandable = !!supervisingAgentId;const chatVisible = chat.open && panelExpandable;+ /**+ * One entry, one destination. A goal with a supervision conversation opens that+ * record; one without opens the side conversation, rather than an empty panel.+ * Re-targeting only when the destination is not already the open one keeps a+ * reopen from bumping the request and remounting the panel.+ */+ const openPanel = () => {+ if (!supervisingAgentId) return;+ const target = managerConversation+ ? { agentId: managerConversation.agentId, topicId: managerConversation.topicId }+ : { agentId: supervisingAgentId, topicId: undefined };+ if (chat.topicId !== target.topicId) {+ clearPortalStack();+ chat.openConversation(target);+ return;+ }+ chat.setOpen(true);+ };+const paused = goal.status === 'paused';// Pace control exists only while the coordinator loop is actually moving (or// explicitly paused). A goal in review awaits the human, and a closed goal@@ -184,29 +208,19 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {</Flexbox>}right={- graphFullscreen ? undefined : (- <Flexbox horizontal align={'center'} gap={8}>- {managerConversation && (- <Button- icon={EyeIcon}- size={'small'}- onClick={() => {- clearPortalStack();- chat.openSupervision(managerConversation);- }}- >- {t('goalProcess.manager.viewTrace')}- </Button>- )}- {panelExpandable && (- <ToggleRightPanelButton+ graphFullscreen+ ? undefined+ : supervisingAgentId && (+ <GoalSupervisorTogglehideWhenExpanded+ agentId={supervisingAgentId}expand={showPortal || chatVisible}- onToggle={() => chat.setOpen(true)}+ label={+ managerConversation ? t('goalProcess.manager.viewTrace') : t('goalChat.title')+ }+ onToggle={openPanel}/>- )}- </Flexbox>- )+ )}/><Flexbox flex={1} style={{ overflowY: 'auto' }}>@@ -258,8 +272,8 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {{/* Same Portal the conversation surface uses — the drill-down chain(metric / node → task detail → topic) rides its view stack, and theheader's back arrow and close come for free. When no drill-down is- open, the panel hosts the conversation with the goal's responsible- agent so a user can just ask about progress.+ open, the panel hosts the goal agent's supervision record, or its side+ conversation when the goal has no record yet.On the agent-less route the task workspace already mounts the portalhost, so a drill-down renders there and this panel stays out of the@@ -281,20 +295,23 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {hasWorkspaceSidePanel ? null : (<PortalContent />)- ) : chat.agentId && chat.topicId ? (+ ) : supervisingAgentId && chat.topicId ? (<GoalSupervision- agentId={chat.agentId}+ agentId={supervisingAgentId}goalId={goalId}- key={`${goalId}:${chat.agentId}:${chat.request}`}+ key={`${goalId}:${supervisingAgentId}:${chat.request}`}topicId={chat.topicId}onCollapse={() => chat.setOpen(false)}+ // The record is read-only and the avatar is the panel's only entry, so+ // this is how a goal with a record gets back to an editable chat.+ onOpenChat={() => chat.openConversation({ agentId: supervisingAgentId })}/>- ) : chat.agentId ? (+ ) : supervisingAgentId ? (<GoalChat- agentId={chat.agentId}+ agentId={supervisingAgentId}goalId={goalId}initialTopicId={chat.topicId}- key={`${goalId}:${chat.agentId}:${chat.request}`}+ key={`${goalId}:${supervisingAgentId}:${chat.request}`}onCollapse={() => chat.setOpen(false)}/>) : null}diff --git a/src/features/AgentGoals/GoalSupervision.tsx b/src/features/AgentGoals/GoalSupervision.tsxindex 5b89a12649e..d1fc26df063 100644--- a/src/features/AgentGoals/GoalSupervision.tsx+++ b/src/features/AgentGoals/GoalSupervision.tsx@@ -2,7 +2,13 @@ import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';import { agentDisplayName } from '@lobechat/types';import { copyToClipboard, type DropdownItem, DropdownMenu, Flexbox } from '@lobehub/ui';import { ActionIcon, Text, toast } from '@lobehub/ui/base-ui';-import { CopyIcon, ExternalLink, MoreHorizontal, PanelRightCloseIcon } from 'lucide-react';+import {+ CopyIcon,+ ExternalLink,+ MessagesSquareIcon,+ MoreHorizontal,+ PanelRightCloseIcon,+} from 'lucide-react';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -20,6 +26,8 @@ interface GoalSupervisionProps {agentId: string;goalId: string;onCollapse: () => void;+ /** Hand the panel back to the agent's editable side conversation. */+ onOpenChat?: () => void;topicId: string;}@@ -41,7 +49,13 @@ const WaitingForFirstRun = memo(() => {WaitingForFirstRun.displayName = 'GoalSupervisionWaiting';/** The manager's ongoing record is inspectable without sending or editing messages. */-export const GoalSupervision = ({ agentId, goalId, onCollapse, topicId }: GoalSupervisionProps) => {+export const GoalSupervision = ({+ agentId,+ goalId,+ onCollapse,+ onOpenChat,+ topicId,+}: GoalSupervisionProps) => {const { t } = useTranslation('chat');const useFetchAgentConfig = useAgentStore((s) => s.useFetchAgentConfig);useFetchAgentConfig(true, agentId);@@ -60,6 +74,19 @@ export const GoalSupervision = ({ agentId, goalId, onCollapse, topicId }: GoalSu// referencing it elsewhere (`lh topic view`, a bug report), like a task run's.const menuItems = useMemo<DropdownItem[]>(() => [+ // The record is read-only and the avatar is the panel's only entry, so the+ // way back to an editable conversation has to live here — otherwise a goal+ // with a record would have no route to asking its agent anything.+ ...(onOpenChat+ ? [+ {+ icon: MessagesSquareIcon,+ key: 'openChat',+ label: t('goalChat.title'),+ onClick: onOpenChat,+ },+ ]+ : []),{icon: ExternalLink,key: 'openAgentTopic',@@ -76,7 +103,7 @@ export const GoalSupervision = ({ agentId, goalId, onCollapse, topicId }: GoalSu},},],- [agentId, navigate, t, topicId],+ [agentId, navigate, onOpenChat, t, topicId],);return (diff --git a/src/features/AgentGoals/GoalSupervisorToggle.tsx b/src/features/AgentGoals/GoalSupervisorToggle.tsxnew file mode 100644index 00000000000..47e8b8b627c--- /dev/null+++ b/src/features/AgentGoals/GoalSupervisorToggle.tsx@@ -0,0 +1,62 @@+'use client';++import { ActionIcon } from '@lobehub/ui/base-ui';++import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';+import AssigneeAvatar from '@/features/AgentTasks/features/AssigneeAvatar';+import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';++/** Fits the 28px header control without crowding it. */+const AVATAR_SIZE = 20;++interface GoalSupervisorToggleProps {+ /** The agent that supervises the goal; its avatar is the panel's entry. */+ agentId: string;+ /** Whether the panel is open — drives the pressed state. */+ expand: boolean;+ hideWhenExpanded?: boolean;+ /** What a press opens, so the tooltip names the action rather than a generic toggle. */+ label: string;+ onToggle: () => void;+}++/**+ * The supervising agent's avatar as the goal panel's entry.+ *+ * The header used to carry two entries for one destination — a panel toggle and a+ * separate "view supervision progress" button. The avatar replaces both, so who+ * is watching and where to see it read as one affordance, and the entry names a+ * person instead of a generic panel glyph.+ */+const GoalSupervisorToggle = ({+ agentId,+ expand,+ hideWhenExpanded,+ label,+ onToggle,+}: GoalSupervisorToggleProps) => {+ const meta = useAgentDisplayMeta(agentId);++ if (hideWhenExpanded && expand) return null;++ // The avatar carries the identity; the tooltip has to carry the action too,+ // because an avatar alone does not tell a screen reader (or a hovering user)+ // that pressing it opens something.+ const title = meta?.title ? `${meta.title} · ${label}` : label;++ return (+ <ActionIcon+ active={expand}+ aria-label={title}+ data-testid={'goal-supervisor-toggle'}+ icon={<AssigneeAvatar agentId={agentId} size={AVATAR_SIZE} />}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={title}+ onClick={onToggle}+ />+ );+};++GoalSupervisorToggle.displayName = 'GoalSupervisorToggle';++export default GoalSupervisorToggle;diff --git a/src/features/AgentGoals/useGoalChatPanel.test.ts b/src/features/AgentGoals/useGoalChatPanel.test.tsindex b1f2bda0684..2cb7cb2c0b2 100644--- a/src/features/AgentGoals/useGoalChatPanel.test.ts+++ b/src/features/AgentGoals/useGoalChatPanel.test.ts@@ -12,21 +12,33 @@ describe('useGoalChatPanel', () => {expect(result.current.agentId).toBe('worker');act(() => result.current.setOpen(true));expect(result.current.open).toBe(true);- act(() => result.current.openSupervision(manager));+ act(() => result.current.openConversation(manager));expect(result.current).toMatchObject({ open: true, ...manager });const firstRequest = result.current.request;act(() => result.current.setOpen(false));expect(result.current.open).toBe(false);- act(() => result.current.openSupervision(manager));+ act(() => result.current.openConversation(manager));expect(result.current).toMatchObject({ open: true, ...manager });expect(result.current.request).not.toBe(firstRequest);});+ // The same destination carries both panel contents: a target without a topic+ // means the agent's side conversation, which is how a managed goal's record+ // hands the reader back an editable chat.+ it('opens the agent’s side conversation when the target names no topic', () => {+ const { result } = renderHook(() => useGoalChatPanel('goal-a'));++ act(() => result.current.openConversation({ agentId: 'worker' }));++ expect(result.current).toMatchObject({ agentId: 'worker', open: true });+ expect(result.current.topicId).toBeUndefined();+ });+it('never carries another goal’s open panel or creator into the next goal', () => {const { result, rerender } = renderHook(({ id, agent }) => useGoalChatPanel(id, agent), {initialProps: { id: 'goal-a', agent: 'worker-a' },});- act(() => result.current.openSupervision(manager));+ act(() => result.current.openConversation(manager));rerender({ id: 'goal-b', agent: 'worker-b' });expect(result.current).toMatchObject({ open: false, agentId: 'worker-b' });expect(result.current.topicId).toBeUndefined();diff --git a/src/features/AgentGoals/useGoalChatPanel.ts b/src/features/AgentGoals/useGoalChatPanel.tsindex 2c512af052d..ca7f24bdcd9 100644--- a/src/features/AgentGoals/useGoalChatPanel.ts+++ b/src/features/AgentGoals/useGoalChatPanel.ts@@ -2,7 +2,8 @@ import { useState } from 'react';interface ConversationTarget {agentId: string;- topicId: string;+ /** Absent opens the agent's side conversation rather than a specific topic. */+ topicId?: string;}interface PanelState {@@ -22,9 +23,12 @@ export const useGoalChatPanel = (goalId: string, responsibleAgentId?: string) =>return {agentId: current.target?.agentId ?? responsibleAgentId,open: current.open,- // Re-entering supervision must restore its topic even after browsing history- // or starting another conversation in the same agent's panel.- openSupervision: (target: ConversationTarget) => {+ /**+ * Send the panel to one destination: the supervision record when the target+ * names a topic, the agent's side conversation otherwise. Re-targeting bumps+ * `request` because the panel remounts on the new conversation.+ */+ openConversation: (target: ConversationTarget) => {setState({ goalId, open: true, request: current.request + 1, target });},request: current.request,