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: omit duplicate assistant continuations (#17726)

YuTengjing11f7bc8d4434
diff --git a/.agents/skills/debug-frontend-with-browser/SKILL.md b/.agents/skills/debug-frontend-with-browser/SKILL.md
new file mode 100644
index 00000000000..18ee08c0655
--- /dev/null
+++ b/.agents/skills/debug-frontend-with-browser/SKILL.md
@@ -0,0 +1,176 @@
+---
+name: debug-frontend-with-browser
+description: Reproduce, isolate, and verify frontend bugs with agent-browser across web and Electron surfaces. Use for intermittent rendering, ordering, stale-state, navigation, virtual-list, React/Zustand, optimistic-update, refresh-dependent, or browser-only failures where the broken boundary may be DOM, component props, derived store state, network data, or a pure transformation. Also use when collecting browser evidence, replaying an exact frontend fixture against local code, or attributing a frontend regression to a commit or PR.
+---
+
+# Debug Frontend with Browser
+
+Find the first boundary where correct data becomes incorrect. Capture enough evidence to
+separate a visible symptom from its source, then fix and verify at that source.
+
+## Setup
+
+1. Read the repository instructions and preserve the starting worktree state.
+
+2. Load the installed browser workflows before driving the app:
+
+ ```bash
+ agent-browser skills get core
+ agent-browser skills get electron # Electron only
+ ```
+
+3. Use the project's acceptance or agent-testing skill when the result needs a formal report.
+ This skill owns diagnosis; the acceptance skill owns plan confirmation, evidence packaging,
+ and publication.
+
+4. Define a mutation budget before touching production data. Prefer a disposable fixture. If the
+ real account is required, state the exact bounded actions and obtain approval.
+
+5. Never read secret files or print credentials, tokens, private message content, or full live
+ objects. Extract structural projections only.
+
+## Workflow
+
+### 1. Make the symptom falsifiable
+
+Write one expected invariant and one observed violation. Include:
+
+- the triggering action;
+- the state before, during, and after it;
+- whether refresh, navigation, tab switching, or waiting changes the symptom;
+- the identifiers needed to follow the same entity across layers.
+
+For timing or ordering bugs, define an event timeline before inspecting code.
+
+### 2. Attach to the correct surface
+
+For web pages, use a named browser session and the snapshot β†’ action β†’ re-snapshot loop.
+
+For Electron:
+
+1. Confirm the app was already running so it can be restored later.
+2. Quit it gracefully.
+3. Relaunch with a dedicated CDP port.
+4. Pass `--cdp <port>` on every command in the attached session.
+5. List targets when multiple windows or webviews exist.
+
+Do not use `agent-browser open app://...`. Navigate custom-protocol SPAs through visible UI or:
+
+```bash
+agent-browser --cdp "$PORT" --session "$SESSION" pushstate '/target/path'
+```
+
+Read [references/pitfalls.md](references/pitfalls.md) for Electron, React-root, virtualization,
+refresh, and attribution traps.
+
+### 3. Reproduce before explaining
+
+- Reproduce once without recording to prove the path.
+- For an intermittent bug, retry with the same controlled action and record the hit rate.
+- Record a GIF/video for behavior over time; use a screenshot only for a static broken state.
+- Verify that the intended action actually happened by checking a new ID, network request, visible
+ text, or state transition. A recording of the wrong click is not evidence.
+- Re-snapshot after every navigation or major render because element refs become stale.
+
+Keep failed captures, but cite only evidence that proves the claim.
+
+### 4. Find the first broken boundary
+
+Inspect layers from the visible consumer toward the source. At each layer, compare the same entity
+IDs and state the result as `correct` or `incorrect`.
+
+| Boundary | Inspect | What it rules out |
+| ------------------- | -------------------------------------------- | ------------------------------------------ |
+| DOM / visible row | text, order, screenshot, timeline | Confirms the symptom only |
+| Renderer input | virtual-list `dataSource`, component props | Renderer versus upstream input |
+| Derived state | selectors, parsed/display messages | Store derivation versus raw state |
+| Raw client state | provider props, fetched records, cache value | Fetch/cache versus transformation |
+| Network/server | response status and structural payload | Client versus server persistence |
+| Pure transformation | exact input passed to parser/normalizer | Browser/runtime versus deterministic logic |
+
+Important:
+
+- DOM absence is not proof of state absence in a virtualized list.
+- Multiple retained tabs can own multiple React roots and stores. Qualify a store by stable IDs,
+ not by whichever Fiber is found first.
+- Prefer the installed `agent-browser react` commands when React DevTools can be enabled. Use
+ targeted Fiber evaluation only as a fallback, and serialize copied values immediately.
+- Do not reorder data in the final renderer if an upstream parser already emits the wrong order.
+
+Stop expanding the search once a pure local function reproduces the exact bad output.
+
+### 5. Extract a safe exact fixture
+
+Project the minimum fields required by the suspected transformation, usually:
+
+- `id`, `role`, `parentId`, `createdAt`, and `updatedAt`;
+- branch metadata;
+- tool call/result linkage;
+- agent, topic, thread, or group IDs when they affect grouping.
+
+Omit content and unrelated metadata. Feed the exact array from the browser into the local function
+without writing it to a tracked file:
+
+```bash
+agent-browser ... eval '<return JSON.stringify(projectedInput)>' \
+ | jq -r . \
+ | bun -e 'const input = JSON.parse(await Bun.stdin.text()); /* run local transform */'
+```
+
+Record input count, output count, the target ID's index, group membership, and a short output tail.
+
+### 6. Attribute with the same fixture
+
+Do not infer causality from PR timing or file names.
+
+1. Run the same fixture against the suspected revision and its parent.
+2. If needed, archive package snapshots into a temporary directory and import each snapshot without
+ checking out the worktree.
+3. Find the first revision where the observable output changes.
+4. Verify the PR's actual file list, merge parent, and merge time.
+5. Compare the trigger-data timestamps with the deployment or merge timestamp.
+
+Local shallow or grafted histories can misattribute unrelated tree changes to the next visible
+commit. Verify the real commit parent and path history through the GitHub API or `gh`.
+
+### 7. Fix the earliest incorrect transformation
+
+- Change the layer that first produced the invalid state.
+- Preserve other branch, task, signal, and optimistic-update semantics.
+- Add a behavior-level regression test with a sanitized minimal fixture.
+- Add a JSDoc comment when the fix protects a non-obvious invariant or historical data shape.
+- Avoid timeouts, refreshes, DOM sorting, or downstream filters as substitutes for a state fix.
+
+### 8. Verify both synthetic and real inputs
+
+Run, in order:
+
+1. the focused regression test;
+2. related package tests;
+3. the exact real-data replay through the fixed local transformation;
+4. the repository quality command;
+5. visual/browser verification when the source change affects rendering behavior.
+
+For real-data replay, make it read-only. The fixed output should remove the violating ID while
+preserving the active group and newest valid tail.
+
+### 9. Restore the environment
+
+- Close only browser sessions created by this investigation.
+- Quit the CDP-launched Electron app and reopen it normally if it was running before.
+- Confirm the CDP port is closed.
+- Remove or trash only exact temporary paths created by the investigation.
+- Recheck both the root worktree and any submodule worktree; report pre-existing changes separately.
+
+## Report
+
+Lead with:
+
+1. root cause and confidence;
+2. the first broken boundary;
+3. why suspected recent changes are or are not causal;
+4. the fix and regression coverage;
+5. remaining uncertainty.
+
+Reference exact `path:line` locations before discussing implementation symbols. Link the issue,
+PRs, acceptance report, and local evidence directory when available.
diff --git a/.agents/skills/debug-frontend-with-browser/agents/openai.yaml b/.agents/skills/debug-frontend-with-browser/agents/openai.yaml
new file mode 100644
index 00000000000..867c6192751
--- /dev/null
+++ b/.agents/skills/debug-frontend-with-browser/agents/openai.yaml
@@ -0,0 +1,4 @@
+interface:
+ display_name: 'Debug Frontend with Browser'
+ short_description: 'Trace frontend state across browser, store, and parser'
+ default_prompt: 'Use $debug-frontend-with-browser to reproduce and isolate this frontend bug with browser evidence.'
diff --git a/.agents/skills/debug-frontend-with-browser/references/pitfalls.md b/.agents/skills/debug-frontend-with-browser/references/pitfalls.md
new file mode 100644
index 00000000000..d53679ccf2c
--- /dev/null
+++ b/.agents/skills/debug-frontend-with-browser/references/pitfalls.md
@@ -0,0 +1,177 @@
+# Browser Frontend Debugging Pitfalls
+
+Use this reference for Electron custom protocols, intermittent rendering, React state inspection,
+virtualized lists, and commit attribution.
+
+## Contents
+
+- [Electron and sessions](#electron-and-sessions)
+- [React and retained roots](#react-and-retained-roots)
+- [Virtualized and optimistic UI](#virtualized-and-optimistic-ui)
+- [Evidence integrity](#evidence-integrity)
+- [Data and auth boundaries](#data-and-auth-boundaries)
+- [Regression attribution](#regression-attribution)
+- [Teardown](#teardown)
+
+## Electron and sessions
+
+### Relaunch before attaching
+
+Electron reads `--remote-debugging-port` only during process startup. If the app is already open,
+quit it before relaunching with CDP.
+
+### Keep `--cdp` on every command
+
+A named agent-browser session does not guarantee that later commands remain attached to the
+Electron target. A command without `--cdp` may silently operate on `about:blank` or a separate
+browser. Check `get url` before collecting evidence.
+
+### Do not open custom protocols
+
+`agent-browser open app://renderer/...` may be normalized into a broken HTTP URL such as
+`https://app//renderer/...`. Use in-app navigation or `pushstate '/path'` from the existing
+`app://renderer` page.
+
+### Prefer conditions over sleeps
+
+Wait for a URL, visible marker, operation state, or DOM condition. Use fixed sleeps only to make a
+repro recording human-readable.
+
+## React and retained roots
+
+### The first store may be hidden
+
+Keep-alive routers, Activities, portals, and background tabs can retain multiple component trees.
+Several stores can contain the same topic, while another visible tab owns a different store.
+
+For every candidate store, print a structural summary:
+
+- stable context ID;
+- raw and derived item counts;
+- first/last IDs;
+- whether the target ID exists;
+- visibility or owning tab when available.
+
+Do not treat the first matching Fiber as authoritative.
+
+### Prefer React DevTools, then use a narrow fallback
+
+Launch with React DevTools support when possible:
+
+```bash
+agent-browser open --enable react-devtools http://localhost:3000
+agent-browser react tree
+agent-browser react inspect <fiberId>
+```
+
+For an already-packaged Electron app where DevTools injection is unavailable, a targeted
+`agent-browser eval --stdin` can walk `__reactFiber$*` links. Keep the fallback narrow:
+
+1. identify roots from DOM-owned Fibers;
+2. de-duplicate Fibers;
+3. match stable IDs and expected field shapes;
+4. return summaries or `JSON.stringify` snapshots, never live objects or full private content.
+
+Browser DevTools shows live object references. Serialize copied objects immediately:
+
+```javascript
+JSON.stringify(value, null, 2);
+```
+
+## Virtualized and optimistic UI
+
+### DOM absence is not state absence
+
+A virtualized list can keep an item in `dataSource` while its DOM row is offscreen or recycled.
+Compare these boundaries separately:
+
+1. raw messages;
+2. parsed/display messages;
+3. virtual-list IDs;
+4. visible DOM rows.
+
+### Optimistic state can temporarily reverse order
+
+During a send, the UI may append a new user/assistant pair to the current derived list. When the
+server response arrives, a deterministic parser can rebuild the list into a different order.
+Capture before-send, optimistic, reconciled, and post-scroll states before blaming the renderer.
+
+### Refresh can hide rather than fix
+
+Refresh changes viewport position, retained roots, optimistic buffers, and cache timing. Reinspect
+raw and derived state after refresh. A visually normal viewport does not prove the underlying list
+is repaired.
+
+## Evidence integrity
+
+### Prove the action happened
+
+Dense chat UIs can expose several nearby icon buttons. A click may open an approval or attachment
+menu instead of sending. Confirm the action with a created message ID, request, or operation state
+before citing the recording.
+
+### Use evidence that matches the claim
+
+- Static layout or text: screenshot.
+- Ordering, flicker, loading, or state transitions: GIF/video plus a final screenshot.
+- Server/store/parser boundaries: paired reasoning and execution text.
+
+Keep failed captures for auditability, but do not cite them as proof.
+
+### Bound production mutations
+
+State the maximum number and exact type of writes before testing. Use unique debug labels so test
+messages can be identified later. Stop when enough evidence exists.
+
+## Data and auth boundaries
+
+### Use the app's authenticated origin
+
+An Electron `app://` page may authenticate relative application requests but reject an invented
+absolute `https://` call because cookies, headers, or protocol handling differ. Reuse the request
+shape the app already makes and inspect network traffic before changing origins.
+
+### Project structure, not content
+
+For a message-order bug, IDs, roles, parent links, timestamps, branch metadata, and tool linkage are
+usually sufficient. Do not dump prompts, replies, tokens, cookies, or unrelated metadata.
+
+### Pure replay is the strongest boundary
+
+If the exact raw browser input reproduces in a local pure function, Electron, React, Zustand, and
+the virtual list are no longer required to explain the bug. Fix and test the pure transformation.
+
+## Regression attribution
+
+### Do not trust a shallow path log blindly
+
+Shallow or grafted repositories can hide intermediate commits. The next visible commit may appear
+to add or change a package even when its GitHub PR did not touch that package.
+
+Before naming a first-bad PR:
+
+1. query path commits for the real date range;
+2. inspect the commit's actual parent through GitHub;
+3. compare the PR file list;
+4. run the same fixture on the real parent and merge commit.
+
+### Separate trigger creation from latent bug introduction
+
+A parser bug can exist for weeks and become visible only when a topic acquires a rare sibling or
+branch shape. Compare:
+
+- first bad code revision;
+- trigger-data creation time;
+- suspected PR merge/deployment time.
+
+A recent trigger does not make the newest PR causal.
+
+## Teardown
+
+- Use `agent-browser --session <name> close`; `agent-browser session close <name>` only prints or
+ selects a session on some CLI versions.
+- Restore the Electron app without CDP.
+- Verify the debugging port no longer listens.
+- Prefer the platform trash command for temporary directories when deletion policies reject
+ recursive removal.
+- Preserve screenshots, videos, and reports referenced by acceptance evidence.
diff --git a/packages/conversation-flow/src/__tests__/dualForm.test.ts b/packages/conversation-flow/src/__tests__/dualForm.test.ts
index f60400cfec8..db58181868c 100644
--- a/packages/conversation-flow/src/__tests__/dualForm.test.ts
+++ b/packages/conversation-flow/src/__tests__/dualForm.test.ts
@@ -378,7 +378,93 @@ describe('dual-form message chain', () => {
expect(r0.flatList.map((m) => m.id)).not.toContain('a2b');
});
- it('⑦ async-task summary with assistant-anchored parent stays out of the group', () => {
+ it('⑦ tool-anchored duplicate continuation omits the unselected sibling', () => {
+ const messages: Message[] = [
+ { content: 'q', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },
+ {
+ agentId: 'agent-a',
+ content: 'step1',
+ createdAt: 1,
+ id: 'a1',
+ parentId: 'u1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'x',
+ arguments: '{}',
+ id: 'tc1',
+ identifier: 'x',
+ result_msg_id: 'a1__tc1',
+ type: 'default',
+ },
+ ],
+ updatedAt: 0,
+ },
+ {
+ content: 'r',
+ createdAt: 2,
+ id: 'a1__tc1',
+ parentId: 'a1',
+ role: 'tool',
+ tool_call_id: 'tc1',
+ updatedAt: 0,
+ },
+ {
+ agentId: 'agent-a',
+ content: 'duplicate output',
+ createdAt: 3,
+ id: 'a2-duplicate',
+ parentId: 'a1__tc1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ {
+ agentId: 'agent-a',
+ content: 'selected output',
+ createdAt: 4,
+ id: 'a2-selected',
+ parentId: 'a1__tc1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ {
+ content: 'next question',
+ createdAt: 5,
+ id: 'u2',
+ parentId: 'a2-selected',
+ role: 'user',
+ updatedAt: 0,
+ },
+ {
+ agentId: 'agent-a',
+ content: 'next answer',
+ createdAt: 6,
+ id: 'a3',
+ parentId: 'u2',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ];
+
+ const result = parse(messages);
+
+ expect(shape(result.flatList)).toEqual([
+ { childIds: undefined, id: 'u1', role: 'user' },
+ {
+ childIds: [
+ { id: 'a1', tools: ['a1__tc1'] },
+ { id: 'a2-selected', tools: [] },
+ ],
+ id: 'a1',
+ role: 'assistantGroup',
+ },
+ { childIds: undefined, id: 'u2', role: 'user' },
+ { childIds: undefined, id: 'a3', role: 'assistant' },
+ ]);
+ expect(result.flatList.map((message) => message.id)).not.toContain('a2-duplicate');
+ });
+
+ it('β‘§ async-task summary with assistant-anchored parent stays out of the group', () => {
// a1 spawns async tasks under its tool; the follow-up summary uses the NEW
// assistant-anchored parent (summary.parentId === a1). It must render after
// the tasks aggregation (group β†’ tasks β†’ summary), NOT inside the group.
diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.ts
index 733e4f9f0ee..294827eec99 100644
--- a/packages/conversation-flow/src/transformation/MessageCollector.ts
+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts
@@ -282,7 +282,36 @@ export class MessageCollector {
.sort((a, b) => a.createdAt - b.createdAt);
const activeId = this.resolveActiveContinuationId(candidates);
- return activeId ? candidates.find((m) => m.id === activeId) : undefined;
+ if (!activeId) return;
+
+ const activeContinuation = candidates.find((message) => message.id === activeId);
+ if (!activeContinuation) return;
+
+ this.markUnselectedContinuationSiblings(activeContinuation, candidates, processedIds);
+ return activeContinuation;
+ }
+
+ /**
+ * Multiple assistant continuations can share a tool-result parent, including
+ * duplicate outputs left by a retried execution. Once BranchResolver selects
+ * the continuation for the current chain, the other same-parent assistants
+ * must be treated as consumed;
+ * otherwise FlatListBuilder's post-group continuation drain emits them later
+ * as standalone messages, often after a much newer turn.
+ */
+ private markUnselectedContinuationSiblings(
+ activeContinuation: Message,
+ candidates: Message[],
+ processedIds: Set<string>,
+ ): void {
+ for (const candidate of candidates) {
+ if (
+ candidate.id !== activeContinuation.id &&
+ candidate.parentId === activeContinuation.parentId
+ ) {
+ processedIds.add(candidate.id);
+ }
+ }
}
/**