Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(agent-document): show not-found for the whole module when a doc is absent (#16679)

Arvin Xua3cbfbf5f69e
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.md
index cb649d931da..b95dd962ba5 100644
--- a/.agents/skills/agent-testing/SKILL.md
+++ b/.agents/skills/agent-testing/SKILL.md
@@ -19,7 +19,7 @@ also run as full cloud automation. Every test session follows the same
contract:
```
-Step -2: Read the two living logs β†’ Step -1: Plan approval β†’ Step 0: Env + Auth β†’ Step 1: Pick surface β†’ Step 2: Run β†’ Step 3: Structured report β†’ Step 4: Publish to LobeHub
+Step -2: Read the two living logs β†’ Step -1: Plan approval β†’ Step 0: Env + Auth β†’ Step 1: Pick surface β†’ Step 2: Run β†’ Step 3: Structured report β†’ Step 4: Publish to LobeHub β†’ Step 5: Teardown
```
## Step -2 β€” Read the two living logs (mandatory, before every run)
@@ -534,6 +534,38 @@ Notes:
report. If the evidence must appear, publish against an env with real storage
(e.g. production) or attach it inline with `verify evidence upload --content`.
+## Step 5 β€” Teardown (default: stop what you started)
+
+A test run leaves processes and code edits behind. Clean them up by default once
+the report is published β€” a dev server left listening or an injection left in a
+service file silently corrupts the next run (and the next agent's mental model).
+
+- **Stop the dev server you started.** If you launched it via `init-dev-env.sh dev`
+ (the no-`.env` path), tear it down with:
+
+ ```bash
+ ./.agents/skills/agent-testing/scripts/init-dev-env.sh clean # stop dev server; keep DB/Redis
+ ```
+
+ `clean` stops the Next + Vite processes on the resolved `SERVER_PORT` / `SPA_PORT`
+ and the `bun run dev` supervisor, and **leaves the managed Postgres/Redis
+ containers running** (they are idempotently reused across runs β€” `setup-db` is a
+ no-op when they're up). Use `clean-db` only when you deliberately want the
+ containers gone, or `stop-dev` for just the server with no note. If the user
+ started their own `.env` dev server, leave it β€” you didn't start it.
+
+- **Revert every code injection.** Any HMR fault-injection (A4/A6/A8 in
+ `probe-mock-patterns.md`) must be undone and verified: `git checkout -- <files>`
+ then `grep -rn AGENT-TEST src/` returns nothing. Never leave an injection or a
+ debug global (`__DBG`, `__loadMoreCalls`) behind.
+
+- **Keep the report + evidence.** `.records/reports/**` is the deliverable β€” do
+ NOT delete it in teardown; it's gitignored and the published verify run points at
+ it.
+
+Skip teardown only when the user explicitly wants the environment left up (e.g.
+"leave the dev server running, I'll keep poking at it").
+
## Directory map
```
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index d93761cf1ec..4be58bef894 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -77,6 +77,109 @@
After reverting, **re-navigate** (`agent-browser open .../task/<id>`) and re-fetch
element refs before continuing the recovery test.
+### A7. βœ… WORKS β€” render a message-attached error card (hetero guide, AsyncError) by in-memory store dispatch
+
+- To render an error state that lives on a **chat message** (e.g. the heterogeneous
+ `overloaded` / `interrupted` guide card), no network fault or real agent run is
+ needed β€” inject the error straight into the chat store, **in-memory, no DB write**:
+ ```js
+ // agent-browser --cdp <port> eval --stdin
+ var c = window.__LOBE_STORES.chat();
+ var id = 'tmp_probe';
+ // 1. create a temp assistant message (in the ACTIVE conversation)
+ c.internal_dispatchMessage({
+ id,
+ type: 'createMessage',
+ value: { role: 'assistant', content: 'partial work UNIQUE_MARKER', provider: 'claude-code' },
+ });
+ // 2. attach the error whose `body.code` drives the card
+ c.internal_dispatchMessage({
+ id,
+ type: 'updateMessage',
+ value: {
+ error: {
+ type: 'AgentRuntimeError',
+ message: 'API Error: Connection closed mid-response.',
+ body: {
+ agentType: 'claude-code',
+ code: 'interrupted',
+ message: 'API Error: Connection closed mid-response.',
+ },
+ },
+ },
+ });
+ ```
+ This renders the real component (real i18n) in the running app. `code: 'overloaded'`
+ β†’ OverloadedState; `code: 'interrupted'` β†’ InterruptedState; etc. Clean up with
+ `internal_dispatchMessage({ id, type: 'deleteMessage' })`.
+- **No persistence / no side effects**: `internal_dispatchMessage` is the optimistic
+ in-memory path (same as `optimisticCreateTmpMessage`). Nothing hits the DB, and a
+ reload clears it. Safe even against a **real** account's synced data β€” do it in an
+ isolated `electron-dev.sh start <id>` instance (copied login) to be extra safe.
+- **Suppress auto-actions on purpose**: the hetero auto-retry only arms when
+ `getRetryScopeId(messageId)` finds a `user` ancestor in `dbMessages`. A tmp message
+ is NOT in `dbMessages`, so scope resolves `undefined` β†’ the card renders in its
+ **manual** state (retry button, no countdown) and **does not auto-fire** (won't spawn
+ a real CLI). To exercise the auto-retry countdown live you'd need a real user→assistant
+ chain in `dbMessages`; otherwise cover the countdown with the component RTL test.
+- **Gotcha β€” `messagesMap` landing is unreliable to assert; the render is the truth.**
+ `internal_dispatchMessage` (no explicit context) targets the active conversation and
+ the message may not show up where a naive `Object.keys(messagesMap)` scan looks, yet
+ it still renders. Verify by the DOM, not by the store map.
+- **Gotcha β€” `document.body.innerText` keyword match false-positives in long chats.**
+ The conversation's own text (and the right-hand diff/review panel) frequently contains
+ your assert strings (e.g. `连ζŽ₯δΈ­ζ–­`, `重试`, `Retry`). Match on a **unique injected
+ marker** instead, `scrollIntoView` its node, then **open the screenshot with Read** to
+ confirm the card (Case 1 rule). Find + scroll to the node:
+ ```js
+ var w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null),
+ n,
+ hit;
+ while ((n = w.nextNode())) {
+ if (n.nodeValue.indexOf('UNIQUE_MARKER') >= 0) {
+ hit = n;
+ break;
+ }
+ }
+ var el = hit.parentElement;
+ for (var i = 0; i < 6 && el.parentElement; i++) el = el.parentElement;
+ el.scrollIntoView({ block: 'center' });
+ ```
+
+### A8. βœ… WORKS β€” trigger a REAL failed load-more via store action when scroll/observer won't trip
+
+- **Situation**: verifying an infinite-scroll `loadMoreError` inline retry row. The
+ `IntersectionObserver` won't fire because the seed data is a short list that fits
+ the viewport without scrolling (virtua renders no scrollable overflow), so
+ `scrollTop = scrollHeight` scrolls nothing and `loadMore` is never called.
+- **Doesn't work**: scrolling any element to the bottom β€” with only 2 rows there is
+ no scroll container (`scrollHeight <= clientHeight`), and virtua's sentinel never
+ intersects.
+- **Works β€” two parts**:
+ 1. **Force pagination with tiny seed data via HMR**: lower the component's page-size
+ const so a small dataset paginates. `AgentTopicManager` `PAGE_SIZE = 30` β†’ `2`,
+ then an agent with 3 topics loads page-1 = 2, `hasMore = true`.
+ 2. **Call the real store action directly** (bypasses the observer, but runs the real
+ fetch + real `catch`): `window.__LOBE_STORES.<store>` is a bound hook β€” CALL it to
+ get live state + actions (`.getState`/`.setState` are NOT exposed, C1).
+ ```js
+ // agent-browser --session <s> eval
+ var c = window.__LOBE_STORES.chat();
+ await c.loadMoreAgentTopicsView(); // hits the injected getTopics(current>0) throw
+ // β†’ real catch sets agentTopicsViewMap[key].loadMoreError β†’ inline AsyncError row renders
+ ```
+ Pair the service injection (A4, throw only when `params.current > 0` so page-1 loads
+ and page-2 fails) with a **call counter** to prove the observer gate does NOT loop:
+ `(globalThis).__loadMoreCalls = (…||0)+1` inside the throw; after the failure, wait a
+ few seconds and assert `window.__loadMoreCalls` stays `1` (no runaway re-trigger).
+- **Caveat**: calling the action directly proves the render + the real error code path +
+ no-runaway, but NOT the observer's `!loadMoreError` gate under real scroll (the gate
+ lives in the component's IntersectionObserver callback). To exercise the gate live you
+ need a real scrollable list β€” seed `> PAGE_SIZE` visible-source topics on one agent.
+- **Gotcha β€” the manager view filters by source (`ζ₯源: 对话`) by default.** Topics with a
+ non-conversation source/trigger show `0` even though the agent owns them in the DB;
+ click **清空筛选 / Clear filters** (or `setStatus('all')` + clear) to reveal them.
+
---
## B. Cache / stale state that MASKS the failure
diff --git a/.agents/skills/agent-testing/scripts/init-dev-env.sh b/.agents/skills/agent-testing/scripts/init-dev-env.sh
index 3deb97e52f2..e12a98f6e79 100755
--- a/.agents/skills/agent-testing/scripts/init-dev-env.sh
+++ b/.agents/skills/agent-testing/scripts/init-dev-env.sh
@@ -19,6 +19,8 @@
# init-dev-env.sh preflight # check agent-runtime prerequisites (QStash up in queue mode)
# init-dev-env.sh dev-next # exec `pnpm run dev:next` with this env
# init-dev-env.sh dev # exec `bun run dev` with this env
+# init-dev-env.sh stop-dev # stop the dev server (Next + Vite) started by `dev`
+# init-dev-env.sh clean # teardown: stop dev server (DB/Redis containers kept)
# init-dev-env.sh clean-db # remove the managed Postgres/Redis containers
#
# Overrides:
@@ -576,8 +578,40 @@ cmd_clean_db() {
fi
}
+cmd_stop_dev() {
+ apply_env
+ local any=0 pids port
+ for port in "$SERVER_PORT" "$SPA_PORT"; do
+ pids="$(lsof -ti "tcp:$port" -sTCP:LISTEN 2>/dev/null || true)"
+ if [[ -n "$pids" ]]; then
+ # shellcheck disable=SC2086
+ kill $pids 2>/dev/null || true
+ note "stopped listener(s) on :$port ($(echo "$pids" | tr '\n' ' '))"
+ any=1
+ fi
+ done
+ # `bun run dev` supervises Next + Vite; kill the parent too so neither respawns.
+ if pkill -f "bun run dev" 2>/dev/null; then
+ note "stopped 'bun run dev' supervisor"
+ any=1
+ fi
+ if [[ "$any" == 1 ]]; then
+ ok "dev server stopped"
+ else
+ note "no dev server running on :$SERVER_PORT / :$SPA_PORT"
+ fi
+}
+
+cmd_clean() {
+ # Default teardown after a test run: stop the dev server. The managed
+ # Postgres/Redis containers are intentionally reused across runs (setup-db is
+ # idempotent), so they are left running β€” remove them explicitly with clean-db.
+ cmd_stop_dev
+ note "managed DB/Redis containers left running (reused across runs); remove with: $0 clean-db"
+}
+
usage() {
- sed -n '3,24p' "$0" >&2
+ sed -n '3,27p' "$0" >&2
}
COMMAND="${1:-status}"
@@ -601,6 +635,8 @@ case "$COMMAND" in
preflight) cmd_preflight ;;
dev-next) cmd_dev_next ;;
dev) cmd_dev ;;
+ stop-dev | stop) cmd_stop_dev ;;
+ clean) cmd_clean ;;
clean-db) cmd_clean_db ;;
status) cmd_status ;;
*)
diff --git a/src/features/AgentDocumentPage/index.test.tsx b/src/features/AgentDocumentPage/index.test.tsx
index 6eb466b3f51..1f66cba64cb 100644
--- a/src/features/AgentDocumentPage/index.test.tsx
+++ b/src/features/AgentDocumentPage/index.test.tsx
@@ -17,6 +17,10 @@ vi.mock('@lobehub/ui', () => ({
),
}));
+vi.mock('@/components/404', () => ({
+ default: () => <div data-testid="not-found" />,
+}));
+
vi.mock('@/features/PageEditor', () => ({
PageEditor: ({ pageId, header }: { header?: ReactNode; pageId?: string }) => (
<div data-page-id={pageId} data-testid="page-editor">
@@ -45,7 +49,8 @@ vi.mock('./Header', () => ({
const agentDocumentItemState = vi.hoisted(() => ({
current: {
error: undefined as unknown,
- item: { filename: 'spec.md', id: 'agent-document-1', title: 'Spec' },
+ isNotFound: false as boolean | undefined,
+ item: { filename: 'spec.md', id: 'agent-document-1', title: 'Spec' } as unknown,
mutate: vi.fn(),
skillBundle: undefined as unknown,
},
@@ -102,6 +107,7 @@ describe('AgentDocumentPage', () => {
mockUserState.current.preference.lab.enableAgentDocumentFloatingChatPanel = false;
agentDocumentItemState.current = {
error: undefined,
+ isNotFound: false,
item: { filename: 'spec.md', id: 'agent-document-1', title: 'Spec' },
mutate: vi.fn(),
skillBundle: undefined,
@@ -126,6 +132,16 @@ describe('AgentDocumentPage', () => {
expect(screen.getByTestId('header').dataset.documentId).toBe('docs_abc');
});
+ it('renders the not-found module (no header/editor) when the doc is genuinely absent', () => {
+ agentDocumentItemState.current = { ...agentDocumentItemState.current, isNotFound: true };
+
+ render(<AgentDocumentPage documentId="docs_missing" />);
+
+ expect(screen.getByTestId('not-found')).toBeInTheDocument();
+ expect(screen.queryByTestId('page-editor')).toBeNull();
+ expect(screen.queryByTestId('header')).toBeNull();
+ });
+
it('passes document list fetch errors to the header', () => {
const itemError = new Error('metadata failed');
agentDocumentItemState.current = { ...agentDocumentItemState.current, error: itemError };
diff --git a/src/features/AgentDocumentPage/index.tsx b/src/features/AgentDocumentPage/index.tsx
index 093f30643e6..3f4dfd9945a 100644
--- a/src/features/AgentDocumentPage/index.tsx
+++ b/src/features/AgentDocumentPage/index.tsx
@@ -4,6 +4,7 @@ import { Flexbox } from '@lobehub/ui';
import { memo, useCallback, useMemo } from 'react';
import { useParams } from 'react-router';
+import NotFound from '@/components/404';
import FloatingChatPanel from '@/features/FloatingChatPanel';
import { useDocumentChatTopic } from '@/features/FloatingChatPanel/useDocumentChatTopic';
import { PageEditor } from '@/features/PageEditor';
@@ -31,7 +32,13 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
const { aid } = useParams<{ aid: string }>();
const agentId = aid ?? '';
const navigate = useWorkspaceAwareNavigate();
- const { error: itemError, item, mutate, skillBundle } = useAgentDocumentItem(agentId, documentId);
+ const {
+ error: itemError,
+ isNotFound,
+ item,
+ mutate,
+ skillBundle,
+ } = useAgentDocumentItem(agentId, documentId);
const enableFloatingChatPanel = useUserStore(
labPreferSelectors.enableAgentDocumentFloatingChatPanel,
@@ -72,6 +79,17 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
[agentId, backToChat, documentId, item?.id, item?.updatedAt, itemError, title],
);
+ // Genuinely-absent doc: show the not-found state for the whole content module
+ // rather than a breadcrumb with a placeholder "ζ— ζ ‡ι’˜" title + a title skeleton
+ // sitting above a 404 body.
+ if (isNotFound) {
+ return (
+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0 }} width={'100%'}>
+ <NotFound />
+ </Flexbox>
+ );
+ }
+
return (
<Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }} width={'100%'}>
<Flexbox flex={1} style={{ minHeight: 0 }} width={'100%'}>
diff --git a/src/features/AgentDocumentPage/useAgentDocumentItem.ts b/src/features/AgentDocumentPage/useAgentDocumentItem.ts
index 2dae3503197..55aeecf4b30 100644
--- a/src/features/AgentDocumentPage/useAgentDocumentItem.ts
+++ b/src/features/AgentDocumentPage/useAgentDocumentItem.ts
@@ -29,5 +29,13 @@ export const useAgentDocumentItem = (agentId: string | undefined, documentId: st
? data?.find((d) => d.documentId === item.parentId)
: undefined;
- return { error, item, mutate, skillBundle };
+ // The list resolved successfully (`data` defined, no `error`) but this
+ // documentId isn't in it β†’ the doc genuinely doesn't exist for this agent.
+ // Distinct from a fetch failure (`error`) and from still-loading
+ // (`data === undefined`). The header title is sourced from this same list, so
+ // gating not-found here keeps the whole module consistent instead of letting
+ // the breadcrumb render a placeholder title over a 404 body.
+ const isNotFound = !!agentId && data !== undefined && !error && !item;
+
+ return { error, isNotFound, item, mutate, skillBundle };
};