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: prevent resolved briefs from reappearing after navigation (#17760)

YuTengjing197ba3547f2d
diff --git a/.agents/skills/debug-frontend-with-browser/SKILL.md b/.agents/skills/debug-frontend-with-browser/SKILL.md
index 18ee08c0655..1e9c96ae674 100644
--- a/.agents/skills/debug-frontend-with-browser/SKILL.md
+++ b/.agents/skills/debug-frontend-with-browser/SKILL.md
@@ -1,176 +1,137 @@
---
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.
+description: Frontend diagnosis extension for agent-testing. Use for intermittent rendering, ordering, stale-state, navigation, virtual-list, React/Zustand, optimistic-update, refresh-dependent, or browser-only failures where the first broken boundary may be DOM, component input, derived state, client cache, network data, or a pure transformation. Before any browser, Electron, or live-app interaction, this skill must load and follow agent-testing; it adds only boundary tracing, minimal fixture replay, and regression attribution.
---
# 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.
+Find the first boundary where correct data becomes incorrect. This skill extends
+`agent-testing`; it does not define a separate test workflow.
-## Setup
+## Mandatory foundation
-1. Read the repository instructions and preserve the starting worktree state.
+Before any browser, Electron, network, cache, or application interaction:
-2. Load the installed browser workflows before driving the app:
+1. Read [`../agent-testing/SKILL.md`](../agent-testing/SKILL.md) in full.
+2. Follow its target grounding, living logs, project adapter, environment and auth
+ checks, approval gate, evidence rules, publication, and teardown.
+3. Enter this diagnostic workflow only after `agent-testing` has established the
+ approved execution surface. If its environment or auth gate is blocked, stop
+ there instead of inventing another execution path.
+4. Use the isolated environment and fixture strategy selected by the project
+ adapter. Never use the user's signed-in production browser or Electron client
+ as a fixture container or test sandbox.
+5. Treat an explicit production investigation as read-only unless the user
+ separately authorizes an exact live mutation and the project adapter permits
+ it. This skill never grants production-mutation authority.
+6. Never read secret files or print credentials, tokens, private content, or full
+ live objects. Return structural projections only.
- ```bash
- agent-browser skills get core
- agent-browser skills get electron # Electron only
- ```
+If `agent-testing` is unavailable, say so and stop before touching a live surface.
-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.
+## Responsibility boundary
-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.
+| `agent-testing` owns | This skill adds |
+| ------------------------------------------- | -------------------------------------- |
+| Environment isolation and service lifecycle | Falsifiable symptom and event timeline |
+| Authentication and fixture seeding | Boundary-by-boundary state comparison |
+| Browser/Electron driver setup | Safe minimal fixture extraction |
+| Approval and mutation authority | Pure-function replay and commit A/B |
+| Evidence, report, publication, teardown | Earliest-boundary fix guidance |
-5. Never read secret files or print credentials, tokens, private message content, or full live
- objects. Extract structural projections only.
+Do not duplicate or weaken `agent-testing` rules here. When the two skills appear
+to conflict, `agent-testing` and the project adapter control execution.
-## Workflow
+## Diagnostic workflow
### 1. Make the symptom falsifiable
-Write one expected invariant and one observed violation. Include:
+Write one expected invariant and one observed violation. Record:
- 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.
+- state before, during, and after it;
+- whether navigation, remount, refresh, tab switching, or waiting changes it;
+- stable identifiers required to follow the same entity across layers.
-For timing or ordering bugs, define an event timeline before inspecting code.
+For timing or ordering defects, define the expected and observed event timelines
+before reading implementation 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
+### 2. Reproduce on the approved isolated surface
- 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.
+- For an intermittent defect, repeat the same controlled action and record the
+ hit rate.
+- Verify the intended action through a new ID, request, or state transition.
+- Use a GIF or video for flicker and other time-based behavior.
+- Re-snapshot after navigation or a major render because element references expire.
-Keep failed captures, but cite only evidence that proves the claim.
+Use the surface and capture method chosen by `agent-testing`; do not relaunch or
+reattach to the user's resident application.
-### 4. Find the first broken boundary
+### 3. 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`.
+Compare the same entity IDs at each layer and mark each boundary `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 |
+| Boundary | Inspect | What it distinguishes |
+| ------------------- | ----------------------------------------- | ------------------------------ |
+| DOM / visible row | Text, order, recording | Symptom only |
+| Renderer input | Component props, virtual-list data | Renderer vs upstream input |
+| Derived state | Selectors, parsed/display items | Derivation vs raw state |
+| Raw client state | Store records, SWR state, persisted cache | Cache vs transformation |
+| Network / server | Structural response and persisted row | Client vs server |
+| Pure transformation | Exact parser/normalizer input | Runtime vs 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.
+- DOM absence is not state absence in a virtualized list.
+- Retained tabs can own multiple React roots and stores; qualify them by stable
+ IDs and the visible route.
+- For cache defects, distinguish in-memory fetch cache, Zustand state, persisted
+ cache, and server state instead of calling all of them "the cache."
+- Stop expanding the search when a pure local function reproduces the exact
+ invalid output.
-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`.
+### 4. Build the smallest safe fixture
-### 7. Fix the earliest incorrect transformation
+Create the fixture through the isolated environment's supported seed path. Keep
+only fields required by the suspected boundary, such as:
-- 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.
+- `id`, type or role, parent linkage, and timestamps;
+- cache key and lifecycle state;
+- branch or group metadata;
+- entity identifiers that affect selection or grouping.
-### 8. Verify both synthetic and real inputs
+Store reusable inputs through the `agent-testing` fixture layout. Do not copy
+private production content into fixtures or tracked files.
-Run, in order:
+### 5. Attribute with the same fixture
-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.
+Do not infer causality from PR timing or filenames.
-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.
+1. Run the same fixture against the suspected revision and its real parent.
+2. Compare the same observable boundary, not two different screenshots.
+3. Verify the commit parent, PR file list, merge time, and deployment timing.
+4. Separate the revision that introduced the latent bug from the data event that
+ first exposed it.
-### 9. Restore the environment
+### 6. Fix the earliest incorrect boundary
-- 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.
+- Change the layer that first produces invalid state.
+- Preserve unrelated branch, optimistic-update, and cache semantics.
+- Add a behavior-level regression test with the sanitized minimal fixture.
+- Add a JSDoc comment when the fix protects a non-obvious invariant.
+- Do not substitute timeouts, refreshes, DOM sorting, or downstream filters for a
+ source-state fix.
-## Report
+### 7. Return to agent-testing for verification
-Lead with:
+After diagnosis or a fix, resume the parent `agent-testing` workflow. It owns the
+focused checks, isolated visual replay, evidence inspection, structured report,
+publication, and cleanup. Do not publish a separate browser-debugging verdict.
-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.
+## Diagnostic supplements
-Reference exact `path:line` locations before discussing implementation symbols. Link the issue,
-PRs, acceptance report, and local evidence directory when available.
+Read [references/pitfalls.md](references/pitfalls.md) when the suspected boundary
+involves retained React roots, virtualized data, optimistic reconciliation, stale
+client caches, pure replay, or regression attribution.
diff --git a/.agents/skills/debug-frontend-with-browser/agents/openai.yaml b/.agents/skills/debug-frontend-with-browser/agents/openai.yaml
index 867c6192751..45122327f61 100644
--- a/.agents/skills/debug-frontend-with-browser/agents/openai.yaml
+++ b/.agents/skills/debug-frontend-with-browser/agents/openai.yaml
@@ -1,4 +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.'
+ short_description: 'Diagnose frontend state after isolated test setup'
+ default_prompt: 'Use $debug-frontend-with-browser after $agent-testing to isolate the first broken frontend state boundary.'
diff --git a/.agents/skills/debug-frontend-with-browser/references/pitfalls.md b/.agents/skills/debug-frontend-with-browser/references/pitfalls.md
index d53679ccf2c..64f2f11c676 100644
--- a/.agents/skills/debug-frontend-with-browser/references/pitfalls.md
+++ b/.agents/skills/debug-frontend-with-browser/references/pitfalls.md
@@ -1,177 +1,109 @@
-# Browser Frontend Debugging Pitfalls
+# Frontend Diagnosis Supplements
-Use this reference for Electron custom protocols, intermittent rendering, React state inspection,
-virtualized lists, and commit attribution.
+Read this only after the mandatory `agent-testing` workflow has selected and
+approved an isolated execution surface.
## 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)
+- [Virtualized and optimistic state](#virtualized-and-optimistic-state)
+- [Cache ownership and remounts](#cache-ownership-and-remounts)
+- [Safe fixture replay](#safe-fixture-replay)
- [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.
+Keep-alive routers, Activities, portals, and background tabs can retain multiple
+component trees. Several stores can contain the same entity while the visible tab
+owns another store.
-For every candidate store, print a structural summary:
+For every candidate store, compare a structural summary:
-- stable context ID;
+- stable context and route ID;
- raw and derived item counts;
-- first/last IDs;
+- first and 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.
+Do not treat the first matching Fiber as authoritative. Prefer the project's
+state probe or React DevTools. Use targeted Fiber inspection only as a fallback,
+and serialize copied values immediately with `JSON.stringify(value, null, 2)`.
-Browser DevTools shows live object references. Serialize copied objects immediately:
-
-```javascript
-JSON.stringify(value, null, 2);
-```
-
-## Virtualized and optimistic UI
+## Virtualized and optimistic state
### 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:
+A virtualized list can retain an item in its data source while its DOM row is
+offscreen or recycled. Compare raw records, derived records, virtual-list IDs,
+and visible rows separately.
-1. raw messages;
-2. parsed/display messages;
-3. virtual-list IDs;
-4. visible DOM rows.
+### Optimistic state can hide the reconciliation defect
-### 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.
+Capture the state immediately before the action, after the optimistic update,
+after server reconciliation, and after a remount. A correct optimistic frame
+does not prove that the authoritative cache was updated.
### 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
+Refresh changes the React root, viewport, optimistic buffers, in-memory cache, and
+revalidation timing. Reinspect the underlying state after refresh; a visually
+correct final frame does not explain an earlier stale frame.
-- 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.
+## Cache ownership and remounts
-Keep failed captures for auditability, but do not cite them as proof.
+Treat each cache boundary as a separate owner:
-### Bound production mutations
+1. server persistence;
+2. network response;
+3. SWR or query-client in-memory entry;
+4. Zustand or component state;
+5. persisted browser cache;
+6. remounted consumer state.
-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.
+For a mutation followed by navigation, record this exact timeline:
-## Data and auth boundaries
+1. mutation result;
+2. optimistic/local state update;
+3. query-cache update or invalidation;
+4. persisted-cache write;
+5. route unmount;
+6. remount hydration;
+7. server revalidation.
-### Use the app's authenticated origin
+If a stale item appears only after remount and disappears after revalidation,
+compare the mutation's local store update with the query cache under the same
+key. A mutation that updates Zustand but leaves SWR unchanged can be overwritten
+when the remounted fetch hook hydrates Zustand from the stale SWR entry.
-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.
+Do not prove this by manually injecting storage into a production client. Seed
+the server-side fixture and client cache state inside the approved isolated
+environment, then observe the real application lifecycle.
-### Project structure, not content
+## Safe fixture replay
-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.
+Project structure rather than private content. IDs, types or roles, parent links,
+timestamps, branch metadata, cache keys, and tool linkage are usually sufficient.
-### 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.
+When an exact browser input reproduces in a local pure function, Electron, React,
+Zustand, and the virtual list are no longer required to explain that boundary.
+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:
+Shallow or grafted repositories can hide intermediate commits. Before naming a
+first-bad PR:
1. query path commits for the real date range;
-2. inspect the commit's actual parent through GitHub;
+2. inspect the commit's real parent;
3. compare the PR file list;
-4. run the same fixture on the real parent and merge commit.
+4. run the same fixture on the 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.
+Compare the first bad code revision, trigger-data creation time, and deployment
+time. A recent data event can expose an older latent defect; it does not make the
+newest PR causal.
diff --git a/src/store/brief/slices/list/action.test.ts b/src/store/brief/slices/list/action.test.ts
new file mode 100644
index 00000000000..a1178953e4e
--- /dev/null
+++ b/src/store/brief/slices/list/action.test.ts
@@ -0,0 +1,72 @@
+// @vitest-environment node
+import type { ScopedMutator } from 'swr/_internal';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { setScopedMutate } from '@/libs/swr';
+import { briefKeys } from '@/libs/swr/keys';
+import { briefService } from '@/services/brief';
+import type { BriefStore } from '@/store/brief/store';
+import type { BriefItem } from '@/store/brief/types';
+
+import { BriefListActionImpl } from './action';
+
+const createBrief = (id: string): BriefItem => ({
+ actions: null,
+ agent: null,
+ agentId: null,
+ artifacts: null,
+ createdAt: '2026-07-31T00:00:00.000Z',
+ cronJobId: null,
+ id,
+ priority: null,
+ readAt: null,
+ resolvedAction: null,
+ resolvedAt: null,
+ resolvedComment: null,
+ summary: `${id} summary`,
+ taskId: null,
+ title: `${id} title`,
+ topicId: null,
+ type: 'result',
+ userId: 'user-1',
+});
+
+describe('BriefListActionImpl', () => {
+ const cache = new Map<string, BriefItem[]>();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ cache.clear();
+ setScopedMutate((async (key, data) => {
+ if (Array.isArray(data)) cache.set(JSON.stringify(key), data);
+ return data;
+ }) as ScopedMutator);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('should remove resolved briefs from the SWR snapshot used on route remount', async () => {
+ const resolvedBrief = createBrief('brief-resolved');
+ const remainingBrief = createBrief('brief-remaining');
+ const initialBriefs = [resolvedBrief, remainingBrief];
+ const cacheKey = JSON.stringify(briefKeys.list(true));
+ cache.set(cacheKey, initialBriefs);
+
+ const state = { briefs: initialBriefs, isBriefsInit: true };
+ const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));
+ const action = new BriefListActionImpl(set as never, () => state as BriefStore);
+ vi.spyOn(briefService, 'resolveManyAsRead').mockResolvedValue({
+ data: [resolvedBrief.id],
+ } as never);
+
+ await action.resolveBriefsAsRead(initialBriefs.map((brief) => brief.id));
+
+ expect(state.briefs).toEqual([remainingBrief]);
+ expect(cache.get(cacheKey)).toEqual([remainingBrief]);
+
+ state.briefs = cache.get(cacheKey) ?? [];
+ expect(state.briefs).not.toContainEqual(expect.objectContaining({ id: resolvedBrief.id }));
+ });
+});
diff --git a/src/store/brief/slices/list/action.ts b/src/store/brief/slices/list/action.ts
index e3a197956b9..955b9da25d9 100644
--- a/src/store/brief/slices/list/action.ts
+++ b/src/store/brief/slices/list/action.ts
@@ -1,7 +1,7 @@
import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
-import { useClientDataSWRWithSync } from '@/libs/swr';
+import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
import { briefKeys } from '@/libs/swr/keys';
import { briefService } from '@/services/brief';
import { taskService } from '@/services/task';
@@ -48,12 +48,12 @@ export class BriefListActionImpl {
this.internal_updateBrief(id, { readAt: new Date().toISOString() });
};
- // "Mark all read" over the news section: resolves the briefs with the
- // neutral `read` action (server-side, never `approve` β€” bulk dismissal must
- // not complete tasks) and drops them from the feed, mirroring what the next
- // unresolved-only fetch would return. Only the ids the server actually
- // resolved are removed, so a brief resolved elsewhere in the meantime keeps
- // its own resolution.
+ /**
+ * "Mark all read" resolves news briefs with the neutral `read` action and drops
+ * them from both Zustand and its backing SWR snapshot. Route remounts hydrate
+ * Zustand from SWR before revalidation, so the cache write prevents stale briefs
+ * from reappearing after navigation.
+ */
resolveBriefsAsRead = async (ids: string[]) => {
if (ids.length === 0) return;
@@ -63,6 +63,7 @@ export class BriefListActionImpl {
const briefs = this.#get().briefs.filter((b) => !resolvedIds.has(b.id));
this.#set({ briefs }, false, n('resolveBriefsAsRead'));
+ void mutate(briefKeys.list(true), briefs, { revalidate: false });
};
resolveBrief = async (id: string, action?: string, comment?: string) => {