🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(goal): sync island dismissals across clients (#22882)
Rdmclin2a8d7733ecdc5
diff --git a/apps/server/src/routers/lambda/user/index.procedures.test.ts b/apps/server/src/routers/lambda/user/index.procedures.test.tsindex ae6bdc8b197..827d1709e01 100644--- a/apps/server/src/routers/lambda/user/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/user/index.procedures.test.ts@@ -25,6 +25,7 @@ function expected(): Array<[name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]> {return [+ ['addIslandDismissals', 'mutation', 11],['confirmOnboardingUnderstanding', 'mutation', 14],['createOnboardingTasks', 'mutation', 13],['finishOnboarding', 'mutation', 11],diff --git a/apps/server/src/routers/lambda/user/settings.ts b/apps/server/src/routers/lambda/user/settings.tsindex 740026ed4e0..9d0d8ef06ac 100644--- a/apps/server/src/routers/lambda/user/settings.ts+++ b/apps/server/src/routers/lambda/user/settings.ts@@ -1,4 +1,5 @@import { hasApiKeyScope, isFullAccessApiKey } from '@lobechat/const/apiKeyScope';+import { MAX_ISLAND_DISMISSALS } from '@lobechat/const/goal';import type { UserSettings } from '@lobechat/types';import {NotificationSettingsSchema,@@ -30,6 +31,16 @@ const hasMemberSettingChange = (input: Partial<UserSettings>) =>MEMBER_SETTING_KEYS.some((key) => input[key] !== undefined);export const settingsRouter = router({+ /**+ * Record goal asks the user waved off the approval island. Kept server-side+ * so every client of the account stops showing them; the goal island reads+ * leave these keys out. Append-only, so it never takes the whole preference.+ */+ addIslandDismissals: userProcedure+ .input(+ z.object({ keys: z.array(z.string().min(1).max(512)).min(1).max(MAX_ISLAND_DISMISSALS) }),+ )+ .mutation(async ({ ctx, input }) => ctx.userModel.addIslandDismissals(input.keys)),getNotificationSettings: userProcedure.query(async ({ ctx }) => {return ctx.userModel.getNotificationSetting();}),diff --git a/apps/server/src/services/goal/GoalService/__tests__/islandDismissals.test.ts b/apps/server/src/services/goal/GoalService/__tests__/islandDismissals.test.tsnew file mode 100644index 00000000000..e3a9815a314--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/islandDismissals.test.ts@@ -0,0 +1,70 @@+// @vitest-environment node+import {+ goalClarificationIslandKey,+ goalDecisionIslandKey,+ goalSignOffIslandKey,+} from '@lobechat/const/goal';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { UserModel } from '@/database/models/user';+import { GoalRepository } from '@/database/repositories/goal';+import type { LobeChatDatabase } from '@/database/type';++import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';+import type { GoalBriefService } from '../../goalBriefs';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-island-dismissals-user';++registerGoalServiceTestCleanup(serverDB, userId);++const dismiss = (keys: string[]) => new UserModel(serverDB, userId).addIslandDismissals(keys);++describe('GoalService island dismissals', () => {+ it('stops asking a dismissed clarification round on every client, but keeps it on the goal', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ assumptions: [],+ problemStatement: '写发布说明',+ questions: [{ assumption: '终端用户', blocking: true, options: [], question: '给谁看?' }],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: '写', title: '撰写' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Release notes' });+ await service.tick(graph.goal.id);+ const [round] = await service.pendingClarifications();++ // Another round of the same goal is a different ask and still shows.+ await dismiss([goalClarificationIslandKey({ goalId: graph.goal.id, questions: [] })]);+ expect(await service.pendingClarifications()).toHaveLength(1);++ await dismiss([goalClarificationIslandKey(round)]);+ // A fresh service stands in for another client of the same account.+ expect(await new GoalService(serverDB, userId).pendingClarifications()).toEqual([]);+ // The question itself is still open, so the goal page keeps asking it.+ const open = await new GoalRepository(serverDB, userId).listPendingClarifications();+ expect(open.map((row) => row.decisionId)).toEqual([round.questions[0].decisionId]);+ });++ it('leaves dismissed gates and sign-offs out of the island list', async () => {+ const decision = (decisionId: string) => ({ decisionId, goalId: 'g1', options: null });+ const service = new GoalService(serverDB, userId);+ const internals = service as unknown as { briefs: GoalBriefService; goalModel: GoalRepository };+ vi.spyOn(internals.goalModel, 'listPendingDecisions').mockResolvedValue([+ decision('d1'),+ decision('d2'),+ ] as any);+ vi.spyOn(internals.briefs, 'listOpenSignOffs').mockResolvedValue([+ { acceptanceId: 'a1' },+ { acceptanceId: 'a2' },+ ] as any);++ await dismiss([goalDecisionIslandKey('d1'), goalSignOffIslandKey('a2')]);++ const island = await service.pendingForIsland();+ expect(island.decisions.map((row) => row.decisionId)).toEqual(['d2']);+ expect(island.signOffs.map((row) => row.acceptanceId)).toEqual(['a1']);+ });+});diff --git a/apps/server/src/services/goal/GoalService/reads.ts b/apps/server/src/services/goal/GoalService/reads.tsindex 92b0bd8a77c..2f67df31c39 100644--- a/apps/server/src/services/goal/GoalService/reads.ts+++ b/apps/server/src/services/goal/GoalService/reads.ts@@ -1,3 +1,8 @@+import {+ goalClarificationIslandKey,+ goalDecisionIslandKey,+ goalSignOffIslandKey,+} from '@lobechat/const/goal';import type {GoalDecisionOption,GoalEventEntityType,@@ -11,6 +16,7 @@ import { TRPCError } from '@trpc/server';import pMap from 'p-map';import { AgentOperationModel } from '@/database/models/agentOperation';+import { UserModel } from '@/database/models/user';import { classifyRunFailure, QUOTA_RESET_MARGIN_MS } from '../recoveryPolicy';import { GoalReportStore } from '../reportStore';@@ -284,20 +290,35 @@ export const status = async (* waiting on the person (clarification rounds have their own form) and the* finished goals waiting for their sign-off.*/+/**+ * The asks this user waved off the island, on any of their clients. Only the+ * island reads leave them out; the goal page and the Home inbox still show them.+ */+const islandDismissals = async (ctx: GoalServiceContext): Promise<Set<string>> =>+ new Set(await new UserModel(ctx.db, ctx.userId).getIslandDismissals());+export const pendingForIsland = async (ctx: GoalServiceContext) => {- const [decisions, signOffs] = await Promise.all([+ const [decisions, signOffs, dismissed] = await Promise.all([ctx.goalModel.listPendingDecisions(),ctx.briefs.listOpenSignOffs(),+ islandDismissals(ctx),]);return {- decisions: decisions.map((row) => ({ ...row, options: row.options ?? [] })),- signOffs,+ decisions: decisions+ .filter((row) => !dismissed.has(goalDecisionIslandKey(row.decisionId)))+ .map((row) => ({ ...row, options: row.options ?? [] })),+ signOffs: signOffs.filter(+ (signOff) => !dismissed.has(goalSignOffIslandKey(signOff.acceptanceId)),+ ),};};/** Pending clarifications grouped by goal, for surfaces outside the goal page. */export const pendingClarifications = async (ctx: GoalServiceContext) => {- const rows = await ctx.goalModel.listPendingClarifications();+ const [rows, dismissed] = await Promise.all([+ ctx.goalModel.listPendingClarifications(),+ islandDismissals(ctx),+ ]);const byGoal = new Map<string,{@@ -329,7 +350,7 @@ export const pendingClarifications = async (ctx: GoalServiceContext) => {});byGoal.set(row.goalId, group);}- return [...byGoal.values()];+ return [...byGoal.values()].filter((group) => !dismissed.has(goalClarificationIslandKey(group)));};export const requireGraph = async (ctx: GoalServiceContext, goalId: string) => {diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 457ad2066a7..93ec410ca24 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -475,6 +475,7 @@"gatewayMode.desc": "Run agents in the cloud through LobeHub's Agent Gateway. Tasks keep running even after you close the page.","globalApproval.collapse": "Collapse","globalApproval.dismiss": "Dismiss",+ "globalApproval.dismissFailed": "Couldn't dismiss it. Please try again.","globalApproval.dismissHint": "Hide it here; it stays on Home","globalApproval.dismissed": "Dismissed. You can still handle it from Home.","globalApproval.goToConversation": "Open conversation",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex ee8738ce8a1..d6853694809 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -475,6 +475,7 @@"gatewayMode.desc": "通过 LobeHub 的 Agent Gateway 在云端执行 Agent,即使关闭网页,任务也会继续运行。","globalApproval.collapse": "收起","globalApproval.dismiss": "忽略",+ "globalApproval.dismissFailed": "忽略失败,请重试","globalApproval.dismissHint": "只在这里隐藏,首页仍保留","globalApproval.dismissed": "已忽略,可在首页继续处理","globalApproval.goToConversation": "打开会话",diff --git a/packages/const/src/goal.test.ts b/packages/const/src/goal.test.tsindex 38e77f1307c..ffb6cbc8374 100644--- a/packages/const/src/goal.test.ts+++ b/packages/const/src/goal.test.ts@@ -5,7 +5,14 @@ import type {} from '@lobechat/types';import { describe, expect, expectTypeOf, it } from 'vitest';-import { goalRolloutTriggers, goalStatuses, goalSubjectTypes } from './goal';+import {+ goalClarificationIslandKey,+ goalRolloutTriggers,+ goalStatuses,+ goalSubjectTypes,+ MAX_ISLAND_DISMISSALS,+ mergeIslandDismissals,+} from './goal';describe('goal consts', () => {it('stays in sync with the @lobechat/types unions', () => {@@ -20,3 +27,30 @@ describe('goal consts', () => {expect(goalRolloutTriggers).toContain('canary');});});++describe('island dismissal keys', () => {+ const round = (goalId: string, decisionIds: string[]) => ({+ goalId,+ questions: decisionIds.map((decisionId) => ({ decisionId })),+ });++ it('tells two clarification rounds of the same goal apart', () => {+ expect(goalClarificationIslandKey(round('g1', ['d1', 'd2']))).not.toBe(+ goalClarificationIslandKey(round('g1', ['d3'])),+ );+ });++ it('adds only new keys and returns the same list when nothing is new', () => {+ const current = ['a'];+ expect(mergeIslandDismissals(current, ['b', 'a', 'b'])).toEqual(['a', 'b']);+ expect(mergeIslandDismissals(current, ['a'])).toBe(current);+ });++ it('keeps only the newest keys once the cap is reached', () => {+ const full = Array.from({ length: MAX_ISLAND_DISMISSALS }, (_, i) => `k${i}`);+ const next = mergeIslandDismissals(full, ['new']);+ expect(next).toHaveLength(MAX_ISLAND_DISMISSALS);+ expect(next[0]).toBe('k1');+ expect(next.at(-1)).toBe('new');+ });+});diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.tsindex 230ad8c5da2..9031fe4eb43 100644--- a/packages/const/src/goal.ts+++ b/packages/const/src/goal.ts@@ -280,3 +280,33 @@ export const GOAL_BATCH_RELEASE_QUESTION_TAIL = 'Release the next wave?';* language — mirroring the other coordinator question tails.*/export const GOAL_BATCH_BREAK_QUESTION_TAIL = 'How should this batch proceed?';++/**+ * Keys of the goal asks a person waved off the approval island. They are kept+ * on the server per user, so a card dismissed on one client stays dismissed on+ * every other client of the same account. Only the newest keys are kept: old+ * ones point at asks long since answered.+ */+export const MAX_ISLAND_DISMISSALS = 200;++export const goalDecisionIslandKey = (decisionId: string): string => `goal-decision:${decisionId}`;++export const goalSignOffIslandKey = (acceptanceId: string): string =>+ `goal-sign-off:${acceptanceId}`;++/**+ * A clarification round is keyed by its questions, not just its goal: waving+ * off one round must not hide the next round the same goal asks.+ */+export const goalClarificationIslandKey = (round: {+ goalId: string;+ questions: { decisionId: string }[];+}): string => `goal-clarify:${round.goalId}:${round.questions.map((q) => q.decisionId).join(',')}`;++/** Union of the stored and new keys, newest last, capped at {@link MAX_ISLAND_DISMISSALS}. */+export const mergeIslandDismissals = (current: string[], added: string[]): string[] => {+ const fresh = added.filter(+ (key, index) => !current.includes(key) && added.indexOf(key) === index,+ );+ return fresh.length === 0 ? current : [...current, ...fresh].slice(-MAX_ISLAND_DISMISSALS);+};diff --git a/packages/database/src/models/__tests__/user.islandDismissals.test.ts b/packages/database/src/models/__tests__/user.islandDismissals.test.tsnew file mode 100644index 00000000000..8d5db9b1c21--- /dev/null+++ b/packages/database/src/models/__tests__/user.islandDismissals.test.ts@@ -0,0 +1,101 @@+import { MAX_ISLAND_DISMISSALS } from '@lobechat/const/goal';+import { UserPreferenceSchema } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { UserModel } from '../user';++const userId = 'user-island-dismissals-test';++const serverDB: LobeChatDatabase = await getTestDB();+const userModel = new UserModel(serverDB, userId);++const readPreference = async () =>+ (await serverDB.query.users.findFirst({ where: eq(users.id, userId) }))?.preference as Record<+ string,+ unknown+ >;++describe('UserModel island dismissals', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId, preference: { topicGroupMode: 'byTime' } });+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ it('returns an empty list when nothing is stored', async () => {+ expect(await userModel.getIslandDismissals()).toEqual([]);+ });++ it('adds keys once and keeps the other preference fields', async () => {+ await userModel.addIslandDismissals(['goal-decision:d1']);+ const stored = await userModel.addIslandDismissals(['goal-decision:d1', 'goal-sign-off:a1']);++ expect(stored).toEqual(['goal-decision:d1', 'goal-sign-off:a1']);+ expect(await userModel.getIslandDismissals()).toEqual(stored);+ expect(await readPreference()).toMatchObject({ topicGroupMode: 'byTime' });+ });++ it('keeps only the newest keys once the cap is reached', async () => {+ const full = Array.from({ length: MAX_ISLAND_DISMISSALS }, (_, i) => `k${i}`);+ await userModel.addIslandDismissals(full);++ const stored = await userModel.addIslandDismissals(['newest']);++ expect(stored).toHaveLength(MAX_ISLAND_DISMISSALS);+ expect(stored[0]).toBe('k1');+ expect(stored.at(-1)).toBe('newest');+ });++ it('keeps both clients keys when they dismiss at the same time', async () => {+ const other = new UserModel(serverDB, userId);+ await Promise.all([+ userModel.addIslandDismissals(['from-web']),+ other.addIslandDismissals(['from-desktop']),+ ]);++ expect([...(await userModel.getIslandDismissals())].sort()).toEqual([+ 'from-desktop',+ 'from-web',+ ]);+ });++ it('keeps a dismissal that commits while a preference save waits on the row', async () => {+ let saving: Promise<void> | undefined;+ await serverDB.transaction(async (trx) => {+ await trx.select({ id: users.id }).from(users).where(eq(users.id, userId)).for('update');+ // On a real server this save starts while the dismissal below holds the+ // row; read without the lock, it would write the old JSON back over it.+ saving = userModel.updatePreference({ topicGroupMode: 'byProject' });+ await new Promise((resolve) => setTimeout(resolve, 100));+ await trx+ .update(users)+ .set({ preference: { islandDismissals: ['goal-decision:d1'], topicGroupMode: 'byTime' } })+ .where(eq(users.id, userId));+ });+ await saving;++ expect(await userModel.getIslandDismissals()).toEqual(['goal-decision:d1']);+ expect(await readPreference()).toMatchObject({ topicGroupMode: 'byProject' });+ });++ it('is not overwritten by a stale client saving its whole preference', async () => {+ await userModel.addIslandDismissals(['goal-decision:d1', 'goal-decision:d2']);++ // A client that loaded before d2 sends back its full preference object.+ const stale = UserPreferenceSchema.parse({+ islandDismissals: ['goal-decision:other'],+ topicGroupMode: 'byProject',+ });+ await userModel.updatePreference(stale);++ expect(await userModel.getIslandDismissals()).toEqual(['goal-decision:d1', 'goal-decision:d2']);+ expect(await readPreference()).toMatchObject({ topicGroupMode: 'byProject' });+ });+});diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex d8a5f49556a..2ac033265cf 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -1,3 +1,4 @@+import { mergeIslandDismissals } from '@lobechat/const/goal';import type {NotificationSettings,SSOProvider,@@ -510,27 +511,70 @@ export class UserModel {return notification;};- updatePreference = async (value: Partial<UserPreference>) => {- const user = await this.db.query.users.findFirst({ where: eq(users.id, this.userId) });- if (!user) return;+ /**+ * Read, change and write back `users.preference` while the row is locked.+ * Every preference writer goes through here: one that read the old JSON+ * without the lock would write it back over a concurrent change, such as an+ * island dismissal another client just added. Returns undefined when the+ * user does not exist.+ */+ private mutatePreference = async <T>(+ change: (prev: UserPreference) => { next: UserPreference; result: T },+ ): Promise<T | undefined> =>+ this.db.transaction(async (trx) => {+ const [user] = await trx+ .select({ preference: users.preference })+ .from(users)+ .where(eq(users.id, this.userId))+ .for('update');+ if (!user) return undefined;++ const prev = (user.preference || {}) as UserPreference;+ const { next, result } = change(prev);+ if (next !== prev) {+ await trx.update(users).set({ preference: next }).where(eq(users.id, this.userId));+ }+ return result;+ });- return this.db- .update(users)- .set({ preference: merge(user.preference, value) })- .where(eq(users.id, this.userId));+ updatePreference = async (value: Partial<UserPreference>) => {+ await this.mutatePreference((prev) => ({+ next: merge(prev, value) as UserPreference,+ result: undefined,+ }));};updateGuide = async (value: Partial<UserGuide>) => {- const user = await this.db.query.users.findFirst({ where: eq(users.id, this.userId) });- if (!user) return;+ await this.mutatePreference((prev) => ({+ next: { ...prev, guide: merge(prev.guide || {}, value) },+ result: undefined,+ }));+ };- const prevPreference = (user.preference || {}) as UserPreference;- return this.db- .update(users)- .set({ preference: { ...prevPreference, guide: merge(prevPreference.guide || {}, value) } })- .where(eq(users.id, this.userId));+ /** Keys of the goal asks this user dismissed from the approval island. */+ getIslandDismissals = async (): Promise<string[]> => {+ const user = await this.db.query.users.findFirst({+ columns: { preference: true },+ where: eq(users.id, this.userId),+ });+ return (user?.preference as UserPreference | null)?.islandDismissals ?? [];};+ /**+ * Add keys to `preference.islandDismissals` and return the stored list. Done+ * under the same row lock as every other preference writer, so neither two+ * clients dismissing at once nor a concurrent preference save can drop a key.+ */+ addIslandDismissals = async (keys: string[]): Promise<string[]> =>+ (await this.mutatePreference((prev) => {+ const current = prev.islandDismissals ?? [];+ const next = mergeIslandDismissals(current, keys);+ return {+ next: next === current ? prev : { ...prev, islandDismissals: next },+ result: next,+ };+ })) ?? [];+/*** Normalize unique user fields so empty strings become null, keeping unique constraints safe.*/diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 08d165d4c05..50b6246fe2f 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1796,6 +1796,7 @@ export default {'floatingChatPanel.expand': 'Expand chat','globalApproval.collapse': 'Collapse','globalApproval.dismiss': 'Dismiss',+ 'globalApproval.dismissFailed': "Couldn't dismiss it. Please try again.",'globalApproval.dismissHint': 'Hide it here; it stays on Home','globalApproval.dismissed': 'Dismissed. You can still handle it from Home.','globalApproval.goToConversation': 'Open conversation',diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex e10b5b30911..329f601865f 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -319,6 +319,15 @@ export interface UserPreference {* opt-out.*/integration?: UserIntegrationPreference;+ /**+ * Keys of the goal asks this user dismissed from the approval island, shared+ * by every client of the account. Written only through+ * `UserModel.addIslandDismissals`; deliberately absent from+ * {@link UserPreferenceSchema}, because `updatePreference` sends the whole+ * object and replaces arrays, so a stale client would overwrite keys+ * another client added.+ */+ islandDismissals?: string[];lab?: UserLab;/*** Last active workspace id. Used on cloud to land the user back in thediff --git a/src/features/GlobalApprovalNotification/index.tsx b/src/features/GlobalApprovalNotification/index.tsxindex 4f655ffdcee..7ba6c9466fb 100644--- a/src/features/GlobalApprovalNotification/index.tsx+++ b/src/features/GlobalApprovalNotification/index.tsx@@ -1,13 +1,17 @@'use client';+import { goalClarificationIslandKey } from '@lobechat/const/goal';import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';import { toast } from '@lobehub/ui';import { AnimatePresence } from 'motion/react';import * as m from 'motion/react-m';-import { memo, useMemo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import { isDesktop } from '@/const/version';+import { usePermission } from '@/hooks/usePermission';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import ApprovalCard from './ApprovalCard';import GoalClarificationCard from './GoalClarificationCard';@@ -15,7 +19,7 @@ import GoalDecisionCard from './GoalDecisionCard';import { styles } from './styles';import { useApprovalIslandCollapse } from './useApprovalIslandCollapse';import { useGlobalPendingApprovals } from './useGlobalPendingApprovals';-import { goalClarificationIslandKey, useIslandDismissals } from './useIslandDismissals';+import { useIslandDismissals } from './useIslandDismissals';import { usePendingGoalClarifications } from './usePendingGoalClarifications';import { usePendingGoalDecisions } from './usePendingGoalDecisions';@@ -37,25 +41,26 @@ const GlobalApprovalNotification = memo(() => {const groups = useGlobalPendingApprovals();// A goal waiting on its clarification round asks through the same island.// Run approvals go first: a run is blocked mid-turn, a goal has not started.- const pendingGoalGroups = usePendingGoalClarifications();+ const goalGroups = usePendingGoalClarifications();// Then the gates a running goal stopped on, then finished goals awaiting// sign-off — each blocks less than the one before it.- const pendingGoalItems = usePendingGoalDecisions();+ const goalItems = usePendingGoalDecisions();// Goal asks the user waved off leave the island but stay in the Home inbox,// so they are never lost — a run approval has no such fallback and stays.- const { dismiss: dismissKey, dismissed } = useIslandDismissals();- const dismiss = (key: string) => {- dismissKey(key);- toast.info({ placement: 'top', title: t('globalApproval.dismissed') });+ // The server leaves dismissed asks out of both lists, on every client.+ const enableGoals = useUserStore(labPreferSelectors.enableGoals);+ const { allowed: canAnswerGoals } = usePermission('create_content');+ const dismissKey = useIslandDismissals(enableGoals && canAnswerGoals);+ // Confirm only once the server kept it; on failure the card comes back.+ const dismiss = async (key: string) => {+ try {+ await dismissKey(key);+ toast.info({ placement: 'top', title: t('globalApproval.dismissed') });+ } catch (error) {+ console.error('[island] failed to dismiss', error);+ toast.error({ placement: 'top', title: t('globalApproval.dismissFailed') });+ }};- const goalGroups = useMemo(- () => pendingGoalGroups.filter((group) => !dismissed.has(goalClarificationIslandKey(group))),- [dismissed, pendingGoalGroups],- );- const goalItems = useMemo(- () => pendingGoalItems.filter((item) => !dismissed.has(item.key)),- [dismissed, pendingGoalItems],- );const total = groups.length + goalGroups.length + goalItems.length;const [collapsed, setCollapsed] = useApprovalIslandCollapse(total);diff --git a/src/features/GlobalApprovalNotification/useIslandDismissals.test.ts b/src/features/GlobalApprovalNotification/useIslandDismissals.test.tsindex c8fdf87d1ba..bea2d8fdd18 100644--- a/src/features/GlobalApprovalNotification/useIslandDismissals.test.ts+++ b/src/features/GlobalApprovalNotification/useIslandDismissals.test.ts@@ -1,38 +1,80 @@-import { describe, expect, it } from 'vitest';--import {- appendDismissedIslandKey,- goalClarificationIslandKey,- MAX_DISMISSED_ISLAND_KEYS,-} from './useIslandDismissals';--const round = (goalId: string, decisionIds: string[]) => ({- agentId: null,- goalId,- questions: decisionIds.map((decisionId) => ({ decisionId }) as any),- title: goalId,+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useGlobalStore } from '@/store/global';+import { useGoalStore } from '@/store/goal';++import { useIslandDismissals } from './useIslandDismissals';++const dismissIslandItems = vi.fn<(keys: string[]) => Promise<void>>();++const setStatus = (status: Record<string, unknown>) =>+ useGlobalStore.setState((s) => ({ isStatusInit: true, status: { ...s.status, ...status } }));++beforeEach(() => {+ dismissIslandItems.mockReset().mockResolvedValue();+ useGoalStore.setState({ dismissIslandItems } as any);+ useGlobalStore.setState((s) => ({+ isStatusInit: true,+ status: {+ ...s.status,+ dismissedIslandItemKeys: undefined,+ islandDismissalsUploaded: undefined,+ },+ }));});-describe('appendDismissedIslandKey', () => {- it('appends a new key and leaves a known one alone', () => {- const current = ['a'];- expect(appendDismissedIslandKey(current, 'b')).toEqual(['a', 'b']);- expect(appendDismissedIslandKey(current, 'a')).toBe(current);+describe('useIslandDismissals', () => {+ it('sends a dismissal to the server instead of keeping it on this client', async () => {+ setStatus({ islandDismissalsUploaded: true });+ const { result } = renderHook(() => useIslandDismissals(true));++ await act(() => result.current('goal-decision:d1'));++ expect(dismissIslandItems).toHaveBeenCalledWith(['goal-decision:d1']);+ expect(useGlobalStore.getState().status.dismissedIslandItemKeys).toBeUndefined();});- it('keeps only the newest keys once the cap is reached', () => {- const full = Array.from({ length: MAX_DISMISSED_ISLAND_KEYS }, (_, i) => `k${i}`);- const next = appendDismissedIslandKey(full, 'new');- expect(next).toHaveLength(MAX_DISMISSED_ISLAND_KEYS);- expect(next[0]).toBe('k1');- expect(next.at(-1)).toBe('new');+ it('rejects when the server does not keep the dismissal', async () => {+ setStatus({ islandDismissalsUploaded: true });+ dismissIslandItems.mockRejectedValueOnce(new Error('offline'));+ const { result } = renderHook(() => useIslandDismissals(true));++ await expect(result.current('goal-decision:d1')).rejects.toThrow('offline');});-});-describe('goalClarificationIslandKey', () => {- it('tells two rounds of the same goal apart', () => {- expect(goalClarificationIslandKey(round('g1', ['d1', 'd2']))).not.toBe(- goalClarificationIslandKey(round('g1', ['d3'])),+ it('uploads the keys this client dismissed locally before, once', async () => {+ setStatus({ dismissedIslandItemKeys: ['goal-decision:old', 'goal-sign-off:a1'] });+ const { rerender } = renderHook(() => useIslandDismissals(true));++ await waitFor(() =>+ expect(useGlobalStore.getState().status.islandDismissalsUploaded).toBe(true),);+ rerender();++ expect(dismissIslandItems).toHaveBeenCalledTimes(1);+ expect(dismissIslandItems).toHaveBeenCalledWith(['goal-decision:old', 'goal-sign-off:a1']);+ });++ it('retries the upload on the next launch when it fails', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ dismissIslandItems.mockRejectedValueOnce(new Error('offline'));+ setStatus({ dismissedIslandItemKeys: ['goal-decision:old'] });++ renderHook(() => useIslandDismissals(true));++ await waitFor(() => expect(dismissIslandItems).toHaveBeenCalled());+ expect(useGlobalStore.getState().status.islandDismissalsUploaded).toBeUndefined();+ });++ it('does not upload while goals are off for this user', () => {+ setStatus({ dismissedIslandItemKeys: ['goal-decision:old'] });++ renderHook(() => useIslandDismissals(false));++ expect(dismissIslandItems).not.toHaveBeenCalled();});});diff --git a/src/features/GlobalApprovalNotification/useIslandDismissals.ts b/src/features/GlobalApprovalNotification/useIslandDismissals.tsindex 822c4388bfc..dfd88da50b8 100644--- a/src/features/GlobalApprovalNotification/useIslandDismissals.ts+++ b/src/features/GlobalApprovalNotification/useIslandDismissals.ts@@ -1,44 +1,37 @@-import { useCallback, useMemo } from 'react';+import { useCallback, useEffect } from 'react';import { useGlobalStore } from '@/store/global';--import type { GoalClarificationGroup } from './usePendingGoalClarifications';--/**- * Old keys point at asks long since answered, so only the newest ones are worth- * keeping. The cap holds the array's length steady once reached:- * `updateSystemStatus` merges arrays by index and could never shrink it.- */-export const MAX_DISMISSED_ISLAND_KEYS = 200;--export const appendDismissedIslandKey = (current: string[], key: string): string[] =>- current.includes(key) ? current : [...current, key].slice(-MAX_DISMISSED_ISLAND_KEYS);--/**- * A clarification round is keyed by its questions, not just its goal: waving- * off one round must not hide the next round the same goal asks.- */-export const goalClarificationIslandKey = (group: GoalClarificationGroup): string =>- `goal-clarify:${group.goalId}:${group.questions.map((q) => q.decisionId).join(',')}`;+import { useGoalStore } from '@/store/goal';/*** Asks the user put away from the island. Dismissing only hides the island* card; the ask itself stays pending and keeps waiting in the Home inbox.+ *+ * The keys are kept on the server, and the island reads already leave them+ * out, so a card dismissed here also stays away on the user's other clients.+ * Keys this client stored locally before that are uploaded once.*/-export const useIslandDismissals = () => {- const keys = useGlobalStore((s) => s.status.dismissedIslandItemKeys);+export const useIslandDismissals = (enabled: boolean) => {+ const dismissIslandItems = useGoalStore((s) => s.dismissIslandItems);+ const isStatusInit = useGlobalStore((s) => s.isStatusInit);+ const legacyKeys = useGlobalStore((s) => s.status.dismissedIslandItemKeys);+ const uploaded = useGlobalStore((s) => s.status.islandDismissalsUploaded);const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);- const dismissed = useMemo(() => new Set(keys), [keys]);-- const dismiss = useCallback(- (key: string) => {- const current = useGlobalStore.getState().status.dismissedIslandItemKeys || [];- const next = appendDismissedIslandKey(current, key);- if (next !== current) updateSystemStatus({ dismissedIslandItemKeys: next });- },- [updateSystemStatus],- );-- return { dismiss, dismissed };+ useEffect(() => {+ if (!enabled || !isStatusInit || uploaded) return;+ const keys = legacyKeys ?? [];+ const markUploaded = () => updateSystemStatus({ islandDismissalsUploaded: true });+ if (keys.length === 0) {+ markUploaded();+ return;+ }+ // Left unmarked on failure, so the next launch tries again.+ dismissIslandItems(keys).then(markUploaded, (error) =>+ console.error('[island] failed to upload local dismissals', error),+ );+ }, [dismissIslandItems, enabled, isStatusInit, legacyKeys, updateSystemStatus, uploaded]);++ // Rejects when the server did not keep it, so the caller can say so.+ return useCallback((key: string) => dismissIslandItems([key]), [dismissIslandItems]);};diff --git a/src/features/GlobalApprovalNotification/usePendingGoalDecisions.ts b/src/features/GlobalApprovalNotification/usePendingGoalDecisions.tsindex 05859e2eebe..2756e00d590 100644--- a/src/features/GlobalApprovalNotification/usePendingGoalDecisions.ts+++ b/src/features/GlobalApprovalNotification/usePendingGoalDecisions.ts@@ -1,3 +1,4 @@+import { goalDecisionIslandKey, goalSignOffIslandKey } from '@lobechat/const/goal';import type { GoalDecisionOption } from '@lobechat/types';import { useMemo } from 'react';import { useLocation } from 'react-router';@@ -59,13 +60,13 @@ export const selectIslandGoalItems = (.filter((decision) => decision.goalId !== portalGoalId).map((decision) => ({decision,- key: `goal-decision:${decision.decisionId}`,+ key: goalDecisionIslandKey(decision.decisionId),type: 'decision' as const,})),...data.signOffs.filter((signOff) => signOff.goalId !== portalGoalId).map((signOff) => ({- key: `goal-sign-off:${signOff.acceptanceId}`,+ key: goalSignOffIslandKey(signOff.acceptanceId),signOff,type: 'signOff' as const,})),diff --git a/src/services/user/index.ts b/src/services/user/index.tsindex ba7da27fbab..5070a5879b8 100644--- a/src/services/user/index.ts+++ b/src/services/user/index.ts@@ -124,6 +124,11 @@ export class UserService {return lambdaClient.user.updateUsername.mutate(username);};+ /** Wave goal asks off the approval island for every client of this account. */+ addIslandDismissals = async (keys: string[]): Promise<string[]> => {+ return lambdaClient.user.addIslandDismissals.mutate({ keys });+ };+updatePreference = async (preference: Partial<UserPreference>) => {return lambdaClient.user.updatePreference.mutate(preference);};diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex 10793e6c2f6..f8eb60ec4c5 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -266,9 +266,9 @@ export interface SystemStatus {*/dismissedBannerIds?: string[];/**- * Keys of goal asks (clarification rounds, gates, sign-offs) the user waved- * off the approval island. Only the island honours them — the same ask stays- * in the Home inbox. Append-only and capped, see `appendDismissedIslandKey`.+ * @deprecated Island dismissals live on the server now (`addIslandDismissals`),+ * shared by every client. Read once to upload what this client dismissed+ * before, then ignored; see `islandDismissalsUploaded`.*/dismissedIslandItemKeys?: string[];dismissedProjectOnboarding?: Record<string, boolean>;@@ -323,6 +323,8 @@ export interface SystemStatus {imagePanelWidth: number;imageTopicPanelWidth?: number;imageTopicViewMode?: 'grid' | 'list';+ /** This client's legacy `dismissedIslandItemKeys` have been uploaded to the server. */+ islandDismissalsUploaded?: boolean;isShowCredit?: boolean;knowledgeBaseModalViewMode?: 'list' | 'masonry';language?: LocaleMode;diff --git a/src/store/goal/action.islandDismissals.test.ts b/src/store/goal/action.islandDismissals.test.tsnew file mode 100644index 00000000000..75b16ed5cf1--- /dev/null+++ b/src/store/goal/action.islandDismissals.test.ts@@ -0,0 +1,97 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { mutate } from '@/libs/swr';+import { goalKeys } from '@/libs/swr/keys';+import { userService } from '@/services/user';++import { useGoalStore } from './index';++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(),+}));++vi.mock('@/services/user', () => ({+ userService: { addIslandDismissals: vi.fn() },+}));++/** The optimistic updater passed for one key, applied to `data`. */+const applyUpdater = (key: unknown[], data: unknown) => {+ const call = vi+ .mocked(mutate)+ .mock.calls.find(([k, updater]) => JSON.stringify(k) === JSON.stringify(key) && updater);+ return (call![1] as (value: unknown) => unknown)(data);+};++describe('dismissIslandItems', () => {+ beforeEach(() => {+ vi.mocked(mutate).mockReset().mockResolvedValue(undefined);+ vi.mocked(userService.addIslandDismissals).mockReset().mockResolvedValue([]);+ });++ it('hides the cards at once, stores the keys on the server and re-reads the island', async () => {+ await useGoalStore+ .getState()+ .dismissIslandItems(['goal-decision:d1', 'goal-sign-off:a2', 'goal-clarify:g1:q1']);++ expect(userService.addIslandDismissals).toHaveBeenCalledWith([+ 'goal-decision:d1',+ 'goal-sign-off:a2',+ 'goal-clarify:g1:q1',+ ]);+ expect(+ applyUpdater(goalKeys.pendingForIsland(), {+ decisions: [{ decisionId: 'd1' }, { decisionId: 'd2' }],+ signOffs: [{ acceptanceId: 'a1' }, { acceptanceId: 'a2' }],+ }),+ ).toEqual({ decisions: [{ decisionId: 'd2' }], signOffs: [{ acceptanceId: 'a1' }] });+ expect(+ applyUpdater(goalKeys.pendingClarifications(), [+ { goalId: 'g1', questions: [{ decisionId: 'q1' }] },+ { goalId: 'g2', questions: [{ decisionId: 'q2' }] },+ ]),+ ).toEqual([{ goalId: 'g2', questions: [{ decisionId: 'q2' }] }]);+ expect(mutate).toHaveBeenCalledWith(goalKeys.pendingForIsland());+ expect(mutate).toHaveBeenCalledWith(goalKeys.pendingClarifications());+ });++ it('brings the cards back from the cache when the server rejects the dismissal', async () => {+ vi.mocked(userService.addIslandDismissals).mockRejectedValue(new Error('offline'));+ const island = { decisions: [{ decisionId: 'd1' }], signOffs: [] };+ const clarifications = [{ goalId: 'g1', questions: [{ decisionId: 'q1' }] }];+ vi.mocked(mutate).mockImplementation(async (key: any, updater?: any) => {+ if (typeof updater !== 'function') return;+ updater(key[0] === goalKeys.pendingForIsland()[0] ? island : clarifications);+ });++ await expect(useGoalStore.getState().dismissIslandItems(['goal-decision:d1'])).rejects.toThrow(+ 'offline',+ );++ // Restored without a fetch, so it holds even while the re-read fails offline.+ expect(mutate).toHaveBeenCalledWith(goalKeys.pendingForIsland(), island, {+ revalidate: false,+ });+ expect(mutate).toHaveBeenCalledWith(goalKeys.pendingClarifications(), clarifications, {+ revalidate: false,+ });+ });++ it('resolves once the server kept the keys even if re-reading the island fails', async () => {+ vi.mocked(mutate).mockImplementation(async (_key: any, updater?: any) => {+ if (updater === undefined) throw new Error('offline');+ });+ vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(+ useGoalStore.getState().dismissIslandItems(['goal-decision:d1']),+ ).resolves.toBeUndefined();+ });++ it('does nothing without keys', async () => {+ await useGoalStore.getState().dismissIslandItems([]);++ expect(userService.addIslandDismissals).not.toHaveBeenCalled();+ expect(mutate).not.toHaveBeenCalled();+ });+});diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex e99ec5ca151..a255ba4a2cb 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -2,6 +2,9 @@ import { TRACING_SCENARIOS } from '@lobechat/const';import {GOAL_ACCEPTANCE_TASK_TITLE,GOAL_TITLE_MAX_LENGTH,+ goalClarificationIslandKey,+ goalDecisionIslandKey,+ goalSignOffIslandKey,type GoalStatus,} from '@lobechat/const/goal';import {@@ -27,6 +30,7 @@ import { goalKeys } from '@/libs/swr/keys';import { aiChatService } from '@/services/aiChat';import { type GoalListItem, goalService } from '@/services/goal';import { type MetricSeriesWithPoints, metricService } from '@/services/metric';+import { userService } from '@/services/user';import { briefListResource } from '@/store/brief/slices/list/projection';import { taskGroupListResource, taskListResource } from '@/store/task/slices/list/projection';import type { StoreSetter } from '@/store/types';@@ -344,6 +348,71 @@ export class GoalActionImpl {await Promise.all([this.refreshGoalGraph(goalId), mutate(goalKeys.pendingClarifications())]);};+ /**+ * Wave goal asks off the approval island on every client of this account.+ * They leave the island at once; the ask itself stays pending on the goal+ * page and in the Home inbox. The server keeps the keys, and the island+ * reads leave them out, so another client drops them on its next poll.+ *+ * Rejects only when the server did not keep the keys; the cards then come+ * back from the cached lists as they were, even when a re-read fails too.+ */+ dismissIslandItems = async (keys: string[]): Promise<void> => {+ if (keys.length === 0) return;+ const hidden = new Set(keys);+ type IslandData = Awaited<ReturnType<typeof goalService.pendingForIsland>>;+ type ClarificationData = Awaited<ReturnType<typeof goalService.pendingClarifications>>;++ let islandBefore: IslandData | undefined;+ let clarificationsBefore: ClarificationData | undefined;+ await Promise.all([+ mutate(+ goalKeys.pendingForIsland(),+ (data?: IslandData) => {+ islandBefore = data;+ return (+ data && {+ decisions: data.decisions.filter(+ (row) => !hidden.has(goalDecisionIslandKey(row.decisionId)),+ ),+ signOffs: data.signOffs.filter(+ (row) => !hidden.has(goalSignOffIslandKey(row.acceptanceId)),+ ),+ }+ );+ },+ { revalidate: false },+ ),+ mutate(+ goalKeys.pendingClarifications(),+ (groups?: ClarificationData) => {+ clarificationsBefore = groups;+ return groups?.filter((group) => !hidden.has(goalClarificationIslandKey(group)));+ },+ { revalidate: false },+ ),+ ]);++ // A failed re-read must not decide the outcome: the write is what counts.+ const reread = () =>+ Promise.all([+ mutate(goalKeys.pendingForIsland()),+ mutate(goalKeys.pendingClarifications()),+ ]).catch((error) => console.error('[island] failed to re-read goal asks', error));++ try {+ await userService.addIslandDismissals(keys);+ } catch (error) {+ await Promise.all([+ mutate(goalKeys.pendingForIsland(), islandBefore, { revalidate: false }),+ mutate(goalKeys.pendingClarifications(), clarificationsBefore, { revalidate: false }),+ ]);+ void reread();+ throw error;+ }+ void reread();+ };+pauseGoal = async (goalId: string): Promise<void> => {await goalService.pause(goalId);await this.refreshGoalGraph(goalId);