π€― 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
'use client';
import { Button, createStaticStyles, Flexbox, Tag, Text, toast } from '@lobehub/ui';
import { ArchiveIcon, ArchiveRestoreIcon, PauseIcon, PlayIcon } from 'lucide-react';
import { memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router';
import NotFound from '@/components/404';
import ConversationSkeleton from '@/components/Skeleton/Conversation/List';
import GoalDetailSkeleton from '@/components/Skeleton/GoalDetail';
import AgentBreadcrumb from '@/features/AgentBreadcrumb';
import { useAgentRoutePath } from '@/features/AgentBreadcrumb/useAgentRoutePath';
import { FavoriteButton, useCurrentFavoritePath } from '@/features/Favorites';
import NavHeader from '@/features/NavHeader';
import { PortalContent } from '@/features/Portal/router';
import { usePortalPanelWidth } from '@/features/Portal/usePortalPanelWidth';
import RightPanel from '@/features/RightPanel';
import { useWorkspaceSidePanel } from '@/features/RightPanel/WorkspaceSidePanel';
import WideScreenContainer from '@/features/WideScreenContainer';
import OtherScopeAsyncError from '@/features/Workspace/OtherScopeAsyncError';
import { type ScopedLambdaClient } from '@/features/Workspace/useLocateInOtherScope';
import { usePermission } from '@/hooks/usePermission';
import { useResourceManageable } from '@/hooks/useResourceManageable';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { goalSelectors, useGoalStore } from '@/store/goal';
import GoalAgentModelConfig from './GoalAgentModelConfig';
import GoalChat from './GoalChat';
import { GoalConversationContext } from './goalConversation';
import GoalDetailActions from './GoalDetailActions';
import GoalDetailTitle from './GoalDetailTitle';
import GoalHeaderMetrics from './GoalHeaderMetrics';
import { goalManagerConversation } from './goalPresentation';
import GoalRequirement from './GoalRequirement';
import { GoalSupervision } from './GoalSupervision';
import GoalSupervisorToggle from './GoalSupervisorToggle';
import GoalVisibilitySelector from './GoalVisibilitySelector';
import GoalWorkspaceBreadcrumb from './GoalWorkspaceBreadcrumb';
import NorthStarMetrics from './NorthStarMetrics';
import ProcessControl from './ProcessControl';
import { useGoalChatPanel } from './useGoalChatPanel';
/**
* The goal detail page. A goal is a Goal Graph β it owns its own decomposition
* and dispatches its own Tasks β so the page reads the graph snapshot directly and
* the route is keyed by the `goals` row id.
*
* Every header metric is a drill-down entry: clicking one opens its detail in
* the right-hand Portal, the same panel the process-control band drills into
* (node β task β topic conversation).
*/
const styles = createStaticStyles(({ css }) => ({
header: css`
padding-block: 8px 4px;
`,
}));
/** A goal 404s outside its own scope; reading it through another scope tells where it lives. */
const probeGoalGraph = (client: ScopedLambdaClient, id: string, signal: AbortSignal) =>
client.goal.graph.query({ id }, { context: { showNotification: false }, signal });
interface GoalDetailPageProps {
/** Absent for a goal with no responsible agent β e.g. one created from a project. */
agentId?: string;
goalId: string;
}
/** How long the panel waits for a send-back's supervision record before giving up on it. */
const AWAIT_RECORD_TIMEOUT = 10_000;
const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
const { t } = useTranslation('chat');
const { allowed: canEdit, reason: editBlockedReason } = usePermission('create_content');
const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
const { error, isLoading, mutate } = useFetchGoalGraph(goalId);
const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
const pauseGoal = useGoalStore((s) => s.pauseGoal);
const resumeGoal = useGoalStore((s) => s.resumeGoal);
const startGoal = useGoalStore((s) => s.startGoal);
const archiveGoal = useGoalStore((s) => s.archiveGoal);
const [restoring, setRestoring] = useState(false);
// The server lets only a draft's creator or a workspace owner launch it.
const canStart = useResourceManageable(snapshot?.goal.userId);
const buildAgentPath = useAgentRoutePath(agentId ?? '');
const favoritePath = useCurrentFavoritePath();
const showPortal = useChatStore(chatPortalSelectors.showPortal);
const currentViewType = useChatStore(chatPortalSelectors.currentViewType);
// On the agent-less `/goal/:goalId` route an ancestor layout already owns the
// side panel; mounting ours as well would give the surface two portal hosts.
const hasWorkspaceSidePanel = useWorkspaceSidePanel();
const chat = useGoalChatPanel(
goalId,
agentId,
snapshot ? goalManagerConversation(snapshot.goal) : undefined,
);
const clearPortalStack = useChatStore((s) => s.clearPortalStack);
// While the exploration map runs fullscreen its overlay carries the portal
// panel; ours unmounts so exactly one PortalContent is alive at a time.
const [graphFullscreen, setGraphFullscreen] = useState(false);
const [starting, setStarting] = useState(false);
// Same per-view width grammar as the conversation portal, but remembered
// under the 'goal' scope: resizing here never affects the chat surface.
const { maxWidth, minWidth, updateWidth, width } = usePortalPanelWidth(currentViewType, 'goal');
/**
* Give a drill-down its reading room by folding the app rail, not the goal.
*
* Opened beside the goal, the Portal used to leave both panes cramped β the
* goal's title wrapping to four lines, its task rows truncated to a few
* characters. Folding the goal pane itself was tried and is wrong: it hides
* the task's own verification state, which is exactly what the reader drilled
* in to check. The rail is the one thing on screen that no one is reading.
*
* `showLeftPanel` is a persisted preference, so this only ever restores what
* it collapsed: a user who already works with the rail folded is left alone,
* and one who folds or opens it themselves while a drill-down is up keeps
* that choice.
*/
const showLeftPanel = useGlobalStore(systemStatusSelectors.showLeftPanel);
const toggleLeftPanel = useGlobalStore((s) => s.toggleLeftPanel);
const collapsedRailRef = useRef(false);
const titleInputRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (showPortal) {
if (showLeftPanel && !collapsedRailRef.current) {
collapsedRailRef.current = true;
toggleLeftPanel(false);
}
return;
}
if (collapsedRailRef.current) {
collapsedRailRef.current = false;
toggleLeftPanel(true);
}
}, [showPortal, showLeftPanel, toggleLeftPanel]);
// Leaving the page with the rail still folded would strand it on every other
// surface, so give it back on the way out.
useEffect(
() => () => {
if (collapsedRailRef.current) {
collapsedRailRef.current = false;
useGlobalStore.getState().toggleLeftPanel(true);
}
},
[],
);
// A send-back's hand-off normally lands with the request; when the main Agent
// cannot take it up, the panel stops waiting and stays where it opened.
const { awaitingRecord, stopAwaitingRecord } = chat;
useEffect(() => {
if (!awaitingRecord) return;
const timer = setTimeout(stopAwaitingRecord, AWAIT_RECORD_TIMEOUT);
return () => clearTimeout(timer);
}, [awaitingRecord, stopAwaitingRecord]);
// The portal stack belongs to this goal's inspection session β leaving the
// page (or switching goals) must not leak it into the conversation surface.
useEffect(() => () => clearPortalStack(), [clearPortalStack, goalId]);
if (error && !snapshot)
return (
<OtherScopeAsyncError
error={error}
pendingFallback={<GoalDetailSkeleton />}
resourceKey={`goal:${goalId}`}
variant={'page'}
probe={(client: ScopedLambdaClient, signal: AbortSignal) =>
probeGoalGraph(client, goalId, signal)
}
onRetry={mutate}
/>
);
if (!snapshot)
return isLoading ? (
<GoalDetailSkeleton />
) : (
<NotFound desc={t('goalDetail.notFoundDescription')} title={t('goalDetail.notFoundTitle')} />
);
const { goal, nodes } = snapshot;
const managerConversation = goalManagerConversation(goal);
// 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 panelTarget = managerConversation
? { agentId: managerConversation.agentId, topicId: managerConversation.topicId }
: supervisingAgentId
? { agentId: supervisingAgentId, topicId: undefined }
: undefined;
const openPanel = () => {
const target = panelTarget;
if (!target) return;
if (chat.topicId !== target.topicId) {
clearPortalStack();
chat.openConversation(target);
return;
}
chat.setOpen(true);
};
// A decision that just messaged the agent (sending a plan back) shows that
// message landing, so the reply is never invisible behind a drill-down. A
// managed goal whose main Agent has no supervision record yet gets one from
// this very turn: the panel opens now and moves there once it exists.
const revealConversation = () => {
setGraphFullscreen(false);
clearPortalStack();
if (goal.config?.manager && !managerConversation && supervisingAgentId)
chat.openAwaitingRecord({ agentId: supervisingAgentId });
else openPanel();
};
// Deferred past the menu closing, which hands focus back to its trigger.
const focusTitleEditor = () => {
requestAnimationFrame(() => {
titleInputRef.current?.focus();
titleInputRef.current?.select();
});
};
// Clipped like the workspace crumb, so a long title cannot push the header's
// actions off the bar.
const goalCrumb = (
<Text ellipsis color={'inherit'} style={{ maxWidth: 'min(320px, 45vw)' }} weight={500}>
{goal.title}
</Text>
);
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
// cannot move β pausing either would be a dead or misleading button.
const canPause =
canEdit &&
nodes.length > 0 &&
['paused', 'planning', 'running', 'verifying'].includes(goal.status);
return (
<GoalConversationContext value={panelTarget ? revealConversation : undefined}>
<Flexbox horizontal flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
<Flexbox flex={1} height={'100%'} style={{ minWidth: 0 }}>
<NavHeader
left={
<Flexbox horizontal align={'center'} gap={4}>
{agentId ? (
<AgentBreadcrumb
agentId={agentId}
extraItems={[goalCrumb]}
// The goal title owns the last crumb, so this one is a way back
// to the agent's goal list rather than a label for this page.
title={<Link to={buildAgentPath('goals')}>{t('goalList.title')}</Link>}
/>
) : (
<GoalWorkspaceBreadcrumb title={goal.title} />
)}
<FavoriteButton
path={favoritePath}
targetId={goal.id}
title={goal.title}
type={'goal'}
/>
{/* Not nested under the breadcrumb: an agent-less goal still has to
be deletable, and this menu is the only place that can do it. */}
<GoalDetailActions
agentId={agentId}
archivedAt={goal.archivedAt ?? null}
goalId={goal.id}
projectId={goal.projectId}
onRename={focusTitleEditor}
/>
</Flexbox>
}
right={
graphFullscreen
? undefined
: supervisingAgentId && (
<GoalSupervisorToggle
hideWhenExpanded
agentId={supervisingAgentId}
expand={showPortal || chatVisible}
label={
managerConversation
? t('goalProcess.manager.viewTrace')
: t('goalChat.title')
}
onToggle={openPanel}
/>
)
}
/>
<Flexbox flex={1} style={{ overflowY: 'auto' }}>
<WideScreenContainer gap={20} paddingBlock={16}>
<Flexbox className={styles.header} gap={8}>
<GoalDetailTitle
creatorUserId={goal.userId}
goalId={goal.id}
inputRef={titleInputRef}
title={goal.title}
/>
<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. */}
{/* A draft is still being arranged: nothing has been dispatched,
and starting it is the one explicit move into running. */}
<Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'} wrap={'wrap'}>
{/* One control at a time: a draft is started, a moving goal is
paused or resumed β the two states never overlap. */}
{goal.archivedAt ? (
// Archived goals stay put: start / resume refuse them until
// restored, so restoring is the one control offered.
<>
<Tag icon={<ArchiveIcon size={12} />}>{t('goalList.archived')}</Tag>
{canEdit && canStart && (
<Button
icon={ArchiveRestoreIcon}
loading={restoring}
onClick={async () => {
setRestoring(true);
try {
await archiveGoal(goal.id, false);
toast.success(t('goalList.unarchiveSuccess'));
} catch {
toast.error(t('goalList.unarchiveFailed'));
} finally {
setRestoring(false);
}
}}
>
{t('goalList.unarchive')}
</Button>
)}
</>
) : goal.status === 'draft' ? (
canEdit &&
canStart && (
<Button
icon={PlayIcon}
loading={starting}
type={'primary'}
onClick={async () => {
setStarting(true);
try {
await startGoal(goal.id);
} catch (error) {
toast.error((error as Error).message);
} finally {
setStarting(false);
}
}}
>
{t('goalProcess.start')}
</Button>
)
) : canPause ? (
<Button
icon={paused ? PlayIcon : PauseIcon}
type={paused ? 'primary' : 'default'}
onClick={() => void (paused ? resumeGoal(goal.id) : pauseGoal(goal.id))}
>
{paused ? t('goalProcess.resume') : t('goalProcess.pause')}
</Button>
) : null}
{/* Who plans the goal and who does its Tasks, next to the control
that starts or pauses that work. Also the way to give an
agent-less goal its main agent. */}
<GoalAgentModelConfig
disabled={!canEdit || !canStart}
goalId={goal.id}
routeAgentId={agentId}
disabledReason={
canEdit ? t('goalDetail.agentManagedByOwner') : editBlockedReason
}
/>
<GoalVisibilitySelector goalId={goal.id} />
{goal.status === 'draft' && !goal.archivedAt && (
<Text fontSize={12} type={'secondary'}>
{t('goalProcess.draft')}
</Text>
)}
</Flexbox>
{goal.requirement && (
<GoalRequirement goalId={goal.id} requirement={goal.requirement} />
)}
{/* North-star strip follows the requirement it measures: the
numbers are what executing that requirement has observed so
far, so they read as its outcome, below it. */}
<NorthStarMetrics canEdit={canEdit} goalId={goalId} />
</Flexbox>
<ProcessControl
goalId={goal.id}
graphFullscreen={graphFullscreen}
onGraphFullscreenChange={setGraphFullscreen}
onFollowUp={
// Viewers can read the result but not talk to its agent; the
// backend would reject the turn, so they get no composer.
canEdit && panelTarget
? (message) => {
// Same destination as the header entry β the supervision record
// when there is one β and it replaces any open drill-down.
clearPortalStack();
chat.openConversation({ ...panelTarget, initialMessage: message });
}
: undefined
}
/>
</WideScreenContainer>
</Flexbox>
</Flexbox>
{/* Same Portal the conversation surface uses β the drill-down chain
(metric / node β task detail β topic) rides its view stack, and the
header's back arrow and close come for free. When no drill-down is
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 portal
host, so a drill-down renders there and this panel stays out of the
way: a second host would render the same detail twice while squeezing
the goal column to nothing beside it. The goal conversation and the
supervision trace have no other home, so those still mount here. */}
<RightPanel
expand={(showPortal ? !hasWorkspaceSidePanel : chatVisible) && !graphFullscreen}
maxWidth={maxWidth}
minWidth={minWidth}
width={width}
onSizeChange={(size) => updateWidth(size?.width)}
onExpandChange={(next) => {
if (!next) clearPortalStack();
chat.setOpen(next);
}}
>
{graphFullscreen ? null : showPortal ? (
hasWorkspaceSidePanel ? null : (
<PortalContent />
)
) : managerConversation ? (
// A goal bound to its supervision record keeps the panel on that
// topic: no side conversation, no other topic can replace it.
<GoalSupervision
agentId={managerConversation.agentId}
goalId={goalId}
initialMessage={chat.initialMessage}
key={`${goalId}:${managerConversation.agentId}:${managerConversation.topicId}:${chat.request}`}
topicId={managerConversation.topicId}
onCollapse={() => chat.setOpen(false)}
onInitialMessageConsumed={chat.consumeInitialMessage}
/>
) : chat.awaitingRecord ? (
// The supervision record is on its way: show it loading, not the
// side conversation's empty welcome.
<Flexbox flex={1} padding={16}>
<ConversationSkeleton />
</Flexbox>
) : supervisingAgentId ? (
<GoalChat
agentId={supervisingAgentId}
goalId={goalId}
initialMessage={chat.initialMessage}
initialTopicId={chat.topicId}
key={`${goalId}:${supervisingAgentId}:${chat.request}`}
onCollapse={() => chat.setOpen(false)}
onInitialMessageConsumed={chat.consumeInitialMessage}
/>
) : null}
</RightPanel>
</Flexbox>
</GoalConversationContext>
);
});
GoalDetailPage.displayName = 'GoalDetailPage';
export default GoalDetailPage;