🤯 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(chat-input): store the goal marker as a structured composer chip (#18167)
Arvin Xuf777343c8919
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.mdindex c3b40a3f648..725161fc692 100644--- a/.agents/acceptance/common-mistakes.md+++ b/.agents/acceptance/common-mistakes.md@@ -10,21 +10,6 @@ in feature specifications or historical field notes, not in this living checklis## Evidence and publication-### L-E5 — Treating historical branch rendering as proof that conversation can continue--**Wrong approach:** render a recovered historical `taskCallback` card beside the-active tool continuation, then call the message-loss regression verified without-sending another user message.--**Why it fails:** read-path recovery proves only that existing rows are visible.-The next user turn exercises a separate write/parent-selection path and can still-attach to the wrong branch, disappear after reconciliation, or vanish after reload.--**Correct approach:** for every conversation-branch regression, continue from the-fixture through the real composer. Assert the new user row in the database, its-parent on the active spine, its rendered presence before and after a cold reload,-and the resulting assistant continuation when the environment supports it.-### L-E1 — Publishing a replacement as a second Acceptance row**Wrong approach:** assign a replacement check a new id without `supersedes`, or@@ -194,6 +179,85 @@ branch. Also re-read `branch` / `commit` at publish time rather than trusting thscaffold: a session that spans a branch switch fills them from whatever is checkedout when `report-init.sh` ran.+### L-E14 — Verifying an insertion affordance without continuing the user's next action++**Wrong approach:** check that a composer affordance (an action-tag chip, a mention,+a file token) inserted the right node, screenshot it, and move on — then verify the+sent payload through a _different_ entry point that happens to be easier to drive.++**Why it fails:** insertion is half the affordance; the caret it leaves behind is+the other half. A caret parked in front of the inserted node sends the user's very+next keystroke to the wrong side of it. For any chip that serializes into the prompt+with position semantics — the `/goal` marker must lead the message for `isGoalPrompt`+to match — that silently rewrites the payload into something the runtime no longer+recognizes, while every screenshot of the insertion itself still looks correct.+Verifying the payload through a different entry point hides it completely: the path+with the defect is never the path that gets sent.++**Correct approach:** for every insertion affordance, continue the user's action in+the same case — type after inserting — and assert the resulting node order, not just+the node's presence. Drive the payload check through the _same_ entry point the case+under test uses; if an affordance has several entries (slash menu, `+` menu), the one+you send from must be the one you are claiming works. Assert order in the persisted+`editor_data`, since that is what both the prompt serializer and the bubble read.++### L-E15 — Treating historical branch rendering as proof that conversation can continue++**Wrong approach:** render a recovered historical `taskCallback` card beside the+active tool continuation, then call the message-loss regression verified without+sending another user message.++**Why it fails:** read-path recovery proves only that existing rows are visible.+The next user turn exercises a separate write/parent-selection path and can still+attach to the wrong branch, disappear after reconciliation, or vanish after reload.++**Correct approach:** for every conversation-branch regression, continue from the+fixture through the real composer. Assert the new user row in the database, its+parent on the active spine, its rendered presence before and after a cold reload,+and the resulting assistant continuation when the environment supports it.++### L-E16 — Treating a terminal reply as evidence of live streaming++**Wrong approach:** ask a device-executed Claude Code agent for a one-token fixed+marker, record until the process exits, and treat the eventual assistant text or+a refreshed screenshot as proof that the reply streamed into the open Topic.++**Why it fails:** `lh hetero exec` can run Claude Code without+`--include-partial-messages`. In that mode the adapter receives only the final+assistant snapshot, so the UI may show an empty target-Agent shell for the whole+run and acquire the text only during terminal reconciliation. A short fixed+marker also has no observable intermediate state even when partial framing works.++The acceptance proves persistence and refresh recovery but+does not prove the user sees the answer arrive live; a GIF of an empty shell is+mistaken for streaming evidence.++**Correct approach:** enable Claude Code partial messages on the device/sandbox+CLI spawn path. Verify with a multi-part response and timestamped DOM/store+samples before any reload, then attach a GIF whose frames visibly progress and+whose final frame contains the complete answer. Check persistence separately by+refreshing only after the live-stream assertion has passed.++### L-E17 — Proving direct-mention routing with a text-only response++**Wrong approach:** verify a leading single-Agent mention only with a plain-text+response, then conclude that the direct-routing message tree is correct for all+target-Agent runs.++**Why it fails:** tool-capable runs add assistant tool-call chunks and+tool-result messages. Those nodes can accidentally inherit the owner Agent,+create a synthetic target-user envelope, or resume the owner after the tool+result even when the initial text response looked correct.++The simple happy path passes while real coding Agents either+lose their tool output, render it under the wrong Agent, or invoke Lobe AI for+the final answer.++**Correct approach:** exercise a deterministic real tool call through the same+gateway/device route, then assert the complete persisted tree: original owner+user, target assistant/tool call, tool result, and target final response. Also+assert there is no owner assistant, `callAgent`, or synthetic target-user row.+## Product and interaction contracts### L-D1 — Rebuilding a canonical surface from visual impression@@ -284,6 +348,26 @@ one. Where that link would otherwise duplicate the segment's own label, render ideeper routes and let the segment name the section on the index route. Verify the deepestroute of every section, not just the index: an index-only pass cannot see this failure.+### L-D8 — Rendering a cross-agent dispatch envelope as a visible user turn++**Wrong approach:** treat every persisted `role: user` row as a user-authored+message when building the visible conversation list.++**Why it fails:** `callAgent` persists a synthetic user envelope beneath the+caller assistant so the target Agent has an isolated execution context. When+that envelope is rendered, the original prompt appears twice even though the+target Agent produced only one reply.++Users see a duplicate prompt bubble and cannot tell whether+the delegation ran once or twice; acceptance screenshots become misleading.++**Correct approach:** stamp synthetic envelopes with explicit dispatch metadata+when they are persisted, keep them in the context tree, and let the presentation+layer hide only rows declared `visibility: internal`. Continue traversal through+the envelope so the target assistant reply remains independently visible.+Never infer authorship from agent-id differences or a parent tool call: a real+cross-Agent user follow-up can have the same tree shape.+## Environment safety### L-S0 — Concluding a dependency moved from the root manifest alone@@ -310,25 +394,6 @@ count the versions under `node_modules/<pkg>` and every `packages/*/node_modulesand require one distinct value — never from the root manifest. Remember `apps/desktop`and `apps/cli` are standalone installs that a root install never covers.-### L-S0b — Reading a first-boot renderer crash as a defect of the change under test--**Wrong approach:** treat the Electron dev instance's first renderer boot as-representative, and diagnose a `ReferenceError: Cannot access '<X>' before-initialization` thrown from the desktop router config as a bug in the branch.--**Why it fails:** the desktop Vite renderer can serve a partially initialized-module graph on the very first boot after a cold start (dependency optimization-runs concurrently with the first evaluation). The app stays on the HTML loading-shell with `rootChildren: 0` while the stores are already exposed, which reads-exactly like a broken route tree. A single `location.reload()` boots it cleanly-with no code change.--**Correct approach:** on a first-boot renderer error, reload once and re-probe-before drawing any conclusion. Only if the error survives a reload does it belong-to the code. Never attribute it to the change under test without that A/B — and-note that `electron-dev.sh start` reports "Ready" even when the renderer never-became interactive, so its own readiness line is not the gate.-### L-S1 — Publishing to an assumed server target**Wrong approach:** strip a server environment variable and treat `lh whoami` as@@ -341,17 +406,27 @@ database may contain the user's synchronized profile.distinguishes environments. For production publishing without changing a locallogin, use an isolated `LOBEHUB_CLI_HOME` for login and ingest.-### L-S2 — Trusting a successful renderer build as proof Electron boots+### L-S2 — Trusting green gates as proof the app boots-**Wrong approach:** use green Vite and Vitest results as blank-screen insurance for-a desktop routing or module-graph change.+**Wrong approach:** use green Vite, Vitest, lint, and type-check results as+blank-screen insurance for a routing or module-graph change, on Electron or Web.**Why it fails:** browser ESM initialization cycles and nested-router invariants can-fail only when the real renderer starts.--**Correct approach:** boot the real Electron instance, require the project readiness-probe to report a non-error UI, and inspect a screenshot. Router-host component tests-must also cover the real outer-router composition.+fail only when the real renderer starts. Vitest resolves a module graph in its own+order, so a cycle that is harmless under test can still put a module-level binding in+the temporal dead zone in the bundler's order — the app then dies at the+`ErrorBoundary` with `Cannot access '<X>' before initialization` while every gate+stays green. Adding a shared constant next to the logic that uses it is the common+way to close such a cycle in a folder where a node/component pair already import each+other.++**Correct approach:** boot the real surface, require the project readiness probe to+report a non-error UI, and inspect a screenshot before claiming a UI change is+delivered. On a boot failure read `agent-browser console` (the ErrorBoundary page+itself shows no stack) and attribute before diagnosing. Keep cross-module constants+in the folder's leaf module — the one that imports nothing from its siblings — rather+than beside their primary consumer. Router-host component tests must also cover the+real outer-router composition.### L-S3 — Verifying Acceptance UI against an unfetched canary ref@@ -443,67 +518,24 @@ teardown even though you did not start the original.----## Cross-agent dispatch envelopes are not visible user turns+### L-S8 — Reading a first-boot renderer crash as a defect of the change under test-**Wrong approach**: treat every persisted `role: user` row as a user-authored-message when building the visible conversation list.--**Why it's wrong**: `callAgent` persists a synthetic user envelope beneath the-caller assistant so the target Agent has an isolated execution context. When-that envelope is rendered, the original prompt appears twice even though the-target Agent produced only one reply.--**What it breaks**: users see a duplicate prompt bubble and cannot tell whether-the delegation ran once or twice; acceptance screenshots become misleading.--**Correct approach**: stamp synthetic envelopes with explicit dispatch metadata-when they are persisted, keep them in the context tree, and let the presentation-layer hide only rows declared `visibility: internal`. Continue traversal through-the envelope so the target assistant reply remains independently visible.-Never infer authorship from agent-id differences or a parent tool call: a real-cross-Agent user follow-up can have the same tree shape.--## A terminal Claude Code reply is not evidence of live streaming--**Wrong approach**: ask a device-executed Claude Code agent for a one-token fixed-marker, record until the process exits, and treat the eventual assistant text or-a refreshed screenshot as proof that the reply streamed into the open Topic.--**Why it's wrong**: `lh hetero exec` can run Claude Code without-`--include-partial-messages`. In that mode the adapter receives only the final-assistant snapshot, so the UI may show an empty target-Agent shell for the whole-run and acquire the text only during terminal reconciliation. A short fixed-marker also has no observable intermediate state even when partial framing works.--**What it breaks**: the acceptance proves persistence and refresh recovery but-does not prove the user sees the answer arrive live; a GIF of an empty shell is-mistaken for streaming evidence.--**Correct approach**: enable Claude Code partial messages on the device/sandbox-CLI spawn path. Verify with a multi-part response and timestamped DOM/store-samples before any reload, then attach a GIF whose frames visibly progress and-whose final frame contains the complete answer. Check persistence separately by-refreshing only after the live-stream assertion has passed.--## A text-only direct mention does not prove tool-call ownership--**Wrong approach**: verify a leading single-Agent mention only with a plain-text-response, then conclude that the direct-routing message tree is correct for all-target-Agent runs.--**Why it's wrong**: tool-capable runs add assistant tool-call chunks and-tool-result messages. Those nodes can accidentally inherit the owner Agent,-create a synthetic target-user envelope, or resume the owner after the tool-result even when the initial text response looked correct.+**Wrong approach:** treat the Electron dev instance's first renderer boot as+representative, and diagnose a `ReferenceError: Cannot access '<X>' before+initialization` thrown from the desktop router config as a bug in the branch.-**What it breaks**: the simple happy path passes while real coding Agents either-lose their tool output, render it under the wrong Agent, or invoke Lobe AI for-the final answer.+**Why it fails:** the desktop Vite renderer can serve a partially initialized+module graph on the very first boot after a cold start (dependency optimization+runs concurrently with the first evaluation). The app stays on the HTML loading+shell with `rootChildren: 0` while the stores are already exposed, which reads+exactly like a broken route tree. A single `location.reload()` boots it cleanly+with no code change.-**Correct approach**: exercise a deterministic real tool call through the same-gateway/device route, then assert the complete persisted tree: original owner-user, target assistant/tool call, tool result, and target final response. Also-assert there is no owner assistant, `callAgent`, or synthetic target-user row.+**Correct approach:** on a first-boot renderer error, reload once and re-probe+before drawing any conclusion. Only if the error survives a reload does it belong+to the code. Never attribute it to the change under test without that A/B — and+note that `electron-dev.sh start` reports "Ready" even when the renderer never+became interactive, so its own readiness line is not the gate.## Historical sourcediff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 7b61bda3925..48e95cf2919 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -285,6 +285,36 @@ no session, so it ends in the same error for a different reason. See also the twneighbouring entries on this proxy (loading-shell in an isolated context; no seededagent-browser session).+### The composer's slash menu needs real key events — `keyboard type` never opens it++**Situation:** driving the chat composer's `/` slash menu (or anything else gated on+a Lexical `KEY_DOWN_COMMAND`) through agent-browser.++**Doesn't work:** `agent-browser keyboard type "/"`. It inserts through CDP+`Input.insertText`, which produces no `keydown` at all — verified by installing a+capturing `document.addEventListener("keydown", …)` and watching it stay empty while+the character lands in the composer. The editor's SlashPlugin keeps `suppressOpen`+true until a keydown with `key.length === 1` resets it, so the text appears and the+menu never does. Reads exactly like "the slash menu is broken", which is worse than+a visible failure because the composer clearly received the input.++**Works:** use `agent-browser press '/'` for the trigger (and `press Backspace` to+clear). `press` goes through `Input.dispatchKeyEvent`, so the keydown reaches+Lexical. `keyboard type` remains fine for bulk text that no plugin is gated on —+type the prose with it, but fire any menu trigger with `press`.++```bash+agent-browser --session "$RS" click '[data-probe=composer]'+agent-browser --session "$RS" press '/' # menu opens+agent-browser --session "$RS" press Enter # selects the highlighted item+```++Confirm the mechanism rather than assuming a menu is missing:++```bash+agent-browser --session "$RS" eval '(() => { window.__KD=[]; document.addEventListener("keydown", e => window.__KD.push(e.key), true); return "installed"; })()'+```+### Reading a transitioned CSS property immediately after focus/hover**Situation:** asserting that a `:focus-within` / `:hover` rule reveals a@@ -1164,7 +1194,7 @@ Cause not established; re-seeding and restarting the same pool id does not help.**Works:** fall back to the legacy single instance (`electron-dev.sh start`, no id),which runs on the golden profile in place and decrypts normally. It boots on the-loading shell once, so reload once before probing (see L-S0b). Gate on+loading shell once, so reload once before probing (see L-S8). Gate on`app-probe.sh auth` AND `server-auth`, never on the helper's "Ready" line.## Detailed referencesdiff --git a/locales/en-US/editor.json b/locales/en-US/editor.jsonindex 2fdc26d768a..e83036c11a2 100644--- a/locales/en-US/editor.json+++ b/locales/en-US/editor.json@@ -64,7 +64,7 @@"skillFrontmatter.saveFailed": "Metadata was not saved. Retry, or keep editing.","skillFrontmatter.title": "Skill metadata","slash.compact": "Compact context",- "slash.goal": "Set goal",+ "slash.goal": "Goal","slash.goal.desc": "Plan and start a goal with editable acceptance criteria","slash.h1": "Heading 1","slash.h2": "Heading 2",diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex 917ac0549c4..2b8904604c3 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -229,7 +229,6 @@"acceptance.tray.goalModal.save": "Save goal","acceptance.tray.goalModal.setTitle": "Set the goal","acceptance.tray.goalSection": "Goal",- "acceptance.tray.menuSetGoal": "Set goal","acceptance.tray.saveFailed.network": "You appear to be offline — the change wasn’t saved.","acceptance.tray.saveFailed.server": "Couldn’t save the change. Please try again.","acceptance.tray.section.method": "How to check",diff --git a/locales/zh-CN/editor.json b/locales/zh-CN/editor.jsonindex 188b8515f23..687b3087429 100644--- a/locales/zh-CN/editor.json+++ b/locales/zh-CN/editor.json@@ -64,7 +64,7 @@"skillFrontmatter.saveFailed": "元信息未保存。请重试,或继续编辑。","skillFrontmatter.title": "技能元信息","slash.compact": "压缩上下文",- "slash.goal": "设定目标",+ "slash.goal": "目标","slash.goal.desc": "规划并启动带有可编辑验收标准的目标","slash.h1": "一级标题","slash.h2": "二级标题",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex 86fae1fd6d1..85e25281465 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -229,7 +229,6 @@"acceptance.tray.goalModal.save": "保存目标","acceptance.tray.goalModal.setTitle": "设定目标","acceptance.tray.goalSection": "目标",- "acceptance.tray.menuSetGoal": "设定目标","acceptance.tray.saveFailed.network": "网络似乎离线,改动未保存。","acceptance.tray.saveFailed.server": "改动保存失败,请重试。","acceptance.tray.section.method": "怎么看",diff --git a/packages/locales/src/default/editor.ts b/packages/locales/src/default/editor.tsindex 4c67886c15a..a70c32d8720 100644--- a/packages/locales/src/default/editor.ts+++ b/packages/locales/src/default/editor.ts@@ -55,7 +55,7 @@ export default {'actionTag.tooltip.skill': 'Loads a reusable skill package for this request.','actionTag.tooltip.tool': 'Marks a tool the user explicitly selected for this request.','slash.compact': 'Compact context',- 'slash.goal': 'Set goal',+ 'slash.goal': 'Goal','slash.goal.desc': 'Plan and start a goal with editable acceptance criteria','slash.h1': 'Heading 1','slash.h2': 'Heading 2',diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex f44cb1692a8..a942c3e2b4c 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -261,7 +261,6 @@ export default {'acceptance.tray.goalSection': 'Goal','acceptance.tray.saveFailed.network': 'You appear to be offline — the change wasn’t saved.','acceptance.tray.saveFailed.server': 'Couldn’t save the change. Please try again.',- 'acceptance.tray.menuSetGoal': 'Set goal','acceptance.tray.section.method': 'How to check','acceptance.tray.section.methodEmpty': 'No method described yet.','acceptance.tray.trackCount': '· {{count}} tracked',diff --git a/src/features/ChatInput/ActionBar/GoalModeChip.tsx b/src/features/ChatInput/ActionBar/GoalModeChip.tsxdeleted file mode 100644index 37ec8ad1fec..00000000000--- a/src/features/ChatInput/ActionBar/GoalModeChip.tsx+++ /dev/null@@ -1,58 +0,0 @@-'use client';--import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';-import { createStaticStyles, cssVar } from 'antd-style';-import { TargetIcon, XIcon } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { useChatInputStore } from '../store';--const styles = createStaticStyles(({ css }) => ({- chip: css`- flex: none;-- height: 28px;- padding-inline: 8px 4px;- border-radius: 14px;-- background: ${cssVar.colorInfoBg};- `,- label: css`- font-size: 12px;- line-height: 1;- color: ${cssVar.colorInfoText};- white-space: nowrap;- `,-}));--/**- * Visible state for the hidden `/goal` send mode.- *- * This deliberately follows the heterogeneous input's armed-action chip- * contract: it is a separate action-bar item immediately after the control- * that armed it, and carries its own clear action.- */-const GoalModeChip = memo(() => {- const { t } = useTranslation('verify');- const [goalMode, setGoalMode] = useChatInputStore((s) => [s.goalMode, s.setGoalMode]);-- if (!goalMode) return null;-- return (- <Flexbox horizontal align={'center'} className={styles.chip} gap={4}>- <Icon icon={TargetIcon} size={12} style={{ color: cssVar.colorInfoText }} />- <Text className={styles.label}>{t('acceptance.tray.menuSetGoal')}</Text>- <ActionIcon- icon={XIcon}- size={'small'}- title={t('acceptance.tray.goalDisarm')}- onClick={() => setGoalMode(false)}- />- </Flexbox>- );-});--GoalModeChip.displayName = 'GoalModeChip';--export default GoalModeChip;diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsxindex 99a88ad83da..4817948e601 100644--- a/src/features/ChatInput/ActionBar/Plus/index.tsx+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx@@ -23,7 +23,7 @@ import {TypeIcon,} from 'lucide-react';import type { ReactNode } from 'react';-import { Fragment, memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { openAttachKnowledgeModal } from '@/features/LibraryModal';@@ -48,11 +48,10 @@ import { useAgentId } from '../../hooks/useAgentId';import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';import { useEffectiveModel } from '../../hooks/useEffectiveModel';import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';-import { enterGoalMode } from '../../InputEditor/goalMode';+import { insertGoalTag } from '../../InputEditor/ActionTag/goalTag';import { useChatInputStore } from '../../store';import { type ActionDropdownMenuItems } from '../components/ActionDropdown';import { ChatInputAction } from '../components/ChatInputAction';-import GoalModeChip from '../GoalModeChip';import { useControls as useKnowledgeControls } from '../Knowledge/useControls';import { useMemoryEnabled } from '../Memory/useMemoryEnabled';import { useControls as useToolsControls } from '../Tools/useControls';@@ -289,7 +288,6 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuIconst { t } = useTranslation('chat');const { t: tEditor } = useTranslation('editor');const { t: tSetting } = useTranslation('setting');- const { t: tVerify } = useTranslation('verify');const isDark = useIsDark();const agentId = useAgentId();const { canConfigureResource } = useChatInputResourceAccess();@@ -328,7 +326,6 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuIconst isMemoryEnabled = useMemoryEnabled(agentId);const [showTypoBar, setShowTypoBar] = useChatInputStore((s) => [s.showTypoBar, s.setShowTypoBar]);const editor = useChatInputStore((s) => s.editor);- const setGoalMode = useChatInputStore((s) => s.setGoalMode);const { canUploadImage, canUploadVideo, canUploadAudio } = useMediaUploadAbility(model,provider,@@ -707,17 +704,19 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI]: uploadItems;- // Goal creation has one canonical entry: put the composer in /goal mode.- // The agent then plans and calls lobe-goal.createGoal, regardless of whether- // this conversation already has a topic.+ // Goal creation has one canonical entry: drop the goal chip at the head of+ // the composer. The agent then plans and calls lobe-goal.createGoal,+ // regardless of whether this conversation already has a topic.const acceptanceItems: ActionDropdownMenuItems = enableTopicAcceptance? [{icon: TargetIcon,key: 'set-topic-goal',- label: tVerify('acceptance.tray.menuSetGoal'),+ // Same string as the chip it inserts: one label for the affordance,+ // so the menu row and the chip can never drift apart.+ label: tEditor('slash.goal'),onClick: () => {- enterGoalMode(editor, setGoalMode);+ insertGoalTag(editor, tEditor('slash.goal'));},},]@@ -740,7 +739,6 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuIcanConfigureResource,effortItem,enableTopicAcceptance,- tVerify,canUploadImage,canUploadVideo,canUploadAudio,@@ -759,7 +757,6 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuIisParamsPanelActive,knowledgeEnabledCount,setShowTypoBar,- setGoalMode,showProviderSearch,showTypoBar,skillActivateMode,@@ -789,20 +786,17 @@ const PlusAction = memo(() => {const { t } = useTranslation('chat');return (- <Fragment>- <ChatInputAction- icon={PlusIcon}- size={{ blockSize: 32, borderRadius: 16, size: 18 }}- title={t('plus.tooltip')}- tooltipProps={{ placement: 'top' }}- dropdown={{- menu: { useItems: usePlusMenuItems },- minWidth: 220,- placement: 'topLeft',- }}- />- <GoalModeChip />- </Fragment>+ <ChatInputAction+ icon={PlusIcon}+ size={{ blockSize: 32, borderRadius: 16, size: 18 }}+ title={t('plus.tooltip')}+ tooltipProps={{ placement: 'top' }}+ dropdown={{+ menu: { useItems: usePlusMenuItems },+ minWidth: 220,+ placement: 'topLeft',+ }}+ />);});diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsxindex 2c516120033..f3d62e5d7f4 100644--- a/src/features/ChatInput/Desktop/index.tsx+++ b/src/features/ChatInput/Desktop/index.tsx@@ -154,7 +154,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(// context-window token tag; without one, SendArea keeps it beside Send.const hasControlBar = Boolean(controlBarSlot) || showControlBar;- const [setExpand, setGoalMode] = useChatInputStore((s) => [s.setExpand, s.setGoalMode]);+ const setExpand = useChatInputStore((s) => s.setExpand);const skillDrop = useSkillDrop();const topicDrop = useTopicDrop();const workspaceFileDrop = useWorkspaceFileDrop();@@ -175,8 +175,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(useEffect(() => {if (editor) editor.focus();setExpand(false);- setGoalMode(false);- }, [chatKey, editor, setExpand, setGoalMode]);+ }, [chatKey, editor, setExpand]);const shouldShowContextContainer =leftActions.flat().includes('fileUpload') || hasContextSelections || hasFiles;diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsx b/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsxindex 59fa4c9a1fe..c9039927d2e 100644--- a/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsx+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsx@@ -1,13 +1,14 @@import { Flexbox, Icon, Tooltip } from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';import { cx } from 'antd-style';-import { TerminalIcon, WrenchIcon } from 'lucide-react';+import { TargetIcon, TerminalIcon, WrenchIcon } from 'lucide-react';import type { FC, MouseEvent } from 'react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { styles } from './style';-import type { ActionTagCategory } from './types';+import type { ActionTagCategory, ActionTagType } from './types';+import { GOAL_COMMAND_TYPE } from './types';export interface ActionMentionProps {category: ActionTagCategory;@@ -25,6 +26,11 @@ export interface ActionMentionProps {description?: string;label: string;onClick?: () => void;+ /**+ * The tag's own type, used only to pick a more specific icon than the+ * category's default (a goal is not a terminal command).+ */+ type?: ActionTagType;}const CATEGORY_ICON: Record<ActionTagCategory, FC<any>> = {@@ -35,6 +41,11 @@ const CATEGORY_ICON: Record<ActionTagCategory, FC<any>> = {tool: WrenchIcon,};+// Per-type icon overrides, applied before the category default.+const TYPE_ICON: Record<string, FC<any>> = {+ [GOAL_COMMAND_TYPE]: TargetIcon,+};+const CATEGORY_I18N_KEY: Record<ActionTagCategory, string> = {agentSkill: 'actionTag.category.agentSkill',command: 'actionTag.category.command',@@ -63,12 +74,12 @@ const CATEGORY_STYLE_KEY: Record<};export const ActionMention = memo<ActionMentionProps>(- ({ category, label, description, clickable, onClick }) => {+ ({ category, label, description, clickable, onClick, type }) => {const { t } = useTranslation('editor');const categoryLabel = t(CATEGORY_I18N_KEY[category] as any);const categoryDescription = t(CATEGORY_TOOLTIP_I18N_KEY[category] as any);- const IconComponent = CATEGORY_ICON[category];+ const IconComponent = (type && TYPE_ICON[type]) || CATEGORY_ICON[category];const styleKey = CATEGORY_STYLE_KEY[category];const isClickable = clickable ?? !!onClick;diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsx b/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsxindex 99e4873a10a..f75da51d282 100644--- a/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsx+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsx@@ -48,6 +48,7 @@ const ActionTag = memo<ActionTagProps>(({ node, editor, label }) => {clickable={!!open}description={skill?.description}label={label}+ type={node.actionType}/></span>);diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTagNode.ts b/src/features/ChatInput/InputEditor/ActionTag/ActionTagNode.tsindex 4251fe9d277..efb8b7685b8 100644--- a/src/features/ChatInput/InputEditor/ActionTag/ActionTagNode.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTagNode.ts@@ -130,6 +130,7 @@ export class ActionTagNode extends DecoratorNode<any> implements HeadlessRenderacategory: this.__actionCategory as ActionTagCategory,key,label: this.__actionLabel,+ type: this.__actionType,});}}diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.test.ts b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.test.tsindex f85bafb45d0..5f35d430cdb 100644--- a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.test.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.test.ts@@ -1,3 +1,4 @@+import { isGoalPrompt } from '@lobechat/builtin-tool-goal';import { AGENT_SKILLS_IDENTIFIER_PREFIX } from '@lobechat/const';import { describe, expect, it } from 'vitest';@@ -5,6 +6,7 @@ import {INLINE_ACTION_TAG_REGEX,isInCodeContext,resolveActionTagFromMatch,+ writeActionTagMarkdown,} from './ActionTagPlugin';// Minimal Lexical-node stand-in for isInCodeContext, which only reads@@ -94,6 +96,45 @@ describe('resolveActionTagFromMatch', () => {});});+describe('writeActionTagMarkdown', () => {+ it('serializes the goal chip back to the `/goal` prefix the runtime detects', () => {+ const markdown = writeActionTagMarkdown({+ actionCategory: 'command',+ actionLabel: '设定目标',+ actionType: 'goal',+ });++ // The chip is structured state; `/goal` is the wire format both the client+ // tool gate and the server system role key off.+ expect(markdown).toBe('/goal ');+ expect(isGoalPrompt(`${markdown}ship the homepage`)).toBe(true);+ });++ it('keeps the other categories on the XML wire format', () => {+ expect(+ writeActionTagMarkdown({+ actionCategory: 'command',+ actionLabel: 'New Topic',+ actionType: 'newTopic',+ }),+ ).toBe('<action type="newTopic" category="command" label="New Topic" />');+ expect(+ writeActionTagMarkdown({+ actionCategory: 'skill',+ actionLabel: 'UX',+ actionType: 'ux-audit',+ }),+ ).toBe('<skill name="ux-audit" label="UX" />');+ expect(+ writeActionTagMarkdown({+ actionCategory: 'tool',+ actionLabel: 'Search',+ actionType: 'search',+ }),+ ).toBe('<tool name="search" label="Search" />');+ });+});+describe('isInCodeContext', () => {it('is false for a plain text node in a paragraph', () => {expect(isInCodeContext(makeNode({ parent: makeNode({ type: 'paragraph' }) }))).toBe(false);diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.tsindex e761544a5fc..6bc3ca268e1 100644--- a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts@@ -14,7 +14,7 @@ import {} from './ActionTagNode';import { registerActionTagCommand } from './command';import { registerActionTagSelectionObserver } from './selectionObserver';-import type { ActionTagCategory, ActionTagType } from './types';+import { type ActionTagCategory, type ActionTagType, GOAL_COMMAND_TYPE } from './types';type IEditorKernel = ReturnType<typeof getKernelFromEditor>;@@ -99,6 +99,46 @@ export const resolveActionTagFromMatch = (return reader(parseAttributeSource(attributeString));};+/**+ * ActionTagNode → markdown, the format the message is actually sent in.+ *+ * Skills → <skill name="..." label="..." />+ * AgentSkill → <skill name="agent-skills:<filename>" label="..." />+ * Wire format collapses to <skill>; the `agent-skills:` prefix in+ * the identifier is what the runtime keys off to route the+ * activation through agentDocumentsService.+ * ProjectSkill → <skill name="<skill-name>" label="..." />+ * Same wire format as a registered skill — the project skill is+ * in the runtime's `<available_skills>` registry (added on the+ * server when a device is active), so the model resolves it+ * through `activateSkill` like any other. Keeps the rendered+ * prompt uniform across skill sources, which the LiteXML+ * round-trip preserves via the category-aware <projectSkill>+ * save format.+ * Tools → <tool name="..." label="..." />+ * Goal → `/goal ` — the one command the model is meant to read: both the+ * client tool gate and the server system role detect a goal turn+ * from the message's literal `/goal` prefix (`isGoalPrompt`), so+ * the chip serializes back to the prefix it stands for. The+ * trailing space keeps `/goal ship it` from collapsing into+ * `/goalship it` when text follows the chip directly.+ * Commands → <action type="..." category="command" label="..." />+ */+export const writeActionTagMarkdown = (node: {+ actionCategory: ActionTagCategory;+ actionLabel: string;+ actionType: ActionTagType;+}): string => {+ const cat = node.actionCategory;++ if (cat === 'command' && node.actionType === GOAL_COMMAND_TYPE) return `/${GOAL_COMMAND_TYPE} `;+ if (cat === 'skill' || cat === 'agentSkill' || cat === 'projectSkill')+ return `<skill name="${node.actionType}" label="${node.actionLabel}" />`;+ if (cat === 'tool') return `<tool name="${node.actionType}" label="${node.actionLabel}" />`;++ return `<action type="${node.actionType}" category="${cat}" label="${node.actionLabel}" />`;+};+// @lobehub/editor code node types: 'code' (CodeMirror block), 'codeInline'// (inline-code element wrapping text), 'code-highlight' (highlighted token// text nodes inside a fenced block).@@ -200,34 +240,9 @@ export class ActionTagPlugin {private registerMarkdown(): void {const mdService = this.kernel.requireService(IMarkdownShortCutService);- // Writer: ActionTagNode → markdown- // Skills → <skill name="..." label="..." />- // AgentSkill → <skill name="agent-skills:<filename>" label="..." />- // Wire format collapses to <skill>; the `agent-skills:`- // prefix in the identifier is what the runtime keys off to- // route the activation through agentDocumentsService.- // ProjectSkill → <skill name="<skill-name>" label="..." />- // Same wire format as a registered skill — the project- // skill is in the runtime's `<available_skills>` registry- // (added on the server when a device is active), so the- // model resolves it through `activateSkill` like any- // other. Keeps the rendered prompt uniform across skill- // sources, which the LiteXML round-trip preserves via the- // category-aware `<projectSkill>` save format.- // Tools → <tool name="..." label="..." />- // Commands → <action type="..." category="command" label="..." />mdService?.registerMarkdownWriter(ActionTagNode.getType(), (ctx: any, node: any) => {if ($isActionTagNode(node)) {- const cat = node.actionCategory;- if (cat === 'skill' || cat === 'agentSkill' || cat === 'projectSkill') {- ctx.appendLine(`<skill name="${node.actionType}" label="${node.actionLabel}" />`);- } else if (cat === 'tool') {- ctx.appendLine(`<tool name="${node.actionType}" label="${node.actionLabel}" />`);- } else {- ctx.appendLine(- `<action type="${node.actionType}" category="${cat}" label="${node.actionLabel}" />`,- );- }+ ctx.appendLine(writeActionTagMarkdown(node));}});}diff --git a/src/features/ChatInput/InputEditor/ActionTag/goalTag.test.ts b/src/features/ChatInput/InputEditor/ActionTag/goalTag.test.tsnew file mode 100644index 00000000000..1a73d2bad3a--- /dev/null+++ b/src/features/ChatInput/InputEditor/ActionTag/goalTag.test.ts@@ -0,0 +1,196 @@+import type { IEditor } from '@lobehub/editor';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ createEditor,+} from 'lexical';+import { describe, expect, it, vi } from 'vitest';++import { $isActionTagNode, ActionTagNode } from './ActionTagNode';+import { insertGoalTag } from './goalTag';+import { GOAL_COMMAND_TYPE } from './types';++const LABEL = 'Set goal';++const createTestEditor = () => {+ const lexicalEditor = createEditor({+ nodes: [ActionTagNode],+ onError: (error) => {+ throw error;+ },+ });++ const editor = {+ focus: vi.fn(),+ getLexicalEditor: () => lexicalEditor,+ } as unknown as IEditor;++ return { editor, lexicalEditor };+};++const seedParagraph = (lexicalEditor: ReturnType<typeof createEditor>, text: string) => {+ lexicalEditor.update(+ () => {+ const paragraph = $createParagraphNode();+ if (text) paragraph.append($createTextNode(text));+ $getRoot().append(paragraph);+ },+ { discrete: true },+ );+};++/** The document's inline nodes, flattened to `[type, textContent]` pairs. */+const readInlineNodes = (lexicalEditor: ReturnType<typeof createEditor>) =>+ lexicalEditor.read(() =>+ $getRoot()+ .getFirstChild<any>()+ ?.getChildren()+ .map((node: any) => [+ $isActionTagNode(node) ? node.actionType : node.getType(),+ node.getTextContent(),+ ]),+ );++/** Type at the current caret, the way the user's next keystroke would. */+const typeAtCaret = (lexicalEditor: ReturnType<typeof createEditor>, text: string) => {+ lexicalEditor.update(+ () => {+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) throw new Error('no caret to type at');+ selection.insertText(text);+ },+ { discrete: true },+ );+};++describe('insertGoalTag', () => {+ it('leaves the caret behind the chip so the typed goal stays behind the marker', () => {+ const { editor, lexicalEditor } = createTestEditor();+ // An empty composer is what the slash path leaves once the plugin has removed+ // the `/goal` query text.+ seedParagraph(lexicalEditor, '');++ insertGoalTag(editor, LABEL);+ typeAtCaret(lexicalEditor, 'ship the homepage');++ // Regression: the caret used to stay at the block start, in front of the+ // chip, so the goal the user typed landed BEFORE the marker — serializing to+ // `ship the homepage/goal ` and silently destroying the `/goal` prefix that+ // makes it a goal turn at all.+ expect(readInlineNodes(lexicalEditor)).toEqual([+ [GOAL_COMMAND_TYPE, LABEL],+ ['text', 'ship the homepage'],+ ]);+ });++ it('keeps a caret that is already behind the chip where the user left it', () => {+ const { editor, lexicalEditor } = createTestEditor();+ seedParagraph(lexicalEditor, 'ship the homepage');+ // The `+` menu path: the user stopped typing at the end of their sentence.+ lexicalEditor.update(+ () => {+ ($getRoot().getFirstChild() as any).selectEnd();+ },+ { discrete: true },+ );++ insertGoalTag(editor, LABEL);+ typeAtCaret(lexicalEditor, ' now');++ expect(readInlineNodes(lexicalEditor)).toEqual([+ [GOAL_COMMAND_TYPE, LABEL],+ ['text', 'ship the homepage now'],+ ]);+ });++ it('leads the message with the goal chip instead of dropping it at the caret', () => {+ const { editor, lexicalEditor } = createTestEditor();+ seedParagraph(lexicalEditor, 'ship the homepage');++ insertGoalTag(editor, LABEL);++ // The chip serializes back to the `/goal ` prefix, and both the client tool+ // gate and the server system role only accept it at the head of the message.+ expect(readInlineNodes(lexicalEditor)).toEqual([+ [GOAL_COMMAND_TYPE, LABEL],+ ['text', 'ship the homepage'],+ ]);+ expect(editor.focus).toHaveBeenCalled();+ });++ it('works when called from inside an ongoing editor update', () => {+ const { editor, lexicalEditor } = createTestEditor();+ seedParagraph(lexicalEditor, '');++ // Regression: the slash menu runs `onSelect` inside its own+ // `lexicalEditor.update()`, and the previous implementation cleared the+ // document there — which threw ("the editor state is empty") and aborted the+ // whole update, so pressing Enter on `/goal` did nothing at all.+ lexicalEditor.update(+ () => {+ insertGoalTag(editor, LABEL);+ },+ { discrete: true },+ );++ expect(readInlineNodes(lexicalEditor)).toEqual([[GOAL_COMMAND_TYPE, LABEL]]);+ });++ it('keeps whatever the user already typed', () => {+ const { editor, lexicalEditor } = createTestEditor();+ seedParagraph(lexicalEditor, 'ship the homepage');++ insertGoalTag(editor, LABEL);++ expect(lexicalEditor.read(() => $getRoot().getTextContent())).toContain('ship the homepage');+ });++ it('inserts at most one chip per message', () => {+ const { editor, lexicalEditor } = createTestEditor();+ seedParagraph(lexicalEditor, 'ship the homepage');++ insertGoalTag(editor, LABEL);+ insertGoalTag(editor, LABEL);++ // A second chip would serialize a second `/goal ` into the prompt.+ expect(readInlineNodes(lexicalEditor)).toEqual([+ [GOAL_COMMAND_TYPE, LABEL],+ ['text', 'ship the homepage'],+ ]);+ });++ it('prepends a paragraph when the draft starts with a block-children container', () => {+ const { editor, lexicalEditor } = createTestEditor();+ // A list / table shape: an ElementNode whose children are blocks, not inline+ // content. Prepending the chip straight into it would break that container's+ // child contract and could move the chip off the head of the message.+ lexicalEditor.update(+ () => {+ const container = $createParagraphNode();+ const innerBlock = $createParagraphNode();+ innerBlock.append($createTextNode('ship the homepage'));+ container.append(innerBlock);+ $getRoot().append(container);+ },+ { discrete: true },+ );++ insertGoalTag(editor, LABEL);++ const blocks = lexicalEditor.read(() =>+ $getRoot()+ .getChildren()+ .map((block: any) => block.getChildren().map((child: any) => child.getType())),+ );+ // The chip leads the document in its own paragraph, ahead of the container.+ expect(blocks[0]).toEqual([ActionTagNode.getType()]);+ expect(blocks).toHaveLength(2);+ });++ it('does nothing without an editor', () => {+ expect(() => insertGoalTag(undefined, LABEL)).not.toThrow();+ });+});diff --git a/src/features/ChatInput/InputEditor/ActionTag/goalTag.ts b/src/features/ChatInput/InputEditor/ActionTag/goalTag.tsnew file mode 100644index 00000000000..9006cf308b1--- /dev/null+++ b/src/features/ChatInput/InputEditor/ActionTag/goalTag.ts@@ -0,0 +1,122 @@+import type { IEditor } from '@lobehub/editor';+import {+ $createParagraphNode,+ $createRangeSelection,+ $getRoot,+ $getSelection,+ $isDecoratorNode,+ $isElementNode,+ $isLineBreakNode,+ $isParagraphNode,+ $isRangeSelection,+ $isTextNode,+ type ElementNode,+ type LexicalNode,+} from 'lexical';++import { $createActionTagNode, $isActionTagNode } from './ActionTagNode';+import { GOAL_COMMAND_TYPE } from './types';++/**+ * The goal marker is stored as a real node in the editor document — not as a+ * composer-level boolean rewritten into the text at send time — so it survives+ * drafts, lands in the persisted `editorData`, and renders as a chip in the sent+ * bubble instead of disappearing into a raw `/goal` prefix nobody can see.+ */+const $hasGoalTag = (): boolean => {+ const stack: LexicalNode[] = $getRoot().getChildren();++ while (stack.length > 0) {+ const node = stack.pop()!;+ if ($isActionTagNode(node) && node.actionType === GOAL_COMMAND_TYPE) return true;+ if ($isElementNode(node)) stack.push(...node.getChildren());+ }++ return false;+};++/**+ * True when `block` holds inline children, so the inline chip can be prepended+ * straight into it.+ *+ * `$isElementNode` alone is not that test: a list, table, or quote-of-blocks is an+ * ElementNode too, and its children are rows / items, not inline content.+ * Prepending the chip there would break that container's child contract, and the+ * chip could end up serialized somewhere other than the head of the message —+ * which is the one place `isGoalPrompt` accepts it.+ */+const $acceptsInlineChildren = (block: ElementNode): boolean => {+ const first = block.getFirstChild();+ // An empty block offers nothing to infer from; only a paragraph is certain.+ if (!first) return $isParagraphNode(block);+ if ($isTextNode(first) || $isLineBreakNode(first)) return true;++ return ($isElementNode(first) || $isDecoratorNode(first)) && first.isInline();+};++/**+ * True when the caret would sit in front of the chip — including the case where+ * there is no usable selection at all, which is what an empty composer leaves+ * behind after the slash plugin removes the `/goal` query text.+ */+const $caretIsInFrontOf = (tag: LexicalNode): boolean => {+ const selection = $getSelection();+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) return true;++ const parent = tag.getParent();+ if (!$isElementNode(parent)) return true;++ // The point immediately behind the chip, to compare the live caret against.+ const boundary = $createRangeSelection();+ boundary.anchor.set(parent.getKey(), tag.getIndexWithinParent() + 1, 'element');++ return selection.anchor.isBefore(boundary.anchor);+};++/**+ * Put the goal chip at the very start of the document, with the caret behind it.+ *+ * Neither half is cosmetic. The markdown writer serializes the chip back to+ * `/goal `, and both the client tool gate and the server system role only accept+ * it as the message's *prefix* (`isGoalPrompt`). Inserting at the caret would+ * bury the chip mid-message — the slash menu can fire from any line start, and+ * the `+` menu can fire after the user has already typed. And leaving the caret+ * where it was is just as damaging on the slash path: an empty composer parks it+ * at the block start, so the goal the user then types lands *in front of* the+ * chip and silently destroys the very prefix the chip stands for.+ *+ * A caret that is already behind the chip is left alone — on the `+` menu path it+ * is wherever the user stopped typing, and yanking it to the head of their own+ * sentence would be its own annoyance.+ */+export const insertGoalTag = (editor: IEditor | undefined, label: string) => {+ const lexicalEditor = editor?.getLexicalEditor();+ if (!editor || !lexicalEditor) return;++ lexicalEditor.update(() => {+ // One goal per message — a second chip would serialize a second `/goal `.+ if ($hasGoalTag()) return;++ const tag = $createActionTagNode(GOAL_COMMAND_TYPE, 'command', label);+ const root = $getRoot();+ const firstBlock = root.getFirstChild();++ // The chip is inline, so it only goes inside a block that actually takes+ // inline children; a list, table, or code block gets a paragraph in front of+ // it instead, which still leaves the chip leading the message.+ if ($isElementNode(firstBlock) && $acceptsInlineChildren(firstBlock)) {+ const firstInline = firstBlock.getFirstChild();+ if (firstInline) firstInline.insertBefore(tag);+ else firstBlock.append(tag);+ } else {+ const paragraph = $createParagraphNode();+ paragraph.append(tag);+ if (firstBlock) firstBlock.insertBefore(paragraph);+ else root.append(paragraph);+ }++ if ($caretIsInFrontOf(tag)) tag.selectNext(0, 0);+ });++ editor.focus();+};diff --git a/src/features/ChatInput/InputEditor/ActionTag/types.ts b/src/features/ChatInput/InputEditor/ActionTag/types.tsindex 13b7bd98b54..00ec671d6ae 100644--- a/src/features/ChatInput/InputEditor/ActionTag/types.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/types.ts@@ -13,8 +13,24 @@*/export type ActionTagCategory = 'command' | 'skill' | 'tool' | 'projectSkill' | 'agentSkill';-// Built-in commands: client-side intercepted, never sent to AI-export type CommandType = 'compact' | 'newTopic';+// Built-in commands: client-side intercepted, never sent to AI.+// `goal` is the exception — it has no client handler; it serializes back to the+// literal `/goal ` prefix the runtime keys off (see `isGoalPrompt`), and exists+// as a tag so the marker is structured in `editorData` instead of being a+// hidden send-time string.+export type CommandType = 'compact' | 'newTopic' | 'goal';++/**+ * The action-tag type carrying the "this message opens a goal" marker.+ *+ * It lives here, in the leaf module of this folder, rather than next to+ * `insertGoalTag`: the chip renderer, the node, the markdown writer and the+ * slash menu all need it, and importing it from `goalTag` closed the cycle+ * `ActionMention → goalTag → ActionTagNode → ActionMention`, which crashed the+ * SPA at boot with a TDZ `Cannot access 'GOAL_COMMAND_TYPE' before+ * initialization`.+ */+export const GOAL_COMMAND_TYPE = 'goal';// Skills use dynamic identifiers from agent config (plugin/tool identifiers)export type SkillType = string & {};diff --git a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.tsindex 3cc40c148eb..27e24adba7b 100644--- a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts@@ -22,9 +22,9 @@ import type { AgentDocumentSkillItem } from '@/store/tool/slices/agentDocumentSkimport { useAgentId } from '../../hooks/useAgentId';import { useChatInputStore } from '../../store';-import { enterGoalMode } from '../goalMode';import { INSERT_ACTION_TAG_COMMAND, type InsertActionTagPayload } from './command';-import { type ActionTagData, BUILTIN_COMMANDS } from './types';+import { insertGoalTag } from './goalTag';+import { type ActionTagData, BUILTIN_COMMANDS, GOAL_COMMAND_TYPE } from './types';import { useInstalledSkillsAndTools } from './useInstalledSkillsAndTools';type SlashItem = NonNullable<SlashOptions['items'] extends (infer U)[] ? U : never>;@@ -45,7 +45,6 @@ const COMMAND_ICONS: Record<string, any> = {export const useSlashActionItems = (): SlashOptions['items'] => {const { t } = useTranslation('editor');const editorInstance = useChatInputStore((s) => s.editor);- const setGoalMode = useChatInputStore((s) => s.setGoalMode);const activeTopicId = useChatStore((s) => s.activeTopicId);// Resolve the active working directory so we can surface filesystem skills.@@ -236,14 +235,16 @@ export const useSlashActionItems = (): SlashOptions['items'] => {if (isAtLineStart) {allItems.push({icon: TargetIcon,- key: 'goal',+ key: GOAL_COMMAND_TYPE,label: t('slash.goal' as any),metadata: {category: 'command',description: t('slash.goal.desc' as any, { defaultValue: '' }),- type: 'goal',+ type: GOAL_COMMAND_TYPE,},- onSelect: (editor: IEditor) => enterGoalMode(editor, setGoalMode, true),+ // Unlike the other commands this one is not inserted at the caret —+ // the chip has to lead the message. See `insertGoalTag`.+ onSelect: (editor: IEditor) => insertGoalTag(editor, t('slash.goal' as any) as string),} as SlashItem);for (const action of BUILTIN_COMMANDS) {if (action.type === 'newTopic' && !activeTopicId) continue;@@ -282,14 +283,6 @@ export const useSlashActionItems = (): SlashOptions['items'] => {return allItems;},- [- t,- editorInstance,- activeTopicId,- projectSkills,- installedSkills,- agentDocumentSkills,- setGoalMode,- ],+ [t, editorInstance, activeTopicId, projectSkills, installedSkills, agentDocumentSkills],);};diff --git a/src/features/ChatInput/InputEditor/goalMode.test.ts b/src/features/ChatInput/InputEditor/goalMode.test.tsdeleted file mode 100644index 733c07437c6..00000000000--- a/src/features/ChatInput/InputEditor/goalMode.test.ts+++ /dev/null@@ -1,36 +0,0 @@-import type { IEditor } from '@lobehub/editor';-import { describe, expect, it, vi } from 'vitest';--import { enterGoalMode } from './goalMode';--const createEditor = (content: string) =>- ({- focus: vi.fn(),- getDocument: vi.fn().mockReturnValue(content),- setDocument: vi.fn(),- }) as unknown as IEditor;--describe('enterGoalMode', () => {- it('enables goal mode without changing an existing draft', () => {- const editor = createEditor('ship the homepage');- const setGoalMode = vi.fn();-- enterGoalMode(editor, setGoalMode);-- expect(editor.setDocument).not.toHaveBeenCalled();- expect(setGoalMode).toHaveBeenCalledWith(true);- expect(editor.focus).toHaveBeenCalled();- });-- it('replaces the partial slash query selected from the command menu', () => {- const editor = createEditor('/go');- const setGoalMode = vi.fn();-- enterGoalMode(editor, setGoalMode, true);-- expect(editor.setDocument).toHaveBeenCalledWith('markdown', '', {- keepHistory: true,- });- expect(setGoalMode).toHaveBeenCalledWith(true);- });-});diff --git a/src/features/ChatInput/InputEditor/goalMode.ts b/src/features/ChatInput/InputEditor/goalMode.tsdeleted file mode 100644index af7aa45e02d..00000000000--- a/src/features/ChatInput/InputEditor/goalMode.ts+++ /dev/null@@ -1,15 +0,0 @@-import type { IEditor } from '@lobehub/editor';--export const enterGoalMode = (- editor: IEditor | undefined,- setGoalMode: (enabled: boolean) => void,- replaceSlashQuery = false,-) => {- if (!editor) return;-- if (replaceSlashQuery) {- editor.setDocument('markdown', '', { keepHistory: true });- }- setGoalMode(true);- editor.focus();-};diff --git a/src/features/ChatInput/store/action.test.ts b/src/features/ChatInput/store/action.test.tsindex 43740c822e7..48913becc96 100644--- a/src/features/ChatInput/store/action.test.ts+++ b/src/features/ChatInput/store/action.test.ts@@ -116,7 +116,9 @@ describe('ChatInput store actions', () => {expect(getInputHistory()).toEqual([]);});- it('adds the hidden /goal prefix only when sending in goal mode', () => {+ it('sends exactly what the document serializes to', () => {+ // The composer no longer rewrites the text on the way out: markers like the+ // goal chip are nodes in the document, so what is sent is what is shown.const onSend = vi.fn(({ clearContent, getMarkdownContent }) => {expect(getMarkdownContent()).toBe('/goal Ship the homepage');clearContent();@@ -125,7 +127,7 @@ describe('ChatInput store actions', () => {cleanDocument: vi.fn(),focus: vi.fn(),getDocument: vi.fn((type: string) =>- type === 'markdown' ? 'Ship the homepage' : { root: {} },+ type === 'markdown' ? '/goal Ship the homepage' : { root: {} },),};const store = createStore({@@ -133,12 +135,10 @@ describe('ChatInput store actions', () => {onSend,});- store.getState().setGoalMode(true);store.getState().handleSendButton();expect(onSend).toHaveBeenCalledOnce();expect(editor.cleanDocument).toHaveBeenCalledOnce();- expect(store.getState().goalMode).toBe(false);});it('does not record history when the input history feature is disabled', () => {diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.tsindex 53a449876ab..1de75bdb6c9 100644--- a/src/features/ChatInput/store/action.ts+++ b/src/features/ChatInput/store/action.ts@@ -21,7 +21,6 @@ export interface Action {setActiveAudioInputMode: (mode?: State['activeAudioInputMode']) => void;setDocument: (type: string, content: any, options?: Record<string, unknown>) => void;setExpand: (expend: boolean) => void;- setGoalMode: (enabled: boolean) => void;setJSONState: (content: any) => void;setShowTypoBar: (show: boolean) => void;updateMarkdownContent: () => void;@@ -97,14 +96,10 @@ export const store: CreateStore = (publicState) => (set, get) => ({clearContent: () => {editor?.cleanDocument();if (sentDraftKey) removeDraft(sentDraftKey);- set({ goalMode: false });},editor: editor!,getEditorData: get().getJSONState,- getMarkdownContent: () => {- const content = get().getMarkdownContent();- return get().goalMode ? `/goal ${content}`.trimEnd() : content;- },+ getMarkdownContent: get().getMarkdownContent,});if (historySnapshot) {@@ -145,10 +140,6 @@ export const store: CreateStore = (publicState) => (set, get) => ({set({ _savedEditorState, expand });},- setGoalMode: (goalMode) => {- set({ goalMode });- },-setJSONState: (content) => {get().editor?.setDocument('json', content);},diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.tsindex 1cc95afbf04..360a05c90be 100644--- a/src/features/ChatInput/store/initialState.ts+++ b/src/features/ChatInput/store/initialState.ts@@ -94,7 +94,6 @@ export interface PublicState {export interface State extends PublicState {_savedEditorState?: Record<string, any>;editor?: IEditor;- goalMode: boolean;inputCompletionError?: InputCompletionError;inputCompletionErrorDismissed: boolean;isContentEmpty: boolean;@@ -107,7 +106,6 @@ export const initialState: State = {allowExpand: true,expand: false,feature: DEFAULT_CHAT_INPUT_FEATURE,- goalMode: false,inputCompletionErrorDismissed: false,isContentEmpty: false,leftActions: [],diff --git a/src/features/Conversation/ChatInput/VerifyTray/useTopicChecklist.ts b/src/features/Conversation/ChatInput/VerifyTray/useTopicChecklist.tsindex 3339556f8a9..b6e5da057a6 100644--- a/src/features/Conversation/ChatInput/VerifyTray/useTopicChecklist.ts+++ b/src/features/Conversation/ChatInput/VerifyTray/useTopicChecklist.ts@@ -92,7 +92,7 @@ const persistGoal = (topicId: string, goal: string, checks: TrayCheck[]) =>/*** Set the topic's Goal without a mounted tray (used by the composer "+" →- * "Set goal" entry). Reads the current state, writes the goal, and revalidates+ * "Goal" entry). Reads the current state, writes the goal, and revalidates* the shared SWR key so the tray reflects it.*/export const setTopicGoal = async (topicId: string, goal: string) => {diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex 9c428352be6..616fee10182 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -279,7 +279,7 @@ const ChatInput = memo<ChatInputProps>();// Pre-topic "armed goal" state (topic Goal lab). `armedAt` is only ever set- // by the lab-gated "+" → Set goal entry, so its presence already implies the+ // by the lab-gated "+" → Goal entry, so its presence already implies the// lab is on. While armed the goal chip rides the action bar and the composer// placeholder prompts for the goal (the next message becomes it).const goalArmedAt = useGoalArmStore((s) => (agentId ? s.armedAt[agentId] : undefined));diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsxindex 07b83d9a46a..0c2967e4600 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsx@@ -16,7 +16,7 @@ import { useTranslation } from 'react-i18next';import { type ActionDropdownMenuItems } from '@/features/ChatInput/ActionBar/components/ActionDropdown';import { ChatInputAction } from '@/features/ChatInput/ActionBar/components/ChatInputAction';-import { enterGoalMode } from '@/features/ChatInput/InputEditor/goalMode';+import { insertGoalTag } from '@/features/ChatInput/InputEditor/ActionTag/goalTag';import { useChatInputStore } from '@/features/ChatInput/store';import { useConversationStore } from '@/features/Conversation';import { useUserStore } from '@/store/user';@@ -40,12 +40,10 @@ import { OFFSETS_IN_HOURS, resolveScheduleTime } from './scheduleTime';const HeteroPlus = memo(() => {const { t } = useTranslation('chat');const { t: tEditor } = useTranslation('editor');- const { t: tVerify } = useTranslation('verify');const [open, setOpen] = useState(false);- const [editor, setGoalMode, showTypoBar, setShowTypoBar] = useChatInputStore((s) => [+ const [editor, showTypoBar, setShowTypoBar] = useChatInputStore((s) => [s.editor,- s.setGoalMode,s.showTypoBar,s.setShowTypoBar,]);@@ -103,17 +101,18 @@ const HeteroPlus = memo(() => {onCheckedChange: (checked: boolean) => setShowTypoBar(checked),type: 'switch',},- // Goal creation shares the same hidden /goal mode as the standard input.+ // Goal creation shares the standard input's goal chip....(enableTopicAcceptance? ([{ type: 'divider' },{icon: TargetIcon,key: 'set-topic-goal',- label: tVerify('acceptance.tray.menuSetGoal'),+ // Same string as the chip it inserts — see the agent composer's Plus.+ label: tEditor('slash.goal'),onClick: () => {setOpen(false);- enterGoalMode(editor, setGoalMode);+ insertGoalTag(editor, tEditor('slash.goal'));},},] as ActionDropdownMenuItems)@@ -122,14 +121,12 @@ const HeteroPlus = memo(() => {}, [t,tEditor,- tVerify,showTypoBar,setShowTypoBar,armSchedule,scheduledSendAt,enableTopicAcceptance,editor,- setGoalMode,]);return (diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsxindex fd2140b9a5d..8b77e304604 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx@@ -10,7 +10,6 @@ import { useTranslation } from 'react-i18next';import { useHeteroAgentCloudConfig } from '@/business/client/hooks/useHeteroAgentCloudConfig';import { isDesktop } from '@/const/version';import { type ActionKeys } from '@/features/ChatInput';-import GoalModeChip from '@/features/ChatInput/ActionBar/GoalModeChip';import HeteroModel from '@/features/ChatInput/ControlBar/HeteroModel';import { ChatInput } from '@/features/Conversation';import { contextSelectors, useConversationStore } from '@/features/Conversation/store';@@ -128,7 +127,6 @@ const HeterogeneousChatInput = memo(() => {const extraActionItems = useMemo<ChatInputActionsProps['items']>(() => [{ alwaysDisplay: true, children: <HeteroPlus />, key: 'heteroPlus' },- { alwaysDisplay: true, children: <GoalModeChip />, key: 'goalModeChip' },{ alwaysDisplay: true, children: <ScheduledSendChip />, key: 'scheduledSendChip' },],[],diff --git a/src/store/chat/slices/agentRun/actions/entries/commandBus/types.ts b/src/store/chat/slices/agentRun/actions/entries/commandBus/types.tsindex 419b9c4d3cc..7388d30dcbc 100644--- a/src/store/chat/slices/agentRun/actions/entries/commandBus/types.ts+++ b/src/store/chat/slices/agentRun/actions/entries/commandBus/types.ts@@ -20,4 +20,9 @@ export interface CommandHandlerContext {export type CommandHandler = (ctx: CommandHandlerContext) => CommandSendOverrides | void;-export type CommandRegistry = Record<CommandType, CommandHandler>;+/**+ * Partial on purpose: not every command tag is intercepted here. `goal` has no+ * client handler — it serializes back into the prompt as `/goal ` and is read by+ * the runtime (see `writeActionTagMarkdown` / `isGoalPrompt`).+ */+export type CommandRegistry = Partial<Record<CommandType, CommandHandler>>;