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(brief): scope the brief feed per workspace, surface failed actions (#17884)

Rdmclin256a28d597caa
diff --git a/apps/server/src/routers/lambda/__tests__/brief.test.ts b/apps/server/src/routers/lambda/__tests__/brief.test.ts
index 44f7badfec9..a9f3517f15d 100644
--- a/apps/server/src/routers/lambda/__tests__/brief.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/brief.test.ts
@@ -18,10 +18,36 @@ const { briefRouter } = await import('../brief');
const createCaller = () =>
briefRouter.createCaller({ serverDB: {}, userId: 'user-1', workspaceId: 'ws-1' } as any);
-describe('briefRouter — write permission gate', () => {
- it('resolveManyAsRead uses the task-domain agent:update permission', async () => {
- await expect(createCaller().resolveManyAsRead({ ids: ['brief-1'] })).rejects.toThrow(
- 'GATE:agent:update',
- );
+/**
+ * `workspace_viewer` is read-only: it holds no `agent:update` grant, so every
+ * brief mutation must sit behind that gate. `resolve` / `resolveManyAsRead` /
+ * `delete` clear the `hasUnresolvedUrgentByTask` predicate that parks a task
+ * between automated runs, so dismissing a brief resumes the agent and spends
+ * workspace budget — not something a read-only role may trigger.
+ */
+describe('briefRouter — every mutation is gated on the writable-role permission', () => {
+ const mutations: [string, () => Promise<unknown>][] = [
+ ['create', () => createCaller().create({ summary: 's', title: 't', type: 'insight' })],
+ ['delete', () => createCaller().delete({ id: 'brief-1' })],
+ ['markRead', () => createCaller().markRead({ id: 'brief-1' })],
+ ['resolve', () => createCaller().resolve({ action: 'approve', id: 'brief-1' })],
+ ['resolveManyAsRead', () => createCaller().resolveManyAsRead({ ids: ['brief-1'] })],
+ ];
+
+ it.each(mutations)('%s requires the task-domain agent:update action', async (_name, call) => {
+ // `task:update` is not an RBAC action and is rejected for every role
+ // including Owner — asserting the exact code keeps that regression out.
+ await expect(call()).rejects.toThrow('GATE:agent:update');
+ });
+});
+
+describe('briefRouter — reads stay open to every workspace role', () => {
+ it('does not gate listUnresolved', async () => {
+ // Reaches the handler (and fails on the stub db) instead of throwing GATE:*.
+ await expect(createCaller().listUnresolved()).rejects.not.toThrow(/^GATE:/);
+ });
+
+ it('does not gate list', async () => {
+ await expect(createCaller().list({ limit: 50, offset: 0 })).rejects.not.toThrow(/^GATE:/);
});
});
diff --git a/apps/server/src/routers/lambda/brief.ts b/apps/server/src/routers/lambda/brief.ts
index be3cde57e02..ff267a62f08 100644
--- a/apps/server/src/routers/lambda/brief.ts
+++ b/apps/server/src/routers/lambda/brief.ts
@@ -12,8 +12,24 @@ import { NIGHTLY_REVIEW_BRIEF_TRIGGER } from '@/server/services/agentSignal/serv
import { BriefService } from '@/server/services/brief';
const briefProcedure = wsCompatProcedure.use(serverDatabase);
-// Briefs are task-domain records. Keep their write gate aligned with task
-// mutations; `task:update` is not an RBAC action and is rejected in workspace mode.
+
+/**
+ * Every brief mutation, gated on the writable-role permission.
+ *
+ * `workspace_viewer` is read-only by product decision, and a brief write is not
+ * the inert per-user bookkeeping it looks like: `resolve`, `resolveManyAsRead`
+ * and `delete` all clear the `hasUnresolvedUrgentByTask` predicate that parks a
+ * task between automated runs (`taskLifecycle`, `heartbeatTick`,
+ * `scheduleTick`). Dismissing a brief therefore lets the agent resume and spend
+ * workspace budget — an action, not a read. `markRead` alone has no lifecycle
+ * effect, but a read-only role gets no brief writes at all; one rule beats a
+ * carve-out nobody will remember.
+ *
+ * `agent:update` is the permission every writable built-in role holds
+ * (`:all` for Owner, `:owner` for Admin/Member) and Viewer does not. It is NOT
+ * `task:update` — that is not an RBAC action at all and is rejected for every
+ * role including Owner, which is what broke this router before (lobehub#17507).
+ */
const briefWriteProcedure = briefProcedure.use(withScopedPermission('agent:update'));
const idInput = z.object({ id: z.string() });
diff --git a/locales/ar/home.json b/locales/ar/home.json
index 8f3d6c64380..531c35e7bcf 100644
--- a/locales/ar/home.json
+++ b/locales/ar/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "تجاهل",
"brief.action.retry": "إعادة المحاولة",
"brief.action.upgrade": "ترقية الخطة",
+ "brief.actionFailed": "لم يتم الأمر. يرجى المحاولة مرة أخرى.",
"brief.addFeedback": "مشاركة الملاحظات",
"brief.agentSignal.selfReview.applied.heading": "محدث",
"brief.agentSignal.selfReview.applied.summary": "تم تطبيق تحديث حلم واحد.",
diff --git a/locales/bg-BG/home.json b/locales/bg-BG/home.json
index 8cf4c789b42..a76e3db0a56 100644
--- a/locales/bg-BG/home.json
+++ b/locales/bg-BG/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Игнорирай",
"brief.action.retry": "Опит отново",
"brief.action.upgrade": "Надграждане на плана",
+ "brief.actionFailed": "Това не се получи. Моля, опитайте отново.",
"brief.addFeedback": "Споделяне на обратна връзка",
"brief.agentSignal.selfReview.applied.heading": "Актуализирано",
"brief.agentSignal.selfReview.applied.summary": "{{count}} актуализация на мечтата беше приложена.",
diff --git a/locales/de-DE/home.json b/locales/de-DE/home.json
index ce0403118a3..e1c77deb469 100644
--- a/locales/de-DE/home.json
+++ b/locales/de-DE/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Ignorieren",
"brief.action.retry": "Erneut versuchen",
"brief.action.upgrade": "Plan upgraden",
+ "brief.actionFailed": "Das hat nicht geklappt. Bitte versuchen Sie es erneut.",
"brief.addFeedback": "Feedback teilen",
"brief.agentSignal.selfReview.applied.heading": "Aktualisiert",
"brief.agentSignal.selfReview.applied.summary": "{{count}} Traumaktualisierung wurde angewendet.",
diff --git a/locales/en-US/home.json b/locales/en-US/home.json
index a75c3b6dd69..1cd3787ee71 100644
--- a/locales/en-US/home.json
+++ b/locales/en-US/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Ignore",
"brief.action.retry": "Retry",
"brief.action.upgrade": "Upgrade plan",
+ "brief.actionFailed": "That didn't go through. Please try again.",
"brief.addFeedback": "Share feedback",
"brief.agentSignal.selfReview.applied.heading": "Updated",
"brief.agentSignal.selfReview.applied.summary": "{{count}} dream update was applied.",
diff --git a/locales/es-ES/home.json b/locales/es-ES/home.json
index d2c80c1c875..bc8002c13d6 100644
--- a/locales/es-ES/home.json
+++ b/locales/es-ES/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Ignorar",
"brief.action.retry": "Reintentar",
"brief.action.upgrade": "Actualizar plan",
+ "brief.actionFailed": "Eso no funcionó. Por favor, inténtalo de nuevo.",
"brief.addFeedback": "Compartir comentarios",
"brief.agentSignal.selfReview.applied.heading": "Actualizado",
"brief.agentSignal.selfReview.applied.summary": "Se aplicó {{count}} actualización de sueño.",
diff --git a/locales/fa-IR/home.json b/locales/fa-IR/home.json
index aa5edfc548d..6413cafa6e3 100644
--- a/locales/fa-IR/home.json
+++ b/locales/fa-IR/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "نادیده گرفتن",
"brief.action.retry": "تلاش دوباره",
"brief.action.upgrade": "ارتقاء طرح",
+ "brief.actionFailed": "این عملیات انجام نشد. لطفاً دوباره تلاش کنید.",
"brief.addFeedback": "اشتراک‌گذاری بازخورد",
"brief.agentSignal.selfReview.applied.heading": "به‌روزرسانی شد",
"brief.agentSignal.selfReview.applied.summary": "{{count}} به‌روزرسانی رویا اعمال شد.",
diff --git a/locales/fr-FR/home.json b/locales/fr-FR/home.json
index 431a02ff39c..7e398184b6e 100644
--- a/locales/fr-FR/home.json
+++ b/locales/fr-FR/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Ignorer",
"brief.action.retry": "Réessayer",
"brief.action.upgrade": "Mettre à niveau le plan",
+ "brief.actionFailed": "Cela n'a pas fonctionné. Veuillez réessayer.",
"brief.addFeedback": "Partager un retour",
"brief.agentSignal.selfReview.applied.heading": "Mis à jour",
"brief.agentSignal.selfReview.applied.summary": "{{count}} mise à jour de rêve a été appliquée.",
diff --git a/locales/it-IT/home.json b/locales/it-IT/home.json
index 699ab056247..49de7c7d5c1 100644
--- a/locales/it-IT/home.json
+++ b/locales/it-IT/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Ignora",
"brief.action.retry": "Riprova",
"brief.action.upgrade": "Aggiorna piano",
+ "brief.actionFailed": "Non è andato a buon fine. Per favore, riprova.",
"brief.addFeedback": "Condividi feedback",
"brief.agentSignal.selfReview.applied.heading": "Aggiornato",
"brief.agentSignal.selfReview.applied.summary": "{{count}} aggiornamento del sogno è stato applicato.",
diff --git a/locales/ja-JP/home.json b/locales/ja-JP/home.json
index 730b1b5bc63..f523e21cb7e 100644
--- a/locales/ja-JP/home.json
+++ b/locales/ja-JP/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "無視する",
"brief.action.retry": "再試行",
"brief.action.upgrade": "プランをアップグレード",
+ "brief.actionFailed": "送信できませんでした。もう一度お試しください。",
"brief.addFeedback": "フィードバックを共有",
"brief.agentSignal.selfReview.applied.heading": "更新済み",
"brief.agentSignal.selfReview.applied.summary": "{{count}} 件の夢の更新が適用されました。",
diff --git a/locales/ko-KR/home.json b/locales/ko-KR/home.json
index 2518e143a1c..7eef5fbc253 100644
--- a/locales/ko-KR/home.json
+++ b/locales/ko-KR/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "무시",
"brief.action.retry": "다시 시도",
"brief.action.upgrade": "플랜 업그레이드",
+ "brief.actionFailed": "작업이 실패했습니다. 다시 시도해 주세요.",
"brief.addFeedback": "피드백 공유",
"brief.agentSignal.selfReview.applied.heading": "업데이트됨",
"brief.agentSignal.selfReview.applied.summary": "{{count}}개의 꿈 업데이트가 적용되었습니다.",
diff --git a/locales/nl-NL/home.json b/locales/nl-NL/home.json
index c877bbed950..c1622b06b88 100644
--- a/locales/nl-NL/home.json
+++ b/locales/nl-NL/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Negeren",
"brief.action.retry": "Opnieuw proberen",
"brief.action.upgrade": "Upgrade plan",
+ "brief.actionFailed": "Dat is niet gelukt. Probeer het opnieuw.",
"brief.addFeedback": "Feedback delen",
"brief.agentSignal.selfReview.applied.heading": "Bijgewerkt",
"brief.agentSignal.selfReview.applied.summary": "{{count}} droomupdate is toegepast.",
diff --git a/locales/pl-PL/home.json b/locales/pl-PL/home.json
index 7e02d7e131f..2b82ec28148 100644
--- a/locales/pl-PL/home.json
+++ b/locales/pl-PL/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Ignoruj",
"brief.action.retry": "Ponów próbę",
"brief.action.upgrade": "Zmień plan",
+ "brief.actionFailed": "Nie udało się. Spróbuj ponownie.",
"brief.addFeedback": "Prześlij opinię",
"brief.agentSignal.selfReview.applied.heading": "Zaktualizowano",
"brief.agentSignal.selfReview.applied.summary": "Zastosowano {{count}} aktualizację snu.",
diff --git a/locales/pt-BR/home.json b/locales/pt-BR/home.json
index 8dc5f394b86..2745a1439f8 100644
--- a/locales/pt-BR/home.json
+++ b/locales/pt-BR/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Ignorar",
"brief.action.retry": "Tentar novamente",
"brief.action.upgrade": "Atualizar plano",
+ "brief.actionFailed": "Isso não deu certo. Por favor, tente novamente.",
"brief.addFeedback": "Compartilhar feedback",
"brief.agentSignal.selfReview.applied.heading": "Atualizado",
"brief.agentSignal.selfReview.applied.summary": "{{count}} atualização de sonho foi aplicada.",
diff --git a/locales/ru-RU/home.json b/locales/ru-RU/home.json
index 0c19371723a..f26537672c0 100644
--- a/locales/ru-RU/home.json
+++ b/locales/ru-RU/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Игнорировать",
"brief.action.retry": "Повторить",
"brief.action.upgrade": "Обновить план",
+ "brief.actionFailed": "Это не удалось. Пожалуйста, попробуйте еще раз.",
"brief.addFeedback": "Оставить отзыв",
"brief.agentSignal.selfReview.applied.heading": "Обновлено",
"brief.agentSignal.selfReview.applied.summary": "Применено {{count}} обновление мечты.",
diff --git a/locales/tr-TR/home.json b/locales/tr-TR/home.json
index aaff754d932..c486665c8c6 100644
--- a/locales/tr-TR/home.json
+++ b/locales/tr-TR/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Yoksay",
"brief.action.retry": "Yeniden dene",
"brief.action.upgrade": "Planı yükselt",
+ "brief.actionFailed": "Bu işlem gerçekleşmedi. Lütfen tekrar deneyin.",
"brief.addFeedback": "Geri bildirim paylaş",
"brief.agentSignal.selfReview.applied.heading": "Güncellendi",
"brief.agentSignal.selfReview.applied.summary": "{{count}} rüya güncellemesi uygulandı.",
diff --git a/locales/vi-VN/home.json b/locales/vi-VN/home.json
index c6f84756340..8db1203725a 100644
--- a/locales/vi-VN/home.json
+++ b/locales/vi-VN/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "Bỏ qua",
"brief.action.retry": "Thử lại",
"brief.action.upgrade": "Nâng cấp gói",
+ "brief.actionFailed": "Điều đó không thành công. Vui lòng thử lại.",
"brief.addFeedback": "Gửi phản hồi",
"brief.agentSignal.selfReview.applied.heading": "Đã cập nhật",
"brief.agentSignal.selfReview.applied.summary": "Đã áp dụng {{count}} cập nhật giấc mơ.",
diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.json
index f9eb6e8c7d2..d0016cbe27a 100644
--- a/locales/zh-CN/home.json
+++ b/locales/zh-CN/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "忽略",
"brief.action.retry": "重试",
"brief.action.upgrade": "升级方案",
+ "brief.actionFailed": "操作没有成功,请再试一次。",
"brief.addFeedback": "分享反馈",
"brief.agentSignal.selfReview.applied.heading": "已更新",
"brief.agentSignal.selfReview.applied.summary": "已应用 {{count}} 条夜间回顾更新。",
diff --git a/locales/zh-TW/home.json b/locales/zh-TW/home.json
index aa7546ace8c..6ae055b0865 100644
--- a/locales/zh-TW/home.json
+++ b/locales/zh-TW/home.json
@@ -11,6 +11,7 @@
"brief.action.ignore": "忽略",
"brief.action.retry": "重試",
"brief.action.upgrade": "升級方案",
+ "brief.actionFailed": "操作未成功,請再試一次。",
"brief.addFeedback": "分享意見回饋",
"brief.agentSignal.selfReview.applied.heading": "已更新",
"brief.agentSignal.selfReview.applied.summary": "已套用 {{count}} 個夢境更新。",
diff --git a/packages/locales/src/default/home.ts b/packages/locales/src/default/home.ts
index 61363ae8907..ee5f2423e64 100644
--- a/packages/locales/src/default/home.ts
+++ b/packages/locales/src/default/home.ts
@@ -12,6 +12,7 @@ export default {
'brief.action.ignore': 'Ignore',
'brief.action.retry': 'Retry',
'brief.action.upgrade': 'Upgrade plan',
+ 'brief.actionFailed': "That didn't go through. Please try again.",
'brief.agentSignal.selfReview.applied.heading': 'Updated',
'brief.agentSignal.selfReview.applied.summary': '{{count}} dream update was applied.',
'brief.agentSignal.selfReview.applied.summary_plural': '{{count}} dream updates were applied.',
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx
index 7d53ad872d5..0a9fa305bcb 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx
@@ -7,7 +7,7 @@ import {
Icon,
Text,
} from '@lobehub/ui';
-import { confirmModal } from '@lobehub/ui/base-ui';
+import { confirmModal, toast } from '@lobehub/ui/base-ui';
import { cssVar } from 'antd-style';
import { Check, ChevronDownIcon, ChevronUpIcon, MoreHorizontal, Trash } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
@@ -43,8 +43,23 @@ const TaskBriefCard = memo<TaskBriefCardProps>(
okButtonProps: { danger: true },
okText: t('brief.deleteConfirm.ok'),
onOk: async () => {
- await deleteBrief(brief.id);
- await onAfterDelete?.();
+ try {
+ await deleteBrief(brief.id);
+ } catch (error) {
+ // Same class as every other brief mutation: the tRPC client only
+ // console.errors non-401 failures, so without this the modal just
+ // closes and the row stays put with no explanation.
+ toast.error((error as Error)?.message || t('brief.actionFailed'));
+ return;
+ }
+
+ // The refresh runs after the delete has already landed — a rejection
+ // here leaves the view stale, it does not mean the delete failed.
+ try {
+ await onAfterDelete?.();
+ } catch (error) {
+ console.error('[TaskBriefCard] post-delete refresh failed', error);
+ }
},
title: t('brief.deleteConfirm.title'),
});
diff --git a/src/features/DailyBrief/BriefCardActions.tsx b/src/features/DailyBrief/BriefCardActions.tsx
index d210e67fb10..b6a9bd0076d 100644
--- a/src/features/DailyBrief/BriefCardActions.tsx
+++ b/src/features/DailyBrief/BriefCardActions.tsx
@@ -1,6 +1,6 @@
import { type BriefAction, DEFAULT_BRIEF_ACTIONS, type TaskStatus } from '@lobechat/types';
import { Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
-import { Button } from '@lobehub/ui/base-ui';
+import { Button, toast } from '@lobehub/ui/base-ui';
import { cssVar } from 'antd-style';
import { Check, SquarePen, Workflow } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
@@ -109,17 +109,59 @@ const BriefCardActions = memo<BriefCardActionsProps>(
[isResult, resultLabelKey, t],
);
+ /**
+ * Run a brief mutation and report a rejection to the user, returning whether
+ * it landed.
+ *
+ * The tRPC client only console.errors non-401 failures, so without the toast
+ * a rejected action (permission denied, brief no longer reachable, network)
+ * reads as a dead button — the user clicks and nothing at all happens.
+ */
+ const runMutation = useCallback(
+ async (mutate: () => Promise<unknown>): Promise<boolean> => {
+ try {
+ await mutate();
+ return true;
+ } catch (error) {
+ toast.error((error as Error)?.message || t('brief.actionFailed'));
+ return false;
+ }
+ },
+ [t],
+ );
+
+ /**
+ * Run the parent's post-action callbacks, which fire *after* the mutation has
+ * already landed (`refreshActiveTask` in `TaskActivities`, list revalidation
+ * elsewhere).
+ *
+ * A rejection here means the view is stale, not that the action failed.
+ * Reporting it as a failure would tell the user to retry a resolve that
+ * already succeeded — and for feedback, to re-send the comment and re-run the
+ * task a second time.
+ */
+ const refreshAfter = useCallback(
+ async (...refreshers: (undefined | (() => void | Promise<void>))[]) => {
+ try {
+ for (const refresh of refreshers) await refresh?.();
+ } catch (error) {
+ console.error('[BriefCardActions] post-action refresh failed', error);
+ }
+ },
+ [],
+ );
+
const handleResolve = useCallback(
async (key: string) => {
setLoadingKey(key);
try {
- await resolveBrief(briefId, key);
- await onAfterResolve?.();
+ if (!(await runMutation(() => resolveBrief(briefId, key)))) return;
+ await refreshAfter(onAfterResolve);
} finally {
setLoadingKey(null);
}
},
- [briefId, resolveBrief, onAfterResolve],
+ [briefId, resolveBrief, onAfterResolve, runMutation, refreshAfter],
);
const handleCommentSubmit = useCallback(
@@ -129,8 +171,10 @@ const BriefCardActions = memo<BriefCardActionsProps>(
if (commentMode.type === 'comment') {
setLoadingKey(commentMode.key);
try {
- await resolveBrief(briefId, commentMode.key, text);
- await onAfterResolve?.();
+ // Keep the editor open on failure — closing it would discard text the
+ // user typed for an action that never landed.
+ if (!(await runMutation(() => resolveBrief(briefId, commentMode.key, text)))) return;
+ await refreshAfter(onAfterResolve);
} finally {
setLoadingKey(null);
}
@@ -138,9 +182,8 @@ const BriefCardActions = memo<BriefCardActionsProps>(
// Free-form feedback must resolve the brief (so the heartbeat
// re-arm gate stops blocking on this urgent brief) AND re-run
// the task so the agent picks up `resolvedComment` next turn.
- await submitFeedback(briefId, taskId, text);
- await onAfterAddComment?.();
- await onAfterResolve?.();
+ if (!(await runMutation(() => submitFeedback(briefId, taskId, text)))) return;
+ await refreshAfter(onAfterAddComment, onAfterResolve);
}
setCommentMode(null);
@@ -153,6 +196,8 @@ const BriefCardActions = memo<BriefCardActionsProps>(
taskId,
onAfterResolve,
onAfterAddComment,
+ runMutation,
+ refreshAfter,
],
);
diff --git a/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx b/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx
index 6449abc0f78..7ff627b84ad 100644
--- a/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx
+++ b/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx
@@ -1,5 +1,6 @@
import type { BriefAction } from '@lobechat/types';
-import { fireEvent, render, screen } from '@testing-library/react';
+import { toast } from '@lobehub/ui/base-ui';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactElement } from 'react';
import { MemoryRouter } from 'react-router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -29,7 +30,31 @@ vi.mock('react-i18next', () => ({
}),
}));
+// The real editor cannot be driven headlessly — `getDocument('markdown')` comes
+// back empty in jsdom, so its send button is a no-op and the submit paths would
+// be untestable. The stub keeps the affordances the other cases assert on.
+vi.mock('../CommentInput', () => ({
+ default: ({
+ onCancel,
+ onSubmit,
+ }: {
+ onCancel: () => void;
+ onSubmit: (text: string) => void | Promise<void>;
+ }) => (
+ <div>
+ <button type={'button'} onClick={onCancel}>
+ Cancel
+ </button>
+ <button title={'Submit feedback'} type={'button'} onClick={() => onSubmit('my feedback')}>
+ send
+ </button>
+ </div>
+ ),
+}));
+
const mockResolveBrief = vi.fn();
+const mockSubmitFeedback = vi.fn();
+const mockToastError = vi.spyOn(toast, 'error').mockReturnValue(undefined as never);
const sampleActions: BriefAction[] = [
{ key: 'approve', label: 'Approve', type: 'resolve' },
@@ -40,6 +65,7 @@ beforeEach(() => {
vi.clearAllMocks();
useBriefStore.setState({
resolveBrief: mockResolveBrief,
+ submitFeedback: mockSubmitFeedback,
});
});
@@ -79,8 +105,10 @@ describe('BriefCardActions', () => {
fireEvent.click(screen.getByText('Approve'));
expect(mockResolveBrief).toHaveBeenCalledWith('brief-1', 'approve');
- await Promise.resolve();
- expect(onAfterResolve).toHaveBeenCalled();
+ // `waitFor`, not a single microtask tick: the refresh runs after the
+ // mutation settles, so the number of awaits in between is an implementation
+ // detail this assertion must not encode.
+ await waitFor(() => expect(onAfterResolve).toHaveBeenCalled());
});
it('should hide action buttons when comment button clicked', () => {
@@ -187,6 +215,115 @@ describe('BriefCardActions', () => {
expect(screen.queryByText('Confirm', { exact: true })).not.toBeInTheDocument();
});
+ // LOBE-12704: the tRPC client only console.errors non-401 failures, so a
+ // rejected action used to read as a dead button — which is how "no permission"
+ // reached us as a bug report with no error on screen.
+ it('should surface the failure reason when a resolve action is rejected', async () => {
+ mockResolveBrief.mockRejectedValueOnce(
+ new Error('You do not have permission to perform this action.'),
+ );
+ const onAfterResolve = vi.fn();
+ renderWithRouter(
+ <BriefCardActions
+ actions={sampleActions}
+ briefId="brief-9"
+ briefType="decision"
+ onAfterResolve={onAfterResolve}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('Approve'));
+
+ await waitFor(() =>
+ expect(mockToastError).toHaveBeenCalledWith(
+ 'You do not have permission to perform this action.',
+ ),
+ );
+ expect(onAfterResolve).not.toHaveBeenCalled();
+ // Still actionable — a failed attempt must not leave the card in limbo.
+ expect(screen.getByText('Approve')).toBeInTheDocument();
+ });
+
+ it('should fall back to a generic message when the failure carries no reason', async () => {
+ // A network abort / non-Error rejection reaches the handler without a message.
+ mockResolveBrief.mockRejectedValueOnce({});
+ renderWithRouter(
+ <BriefCardActions actions={sampleActions} briefId="brief-10" briefType="decision" />,
+ );
+
+ fireEvent.click(screen.getByText('Approve'));
+
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith('brief.actionFailed'));
+ });
+
+ // The parent's refresh callbacks run *after* the mutation landed. Reporting
+ // their rejection as an action failure would tell the user to retry a resolve
+ // that already succeeded — and, on the feedback path, to re-send the comment
+ // and re-run the task a second time.
+ it('should not report a failure when only the post-resolve refresh rejects', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mockResolveBrief.mockResolvedValueOnce(undefined);
+ const onAfterResolve = vi.fn().mockRejectedValue(new Error('refresh failed'));
+ renderWithRouter(
+ <BriefCardActions
+ actions={sampleActions}
+ briefId="brief-11"
+ briefType="decision"
+ onAfterResolve={onAfterResolve}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('Approve'));
+
+ await waitFor(() => expect(onAfterResolve).toHaveBeenCalled());
+ expect(mockToastError).not.toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+
+ it('should close the feedback editor when the mutation lands but the refresh rejects', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mockSubmitFeedback.mockResolvedValueOnce(undefined);
+ const onAfterAddComment = vi.fn().mockRejectedValue(new Error('refresh failed'));
+ const { container } = renderWithRouter(
+ <BriefCardActions
+ actions={sampleActions}
+ briefId="brief-12"
+ briefType="decision"
+ taskId="task-1"
+ onAfterAddComment={onAfterAddComment}
+ />,
+ );
+
+ fireEvent.click(container.querySelector('.brief-comment-btn')!);
+ fireEvent.click(screen.getByTitle('Submit feedback'));
+
+ // Editor closed — leaving it open would invite a second send of feedback
+ // that already resolved the brief and re-ran the task.
+ await waitFor(() => expect(screen.getByText('Approve')).toBeInTheDocument());
+ expect(mockSubmitFeedback).toHaveBeenCalledWith('brief-12', 'task-1', 'my feedback');
+ expect(mockToastError).not.toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+
+ it('should keep the feedback editor open when the mutation itself fails', async () => {
+ mockSubmitFeedback.mockRejectedValueOnce(new Error('You do not have permission.'));
+ const { container } = renderWithRouter(
+ <BriefCardActions
+ actions={sampleActions}
+ briefId="brief-13"
+ briefType="decision"
+ taskId="task-1"
+ />,
+ );
+
+ fireEvent.click(container.querySelector('.brief-comment-btn')!);
+ fireEvent.click(screen.getByTitle('Submit feedback'));
+
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith('You do not have permission.'));
+ // Still open — closing would discard the text the user typed.
+ expect(screen.getByTitle('Submit feedback')).toBeInTheDocument();
+ });
+
it('should label the result action "Confirm" when the parent task is parked at status="scheduled"', () => {
renderWithRouter(
<BriefCardActions
diff --git a/src/features/Home/HomeModeContent.tsx b/src/features/Home/HomeModeContent.tsx
index 72aa89656e0..c3d3ba7737b 100644
--- a/src/features/Home/HomeModeContent.tsx
+++ b/src/features/Home/HomeModeContent.tsx
@@ -272,9 +272,9 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSugges
[inboxTopics.running, myId],
);
const useFetchBriefs = useBriefStore((s) => s.useFetchBriefs);
- const briefsSWR = useFetchBriefs(isLogin);
- const briefs = useBriefStore(briefListSelectors.briefs);
- const briefsInit = useBriefStore(briefListSelectors.isBriefsInit);
+ const briefsSWR = useFetchBriefs(isLogin, cacheScope);
+ const briefs = useBriefStore(briefListSelectors.briefs(cacheScope));
+ const briefsInit = useBriefStore(briefListSelectors.isBriefsInit(cacheScope));
const needsYouCount = useMemo(() => splitBriefs(briefs).needsYou.length, [briefs]);
const topicRecents = recentsSWR.data ?? [];
diff --git a/src/features/HomeInbox/MarkAllReadButton.tsx b/src/features/HomeInbox/MarkAllReadButton.tsx
index 68171f28718..8de4172cf44 100644
--- a/src/features/HomeInbox/MarkAllReadButton.tsx
+++ b/src/features/HomeInbox/MarkAllReadButton.tsx
@@ -1,4 +1,4 @@
-import { Button } from '@lobehub/ui/base-ui';
+import { Button, toast } from '@lobehub/ui/base-ui';
import { CheckCheckIcon } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -24,10 +24,14 @@ const MarkAllReadButton = memo<MarkAllReadButtonProps>(({ news }) => {
setLoading(true);
try {
await resolveBriefsAsRead(news.map((brief) => brief.id));
+ } catch (error) {
+ // Without this the button just stops spinning and the pile stays put —
+ // the tRPC client only console.errors non-401 failures.
+ toast.error((error as Error)?.message || t('brief.actionFailed'));
} finally {
setLoading(false);
}
- }, [news, resolveBriefsAsRead]);
+ }, [news, resolveBriefsAsRead, t]);
return (
<Button
diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsx
index e6dafeff2e3..437809c4582 100644
--- a/src/features/HomeInbox/index.tsx
+++ b/src/features/HomeInbox/index.tsx
@@ -11,6 +11,7 @@ import GroupBlock from '@/features/Home/components/GroupBlock';
import { homeType } from '@/features/Home/components/homeType';
import RailCard from '@/features/Home/components/RailCard';
import Recommendations, { useRecommendationsVisible } from '@/features/Recommendations';
+import { useCacheScope } from '@/libs/swr/useCacheScope';
import { useBriefStore } from '@/store/brief';
import { briefListSelectors } from '@/store/brief/selectors';
import { useUserStore } from '@/store/user';
@@ -98,10 +99,14 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
const isLogin = useUserStore(authSelectors.isLogin);
const myId = useUserStore(userProfileSelectors.userId);
+ // Briefs are per-user AND per-workspace rows, so the feed is read through the
+ // active cache scope — a list left over from the previous workspace holds ids
+ // this one cannot resolve, and every action on it would fail silently.
+ const cacheScope = useCacheScope();
const useFetchBriefs = useBriefStore((s) => s.useFetchBriefs);
- const briefsSWR = useFetchBriefs(isLogin);
- const briefs = useBriefStore(briefListSelectors.briefs);
- const isBriefsInit = useBriefStore(briefListSelectors.isBriefsInit);
+ const briefsSWR = useFetchBriefs(isLogin, cacheScope);
+ const briefs = useBriefStore(briefListSelectors.briefs(cacheScope));
+ const isBriefsInit = useBriefStore(briefListSelectors.isBriefsInit(cacheScope));
const topics = useHomeInboxTopics(isLogin);
const recommendationsVisible = useRecommendationsVisible();
diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts
index 785c977a932..42433edb8af 100644
--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts
+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts
@@ -53,9 +53,16 @@ vi.mock('swr', () => ({
default: mockUseSWR,
}));
+// The brief feed is read through the active cache scope — a list fetched for
+// another user/workspace is treated as not-loaded (see `briefListSelectors`).
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ useCacheScope: () => 'user-1:personal',
+}));
+
vi.mock('@/store/brief', () => ({
useBriefStore: (selector: (state: any) => unknown) =>
selector({
+ briefsScope: 'user-1:personal',
isBriefsInit: true,
useFetchBriefs: mockUseFetchBriefs,
}),
diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts
index 60cdcc20ad4..35dfbf14ea5 100644
--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts
+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts
@@ -12,6 +12,7 @@ import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
import { taskTemplateKeys } from '@/libs/swr/keys';
+import { useCacheScope } from '@/libs/swr/useCacheScope';
import { taskTemplateService } from '@/services/taskTemplate';
import { useBriefStore } from '@/store/brief';
import { briefListSelectors } from '@/store/brief/selectors';
@@ -163,10 +164,11 @@ export function useDailyBriefRecommendationsUI(
const locale = i18n.resolvedLanguage || i18n.language;
const isLogin = useUserStore(authSelectors.isLogin);
+ const cacheScope = useCacheScope();
const useFetchBriefs = useBriefStore((s) => s.useFetchBriefs);
- useFetchBriefs(isLogin);
+ useFetchBriefs(isLogin, cacheScope);
- const isInit = useBriefStore(briefListSelectors.isBriefsInit);
+ const isInit = useBriefStore(briefListSelectors.isBriefsInit(cacheScope));
const interestKeys = useResolvedInterestKeys();
const [refreshSeed, setRefreshSeed] = useSessionStorageState<string>(REFRESH_SEED_STORAGE_KEY, {
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 3222bfeb105..753c5720d18 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -309,7 +309,12 @@ export const workKeys = {
// ---- brief --------------------------------------------------------------
export const briefKeys = {
- list: def('brief:list', (isLogin: boolean) => ['brief:list', isLogin]),
+ /**
+ * Unresolved brief feed, keyed by login + identity scope. Briefs are per-user
+ * AND per-workspace rows, so an entry fetched in one scope must never be
+ * served in another — its ids are unreachable there.
+ */
+ list: def('brief:list', (isLogin: boolean, scope: string) => ['brief:list', isLogin, scope]),
};
// ---- home inbox ---------------------------------------------------------
diff --git a/src/libs/swr/useClientDataSWRWithSync.ts b/src/libs/swr/useClientDataSWRWithSync.ts
index 46fbf723245..fc3257bec9f 100644
--- a/src/libs/swr/useClientDataSWRWithSync.ts
+++ b/src/libs/swr/useClientDataSWRWithSync.ts
@@ -31,10 +31,14 @@ interface UseClientDataSWRWithSyncOptions<T> extends SWRConfiguration<T> {
/**
* Enhanced version of useClientDataSWR with automatic cache data sync to Zustand store
*
+ * Always build the key from its `*Keys` factory in `./keys`, never as a literal
+ * tuple — an imperative `mutate` that hand-writes the same shape drifts silently
+ * and warms an entry no subscriber ever reads.
+ *
* @example
* ```ts
* useClientDataSWRWithSync(
- * isLogin ? ['fetchAgentList', isLogin] : null,
+ * isLogin ? agentKeys.list(isLogin) : null,
* () => homeService.getSidebarAgentList(),
* {
* onData: (data) => {
diff --git a/src/store/brief/slices/list/action.test.ts b/src/store/brief/slices/list/action.test.ts
index a1178953e4e..c95aa5ede7d 100644
--- a/src/store/brief/slices/list/action.test.ts
+++ b/src/store/brief/slices/list/action.test.ts
@@ -47,14 +47,16 @@ describe('BriefListActionImpl', () => {
vi.restoreAllMocks();
});
+ const SCOPE = 'user-1:workspace-1';
+
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));
+ const cacheKey = JSON.stringify(briefKeys.list(true, SCOPE));
cache.set(cacheKey, initialBriefs);
- const state = { briefs: initialBriefs, isBriefsInit: true };
+ const state = { briefs: initialBriefs, briefsScope: SCOPE, 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({
@@ -69,4 +71,49 @@ describe('BriefListActionImpl', () => {
state.briefs = cache.get(cacheKey) ?? [];
expect(state.briefs).not.toContainEqual(expect.objectContaining({ id: resolvedBrief.id }));
});
+
+ // The write-back must land on the entry the list came from. Keying it off the
+ // live scope instead would, on a mid-flight workspace switch, seed the new
+ // workspace's bucket and cache key with the previous workspace's briefs.
+ it('should abandon the write when the workspace changed while the request was in flight', async () => {
+ const brief = createBrief('brief-1');
+ const nextScopeBrief = createBrief('brief-from-next-workspace');
+ const state = { briefs: [brief], briefsScope: SCOPE, 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').mockImplementation(async () => {
+ // The switch lands before the response does.
+ Object.assign(state, { briefs: [nextScopeBrief], briefsScope: 'user-1:workspace-2' });
+ return { data: [brief.id] } as never;
+ });
+
+ await action.resolveBriefsAsRead([brief.id]);
+
+ expect(state.briefs).toEqual([nextScopeBrief]);
+ expect(cache.size).toBe(0);
+ });
+
+ it('should not write an unstamped brief list into any scope entry', async () => {
+ const brief = createBrief('brief-1');
+ const state = { briefs: [brief], briefsScope: undefined, 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: [brief.id] } as never);
+
+ await action.resolveBriefsAsRead([brief.id]);
+
+ expect(set).not.toHaveBeenCalled();
+ expect(cache.size).toBe(0);
+ });
+
+ it('should skip the store write when deleting a brief the list no longer holds', async () => {
+ const state = { briefs: [createBrief('brief-1')], briefsScope: SCOPE, 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, 'delete').mockResolvedValue(undefined as never);
+
+ await action.deleteBrief('brief-from-another-workspace');
+
+ expect(set).not.toHaveBeenCalled();
+ });
});
diff --git a/src/store/brief/slices/list/action.ts b/src/store/brief/slices/list/action.ts
index 955b9da25d9..7e68aeaab3e 100644
--- a/src/store/brief/slices/list/action.ts
+++ b/src/store/brief/slices/list/action.ts
@@ -1,8 +1,10 @@
import isEqual from 'fast-deep-equal';
+import { useEffect } from 'react';
import { type SWRResponse } from 'swr';
import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
import { briefKeys } from '@/libs/swr/keys';
+import { getCacheScope } from '@/libs/swr/useCacheScope';
import { briefService } from '@/services/brief';
import { taskService } from '@/services/task';
import { type BriefStore } from '@/store/brief/store';
@@ -39,7 +41,14 @@ export class BriefListActionImpl {
deleteBrief = async (id: string) => {
await briefService.delete(id);
- const briefs = this.#get().briefs.filter((b) => b.id !== id);
+
+ const previous = this.#get().briefs;
+ const briefs = previous.filter((b) => b.id !== id);
+ // Nothing removed — the brief was already gone, or the list has since been
+ // replaced by another scope's (a workspace switch while the request was in
+ // flight). Either way, writing an identical list only churns subscribers.
+ if (briefs.length === previous.length) return;
+
this.#set({ briefs }, false, n('deleteBrief'));
};
@@ -57,13 +66,25 @@ export class BriefListActionImpl {
resolveBriefsAsRead = async (ids: string[]) => {
if (ids.length === 0) return;
+ // Capture the scope these ids belong to *before* awaiting. Unlike the
+ // id-keyed mutations above, this one rewrites the whole list and patches an
+ // SWR entry, so a workspace switch mid-request would splice the previous
+ // partition's briefs into the next one's bucket and cache key — the exact
+ // leak this slice exists to prevent.
+ const scope = this.#get().briefsScope;
+
const result = await briefService.resolveManyAsRead(ids);
const resolvedIds = new Set(result.data);
if (resolvedIds.size === 0) return;
- const briefs = this.#get().briefs.filter((b) => !resolvedIds.has(b.id));
+ const state = this.#get();
+ // Unstamped, or the scope moved while the request was in flight: the switch
+ // already cleared the bucket, so there is nothing of ours left to patch.
+ if (scope === undefined || state.briefsScope !== scope) return;
+
+ const briefs = state.briefs.filter((b) => !resolvedIds.has(b.id));
this.#set({ briefs }, false, n('resolveBriefsAsRead'));
- void mutate(briefKeys.list(true), briefs, { revalidate: false });
+ void mutate(briefKeys.list(true, scope), briefs, { revalidate: false });
};
resolveBrief = async (id: string, action?: string, comment?: string) => {
@@ -91,18 +112,51 @@ export class BriefListActionImpl {
}
};
- useFetchBriefs = (isLogin: boolean | undefined): SWRResponse<BriefItem[]> => {
+ /**
+ * `scope` is the identity partition (`${userId}:${workspaceId}`) the caller is
+ * rendering. Briefs are per-user AND per-workspace rows, so carrying a list
+ * across a scope change hands the user cards whose ids the server can no
+ * longer resolve — every action on them 404s, and the tRPC client only logs
+ * non-401 failures, so the surface just stops responding. Dropping the bucket
+ * the moment the scope changes is what keeps that from happening.
+ */
+ useFetchBriefs = (isLogin: boolean | undefined, scope: string): SWRResponse<BriefItem[]> => {
+ // Effect (not render-time set) because this writes another store; the
+ // scope-aware selectors already keep the foreign list off screen in the
+ // frame before it runs.
+ useEffect(() => {
+ const { briefsScope } = this.#get();
+ if (briefsScope === undefined || briefsScope === scope) return;
+
+ this.#set(
+ { briefs: [], briefsScope: undefined, isBriefsInit: false },
+ false,
+ n('useFetchBriefs/scopeChanged'),
+ );
+ }, [scope]);
+
return useClientDataSWRWithSync<BriefItem[]>(
- isLogin === true ? briefKeys.list(isLogin) : null,
+ isLogin === true ? briefKeys.list(isLogin, scope) : null,
async () => {
const result = await briefService.listUnresolved();
return result.data as BriefItem[];
},
{
onData: (data) => {
- if (this.#get().isBriefsInit && isEqual(this.#get().briefs, data)) return;
-
- this.#set({ briefs: data, isBriefsInit: true }, false, n('useFetchBriefs/onData'));
+ // A response in flight across a scope switch answers for the previous
+ // partition — writing it back would re-seed exactly the unreachable
+ // list this hook exists to clear.
+ if (getCacheScope() !== scope) return;
+
+ const state = this.#get();
+ if (state.isBriefsInit && state.briefsScope === scope && isEqual(state.briefs, data))
+ return;
+
+ this.#set(
+ { briefs: data, briefsScope: scope, isBriefsInit: true },
+ false,
+ n('useFetchBriefs/onData'),
+ );
},
},
);
diff --git a/src/store/brief/slices/list/initialState.ts b/src/store/brief/slices/list/initialState.ts
index be3fd1a8d03..88370f9db96 100644
--- a/src/store/brief/slices/list/initialState.ts
+++ b/src/store/brief/slices/list/initialState.ts
@@ -2,10 +2,20 @@ import { type BriefItem } from '@/store/brief/types';
export interface BriefListState {
briefs: BriefItem[];
+ /**
+ * Cache scope (`${userId}:${workspaceId}`) the current `briefs` were fetched
+ * for. Briefs are per-user AND per-workspace rows, so a list carried across a
+ * workspace switch is not merely stale — every id in it is unreachable in the
+ * new scope, and acting on one 404s. Readers compare against the live scope
+ * and treat a mismatch as "not loaded yet" rather than rendering rows the
+ * server will refuse.
+ */
+ briefsScope?: string;
isBriefsInit: boolean;
}
export const initialBriefListState: BriefListState = {
briefs: [],
+ briefsScope: undefined,
isBriefsInit: false,
};
diff --git a/src/store/brief/slices/list/selectors.test.ts b/src/store/brief/slices/list/selectors.test.ts
index b01f9480327..1a9338fb3c3 100644
--- a/src/store/brief/slices/list/selectors.test.ts
+++ b/src/store/brief/slices/list/selectors.test.ts
@@ -5,6 +5,9 @@ import { type BriefStore } from '@/store/brief/store';
import { initialBriefListState } from './initialState';
import { briefListSelectors } from './selectors';
+const SCOPE = 'user-1:workspace-1';
+const OTHER_SCOPE = 'user-1:workspace-2';
+
const createState = (overrides: Partial<BriefStore> = {}) =>
({
...initialBriefListState,
@@ -15,37 +18,62 @@ describe('briefListSelectors', () => {
describe('briefs', () => {
it('should return empty array by default', () => {
const state = createState();
- expect(briefListSelectors.briefs(state)).toEqual([]);
+ expect(briefListSelectors.briefs(SCOPE)(state)).toEqual([]);
});
- it('should return briefs from state', () => {
+ it('should return briefs fetched for the active scope', () => {
const briefs = [{ id: 'brief-1', title: 'Test' }] as any;
- const state = createState({ briefs });
- expect(briefListSelectors.briefs(state)).toBe(briefs);
+ const state = createState({ briefs, briefsScope: SCOPE });
+ expect(briefListSelectors.briefs(SCOPE)(state)).toBe(briefs);
+ });
+
+ // The reported bug: after a workspace switch the previous scope's briefs
+ // stayed on screen, and every action on them 404'd silently.
+ it('should hide briefs fetched for another scope', () => {
+ const briefs = [{ id: 'brief-1', title: 'Test' }] as any;
+ const state = createState({ briefs, briefsScope: OTHER_SCOPE, isBriefsInit: true });
+ expect(briefListSelectors.briefs(SCOPE)(state)).toEqual([]);
+ });
+
+ it('should keep a stable identity across scope misses so subscribers do not churn', () => {
+ const state = createState({ briefs: [{ id: 'brief-1' }] as any, briefsScope: OTHER_SCOPE });
+ expect(briefListSelectors.briefs(SCOPE)(state)).toBe(briefListSelectors.briefs(SCOPE)(state));
});
});
describe('hasBriefs', () => {
it('should return false when empty', () => {
const state = createState();
- expect(briefListSelectors.hasBriefs(state)).toBe(false);
+ expect(briefListSelectors.hasBriefs(SCOPE)(state)).toBe(false);
});
it('should return true when has briefs', () => {
- const state = createState({ briefs: [{ id: 'brief-1' }] as any });
- expect(briefListSelectors.hasBriefs(state)).toBe(true);
+ const state = createState({ briefs: [{ id: 'brief-1' }] as any, briefsScope: SCOPE });
+ expect(briefListSelectors.hasBriefs(SCOPE)(state)).toBe(true);
+ });
+
+ it('should return false when the briefs belong to another scope', () => {
+ const state = createState({ briefs: [{ id: 'brief-1' }] as any, briefsScope: OTHER_SCOPE });
+ expect(briefListSelectors.hasBriefs(SCOPE)(state)).toBe(false);
});
});
describe('isBriefsInit', () => {
it('should return false by default', () => {
const state = createState();
- expect(briefListSelectors.isBriefsInit(state)).toBe(false);
+ expect(briefListSelectors.isBriefsInit(SCOPE)(state)).toBe(false);
+ });
+
+ it('should return true when initialized for the active scope', () => {
+ const state = createState({ briefsScope: SCOPE, isBriefsInit: true });
+ expect(briefListSelectors.isBriefsInit(SCOPE)(state)).toBe(true);
});
- it('should return true when initialized', () => {
- const state = createState({ isBriefsInit: true });
- expect(briefListSelectors.isBriefsInit(state)).toBe(true);
+ // Reporting "loaded" for a foreign scope is what suppressed the skeleton and
+ // let the unreachable cards render.
+ it('should report not-initialized when the loaded scope differs', () => {
+ const state = createState({ briefsScope: OTHER_SCOPE, isBriefsInit: true });
+ expect(briefListSelectors.isBriefsInit(SCOPE)(state)).toBe(false);
});
});
});
diff --git a/src/store/brief/slices/list/selectors.ts b/src/store/brief/slices/list/selectors.ts
index 775545965f8..e9546621c40 100644
--- a/src/store/brief/slices/list/selectors.ts
+++ b/src/store/brief/slices/list/selectors.ts
@@ -1,8 +1,26 @@
import { type BriefStore } from '@/store/brief/store';
+import { type BriefItem } from '@/store/brief/types';
-const briefs = (s: BriefStore) => s.briefs;
-const hasBriefs = (s: BriefStore) => s.briefs.length > 0;
-const isBriefsInit = (s: BriefStore) => s.isBriefsInit;
+/** Stable identity so a scope miss never churns `shallow`-compared subscribers. */
+const EMPTY_BRIEFS: BriefItem[] = [];
+
+/**
+ * Briefs are per-user AND per-workspace rows. A list left over from another
+ * scope is not merely stale — every id in it is unreachable now, so acting on
+ * one 404s while the UI shows nothing (the tRPC client only logs non-401
+ * failures). Selectors therefore report a scope miss as "not loaded yet", which
+ * makes the surface paint its skeleton instead of unreachable cards.
+ */
+const isScopeCurrent = (s: BriefStore, scope: string) => s.briefsScope === scope;
+
+const briefs = (scope: string) => (s: BriefStore) =>
+ isScopeCurrent(s, scope) ? s.briefs : EMPTY_BRIEFS;
+
+const hasBriefs = (scope: string) => (s: BriefStore) =>
+ isScopeCurrent(s, scope) && s.briefs.length > 0;
+
+const isBriefsInit = (scope: string) => (s: BriefStore) =>
+ isScopeCurrent(s, scope) && s.isBriefsInit;
export const briefListSelectors = {
briefs,