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.

✨ feat(favorites): pin any page to a sidebar Favorites section (#21572)

Rdmclin2e0597d5a85bb
diff --git a/apps/server/src/routers/lambda/__tests__/favorite.test.ts b/apps/server/src/routers/lambda/__tests__/favorite.test.ts
new file mode 100644
index 00000000000..cac48d93010
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/favorite.test.ts
@@ -0,0 +1,100 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// serverDatabase middleware calls getServerDB(); stub it (the model mock
+// ignores the db handle anyway).
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+const mockAdd = vi.fn();
+const mockUpdate = vi.fn();
+const mockRemove = vi.fn();
+const mockReorder = vi.fn();
+const modelScopes: unknown[][] = [];
+
+vi.mock('@/database/models/favorite', () => ({
+ FavoriteLimitError: class FavoriteLimitError extends Error {},
+ FavoriteModel: vi.fn(function (...args: unknown[]) {
+ modelScopes.push(args.slice(1));
+ return { add: mockAdd, remove: mockRemove, reorder: mockReorder, update: mockUpdate };
+ }),
+}));
+
+const { favoriteRouter } = await import('../favorite');
+
+describe('favoriteRouter', () => {
+ const ctx: any = { serverDB: {}, userId: 'user-1', workspaceId: 'ws-1' };
+ const favoriteId = '0f8fad5b-d9cb-469f-a165-70867728950e';
+ const input = { path: '/page/docs_a', targetId: 'docs_a', title: 'Spec', type: 'page' as const };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ modelScopes.length = 0;
+ });
+
+ it('scopes favorites to the caller and the active workspace', async () => {
+ mockAdd.mockResolvedValue({ ...input, icon: null, id: favoriteId });
+
+ await favoriteRouter.createCaller(ctx).add(input);
+
+ expect(modelScopes).toEqual([['user-1', 'ws-1']]);
+ expect(mockAdd).toHaveBeenCalledWith(input);
+ });
+
+ it.each(['https://evil.example', '//evil.example/page', '/\\evil.example', 'page/docs_a'])(
+ 'refuses a link that leaves the app: %s',
+ async (path) => {
+ await expect(favoriteRouter.createCaller(ctx).add({ ...input, path })).rejects.toThrow();
+ await expect(
+ favoriteRouter.createCaller(ctx).update({ id: favoriteId, value: { path } }),
+ ).rejects.toThrow();
+
+ expect(mockAdd).not.toHaveBeenCalled();
+ expect(mockUpdate).not.toHaveBeenCalled();
+ },
+ );
+
+ it('reports a full sidebar as a bad request', async () => {
+ const { FavoriteLimitError } = await import('@/database/models/favorite');
+ mockAdd.mockRejectedValue(new FavoriteLimitError());
+
+ await expect(favoriteRouter.createCaller(ctx).add(input)).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ });
+
+ it('refuses an id that is not a favorite uuid', async () => {
+ const caller = favoriteRouter.createCaller(ctx);
+
+ await expect(caller.remove({ id: 'optimistic:page:docs_a' })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ await expect(caller.update({ id: 'fav_1', value: { title: 'Spec' } })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ await expect(caller.reorder({ ids: [favoriteId, 'not-a-uuid'] })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+
+ expect(mockRemove).not.toHaveBeenCalled();
+ expect(mockUpdate).not.toHaveBeenCalled();
+ expect(mockReorder).not.toHaveBeenCalled();
+ });
+
+ it('cuts a long page title instead of refusing the favorite', async () => {
+ mockAdd.mockImplementation(async (value) => ({ ...value, icon: null, id: favoriteId }));
+
+ await favoriteRouter.createCaller(ctx).add({ ...input, title: 'a'.repeat(600) });
+
+ expect(mockAdd).toHaveBeenCalledWith({ ...input, title: 'a'.repeat(512) });
+ });
+
+ it('refuses a blank title', async () => {
+ await expect(
+ favoriteRouter.createCaller(ctx).add({ ...input, title: ' ' }),
+ ).rejects.toThrow();
+ });
+});
diff --git a/apps/server/src/routers/lambda/favorite.ts b/apps/server/src/routers/lambda/favorite.ts
new file mode 100644
index 00000000000..277082054dc
--- /dev/null
+++ b/apps/server/src/routers/lambda/favorite.ts
@@ -0,0 +1,94 @@
+import {
+ FAVORITE_LIMIT,
+ FAVORITE_TYPES,
+ type FavoriteItem,
+ toFavoriteTitle,
+} from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { FavoriteLimitError, FavoriteModel } from '@/database/models/favorite';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+
+const favoriteProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ return opts.next({
+ ctx: {
+ favoriteModel: new FavoriteModel(ctx.serverDB, ctx.userId, ctx.workspaceId),
+ },
+ });
+});
+
+/**
+ * Favorites only ever open inside the app, so the path must be an in-app
+ * absolute path: `//host` and `/\host` would leave the origin.
+ */
+const inAppPath = z
+ .string()
+ .min(1)
+ .max(2048)
+ .regex(/^\/(?![/\\])/, 'Favorites must link to a page inside the app');
+
+const favoriteType = z.enum(FAVORITE_TYPES);
+// Page titles have no length limit, so a long one is cut to fit instead of refusing the favorite.
+const title = z.string().trim().min(1).transform(toFavoriteTitle);
+const icon = z.string().max(2048).nullable();
+/** Favorite row ids are uuids; reject anything else before it reaches Postgres. */
+const favoriteId = z.string().uuid();
+
+export const favoriteRouter = router({
+ add: favoriteProcedure
+ .input(
+ z.object({
+ icon: icon.optional(),
+ path: inAppPath,
+ targetId: z.string().min(1).max(2048),
+ title,
+ type: favoriteType,
+ }),
+ )
+ .mutation(async ({ ctx, input }): Promise<FavoriteItem> => {
+ try {
+ return await ctx.favoriteModel.add(input);
+ } catch (error) {
+ if (error instanceof FavoriteLimitError)
+ throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });
+ throw error;
+ }
+ }),
+
+ list: favoriteProcedure.query(async ({ ctx }): Promise<FavoriteItem[]> =>
+ ctx.favoriteModel.query(),
+ ),
+
+ remove: favoriteProcedure
+ .input(z.object({ id: favoriteId }))
+ .mutation(async ({ ctx, input }) => ctx.favoriteModel.remove(input.id)),
+
+ removeByTarget: favoriteProcedure
+ .input(z.object({ targetId: z.string(), type: favoriteType }))
+ .mutation(async ({ ctx, input }) =>
+ ctx.favoriteModel.removeByTarget(input.type, input.targetId),
+ ),
+
+ reorder: favoriteProcedure
+ .input(z.object({ ids: z.array(favoriteId).max(FAVORITE_LIMIT) }))
+ .mutation(async ({ ctx, input }) => ctx.favoriteModel.reorder(input.ids)),
+
+ update: favoriteProcedure
+ .input(
+ z.object({
+ id: favoriteId,
+ value: z.object({
+ icon: icon.optional(),
+ path: inAppPath.optional(),
+ title: title.optional(),
+ }),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => ctx.favoriteModel.update(input.id, input.value)),
+});
+
+export type FavoriteRouter = typeof favoriteRouter;
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index a9f6d3447f1..212805dc355 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -62,6 +62,7 @@ import { documentLikeRouter } from './documentLike';
import { environmentRouter } from './environment';
import { expertiseRouter } from './expertise';
import { exporterRouter } from './exporter';
+import { favoriteRouter } from './favorite';
import { fileRouter } from './file';
import { followUpActionRouter } from './followUpAction';
import { generationRouter } from './generation';
@@ -132,6 +133,7 @@ export const lambdaRouter = router({
agentLabel: agentLabelRouter,
agentSkills: agentSkillsRouter,
environment: environmentRouter,
+ favorite: favoriteRouter,
sandboxStorage: sandboxStorageRouter,
agentTrace: agentTraceRouter,
expertise: expertiseRouter,
diff --git a/locales/ar/common.json b/locales/ar/common.json
index 96713f1fcb2..3e4a2c591d7 100644
--- a/locales/ar/common.json
+++ b/locales/ar/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "تصدير جميع إعدادات الوكلاء",
"exportType.allAgentWithMessage": "تصدير جميع الوكلاء والرسائل",
"exportType.globalSetting": "تصدير الإعدادات العامة",
+ "favorite.add": "أضف إلى المفضلة",
+ "favorite.limitReached": "يمكن أن تحتوي المفضلة على ما يصل إلى {{count}} عنصرًا. قم بإزالة واحد لإضافة آخر.",
+ "favorite.remove": "إزالة من المفضلة",
+ "favorite.reorderError": "تعذر حفظ ترتيب المفضلة لديك. حاول مرة أخرى.",
+ "favorite.section": "المفضلة",
+ "favorite.updateError": "تعذر تحديث المفضلة لديك. حاول مرة أخرى.",
"feedback": "ملاحظات",
"feedback.emailContact": "يمكنك أيضًا مراسلتنا عبر البريد الإلكتروني على <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "الملف يتجاوز الحجم المسموح به (5 ميغابايت)",
diff --git a/locales/ar/hotkey.json b/locales/ar/hotkey.json
index ad78714986b..c319fa7745c 100644
--- a/locales/ar/hotkey.json
+++ b/locales/ar/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "تبديل سريع للوكلاء",
"switchTab.desc": "الانتقال إلى علامة تبويب معينة حسب موقعها (1–9) في شريط علامات التبويب لتطبيق سطح المكتب",
"switchTab.title": "التبديل إلى علامة تبويب حسب الرقم",
+ "toggleFavorite.desc": "أضف الصفحة المفتوحة إلى قسم المفضلة في الشريط الجانبي، أو قم بإزالتها",
+ "toggleFavorite.title": "إضافة إلى / إزالة من المفضلة",
"toggleLeftPanel.desc": "إظهار أو إخفاء اللوحة اليسرى",
"toggleLeftPanel.title": "تبديل اللوحة اليسرى",
"toggleRightPanel.desc": "إظهار أو إخفاء اللوحة اليمنى",
diff --git a/locales/ar/topic.json b/locales/ar/topic.json
index 3ff4da15a1f..85316f6bc8c 100644
--- a/locales/ar/topic.json
+++ b/locales/ar/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "أنت على وشك حذف هذا الموضوع. لا يمكن التراجع عن هذا الإجراء.",
"actions.confirmRemoveTopicFiles": "حذف الصور والملفات المرفوعة في هذا الموضوع أيضًا",
"actions.confirmRemoveTopicTitle": "حذف هذا الموضوع؟",
+ "actions.confirmRemoveUnpinnedWorkspace": "أنت على وشك حذف جميع المواضيع غير المثبتة في قائمة مساحة العمل الحالية، بما في ذلك المواضيع التي أنشأها أعضاء آخرون. ستبقى المواضيع المثبتة. تُنقل المواضيع المحذوفة إلى سلة المهملات ويمكن استعادتها خلال 30 يومًا.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "أفهم أن هذا سينقل المواضيع غير المثبتة الخاصة بالأعضاء الآخرين إلى سلة المهملات.",
"actions.confirmRemoveUnstarred": "أنت على وشك حذف المواضيع غير المميزة. لا يمكن التراجع عن هذا الإجراء.",
"actions.confirmRemoveUnstarredOwn": "أنت على وشك حذف المواضيع غير المميزة بنجمة التي أنشأتها. ستبقى المواضيع التي أنشأها أعضاء آخرون في مساحة العمل. لا يمكن التراجع عن هذا الإجراء.",
- "actions.confirmRemoveUnstarredWorkspace": "أنت على وشك حذف جميع المواضيع غير المميزة بنجمة في قائمة مساحة العمل الحالية، بما في ذلك المواضيع التي أنشأها أعضاء آخرون. ستبقى المواضيع المميزة بنجمة. لا يمكن التراجع عن هذا الإجراء.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "أفهم أن هذا سيؤدي إلى حذف المواضيع غير المميزة بنجمة الخاصة بالأعضاء الآخرين بشكل دائم.",
"actions.copyLink": "نسخ الرابط",
"actions.copyLinkSuccess": "تم نسخ الرابط",
"actions.copySessionId": "نسخ معرّف الجلسة",
@@ -31,23 +31,23 @@
"actions.diagnose": "تحقق من سلسلة الرسائل",
"actions.duplicate": "نسخ",
"actions.export": "تصدير المواضيع",
- "actions.favorite": "المفضلة",
"actions.forwardToAgent": "إعادة التوجيه إلى وكيل آخر",
"actions.import": "استيراد المحادثة",
"actions.markCompleted": "وضع علامة كمكتمل",
"actions.moveToAgent": "نقل إلى مساعد آخر",
"actions.openInNewTab": "افتح في علامة تبويب جديدة",
"actions.openInNewWindow": "فتح في نافذة جديدة",
+ "actions.pin": "تثبيت",
"actions.removeAll": "حذف جميع المواضيع",
"actions.removeAllOwn": "حذف جميع المواضيع التي أنشأتها",
"actions.removeAllWorkspace": "حذف جميع مواضيع مساحة العمل",
"actions.removeTopic": "حذف الموضوع",
+ "actions.removeUnpinnedWorkspace": "حذف جميع المواضيع غير المثبتة",
"actions.removeUnstarred": "حذف المواضيع غير المميزة",
"actions.removeUnstarredOwn": "حذف مواضيعي غير المميزة بنجمة",
- "actions.removeUnstarredWorkspace": "حذف جميع المواضيع غير المميزة بنجمة",
"actions.reportProblem": "الإبلاغ عن مشكلة",
- "actions.unfavorite": "إزالة من المفضلة",
"actions.unmarkCompleted": "وضع علامة كنشط",
+ "actions.unpin": "إلغاء التثبيت",
"defaultTitle": "موضوع افتراضي",
"displayItems": "عرض العناصر",
"doctor.checkFailed": "لم يتمكن من إكمال الفحص.",
@@ -69,7 +69,6 @@
"duplicateLoading": "جارٍ نسخ الموضوع...",
"duplicateSuccess": "تم نسخ الموضوع بنجاح",
"failedStatusTip": "تعرضت هذه العملية لخطأ — افتحها لإلقاء نظرة.",
- "favorite": "مفضل",
"filter.allTopics": "الكل",
"filter.byDevice": "الجهاز: {{value}}",
"filter.byStatus": "الحالة: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "حذف",
"management.bulk.deleteConfirm": "أنت على وشك حذف {{count}} موضوعًا. لا يمكن التراجع عن هذا الإجراء.",
"management.bulk.deleteTitle": "حذف المواضيع؟",
- "management.bulk.favorite": "مفضلة",
"management.bulk.move": "نقل إلى مساعد",
"management.bulk.moveEmpty": "لا يوجد مساعدون آخرون",
"management.bulk.moveSearchPlaceholder": "ابحث عن المساعدين…",
+ "management.bulk.pin": "تثبيت",
"management.bulk.selectedCount_one": "{{count}} محدد",
"management.bulk.selectedCount_other": "{{count}} محددة",
"management.card.noPreview": "لا توجد معاينة متاحة",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "التكامل المستمر قيد التشغيل",
"metaCard.ci.success": "نجح التكامل المستمر",
"metaCard.detached": "رأس منفصل عند {{sha}}",
+ "metaCard.goal": "الهدف المرتبط",
"metaCard.pr.closed": "مغلق",
"metaCard.pr.merged": "مُدمج",
"metaCard.pr.open": "مفتوح",
"newTopic": "موضوع جديد",
+ "pinned": "المثبتة",
"projectStatus.failed_one": "{{count}} موضوع فشل",
"projectStatus.failed_other": "{{count}} مواضيع فشلت",
"projectStatus.loading_one": "{{count}} موضوع قيد التحميل",
diff --git a/locales/bg-BG/common.json b/locales/bg-BG/common.json
index f1c795fefec..df2d5796cca 100644
--- a/locales/bg-BG/common.json
+++ b/locales/bg-BG/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Експортиране на всички настройки на агентите",
"exportType.allAgentWithMessage": "Експортиране на всички агенти и съобщения",
"exportType.globalSetting": "Експортиране на глобални настройки",
+ "favorite.add": "Добавяне към любими",
+ "favorite.limitReached": "Любимите могат да съдържат до {{count}} елемента. Премахнете един, за да добавите друг.",
+ "favorite.remove": "Премахване от любими",
+ "favorite.reorderError": "Не можа да се запази редът на вашите любими. Опитайте отново.",
+ "favorite.section": "Любими",
+ "favorite.updateError": "Не можа да се актуализират вашите любими. Опитайте отново.",
"feedback": "Обратна връзка",
"feedback.emailContact": "Можете също да ни пишете на <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "Файлът надвишава 5MB",
diff --git a/locales/bg-BG/hotkey.json b/locales/bg-BG/hotkey.json
index 50ed78797f6..00a99909055 100644
--- a/locales/bg-BG/hotkey.json
+++ b/locales/bg-BG/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Бързо превключване на агент",
"switchTab.desc": "Прескочете към конкретен раздел според неговата позиция (1–9) в лентата с раздели на приложението за настолен компютър",
"switchTab.title": "Превключване към раздел по номер",
+ "toggleFavorite.desc": "Добавете отворената страница в секцията Любими на страничната лента или я премахнете",
+ "toggleFavorite.title": "Добавяне в / Премахване от Любими",
"toggleLeftPanel.desc": "Показване или скриване на левия панел",
"toggleLeftPanel.title": "Превключване на левия панел",
"toggleRightPanel.desc": "Показване или скриване на десния панел",
diff --git a/locales/bg-BG/topic.json b/locales/bg-BG/topic.json
index e3613dfe730..bb0e519eae9 100644
--- a/locales/bg-BG/topic.json
+++ b/locales/bg-BG/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "На път сте да изтриете тази тема. Това действие не може да бъде отменено.",
"actions.confirmRemoveTopicFiles": "Също така изтрийте изображенията и файловете, качени в тази тема",
"actions.confirmRemoveTopicTitle": "Да изтрия ли тази тема?",
+ "actions.confirmRemoveUnpinnedWorkspace": "На път сте да изтриете всички незакачени теми в текущия списък на работното пространство, включително темите на други членове. Закачените теми ще останат. Изтритите теми се преместват в кошчето и могат да бъдат възстановени в рамките на 30 дни.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Разбирам, че това ще премести незакачените теми на другите членове в кошчето.",
"actions.confirmRemoveUnstarred": "На път сте да изтриете всички немаркирани теми. Това действие не може да бъде отменено.",
"actions.confirmRemoveUnstarredOwn": "Ще изтриете темите, които сте създали и не са маркирани със звезда. Темите, създадени от други членове на работното пространство, ще останат. Това действие не може да бъде отменено.",
- "actions.confirmRemoveUnstarredWorkspace": "Ще изтриете всички немаркирани теми в текущия списък на работното пространство, включително теми, създадени от други членове. Маркираните теми ще останат. Това действие не може да бъде отменено.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Разбирам, че това действие ще изтрие завинаги немаркираните теми на други членове.",
"actions.copyLink": "Копирай линк",
"actions.copyLinkSuccess": "Линкът е копиран",
"actions.copySessionId": "Копирай Session ID",
@@ -31,23 +31,23 @@
"actions.diagnose": "Проверка на съобщенията във веригата",
"actions.duplicate": "Дублирай",
"actions.export": "Експортирай теми",
- "actions.favorite": "Любимо",
"actions.forwardToAgent": "Препрати към друг агент",
"actions.import": "Импортирай разговор",
"actions.markCompleted": "Отбележи като завършена",
"actions.moveToAgent": "Премести към друг асистент",
"actions.openInNewTab": "Отвори в нов раздел",
"actions.openInNewWindow": "Отвори в нов прозорец",
+ "actions.pin": "Закачи",
"actions.removeAll": "Изтрий всички теми",
"actions.removeAllOwn": "Изтрий всички теми, които съм създал",
"actions.removeAllWorkspace": "Изтрий всички теми в работното пространство",
"actions.removeTopic": "Изтриване на тема",
+ "actions.removeUnpinnedWorkspace": "Изтрий всички незакачени теми",
"actions.removeUnstarred": "Изтрий немаркираните теми",
"actions.removeUnstarredOwn": "Изтрий моите немаркирани теми",
- "actions.removeUnstarredWorkspace": "Изтрий всички немаркирани теми",
"actions.reportProblem": "Докладване на проблем",
- "actions.unfavorite": "Нелюбимо",
"actions.unmarkCompleted": "Отбележи като активна",
+ "actions.unpin": "Откачи",
"defaultTitle": "Тема по подразбиране",
"displayItems": "Показване на елементи",
"doctor.checkFailed": "Проверката не можа да бъде завършена.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Копиране на тема...",
"duplicateSuccess": "Темата беше успешно копирана",
"failedStatusTip": "Този процес срещна грешка — отворете го, за да разгледате.",
- "favorite": "Любима",
"filter.allTopics": "Всички",
"filter.byDevice": "Устройство: {{value}}",
"filter.byStatus": "Статус: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Изтрий",
"management.bulk.deleteConfirm": "Ще изтриете {{count}} теми. Това действие не може да бъде отменено.",
"management.bulk.deleteTitle": "Изтриване на теми?",
- "management.bulk.favorite": "Любими",
"management.bulk.move": "Премести към асистент",
"management.bulk.moveEmpty": "Няма други асистенти",
"management.bulk.moveSearchPlaceholder": "Търсене на асистенти…",
+ "management.bulk.pin": "Закачи",
"management.bulk.selectedCount_one": "{{count}} избрана",
"management.bulk.selectedCount_other": "{{count}} избрани",
"management.card.noPreview": "Няма наличен преглед",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI се изпълнява",
"metaCard.ci.success": "CI успешен",
"metaCard.detached": "Отделен HEAD на {{sha}}",
+ "metaCard.goal": "Свързана цел",
"metaCard.pr.closed": "Затворен",
"metaCard.pr.merged": "Слят",
"metaCard.pr.open": "Отворен",
"newTopic": "Нова тема",
+ "pinned": "Закачени",
"projectStatus.failed_one": "{{count}} неуспешна тема",
"projectStatus.failed_other": "{{count}} неуспешни теми",
"projectStatus.loading_one": "{{count}} зареждаща се тема",
diff --git a/locales/de-DE/common.json b/locales/de-DE/common.json
index f11e94a0710..04e523ae843 100644
--- a/locales/de-DE/common.json
+++ b/locales/de-DE/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Alle Agenteneinstellungen exportieren",
"exportType.allAgentWithMessage": "Alle Agenten und Nachrichten exportieren",
"exportType.globalSetting": "Globale Einstellungen exportieren",
+ "favorite.add": "Zu Favoriten hinzufügen",
+ "favorite.limitReached": "Favoriten können bis zu {{count}} Elemente enthalten. Entfernen Sie eines, um ein weiteres hinzuzufügen.",
+ "favorite.remove": "Aus Favoriten entfernen",
+ "favorite.reorderError": "Die Reihenfolge Ihrer Favoriten konnte nicht gespeichert werden. Versuchen Sie es erneut.",
+ "favorite.section": "Favoriten",
+ "favorite.updateError": "Ihre Favoriten konnten nicht aktualisiert werden. Versuchen Sie es erneut.",
"feedback": "Feedback",
"feedback.emailContact": "Sie können uns auch per E-Mail unter <email>{{email}}</email> erreichen",
"feedback.errors.fileTooLarge": "Datei überschreitet 5 MB",
diff --git a/locales/de-DE/hotkey.json b/locales/de-DE/hotkey.json
index 7b499e13e99..23cb431ab22 100644
--- a/locales/de-DE/hotkey.json
+++ b/locales/de-DE/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Schnellwechsel-Agent",
"switchTab.desc": "Springen Sie zu einer bestimmten Registerkarte anhand ihrer Position (1–9) in der Registerkartenleiste der Desktop-App",
"switchTab.title": "Zu Registerkarte nach Nummer wechseln",
+ "toggleFavorite.desc": "Fügen Sie die geöffnete Seite dem Bereich Favoriten in der Seitenleiste hinzu oder entfernen Sie sie",
+ "toggleFavorite.title": "Zu Favoriten hinzufügen / aus Favoriten entfernen",
"toggleLeftPanel.desc": "Linkes Panel ein- oder ausblenden",
"toggleLeftPanel.title": "Linkes Panel umschalten",
"toggleRightPanel.desc": "Rechtes Panel ein- oder ausblenden",
diff --git a/locales/de-DE/topic.json b/locales/de-DE/topic.json
index bad2d024539..65d2dda0e67 100644
--- a/locales/de-DE/topic.json
+++ b/locales/de-DE/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "Sie sind dabei, dieses Thema zu löschen. Diese Aktion kann nicht rückgängig gemacht werden.",
"actions.confirmRemoveTopicFiles": "Auch Bilder und Dateien löschen, die in diesem Thema hochgeladen wurden",
"actions.confirmRemoveTopicTitle": "Dieses Thema löschen?",
+ "actions.confirmRemoveUnpinnedWorkspace": "Sie sind dabei, alle nicht angehefteten Themen in der aktuellen Workspace-Liste zu löschen, einschließlich der Themen anderer Mitglieder. Angeheftete Themen bleiben erhalten. Gelöschte Themen werden in den Papierkorb verschoben und können innerhalb von 30 Tagen wiederhergestellt werden.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Ich verstehe, dass dadurch die nicht angehefteten Themen anderer Mitglieder in den Papierkorb verschoben werden.",
"actions.confirmRemoveUnstarred": "Sie sind dabei, nicht markierte Themen zu löschen. Diese Aktion kann nicht rückgängig gemacht werden.",
"actions.confirmRemoveUnstarredOwn": "Sie sind dabei, nicht markierte Themen zu löschen, die Sie erstellt haben. Themen, die von anderen Mitgliedern des Arbeitsbereichs erstellt wurden, bleiben erhalten. Diese Aktion kann nicht rückgängig gemacht werden.",
- "actions.confirmRemoveUnstarredWorkspace": "Sie sind dabei, alle nicht markierten Themen in der aktuellen Workspace-Liste zu löschen, einschließlich Themen, die von anderen Mitgliedern erstellt wurden. Markierte Themen bleiben erhalten. Diese Aktion kann nicht rückgängig gemacht werden.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Ich verstehe, dass dies die nicht markierten Themen anderer Mitglieder dauerhaft löscht.",
"actions.copyLink": "Link kopieren",
"actions.copyLinkSuccess": "Link kopiert",
"actions.copySessionId": "Sitzungs-ID kopieren",
@@ -31,23 +31,23 @@
"actions.diagnose": "Nachrichtenkette überprüfen",
"actions.duplicate": "Duplizieren",
"actions.export": "Themen exportieren",
- "actions.favorite": "Favorit",
"actions.forwardToAgent": "An einen anderen Agenten weiterleiten",
"actions.import": "Konversation importieren",
"actions.markCompleted": "Als abgeschlossen markieren",
"actions.moveToAgent": "Zu einem anderen Assistenten wechseln",
"actions.openInNewTab": "In neuem Tab öffnen",
"actions.openInNewWindow": "In neuem Fenster öffnen",
+ "actions.pin": "Anheften",
"actions.removeAll": "Alle Themen löschen",
"actions.removeAllOwn": "Alle von mir erstellten Themen löschen",
"actions.removeAllWorkspace": "Alle Themen des Arbeitsbereichs löschen",
"actions.removeTopic": "Thema löschen",
+ "actions.removeUnpinnedWorkspace": "Alle nicht angehefteten Themen löschen",
"actions.removeUnstarred": "Nicht markierte Themen löschen",
"actions.removeUnstarredOwn": "Meine nicht markierten Themen löschen",
- "actions.removeUnstarredWorkspace": "Alle nicht markierten Themen löschen",
"actions.reportProblem": "Ein Problem melden",
- "actions.unfavorite": "Nicht mehr Favorit",
"actions.unmarkCompleted": "Als aktiv markieren",
+ "actions.unpin": "Lösen",
"defaultTitle": "Standardthema",
"displayItems": "Elemente anzeigen",
"doctor.checkFailed": "Die Überprüfung konnte nicht abgeschlossen werden.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Thema wird kopiert...",
"duplicateSuccess": "Thema erfolgreich kopiert",
"failedStatusTip": "Dieser Durchlauf hat einen Fehler — öffnen Sie ihn, um nachzusehen.",
- "favorite": "Favorit",
"filter.allTopics": "Alle",
"filter.byDevice": "Gerät: {{value}}",
"filter.byStatus": "Status: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Löschen",
"management.bulk.deleteConfirm": "Sie sind dabei, {{count}} Themen zu löschen. Diese Aktion kann nicht rückgängig gemacht werden.",
"management.bulk.deleteTitle": "Themen löschen?",
- "management.bulk.favorite": "Favorisieren",
"management.bulk.move": "Zum Assistenten wechseln",
"management.bulk.moveEmpty": "Keine anderen Assistenten",
"management.bulk.moveSearchPlaceholder": "Assistenten suchen…",
+ "management.bulk.pin": "Anheften",
"management.bulk.selectedCount_one": "{{count}} ausgewählt",
"management.bulk.selectedCount_other": "{{count}} ausgewählt",
"management.card.noPreview": "Keine Vorschau verfügbar",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI läuft",
"metaCard.ci.success": "CI erfolgreich",
"metaCard.detached": "Detached HEAD bei {{sha}}",
+ "metaCard.goal": "Verknüpftes Ziel",
"metaCard.pr.closed": "Geschlossen",
"metaCard.pr.merged": "Zusammengeführt",
"metaCard.pr.open": "Offen",
"newTopic": "Neues Thema",
+ "pinned": "Angeheftet",
"projectStatus.failed_one": "{{count}} fehlgeschlagenes Thema",
"projectStatus.failed_other": "{{count}} fehlgeschlagene Themen",
"projectStatus.loading_one": "{{count}} ladendes Thema",
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index 49bb94892c9..6c81fd9c6ee 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -211,6 +211,12 @@
"exportType.allAgent": "Export All Agent Settings",
"exportType.allAgentWithMessage": "Export All Agents and Messages",
"exportType.globalSetting": "Export Global Settings",
+ "favorite.add": "Add to Favorites",
+ "favorite.limitReached": "Favorites can hold up to {{count}} items. Remove one to add another.",
+ "favorite.remove": "Remove from Favorites",
+ "favorite.reorderError": "Couldn't save the order of your favorites. Try again.",
+ "favorite.section": "Favorites",
+ "favorite.updateError": "Couldn't update your favorites. Try again.",
"feedback": "Feedback",
"feedback.emailContact": "You can also email us at <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "File exceeds 5MB",
diff --git a/locales/en-US/hotkey.json b/locales/en-US/hotkey.json
index baebdaf4838..707919492d2 100644
--- a/locales/en-US/hotkey.json
+++ b/locales/en-US/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Quick Switch Agent",
"switchTab.desc": "Jump to a specific tab by its position (1–9) in the Desktop app tab bar",
"switchTab.title": "Switch to Tab by Number",
+ "toggleFavorite.desc": "Add the open page to the Favorites section of the sidebar, or remove it",
+ "toggleFavorite.title": "Add to / Remove from Favorites",
"toggleLeftPanel.desc": "Show or hide the left panel",
"toggleLeftPanel.title": "Toggle Left Panel",
"toggleRightPanel.desc": "Show or hide the right panel",
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index 0fd3519f70d..b9e7487a02b 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "You are about to delete this topic. It will be moved to the trash and can be restored within 30 days.",
"actions.confirmRemoveTopicFiles": "Also delete images and files uploaded in this topic",
"actions.confirmRemoveTopicTitle": "Delete this topic?",
+ "actions.confirmRemoveUnpinnedWorkspace": "You are about to delete all unpinned topics in the current Workspace list, including topics created by other members. Pinned topics will remain. Deleted topics move to the trash and can be restored within 30 days.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "I understand that this moves other members' unpinned topics to the trash.",
"actions.confirmRemoveUnstarred": "You are about to delete unstarred topics. They will be moved to the trash and can be restored within 30 days.",
"actions.confirmRemoveUnstarredOwn": "You are about to delete unstarred topics you created. Topics created by other Workspace members will remain. Deleted topics move to the trash and can be restored within 30 days.",
- "actions.confirmRemoveUnstarredWorkspace": "You are about to delete all unstarred topics in the current Workspace list, including topics created by other members. Starred topics will remain. Deleted topics move to the trash and can be restored within 30 days.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "I understand that this moves other members' unstarred topics to the trash.",
"actions.copyLink": "Copy Link",
"actions.copyLinkSuccess": "Link copied",
"actions.copySessionId": "Copy Topic ID",
@@ -31,23 +31,23 @@
"actions.diagnose": "Check Message Chain",
"actions.duplicate": "Duplicate",
"actions.export": "Export Topics",
- "actions.favorite": "Favorite",
"actions.forwardToAgent": "Forward to another agent",
"actions.import": "Import Topics",
"actions.markCompleted": "Archive",
"actions.moveToAgent": "Move to another agent",
"actions.openInNewTab": "Open in New Tab",
"actions.openInNewWindow": "Open in a new window",
+ "actions.pin": "Pin",
"actions.removeAll": "Delete All Topics",
"actions.removeAllOwn": "Delete My Topics",
"actions.removeAllWorkspace": "Delete All Topics",
"actions.removeTopic": "Delete Topic",
+ "actions.removeUnpinnedWorkspace": "Delete All Unpinned Topics",
"actions.removeUnstarred": "Delete Unstarred Topics",
"actions.removeUnstarredOwn": "Delete My Unstarred Topics",
- "actions.removeUnstarredWorkspace": "Delete All Unstarred Topics",
"actions.reportProblem": "Report Bug",
- "actions.unfavorite": "Unfavorite",
"actions.unmarkCompleted": "Unarchive",
+ "actions.unpin": "Unpin",
"defaultTitle": "Default Topic",
"displayItems": "Display Items",
"doctor.checkFailed": "The check could not be completed.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Copying Topic...",
"duplicateSuccess": "Topic Copied Successfully",
"failedStatusTip": "This run hit an error — open it to take a look.",
- "favorite": "Favorite",
"filter.allTopics": "All",
"filter.byDevice": "Device: {{value}}",
"filter.byStatus": "Status: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Delete",
"management.bulk.deleteConfirm": "You are about to delete {{count}} topics. They will be moved to the trash and can be restored within 30 days.",
"management.bulk.deleteTitle": "Delete topics?",
- "management.bulk.favorite": "Favorite",
"management.bulk.move": "Move to agent",
"management.bulk.moveEmpty": "No other agents",
"management.bulk.moveSearchPlaceholder": "Search agents…",
+ "management.bulk.pin": "Pin",
"management.bulk.selectedCount_one": "{{count}} selected",
"management.bulk.selectedCount_other": "{{count}} selected",
"management.card.noPreview": "No preview available",
@@ -258,6 +257,7 @@
"metaCard.pr.merged": "Merged",
"metaCard.pr.open": "Open",
"newTopic": "New Topic",
+ "pinned": "Pinned",
"projectStatus.failed_one": "{{count}} failed topic",
"projectStatus.failed_other": "{{count}} failed topics",
"projectStatus.loading_one": "{{count}} loading topic",
diff --git a/locales/es-ES/common.json b/locales/es-ES/common.json
index 7409d6385aa..db853a1c5bf 100644
--- a/locales/es-ES/common.json
+++ b/locales/es-ES/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Exportar configuración de todos los agentes",
"exportType.allAgentWithMessage": "Exportar todos los agentes y mensajes",
"exportType.globalSetting": "Exportar configuración global",
+ "favorite.add": "Agregar a Favoritos",
+ "favorite.limitReached": "Los favoritos pueden contener hasta {{count}} elementos. Elimina uno para agregar otro.",
+ "favorite.remove": "Eliminar de Favoritos",
+ "favorite.reorderError": "No se pudo guardar el orden de tus favoritos. Inténtalo de nuevo.",
+ "favorite.section": "Favoritos",
+ "favorite.updateError": "No se pudieron actualizar tus favoritos. Inténtalo de nuevo.",
"feedback": "Comentarios",
"feedback.emailContact": "También puedes enviarnos un correo electrónico a <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "El archivo supera los 5 MB",
diff --git a/locales/es-ES/hotkey.json b/locales/es-ES/hotkey.json
index 3ca67e29bb9..12ba0884e20 100644
--- a/locales/es-ES/hotkey.json
+++ b/locales/es-ES/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Cambio rápido de agente",
"switchTab.desc": "Saltar a una pestaña específica según su posición (1–9) en la barra de pestañas de la aplicación de escritorio",
"switchTab.title": "Cambiar a Pestaña por Número",
+ "toggleFavorite.desc": "Añade la página abierta a la sección de Favoritos de la barra lateral, o elimínala",
+ "toggleFavorite.title": "Añadir a / Eliminar de Favoritos",
"toggleLeftPanel.desc": "Mostrar u ocultar el panel izquierdo",
"toggleLeftPanel.title": "Alternar panel izquierdo",
"toggleRightPanel.desc": "Mostrar u ocultar el panel derecho",
diff --git a/locales/es-ES/topic.json b/locales/es-ES/topic.json
index 758cfd93586..73f54484424 100644
--- a/locales/es-ES/topic.json
+++ b/locales/es-ES/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "Estás a punto de eliminar este tema. Esta acción no se puede deshacer.",
"actions.confirmRemoveTopicFiles": "También eliminar imágenes y archivos subidos en este tema",
"actions.confirmRemoveTopicTitle": "¿Eliminar este tema?",
+ "actions.confirmRemoveUnpinnedWorkspace": "Estás a punto de eliminar todos los temas no fijados de la lista actual del espacio de trabajo, incluidos los creados por otros miembros. Los temas fijados se conservarán. Los temas eliminados se mueven a la papelera y se pueden restaurar durante 30 días.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Entiendo que esto mueve a la papelera los temas no fijados de otros miembros.",
"actions.confirmRemoveUnstarred": "Estás a punto de eliminar los temas no marcados como favoritos. Esta acción no se puede deshacer.",
"actions.confirmRemoveUnstarredOwn": "Estás a punto de eliminar los temas sin marcar como favoritos que creaste. Los temas creados por otros miembros del Espacio de Trabajo permanecerán. Esta acción no se puede deshacer.",
- "actions.confirmRemoveUnstarredWorkspace": "Estás a punto de eliminar todos los temas no destacados en la lista actual del espacio de trabajo, incluidos los temas creados por otros miembros. Los temas destacados permanecerán. Esta acción no se puede deshacer.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Entiendo que esto elimina permanentemente los temas no destacados de otros miembros.",
"actions.copyLink": "Copiar enlace",
"actions.copyLinkSuccess": "Enlace copiado",
"actions.copySessionId": "Copiar ID de sesión",
@@ -31,23 +31,23 @@
"actions.diagnose": "Verificar cadena de mensajes",
"actions.duplicate": "Duplicar",
"actions.export": "Exportar temas",
- "actions.favorite": "Favorito",
"actions.forwardToAgent": "Reenviar a otro agente",
"actions.import": "Importar conversación",
"actions.markCompleted": "Marcar como completada",
"actions.moveToAgent": "Mover a otro asistente",
"actions.openInNewTab": "Abrir en una nueva pestaña",
"actions.openInNewWindow": "Abrir en una nueva ventana",
+ "actions.pin": "Fijar",
"actions.removeAll": "Eliminar todos los temas",
"actions.removeAllOwn": "Eliminar Todos los Temas que Creé",
"actions.removeAllWorkspace": "Eliminar Todos los Temas del Espacio de Trabajo",
"actions.removeTopic": "Eliminar tema",
+ "actions.removeUnpinnedWorkspace": "Eliminar todos los temas no fijados",
"actions.removeUnstarred": "Eliminar temas no favoritos",
"actions.removeUnstarredOwn": "Eliminar Mis Temas Sin Marcar como Favoritos",
- "actions.removeUnstarredWorkspace": "Eliminar todos los temas no destacados",
"actions.reportProblem": "Informar de un problema",
- "actions.unfavorite": "No favorito",
"actions.unmarkCompleted": "Marcar como activa",
+ "actions.unpin": "Desfijar",
"defaultTitle": "Tema predeterminado",
"displayItems": "Mostrar elementos",
"doctor.checkFailed": "No se pudo completar la verificación.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Copiando tema...",
"duplicateSuccess": "Tema copiado con éxito",
"failedStatusTip": "Esta ejecución tuvo un error — ábrela para echar un vistazo.",
- "favorite": "Favorito",
"filter.allTopics": "Todo",
"filter.byDevice": "Dispositivo: {{value}}",
"filter.byStatus": "Estado: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Eliminar",
"management.bulk.deleteConfirm": "Estás a punto de eliminar {{count}} temas. Esta acción no se puede deshacer.",
"management.bulk.deleteTitle": "¿Eliminar temas?",
- "management.bulk.favorite": "Favorito",
"management.bulk.move": "Mover al asistente",
"management.bulk.moveEmpty": "No hay otros asistentes",
"management.bulk.moveSearchPlaceholder": "Buscar asistentes…",
+ "management.bulk.pin": "Fijar",
"management.bulk.selectedCount_one": "{{count}} seleccionado",
"management.bulk.selectedCount_other": "{{count}} seleccionados",
"management.card.noPreview": "Vista previa no disponible",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI en ejecución",
"metaCard.ci.success": "CI aprobado",
"metaCard.detached": "HEAD separado en {{sha}}",
+ "metaCard.goal": "Objetivo vinculado",
"metaCard.pr.closed": "Cerrado",
"metaCard.pr.merged": "Fusionado",
"metaCard.pr.open": "Abierto",
"newTopic": "Nuevo tema",
+ "pinned": "Fijados",
"projectStatus.failed_one": "{{count}} tema fallido",
"projectStatus.failed_other": "{{count}} temas fallidos",
"projectStatus.loading_one": "{{count}} tema cargando",
diff --git a/locales/fa-IR/common.json b/locales/fa-IR/common.json
index f81b409b179..e2078dcd18f 100644
--- a/locales/fa-IR/common.json
+++ b/locales/fa-IR/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "خروجی تمام تنظیمات نماینده",
"exportType.allAgentWithMessage": "خروجی تمام نمایندگان و پیام‌ها",
"exportType.globalSetting": "خروجی تنظیمات کلی",
+ "favorite.add": "افزودن به علاقه‌مندی‌ها",
+ "favorite.limitReached": "علاقه‌مندی‌ها می‌توانند حداکثر {{count}} مورد را نگه دارند. یکی را حذف کنید تا دیگری اضافه شود.",
+ "favorite.remove": "حذف از علاقه‌مندی‌ها",
+ "favorite.reorderError": "ترتیب علاقه‌مندی‌های شما ذخیره نشد. دوباره تلاش کنید.",
+ "favorite.section": "علاقه‌مندی‌ها",
+ "favorite.updateError": "علاقه‌مندی‌های شما به‌روزرسانی نشد. دوباره تلاش کنید.",
"feedback": "بازخورد",
"feedback.emailContact": "همچنین می‌توانید به ما ایمیل بزنید به <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "فایل بیش از ۵ مگابایت است",
diff --git a/locales/fa-IR/hotkey.json b/locales/fa-IR/hotkey.json
index 31099a372c8..528d08f6566 100644
--- a/locales/fa-IR/hotkey.json
+++ b/locales/fa-IR/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "تغییر سریع نماینده",
"switchTab.desc": "به یک تب خاص بر اساس موقعیت آن (۱–۹) در نوار تب‌های برنامه دسکتاپ بروید",
"switchTab.title": "انتقال به تب بر اساس شماره",
+ "toggleFavorite.desc": "صفحه باز را به بخش علاقه‌مندی‌ها در نوار کناری اضافه کنید یا آن را حذف کنید",
+ "toggleFavorite.title": "اضافه کردن به / حذف از علاقه‌مندی‌ها",
"toggleLeftPanel.desc": "نمایش یا پنهان کردن پنل سمت چپ",
"toggleLeftPanel.title": "تغییر وضعیت پنل چپ",
"toggleRightPanel.desc": "نمایش یا پنهان کردن پنل سمت راست",
diff --git a/locales/fa-IR/topic.json b/locales/fa-IR/topic.json
index 05fce270c73..2d39a4b8766 100644
--- a/locales/fa-IR/topic.json
+++ b/locales/fa-IR/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "در حال حذف این گفت‌وگو هستید. این عملیات قابل بازگشت نیست.",
"actions.confirmRemoveTopicFiles": "همچنین تصاویر و فایل‌های آپلود شده در این موضوع را حذف کنید",
"actions.confirmRemoveTopicTitle": "آیا این موضوع حذف شود؟",
+ "actions.confirmRemoveUnpinnedWorkspace": "در حال حذف همه موضوعات سنجاق‌نشده در فهرست فعلی فضای کاری هستید، از جمله موضوعاتی که سایر اعضا ایجاد کرده‌اند. موضوعات سنجاق‌شده باقی می‌مانند. موضوعات حذف‌شده به سطل زباله منتقل می‌شوند و تا ۳۰ روز قابل بازیابی هستند.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "می‌دانم که این کار موضوعات سنجاق‌نشده سایر اعضا را به سطل زباله منتقل می‌کند.",
"actions.confirmRemoveUnstarred": "در حال حذف گفت‌وگوهای بدون ستاره هستید. این عملیات قابل بازگشت نیست.",
"actions.confirmRemoveUnstarredOwn": "شما در حال حذف موضوعات بدون ستاره‌ای هستید که خودتان ایجاد کرده‌اید. موضوعاتی که توسط سایر اعضای فضای کاری ایجاد شده‌اند باقی خواهند ماند. این اقدام قابل بازگشت نیست.",
- "actions.confirmRemoveUnstarredWorkspace": "شما در حال حذف تمام موضوعات بدون ستاره در لیست فضای کاری فعلی هستید، از جمله موضوعاتی که توسط سایر اعضا ایجاد شده‌اند. موضوعات ستاره‌دار باقی خواهند ماند. این اقدام قابل بازگشت نیست.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "متوجه هستم که این اقدام موضوعات بدون ستاره سایر اعضا را به طور دائمی حذف می‌کند.",
"actions.copyLink": "کپی لینک",
"actions.copyLinkSuccess": "لینک کپی شد",
"actions.copySessionId": "کپی شناسه جلسه",
@@ -31,23 +31,23 @@
"actions.diagnose": "بررسی زنجیره پیام",
"actions.duplicate": "ایجاد نسخه مشابه",
"actions.export": "خروجی گرفتن از گفت‌وگوها",
- "actions.favorite": "مورد علاقه",
"actions.forwardToAgent": "ارجاع به یک نماینده دیگر",
"actions.import": "وارد کردن گفت‌وگو",
"actions.markCompleted": "علامت‌گذاری به‌عنوان انجام‌شده",
"actions.moveToAgent": "انتقال به دستیار دیگر",
"actions.openInNewTab": "باز کردن در تب جدید",
"actions.openInNewWindow": "باز کردن در پنجره جدید",
+ "actions.pin": "سنجاق کردن",
"actions.removeAll": "حذف تمام گفت‌وگوها",
"actions.removeAllOwn": "حذف تمام موضوعاتی که من ایجاد کرده‌ام",
"actions.removeAllWorkspace": "حذف تمام موضوعات فضای کاری",
"actions.removeTopic": "حذف موضوع",
+ "actions.removeUnpinnedWorkspace": "حذف همه موضوعات سنجاق‌نشده",
"actions.removeUnstarred": "حذف گفت‌وگوهای بدون ستاره",
"actions.removeUnstarredOwn": "حذف موضوعات بدون ستاره من",
- "actions.removeUnstarredWorkspace": "حذف تمام موضوعات بدون ستاره",
"actions.reportProblem": "گزارش یک مشکل",
- "actions.unfavorite": "لغو مورد علاقه",
"actions.unmarkCompleted": "علامت‌گذاری به‌عنوان فعال",
+ "actions.unpin": "برداشتن سنجاق",
"defaultTitle": "گفت‌وگوی پیش‌فرض",
"displayItems": "نمایش موارد",
"doctor.checkFailed": "بررسی انجام نشد.",
@@ -69,7 +69,6 @@
"duplicateLoading": "در حال کپی‌برداری از گفت‌وگو...",
"duplicateSuccess": "گفت‌وگو با موفقیت کپی شد",
"failedStatusTip": "این اجرا با خطا مواجه شد — برای بررسی آن را باز کنید.",
- "favorite": "نشان‌کردن",
"filter.allTopics": "همه",
"filter.byDevice": "دستگاه: {{value}}",
"filter.byStatus": "وضعیت: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "حذف",
"management.bulk.deleteConfirm": "شما در حال حذف {{count}} موضوع هستید. این عمل قابل بازگشت نیست.",
"management.bulk.deleteTitle": "حذف موضوعات؟",
- "management.bulk.favorite": "مورد علاقه",
"management.bulk.move": "انتقال به دستیار",
"management.bulk.moveEmpty": "هیچ دستیار دیگری وجود ندارد",
"management.bulk.moveSearchPlaceholder": "جستجوی دستیارها...",
+ "management.bulk.pin": "سنجاق کردن",
"management.bulk.selectedCount_one": "{{count}} انتخاب شده",
"management.bulk.selectedCount_other": "{{count}} انتخاب شده",
"management.card.noPreview": "پیش‌نمایشی در دسترس نیست",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI در حال اجرا است",
"metaCard.ci.success": "CI موفق شد",
"metaCard.detached": "HEAD جدا شده در {{sha}}",
+ "metaCard.goal": "هدف مرتبط",
"metaCard.pr.closed": "بسته شده",
"metaCard.pr.merged": "ادغام شده",
"metaCard.pr.open": "باز",
"newTopic": "موضوع جدید",
+ "pinned": "سنجاق‌شده",
"projectStatus.failed_one": "{{count}} موضوع ناموفق",
"projectStatus.failed_other": "{{count}} موضوعات ناموفق",
"projectStatus.loading_one": "{{count}} موضوع در حال بارگذاری",
diff --git a/locales/fr-FR/common.json b/locales/fr-FR/common.json
index b857e7db8b5..0ef232642c1 100644
--- a/locales/fr-FR/common.json
+++ b/locales/fr-FR/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Exporter tous les paramètres des agents",
"exportType.allAgentWithMessage": "Exporter tous les agents et les messages",
"exportType.globalSetting": "Exporter les paramètres globaux",
+ "favorite.add": "Ajouter aux Favoris",
+ "favorite.limitReached": "Les Favoris peuvent contenir jusqu'à {{count}} éléments. Supprimez-en un pour en ajouter un autre.",
+ "favorite.remove": "Retirer des Favoris",
+ "favorite.reorderError": "Impossible de sauvegarder l'ordre de vos favoris. Réessayez.",
+ "favorite.section": "Favoris",
+ "favorite.updateError": "Impossible de mettre à jour vos favoris. Réessayez.",
"feedback": "Retour",
"feedback.emailContact": "Vous pouvez également nous envoyer un e-mail à <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "Le fichier dépasse 5 Mo",
diff --git a/locales/fr-FR/hotkey.json b/locales/fr-FR/hotkey.json
index cf5de77a241..73e44f2673f 100644
--- a/locales/fr-FR/hotkey.json
+++ b/locales/fr-FR/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Changer rapidement d'agent",
"switchTab.desc": "Accéder à un onglet spécifique par sa position (1–9) dans la barre d'onglets de l'application de bureau",
"switchTab.title": "Passer à l'onglet par numéro",
+ "toggleFavorite.desc": "Ajoutez la page ouverte à la section Favoris de la barre latérale, ou supprimez-la",
+ "toggleFavorite.title": "Ajouter aux Favoris / Supprimer des Favoris",
"toggleLeftPanel.desc": "Afficher ou masquer le panneau de gauche",
"toggleLeftPanel.title": "Afficher/Masquer le panneau gauche",
"toggleRightPanel.desc": "Afficher ou masquer le panneau de droite",
diff --git a/locales/fr-FR/topic.json b/locales/fr-FR/topic.json
index 124f27fec36..671ad956e12 100644
--- a/locales/fr-FR/topic.json
+++ b/locales/fr-FR/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "Vous êtes sur le point de supprimer ce sujet. Cette action est irréversible.",
"actions.confirmRemoveTopicFiles": "Supprimer également les images et fichiers téléchargés dans ce sujet",
"actions.confirmRemoveTopicTitle": "Supprimer ce sujet ?",
+ "actions.confirmRemoveUnpinnedWorkspace": "Vous êtes sur le point de supprimer tous les sujets non épinglés de la liste actuelle de l'espace de travail, y compris ceux créés par d'autres membres. Les sujets épinglés seront conservés. Les sujets supprimés sont placés dans la corbeille et peuvent être restaurés pendant 30 jours.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Je comprends que cela place les sujets non épinglés des autres membres dans la corbeille.",
"actions.confirmRemoveUnstarred": "Vous êtes sur le point de supprimer les sujets non favoris. Cette action est irréversible.",
"actions.confirmRemoveUnstarredOwn": "Vous êtes sur le point de supprimer les sujets non étoilés que vous avez créés. Les sujets créés par d'autres membres de l'Espace de travail resteront. Cette action est irréversible.",
- "actions.confirmRemoveUnstarredWorkspace": "Vous êtes sur le point de supprimer tous les sujets non étoilés dans la liste actuelle de l'espace de travail, y compris les sujets créés par d'autres membres. Les sujets étoilés resteront. Cette action est irréversible.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Je comprends que cela supprime définitivement les sujets non étoilés des autres membres.",
"actions.copyLink": "Copier le lien",
"actions.copyLinkSuccess": "Lien copié",
"actions.copySessionId": "Copier l’ID de session",
@@ -31,23 +31,23 @@
"actions.diagnose": "Vérifier la chaîne de messages",
"actions.duplicate": "Dupliquer",
"actions.export": "Exporter les sujets",
- "actions.favorite": "Favori",
"actions.forwardToAgent": "Transférer à un autre agent",
"actions.import": "Importer une conversation",
"actions.markCompleted": "Marquer comme terminé",
"actions.moveToAgent": "Déplacer vers un autre assistant",
"actions.openInNewTab": "Ouvrir dans un nouvel onglet",
"actions.openInNewWindow": "Ouvrir dans une nouvelle fenêtre",
+ "actions.pin": "Épingler",
"actions.removeAll": "Supprimer tous les sujets",
"actions.removeAllOwn": "Supprimer tous les sujets que j'ai créés",
"actions.removeAllWorkspace": "Supprimer tous les sujets de l'Espace de travail",
"actions.removeTopic": "Supprimer le sujet",
+ "actions.removeUnpinnedWorkspace": "Supprimer tous les sujets non épinglés",
"actions.removeUnstarred": "Supprimer les sujets non favoris",
"actions.removeUnstarredOwn": "Supprimer mes sujets non étoilés",
- "actions.removeUnstarredWorkspace": "Supprimer tous les sujets non étoilés",
"actions.reportProblem": "Signaler un problème",
- "actions.unfavorite": "Retirer des favoris",
"actions.unmarkCompleted": "Marquer comme actif",
+ "actions.unpin": "Désépingler",
"defaultTitle": "Sujet par défaut",
"displayItems": "Afficher les éléments",
"doctor.checkFailed": "La vérification n'a pas pu être effectuée.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Copie du sujet en cours...",
"duplicateSuccess": "Sujet copié avec succès",
"failedStatusTip": "Cette exécution a rencontré une erreur — ouvrez-la pour en savoir plus.",
- "favorite": "Favori",
"filter.allTopics": "Tous",
"filter.byDevice": "Appareil : {{value}}",
"filter.byStatus": "Statut : {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Supprimer",
"management.bulk.deleteConfirm": "Vous êtes sur le point de supprimer {{count}} sujets. Cette action est irréversible.",
"management.bulk.deleteTitle": "Supprimer les sujets ?",
- "management.bulk.favorite": "Favori",
"management.bulk.move": "Déplacer vers l'assistant",
"management.bulk.moveEmpty": "Aucun autre assistant",
"management.bulk.moveSearchPlaceholder": "Rechercher des assistants…",
+ "management.bulk.pin": "Épingler",
"management.bulk.selectedCount_one": "{{count}} sélectionné",
"management.bulk.selectedCount_other": "{{count}} sélectionnés",
"management.card.noPreview": "Aucun aperçu disponible",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI en cours d'exécution",
"metaCard.ci.success": "CI réussi",
"metaCard.detached": "HEAD détaché à {{sha}}",
+ "metaCard.goal": "Objectif lié",
"metaCard.pr.closed": "Fermé",
"metaCard.pr.merged": "Fusionné",
"metaCard.pr.open": "Ouvert",
"newTopic": "Nouveau sujet",
+ "pinned": "Épinglés",
"projectStatus.failed_one": "{{count}} sujet échoué",
"projectStatus.failed_other": "{{count}} sujets échoués",
"projectStatus.loading_one": "{{count}} sujet en cours de chargement",
diff --git a/locales/it-IT/common.json b/locales/it-IT/common.json
index 3ffbfba2101..2b2aaaa494b 100644
--- a/locales/it-IT/common.json
+++ b/locales/it-IT/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Esporta tutte le impostazioni degli agenti",
"exportType.allAgentWithMessage": "Esporta tutti gli agenti e i messaggi",
"exportType.globalSetting": "Esporta impostazioni globali",
+ "favorite.add": "Aggiungi ai Preferiti",
+ "favorite.limitReached": "I Preferiti possono contenere fino a {{count}} elementi. Rimuovine uno per aggiungerne un altro.",
+ "favorite.remove": "Rimuovi dai Preferiti",
+ "favorite.reorderError": "Impossibile salvare l'ordine dei tuoi Preferiti. Riprova.",
+ "favorite.section": "Preferiti",
+ "favorite.updateError": "Impossibile aggiornare i tuoi Preferiti. Riprova.",
"feedback": "Feedback",
"feedback.emailContact": "Puoi anche inviarci un'email a <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "Il file supera i 5MB",
diff --git a/locales/it-IT/hotkey.json b/locales/it-IT/hotkey.json
index dfa40361038..a40fcae4d07 100644
--- a/locales/it-IT/hotkey.json
+++ b/locales/it-IT/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Cambio Rapido Agente",
"switchTab.desc": "Vai a un tab specifico in base alla sua posizione (1–9) nella barra dei tab dell'app Desktop",
"switchTab.title": "Passa al Tab per Numero",
+ "toggleFavorite.desc": "Aggiungi la pagina aperta alla sezione Preferiti della barra laterale o rimuovila",
+ "toggleFavorite.title": "Aggiungi a / Rimuovi da Preferiti",
"toggleLeftPanel.desc": "Mostra o nascondi il pannello sinistro",
"toggleLeftPanel.title": "Attiva/Disattiva Pannello Sinistro",
"toggleRightPanel.desc": "Mostra o nascondi il pannello destro",
diff --git a/locales/it-IT/topic.json b/locales/it-IT/topic.json
index ea6edb639bf..a146cb8ecc9 100644
--- a/locales/it-IT/topic.json
+++ b/locales/it-IT/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "Stai per eliminare questo argomento. Questa azione non può essere annullata.",
"actions.confirmRemoveTopicFiles": "Elimina anche immagini e file caricati in questo argomento",
"actions.confirmRemoveTopicTitle": "Eliminare questo argomento?",
+ "actions.confirmRemoveUnpinnedWorkspace": "Stai per eliminare tutti gli argomenti non fissati nella lista corrente del Workspace, inclusi quelli creati da altri membri. Gli argomenti fissati in alto rimarranno. Gli argomenti eliminati vengono spostati nel cestino e possono essere ripristinati entro 30 giorni.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Comprendo che questa azione sposta nel cestino gli argomenti non fissati degli altri membri.",
"actions.confirmRemoveUnstarred": "Stai per eliminare gli argomenti non contrassegnati. Questa azione non può essere annullata.",
"actions.confirmRemoveUnstarredOwn": "Stai per eliminare gli argomenti non contrassegnati con una stella che hai creato. Gli argomenti creati da altri membri del Workspace rimarranno. Questa azione non può essere annullata.",
- "actions.confirmRemoveUnstarredWorkspace": "Stai per eliminare tutti gli argomenti non contrassegnati con una stella nella lista corrente del Workspace, inclusi gli argomenti creati da altri membri. Gli argomenti contrassegnati con una stella rimarranno. Questa azione non può essere annullata.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Comprendo che questa azione elimina permanentemente gli argomenti non contrassegnati con una stella di altri membri.",
"actions.copyLink": "Copia link",
"actions.copyLinkSuccess": "Link copiato",
"actions.copySessionId": "Copia ID sessione",
@@ -31,23 +31,23 @@
"actions.diagnose": "Controlla Catena di Messaggi",
"actions.duplicate": "Duplica",
"actions.export": "Esporta Argomenti",
- "actions.favorite": "Preferito",
"actions.forwardToAgent": "Inoltra a un altro agente",
"actions.import": "Importa Conversazione",
"actions.markCompleted": "Segna come completato",
"actions.moveToAgent": "Sposta a un altro assistente",
"actions.openInNewTab": "Apri in una nuova scheda",
"actions.openInNewWindow": "Apri in una nuova finestra",
+ "actions.pin": "Fissa in alto",
"actions.removeAll": "Elimina Tutti gli Argomenti",
"actions.removeAllOwn": "Elimina Tutti gli Argomenti che Ho Creato",
"actions.removeAllWorkspace": "Elimina Tutti gli Argomenti del Workspace",
"actions.removeTopic": "Elimina Argomento",
+ "actions.removeUnpinnedWorkspace": "Elimina tutti gli argomenti non fissati",
"actions.removeUnstarred": "Elimina Argomenti Non Contrassegnati",
"actions.removeUnstarredOwn": "Elimina i Miei Argomenti Non Contrassegnati",
- "actions.removeUnstarredWorkspace": "Elimina tutti gli argomenti non contrassegnati con una stella",
"actions.reportProblem": "Segnala un Problema",
- "actions.unfavorite": "Non preferito",
"actions.unmarkCompleted": "Segna come attivo",
+ "actions.unpin": "Rimuovi dall'alto",
"defaultTitle": "Argomento Predefinito",
"displayItems": "Visualizza Elementi",
"doctor.checkFailed": "Il controllo non è stato completato.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Copia dell'argomento in corso...",
"duplicateSuccess": "Argomento copiato con successo",
"failedStatusTip": "Questa esecuzione ha riscontrato un errore — aprila per dare un'occhiata.",
- "favorite": "Preferito",
"filter.allTopics": "Tutti",
"filter.byDevice": "Dispositivo: {{value}}",
"filter.byStatus": "Stato: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Elimina",
"management.bulk.deleteConfirm": "Stai per eliminare {{count}} argomenti. Questa azione non può essere annullata.",
"management.bulk.deleteTitle": "Eliminare gli argomenti?",
- "management.bulk.favorite": "Preferiti",
"management.bulk.move": "Sposta all'assistente",
"management.bulk.moveEmpty": "Nessun altro assistente",
"management.bulk.moveSearchPlaceholder": "Cerca assistenti…",
+ "management.bulk.pin": "Fissa in alto",
"management.bulk.selectedCount_one": "{{count}} selezionato",
"management.bulk.selectedCount_other": "{{count}} selezionati",
"management.card.noPreview": "Anteprima non disponibile",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI in esecuzione",
"metaCard.ci.success": "CI superato",
"metaCard.detached": "HEAD scollegato a {{sha}}",
+ "metaCard.goal": "Obiettivo collegato",
"metaCard.pr.closed": "Chiuso",
"metaCard.pr.merged": "Unito",
"metaCard.pr.open": "Aperto",
"newTopic": "Nuovo argomento",
+ "pinned": "Fissati in alto",
"projectStatus.failed_one": "{{count}} argomento fallito",
"projectStatus.failed_other": "{{count}} argomenti falliti",
"projectStatus.loading_one": "{{count}} argomento in caricamento",
diff --git a/locales/ja-JP/common.json b/locales/ja-JP/common.json
index 0c4afced040..ffa4e843e66 100644
--- a/locales/ja-JP/common.json
+++ b/locales/ja-JP/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "すべてのアシスタント設定をエクスポート",
"exportType.allAgentWithMessage": "すべてのアシスタントとメッセージをエクスポート",
"exportType.globalSetting": "グローバル設定をエクスポート",
+ "favorite.add": "お気に入りに追加",
+ "favorite.limitReached": "お気に入りには最大{{count}}件まで追加できます。追加するには1件削除してください。",
+ "favorite.remove": "お気に入りから削除",
+ "favorite.reorderError": "お気に入りの順序を保存できませんでした。もう一度お試しください。",
+ "favorite.section": "お気に入り",
+ "favorite.updateError": "お気に入りを更新できませんでした。もう一度お試しください。",
"feedback": "フィードバック",
"feedback.emailContact": "また、<email>{{email}}</email> にメールを送ることもできます",
"feedback.errors.fileTooLarge": "ファイルサイズが5MBを超えています",
diff --git a/locales/ja-JP/hotkey.json b/locales/ja-JP/hotkey.json
index 7532376ab38..3be4d76732d 100644
--- a/locales/ja-JP/hotkey.json
+++ b/locales/ja-JP/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "アシスタントを素早く切り替え",
"switchTab.desc": "デスクトップアプリのタブバーで位置(1~9)によって特定のタブにジャンプします。",
"switchTab.title": "番号でタブを切り替え",
+ "toggleFavorite.desc": "開いているページをサイドバーのお気に入りセクションに追加するか、削除します",
+ "toggleFavorite.title": "お気に入りに追加 / 削除",
"toggleLeftPanel.desc": "左側パネルの表示・非表示を切り替えます",
"toggleLeftPanel.title": "左側パネルの表示/非表示",
"toggleRightPanel.desc": "右側パネルの表示・非表示を切り替えます",
diff --git a/locales/ja-JP/topic.json b/locales/ja-JP/topic.json
index 6c726516b59..c3e24a8e360 100644
--- a/locales/ja-JP/topic.json
+++ b/locales/ja-JP/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "このトピックを削除しようとしています。この操作は元に戻せません。",
"actions.confirmRemoveTopicFiles": "このトピックでアップロードされた画像やファイルも削除しますか",
"actions.confirmRemoveTopicTitle": "このトピックを削除しますか?",
+ "actions.confirmRemoveUnpinnedWorkspace": "現在のワークスペースリストにあるピン留めされていないトピックをすべて削除します。他のメンバーが作成したトピックも含まれます。ピン留めされたトピックは残ります。削除したトピックはゴミ箱に移動し、30 日以内であれば復元できます。",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "他のメンバーのピン留めされていないトピックがゴミ箱に移動されることを理解しました。",
"actions.confirmRemoveUnstarred": "スターの付いていないトピックを削除しようとしています。この操作は元に戻せません。",
"actions.confirmRemoveUnstarredOwn": "スターが付いていない自分が作成したトピックを削除しようとしています。他のワークスペースメンバーが作成したトピックは残ります。この操作は元に戻せません。",
- "actions.confirmRemoveUnstarredWorkspace": "現在のワークスペースリスト内のすべてのスターが付いていないトピックを削除しようとしています。他のメンバーが作成したトピックも含まれます。スター付きのトピックは残ります。この操作は元に戻せません。",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "他のメンバーのスターが付いていないトピックを永久に削除することを理解しました。",
"actions.copyLink": "リンクをコピー",
"actions.copyLinkSuccess": "リンクをコピーしました",
"actions.copySessionId": "セッションIDをコピー",
@@ -31,23 +31,23 @@
"actions.diagnose": "メッセージチェーンを確認",
"actions.duplicate": "複製",
"actions.export": "トピックをエクスポート",
- "actions.favorite": "お気に入り",
"actions.forwardToAgent": "別のエージェントに転送",
"actions.import": "会話をインポート",
"actions.markCompleted": "完了としてマーク",
"actions.moveToAgent": "別のアシスタントに移動",
"actions.openInNewTab": "新しいタブで開く",
"actions.openInNewWindow": "新しいウィンドウで開く",
+ "actions.pin": "ピン留め",
"actions.removeAll": "すべてのトピックを削除",
"actions.removeAllOwn": "自分が作成したすべてのトピックを削除",
"actions.removeAllWorkspace": "ワークスペース内のすべてのトピックを削除",
"actions.removeTopic": "トピックを削除",
+ "actions.removeUnpinnedWorkspace": "ピン留めされていないすべてのトピックを削除",
"actions.removeUnstarred": "未お気に入りのトピックを削除",
"actions.removeUnstarredOwn": "スターが付いていない自分のトピックを削除",
- "actions.removeUnstarredWorkspace": "スターが付いていないすべてのトピックを削除",
"actions.reportProblem": "問題を報告",
- "actions.unfavorite": "お気に入り解除",
"actions.unmarkCompleted": "アクティブに戻す",
+ "actions.unpin": "ピン留めを解除",
"defaultTitle": "デフォルトトピック",
"displayItems": "項目を表示",
"doctor.checkFailed": "チェックを完了できませんでした。",
@@ -69,7 +69,6 @@
"duplicateLoading": "トピックをコピー中...",
"duplicateSuccess": "トピックのコピーに成功しました",
"failedStatusTip": "この実行中にエラーが発生しました — 詳細を確認してください。",
- "favorite": "お気に入り",
"filter.allTopics": "すべて",
"filter.byDevice": "デバイス: {{value}}",
"filter.byStatus": "ステータス: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "削除",
"management.bulk.deleteConfirm": "{{count}}件のトピックを削除しようとしています。この操作は元に戻せません。",
"management.bulk.deleteTitle": "トピックを削除しますか?",
- "management.bulk.favorite": "お気に入り",
"management.bulk.move": "アシスタントに移動",
"management.bulk.moveEmpty": "他のアシスタントがありません",
"management.bulk.moveSearchPlaceholder": "アシスタントを検索…",
+ "management.bulk.pin": "ピン留め",
"management.bulk.selectedCount_one": "{{count}}件選択済み",
"management.bulk.selectedCount_other": "{{count}}件選択済み",
"management.card.noPreview": "プレビューは利用できません",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI実行中",
"metaCard.ci.success": "CIが成功しました",
"metaCard.detached": "{{sha}}でデタッチされたHEAD",
+ "metaCard.goal": "リンクされた目標",
"metaCard.pr.closed": "クローズ済み",
"metaCard.pr.merged": "マージ済み",
"metaCard.pr.open": "オープン",
"newTopic": "新しいトピック",
+ "pinned": "ピン留め済み",
"projectStatus.failed_one": "{{count}} 件のトピックが失敗しました",
"projectStatus.failed_other": "{{count}} 件のトピックが失敗しました",
"projectStatus.loading_one": "{{count}} 件のトピックを読み込み中",
diff --git a/locales/ko-KR/common.json b/locales/ko-KR/common.json
index fa40530f355..f3d3c2acae9 100644
--- a/locales/ko-KR/common.json
+++ b/locales/ko-KR/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "모든 도우미 설정 내보내기",
"exportType.allAgentWithMessage": "모든 도우미 및 메시지 내보내기",
"exportType.globalSetting": "전체 설정 내보내기",
+ "favorite.add": "즐겨찾기에 추가",
+ "favorite.limitReached": "즐겨찾기는 최대 {{count}}개의 항목을 저장할 수 있습니다. 다른 항목을 추가하려면 하나를 제거하세요.",
+ "favorite.remove": "즐겨찾기에서 제거",
+ "favorite.reorderError": "즐겨찾기의 순서를 저장할 수 없습니다. 다시 시도하세요.",
+ "favorite.section": "즐겨찾기",
+ "favorite.updateError": "즐겨찾기를 업데이트할 수 없습니다. 다시 시도하세요.",
"feedback": "피드백 및 제안",
"feedback.emailContact": "<email>{{email}}</email>로 이메일을 보내주실 수도 있습니다",
"feedback.errors.fileTooLarge": "파일 크기가 5MB를 초과합니다",
diff --git a/locales/ko-KR/hotkey.json b/locales/ko-KR/hotkey.json
index c97f07a9b34..8a3e101fcdb 100644
--- a/locales/ko-KR/hotkey.json
+++ b/locales/ko-KR/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "도우미 빠르게 전환",
"switchTab.desc": "데스크톱 앱 탭 바에서 위치(1–9)에 따라 특정 탭으로 바로 이동합니다.",
"switchTab.title": "번호로 탭 전환",
+ "toggleFavorite.desc": "열린 페이지를 사이드바의 즐겨찾기 섹션에 추가하거나 제거합니다",
+ "toggleFavorite.title": "즐겨찾기에 추가 / 제거",
"toggleLeftPanel.desc": "왼쪽 패널 표시 또는 숨기기",
"toggleLeftPanel.title": "왼쪽 패널 표시/숨기기",
"toggleRightPanel.desc": "오른쪽 패널 표시 또는 숨기기",
diff --git a/locales/ko-KR/topic.json b/locales/ko-KR/topic.json
index f4117ad479e..0134569277a 100644
--- a/locales/ko-KR/topic.json
+++ b/locales/ko-KR/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "이 주제를 삭제하려고 합니다. 이 작업은 되돌릴 수 없습니다.",
"actions.confirmRemoveTopicFiles": "이 주제에 업로드된 이미지와 파일도 삭제하시겠습니까?",
"actions.confirmRemoveTopicTitle": "이 주제를 삭제하시겠습니까?",
+ "actions.confirmRemoveUnpinnedWorkspace": "현재 워크스페이스 목록에서 다른 멤버가 만든 주제를 포함해 고정되지 않은 모든 주제를 삭제합니다. 고정된 주제는 유지됩니다. 삭제된 주제는 휴지통으로 이동하며 30일 이내에 복원할 수 있습니다.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "다른 멤버의 고정되지 않은 주제가 휴지통으로 이동된다는 것을 이해합니다.",
"actions.confirmRemoveUnstarred": "즐겨찾기되지 않은 주제를 삭제하려고 합니다. 이 작업은 되돌릴 수 없습니다.",
"actions.confirmRemoveUnstarredOwn": "내가 생성한 별표가 없는 주제를 삭제하려고 합니다. 다른 워크스페이스 멤버가 생성한 주제는 유지됩니다. 이 작업은 되돌릴 수 없습니다.",
- "actions.confirmRemoveUnstarredWorkspace": "현재 워크스페이스 목록에서 다른 멤버가 생성한 주제를 포함하여 모든 별표가 없는 주제를 삭제하려고 합니다. 별표가 있는 주제는 유지됩니다. 이 작업은 되돌릴 수 없습니다.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "다른 멤버의 별표가 없는 주제를 영구적으로 삭제한다는 것을 이해합니다.",
"actions.copyLink": "링크 복사",
"actions.copyLinkSuccess": "링크가 복사되었습니다",
"actions.copySessionId": "세션 ID 복사",
@@ -31,23 +31,23 @@
"actions.diagnose": "메시지 체인 확인",
"actions.duplicate": "복제",
"actions.export": "주제 내보내기",
- "actions.favorite": "즐겨찾기",
"actions.forwardToAgent": "다른 상담원에게 전달",
"actions.import": "대화 가져오기",
"actions.markCompleted": "완료로 표시",
"actions.moveToAgent": "다른 어시스턴트로 이동",
"actions.openInNewTab": "새 탭에서 열기",
"actions.openInNewWindow": "새 창에서 열기",
+ "actions.pin": "고정",
"actions.removeAll": "모든 주제 삭제",
"actions.removeAllOwn": "내가 생성한 모든 주제 삭제",
"actions.removeAllWorkspace": "워크스페이스의 모든 주제 삭제",
"actions.removeTopic": "주제 삭제",
+ "actions.removeUnpinnedWorkspace": "고정되지 않은 모든 주제 삭제",
"actions.removeUnstarred": "즐겨찾기하지 않은 주제 삭제",
"actions.removeUnstarredOwn": "내 별표 없는 주제 삭제",
- "actions.removeUnstarredWorkspace": "별표가 없는 모든 주제 삭제",
"actions.reportProblem": "문제 보고",
- "actions.unfavorite": "즐겨찾기 해제",
"actions.unmarkCompleted": "활성으로 표시",
+ "actions.unpin": "고정 해제",
"defaultTitle": "기본 주제",
"displayItems": "항목 표시",
"doctor.checkFailed": "검사를 완료할 수 없습니다.",
@@ -69,7 +69,6 @@
"duplicateLoading": "주제 복사 중...",
"duplicateSuccess": "주제 복사 성공",
"failedStatusTip": "이 실행에서 오류가 발생했습니다 — 열어서 확인하세요.",
- "favorite": "즐겨찾기",
"filter.allTopics": "모두",
"filter.byDevice": "장치: {{value}}",
"filter.byStatus": "상태: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "삭제",
"management.bulk.deleteConfirm": "{{count}}개의 주제를 삭제하려고 합니다. 이 작업은 되돌릴 수 없습니다.",
"management.bulk.deleteTitle": "주제를 삭제하시겠습니까?",
- "management.bulk.favorite": "즐겨찾기",
"management.bulk.move": "어시스턴트로 이동",
"management.bulk.moveEmpty": "다른 어시스턴트 없음",
"management.bulk.moveSearchPlaceholder": "어시스턴트 검색…",
+ "management.bulk.pin": "고정",
"management.bulk.selectedCount_one": "{{count}}개 선택됨",
"management.bulk.selectedCount_other": "{{count}}개 선택됨",
"management.card.noPreview": "미리보기를 사용할 수 없습니다",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI 실행 중",
"metaCard.ci.success": "CI 성공",
"metaCard.detached": "HEAD가 {{sha}}에서 분리됨",
+ "metaCard.goal": "연결된 목표",
"metaCard.pr.closed": "닫힘",
"metaCard.pr.merged": "병합됨",
"metaCard.pr.open": "열림",
"newTopic": "새 토픽",
+ "pinned": "고정됨",
"projectStatus.failed_one": "{{count}}개의 실패한 주제",
"projectStatus.failed_other": "{{count}}개의 실패한 주제들",
"projectStatus.loading_one": "{{count}}개의 로딩 중인 주제",
diff --git a/locales/nl-NL/common.json b/locales/nl-NL/common.json
index 558b46d33b7..8ee4e2984f5 100644
--- a/locales/nl-NL/common.json
+++ b/locales/nl-NL/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Alle agentinstellingen exporteren",
"exportType.allAgentWithMessage": "Alle agents en berichten exporteren",
"exportType.globalSetting": "Globale instellingen exporteren",
+ "favorite.add": "Toevoegen aan favorieten",
+ "favorite.limitReached": "Favorieten kunnen maximaal {{count}} items bevatten. Verwijder er een om een andere toe te voegen.",
+ "favorite.remove": "Verwijderen uit favorieten",
+ "favorite.reorderError": "De volgorde van je favorieten kon niet worden opgeslagen. Probeer het opnieuw.",
+ "favorite.section": "Favorieten",
+ "favorite.updateError": "Je favorieten konden niet worden bijgewerkt. Probeer het opnieuw.",
"feedback": "Feedback",
"feedback.emailContact": "Je kunt ons ook e-mailen op <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "Bestand is groter dan 5MB",
diff --git a/locales/nl-NL/hotkey.json b/locales/nl-NL/hotkey.json
index 4948bedfbe4..471623f354a 100644
--- a/locales/nl-NL/hotkey.json
+++ b/locales/nl-NL/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Snel Wisselen van Agent",
"switchTab.desc": "Spring naar een specifiek tabblad op basis van zijn positie (1–9) in de tabbladenbalk van de Desktop-app",
"switchTab.title": "Schakel naar Tabblad op Nummer",
+ "toggleFavorite.desc": "Voeg de geopende pagina toe aan de sectie Favorieten in de zijbalk, of verwijder deze",
+ "toggleFavorite.title": "Toevoegen aan / Verwijderen uit Favorieten",
"toggleLeftPanel.desc": "Toon of verberg het linker paneel",
"toggleLeftPanel.title": "Linker Paneel Wisselen",
"toggleRightPanel.desc": "Toon of verberg het rechter paneel",
diff --git a/locales/nl-NL/topic.json b/locales/nl-NL/topic.json
index 7ab7378ff7a..6d289d813c1 100644
--- a/locales/nl-NL/topic.json
+++ b/locales/nl-NL/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "Je staat op het punt om dit onderwerp te verwijderen. Deze actie kan niet ongedaan worden gemaakt.",
"actions.confirmRemoveTopicFiles": "Verwijder ook afbeeldingen en bestanden die in dit onderwerp zijn geüpload",
"actions.confirmRemoveTopicTitle": "Dit onderwerp verwijderen?",
+ "actions.confirmRemoveUnpinnedWorkspace": "Je staat op het punt alle niet-vastgezette onderwerpen in de huidige Workspace-lijst te verwijderen, inclusief onderwerpen van andere leden. Vastgezette onderwerpen blijven behouden. Verwijderde onderwerpen gaan naar de prullenbak en kunnen binnen 30 dagen worden hersteld.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Ik begrijp dat dit de niet-vastgezette onderwerpen van andere leden naar de prullenbak verplaatst.",
"actions.confirmRemoveUnstarred": "Je staat op het punt om niet-gemarkeerde onderwerpen te verwijderen. Deze actie kan niet ongedaan worden gemaakt.",
"actions.confirmRemoveUnstarredOwn": "Je staat op het punt om niet-gemarkeerde onderwerpen die je hebt gemaakt te verwijderen. Onderwerpen die door andere Workspace-leden zijn gemaakt, blijven behouden. Deze actie kan niet ongedaan worden gemaakt.",
- "actions.confirmRemoveUnstarredWorkspace": "Je staat op het punt alle niet-gemarkeerde onderwerpen in de huidige Workspace-lijst te verwijderen, inclusief onderwerpen die door andere leden zijn gemaakt. Gemarkeerde onderwerpen blijven behouden. Deze actie kan niet ongedaan worden gemaakt.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Ik begrijp dat dit permanent de niet-gemarkeerde onderwerpen van andere leden verwijdert.",
"actions.copyLink": "Link kopiëren",
"actions.copyLinkSuccess": "Link gekopieerd",
"actions.copySessionId": "Sessie-ID kopiëren",
@@ -31,23 +31,23 @@
"actions.diagnose": "Controleer berichtketen",
"actions.duplicate": "Dupliceren",
"actions.export": "Onderwerpen exporteren",
- "actions.favorite": "Favoriet",
"actions.forwardToAgent": "Doorschakelen naar een andere agent",
"actions.import": "Gesprek importeren",
"actions.markCompleted": "Markeren als voltooid",
"actions.moveToAgent": "Verplaatsen naar een andere assistent",
"actions.openInNewTab": "Openen in nieuw tabblad",
"actions.openInNewWindow": "Openen in een nieuw venster",
+ "actions.pin": "Vastzetten",
"actions.removeAll": "Alle onderwerpen verwijderen",
"actions.removeAllOwn": "Verwijder Alle Onderwerpen Die Ik Heb Gemaakt",
"actions.removeAllWorkspace": "Verwijder Alle Workspace Onderwerpen",
"actions.removeTopic": "Onderwerp verwijderen",
+ "actions.removeUnpinnedWorkspace": "Alle niet-vastgezette onderwerpen verwijderen",
"actions.removeUnstarred": "Niet-gemarkeerde onderwerpen verwijderen",
"actions.removeUnstarredOwn": "Verwijder Mijn Niet-Gemarkeerde Onderwerpen",
- "actions.removeUnstarredWorkspace": "Verwijder alle niet-gemarkeerde onderwerpen",
"actions.reportProblem": "Een probleem melden",
- "actions.unfavorite": "Niet meer favoriet",
"actions.unmarkCompleted": "Markeren als actief",
+ "actions.unpin": "Losmaken",
"defaultTitle": "Standaardonderwerp",
"displayItems": "Items weergeven",
"doctor.checkFailed": "De controle kon niet worden voltooid.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Onderwerp wordt gekopieerd...",
"duplicateSuccess": "Onderwerp succesvol gekopieerd",
"failedStatusTip": "Deze run heeft een fout opgelopen — open het om te bekijken.",
- "favorite": "Favoriet",
"filter.allTopics": "Alle",
"filter.byDevice": "Apparaat: {{value}}",
"filter.byStatus": "Status: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Verwijderen",
"management.bulk.deleteConfirm": "Je staat op het punt om {{count}} onderwerpen te verwijderen. Deze actie kan niet ongedaan worden gemaakt.",
"management.bulk.deleteTitle": "Onderwerpen verwijderen?",
- "management.bulk.favorite": "Favoriet",
"management.bulk.move": "Verplaatsen naar assistent",
"management.bulk.moveEmpty": "Geen andere assistenten",
"management.bulk.moveSearchPlaceholder": "Zoek assistenten…",
+ "management.bulk.pin": "Vastzetten",
"management.bulk.selectedCount_one": "{{count}} geselecteerd",
"management.bulk.selectedCount_other": "{{count}} geselecteerd",
"management.card.noPreview": "Geen voorbeeld beschikbaar",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI wordt uitgevoerd",
"metaCard.ci.success": "CI geslaagd",
"metaCard.detached": "Losgekoppelde HEAD bij {{sha}}",
+ "metaCard.goal": "Gekoppeld doel",
"metaCard.pr.closed": "Gesloten",
"metaCard.pr.merged": "Samengevoegd",
"metaCard.pr.open": "Open",
"newTopic": "Nieuw onderwerp",
+ "pinned": "Vastgezet",
"projectStatus.failed_one": "{{count}} mislukt onderwerp",
"projectStatus.failed_other": "{{count}} mislukte onderwerpen",
"projectStatus.loading_one": "{{count}} onderwerp wordt geladen",
diff --git a/locales/pl-PL/common.json b/locales/pl-PL/common.json
index 0288ec1519c..9a690361e87 100644
--- a/locales/pl-PL/common.json
+++ b/locales/pl-PL/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Eksportuj wszystkie ustawienia agentów",
"exportType.allAgentWithMessage": "Eksportuj wszystkich agentów i wiadomości",
"exportType.globalSetting": "Eksportuj ustawienia globalne",
+ "favorite.add": "Dodaj do Ulubionych",
+ "favorite.limitReached": "Ulubione mogą zawierać maksymalnie {{count}} elementów. Usuń jeden, aby dodać kolejny.",
+ "favorite.remove": "Usuń z Ulubionych",
+ "favorite.reorderError": "Nie udało się zapisać kolejności ulubionych. Spróbuj ponownie.",
+ "favorite.section": "Ulubione",
+ "favorite.updateError": "Nie udało się zaktualizować ulubionych. Spróbuj ponownie.",
"feedback": "Opinie",
"feedback.emailContact": "Możesz również wysłać do nas e-mail na adres <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "Plik przekracza 5 MB",
diff --git a/locales/pl-PL/hotkey.json b/locales/pl-PL/hotkey.json
index 8630f3d1594..7b5f1d3d912 100644
--- a/locales/pl-PL/hotkey.json
+++ b/locales/pl-PL/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Szybkie przełączanie agenta",
"switchTab.desc": "Przejdź do konkretnej zakładki według jej pozycji (1–9) na pasku zakładek aplikacji Desktop",
"switchTab.title": "Przełącz na zakładkę według numeru",
+ "toggleFavorite.desc": "Dodaj otwartą stronę do sekcji Ulubione na pasku bocznym lub usuń ją",
+ "toggleFavorite.title": "Dodaj do / Usuń z Ulubionych",
"toggleLeftPanel.desc": "Pokaż lub ukryj lewy panel",
"toggleLeftPanel.title": "Przełącz lewy panel",
"toggleRightPanel.desc": "Pokaż lub ukryj prawy panel",
diff --git a/locales/pl-PL/topic.json b/locales/pl-PL/topic.json
index d9a1bb9a7ef..55f90b000cd 100644
--- a/locales/pl-PL/topic.json
+++ b/locales/pl-PL/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "Zamierzasz usunąć ten temat. Tej operacji nie można cofnąć.",
"actions.confirmRemoveTopicFiles": "Usuń również obrazy i pliki przesłane w tym temacie",
"actions.confirmRemoveTopicTitle": "Usunąć ten temat?",
+ "actions.confirmRemoveUnpinnedWorkspace": "Zamierzasz usunąć wszystkie nieprzypięte tematy z bieżącej listy przestrzeni roboczej, w tym tematy utworzone przez innych członków. Przypięte tematy pozostaną. Usunięte tematy trafiają do kosza i można je przywrócić w ciągu 30 dni.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Rozumiem, że to przeniesie nieprzypięte tematy innych członków do kosza.",
"actions.confirmRemoveUnstarred": "Zamierzasz usunąć nieoznaczone gwiazdką tematy. Tej operacji nie można cofnąć.",
"actions.confirmRemoveUnstarredOwn": "Zamierzasz usunąć nieoznaczone gwiazdką tematy, które utworzyłeś. Tematy utworzone przez innych członków Workspace pozostaną. Ta akcja jest nieodwracalna.",
- "actions.confirmRemoveUnstarredWorkspace": "Zamierzasz usunąć wszystkie nieoznaczone gwiazdką tematy z bieżącej listy przestrzeni roboczej, w tym tematy utworzone przez innych członków. Tematy oznaczone gwiazdką pozostaną. Ta operacja jest nieodwracalna.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Rozumiem, że to trwale usuwa nieoznaczone gwiazdką tematy innych członków.",
"actions.copyLink": "Kopiuj link",
"actions.copyLinkSuccess": "Link skopiowany",
"actions.copySessionId": "Kopiuj ID sesji",
@@ -31,23 +31,23 @@
"actions.diagnose": "Sprawdź łańcuch wiadomości",
"actions.duplicate": "Duplikuj",
"actions.export": "Eksportuj tematy",
- "actions.favorite": "Ulubione",
"actions.forwardToAgent": "Przekaż do innego agenta",
"actions.import": "Importuj rozmowę",
"actions.markCompleted": "Oznacz jako ukończone",
"actions.moveToAgent": "Przenieś do innego asystenta",
"actions.openInNewTab": "Otwórz w nowej karcie",
"actions.openInNewWindow": "Otwórz w nowym oknie",
+ "actions.pin": "Przypnij",
"actions.removeAll": "Usuń wszystkie tematy",
"actions.removeAllOwn": "Usuń wszystkie tematy, które utworzyłem",
"actions.removeAllWorkspace": "Usuń wszystkie tematy Workspace",
"actions.removeTopic": "Usuń temat",
+ "actions.removeUnpinnedWorkspace": "Usuń wszystkie nieprzypięte tematy",
"actions.removeUnstarred": "Usuń nieoznaczone gwiazdką tematy",
"actions.removeUnstarredOwn": "Usuń moje tematy bez gwiazdki",
- "actions.removeUnstarredWorkspace": "Usuń wszystkie nieoznaczone gwiazdką tematy",
"actions.reportProblem": "Zgłoś problem",
- "actions.unfavorite": "Nieulubione",
"actions.unmarkCompleted": "Oznacz jako aktywne",
+ "actions.unpin": "Odepnij",
"defaultTitle": "Domyślny temat",
"displayItems": "Wyświetl elementy",
"doctor.checkFailed": "Nie udało się zakończyć sprawdzania.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Kopiowanie tematu...",
"duplicateSuccess": "Temat skopiowany pomyślnie",
"failedStatusTip": "Ten przebieg napotkał błąd — otwórz go, aby zobaczyć szczegóły.",
- "favorite": "Ulubione",
"filter.allTopics": "Wszystkie",
"filter.byDevice": "Urządzenie: {{value}}",
"filter.byStatus": "Status: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Usuń",
"management.bulk.deleteConfirm": "Zamierzasz usunąć {{count}} tematów. Ta operacja jest nieodwracalna.",
"management.bulk.deleteTitle": "Usunąć tematy?",
- "management.bulk.favorite": "Ulubione",
"management.bulk.move": "Przenieś do asystenta",
"management.bulk.moveEmpty": "Brak innych asystentów",
"management.bulk.moveSearchPlaceholder": "Szukaj asystentów…",
+ "management.bulk.pin": "Przypnij",
"management.bulk.selectedCount_one": "{{count}} wybrany",
"management.bulk.selectedCount_other": "{{count}} wybranych",
"management.card.noPreview": "Brak dostępnego podglądu",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI w toku",
"metaCard.ci.success": "CI zakończone pomyślnie",
"metaCard.detached": "Odłączony HEAD na {{sha}}",
+ "metaCard.goal": "Powiązany cel",
"metaCard.pr.closed": "Zamknięte",
"metaCard.pr.merged": "Scalone",
"metaCard.pr.open": "Otwarte",
"newTopic": "Nowy temat",
+ "pinned": "Przypięte",
"projectStatus.failed_one": "{{count}} nieudany temat",
"projectStatus.failed_other": "{{count}} nieudane tematy",
"projectStatus.loading_one": "{{count}} ładowany temat",
diff --git a/locales/pt-BR/common.json b/locales/pt-BR/common.json
index e4816b896d2..7bc59fd8198 100644
--- a/locales/pt-BR/common.json
+++ b/locales/pt-BR/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Exportar Todas as Configurações dos Agentes",
"exportType.allAgentWithMessage": "Exportar Todos os Agentes e Mensagens",
"exportType.globalSetting": "Exportar Configurações Globais",
+ "favorite.add": "Adicionar aos Favoritos",
+ "favorite.limitReached": "Os Favoritos podem conter até {{count}} itens. Remova um para adicionar outro.",
+ "favorite.remove": "Remover dos Favoritos",
+ "favorite.reorderError": "Não foi possível salvar a ordem dos seus favoritos. Tente novamente.",
+ "favorite.section": "Favoritos",
+ "favorite.updateError": "Não foi possível atualizar seus favoritos. Tente novamente.",
"feedback": "Feedback",
"feedback.emailContact": "Você também pode nos enviar um e-mail para <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "O arquivo excede 5MB",
diff --git a/locales/pt-BR/hotkey.json b/locales/pt-BR/hotkey.json
index 590fd2fff66..1adacab6b43 100644
--- a/locales/pt-BR/hotkey.json
+++ b/locales/pt-BR/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Trocar Agente Rapidamente",
"switchTab.desc": "Ir para uma aba específica pela sua posição (1–9) na barra de abas do aplicativo Desktop",
"switchTab.title": "Alternar para Aba por Número",
+ "toggleFavorite.desc": "Adicione a página aberta à seção Favoritos da barra lateral ou remova-a",
+ "toggleFavorite.title": "Adicionar aos / Remover dos Favoritos",
"toggleLeftPanel.desc": "Mostrar ou ocultar o painel esquerdo",
"toggleLeftPanel.title": "Alternar Painel Esquerdo",
"toggleRightPanel.desc": "Mostrar ou ocultar o painel direito",
diff --git a/locales/pt-BR/topic.json b/locales/pt-BR/topic.json
index c5c96715704..6b6a4c27e3f 100644
--- a/locales/pt-BR/topic.json
+++ b/locales/pt-BR/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "Você está prestes a excluir este tópico. Esta ação não pode ser desfeita.",
"actions.confirmRemoveTopicFiles": "Também excluir imagens e arquivos enviados neste tópico",
"actions.confirmRemoveTopicTitle": "Excluir este tópico?",
+ "actions.confirmRemoveUnpinnedWorkspace": "Você está prestes a excluir todos os tópicos não fixados da lista atual do Workspace, incluindo tópicos criados por outros membros. Os tópicos fixados serão mantidos. Os tópicos excluídos vão para a lixeira e podem ser restaurados em até 30 dias.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Entendo que isso move para a lixeira os tópicos não fixados de outros membros.",
"actions.confirmRemoveUnstarred": "Você está prestes a excluir os tópicos não favoritados. Esta ação não pode ser desfeita.",
"actions.confirmRemoveUnstarredOwn": "Você está prestes a excluir os tópicos não estrelados que criou. Tópicos criados por outros membros do Workspace permanecerão. Esta ação não pode ser desfeita.",
- "actions.confirmRemoveUnstarredWorkspace": "Você está prestes a excluir todos os tópicos não favoritados na lista atual do Workspace, incluindo tópicos criados por outros membros. Tópicos favoritados permanecerão. Esta ação não pode ser desfeita.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Eu entendo que isso exclui permanentemente os tópicos não favoritados de outros membros.",
"actions.copyLink": "Copiar link",
"actions.copyLinkSuccess": "Link copiado",
"actions.copySessionId": "Copiar ID da sessão",
@@ -31,23 +31,23 @@
"actions.diagnose": "Verificar Cadeia de Mensagens",
"actions.duplicate": "Duplicar",
"actions.export": "Exportar Tópicos",
- "actions.favorite": "Favoritar",
"actions.forwardToAgent": "Encaminhar para outro agente",
"actions.import": "Importar Conversa",
"actions.markCompleted": "Marcar como Concluída",
"actions.moveToAgent": "Mover para outro assistente",
"actions.openInNewTab": "Abrir em Nova Aba",
"actions.openInNewWindow": "Abrir em nova janela",
+ "actions.pin": "Fixar",
"actions.removeAll": "Excluir Todos os Tópicos",
"actions.removeAllOwn": "Excluir Todos os Tópicos que Criei",
"actions.removeAllWorkspace": "Excluir Todos os Tópicos do Workspace",
"actions.removeTopic": "Excluir Tópico",
+ "actions.removeUnpinnedWorkspace": "Excluir todos os tópicos não fixados",
"actions.removeUnstarred": "Excluir Tópicos Não Favoritados",
"actions.removeUnstarredOwn": "Excluir Meus Tópicos Não Estrelados",
- "actions.removeUnstarredWorkspace": "Excluir Todos os Tópicos Não Favoritados",
"actions.reportProblem": "Relatar um Problema",
- "actions.unfavorite": "Desfavoritar",
"actions.unmarkCompleted": "Marcar como Ativa",
+ "actions.unpin": "Desafixar",
"defaultTitle": "Tópico Padrão",
"displayItems": "Exibir Itens",
"doctor.checkFailed": "A verificação não pôde ser concluída.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Copiando Tópico...",
"duplicateSuccess": "Tópico Copiado com Sucesso",
"failedStatusTip": "Esta execução encontrou um erro — abra para dar uma olhada.",
- "favorite": "Favorito",
"filter.allTopics": "Todos",
"filter.byDevice": "Dispositivo: {{value}}",
"filter.byStatus": "Status: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Excluir",
"management.bulk.deleteConfirm": "Você está prestes a excluir {{count}} tópicos. Esta ação não pode ser desfeita.",
"management.bulk.deleteTitle": "Excluir tópicos?",
- "management.bulk.favorite": "Favoritar",
"management.bulk.move": "Mover para assistente",
"management.bulk.moveEmpty": "Nenhum outro assistente",
"management.bulk.moveSearchPlaceholder": "Buscar assistentes…",
+ "management.bulk.pin": "Fixar",
"management.bulk.selectedCount_one": "{{count}} selecionado",
"management.bulk.selectedCount_other": "{{count}} selecionados",
"management.card.noPreview": "Nenhuma prévia disponível",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI em execução",
"metaCard.ci.success": "CI aprovado",
"metaCard.detached": "HEAD destacado em {{sha}}",
+ "metaCard.goal": "Objetivo vinculado",
"metaCard.pr.closed": "Fechado",
"metaCard.pr.merged": "Mesclado",
"metaCard.pr.open": "Aberto",
"newTopic": "Novo tópico",
+ "pinned": "Fixados",
"projectStatus.failed_one": "{{count}} tópico falhou",
"projectStatus.failed_other": "{{count}} tópicos falharam",
"projectStatus.loading_one": "{{count}} tópico carregando",
diff --git a/locales/ru-RU/common.json b/locales/ru-RU/common.json
index 0bc117c3363..a6e52730474 100644
--- a/locales/ru-RU/common.json
+++ b/locales/ru-RU/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Экспорт всех настроек агентов",
"exportType.allAgentWithMessage": "Экспорт всех агентов и сообщений",
"exportType.globalSetting": "Экспорт глобальных настроек",
+ "favorite.add": "Добавить в избранное",
+ "favorite.limitReached": "В избранное можно добавить до {{count}} элементов. Удалите один, чтобы добавить другой.",
+ "favorite.remove": "Удалить из избранного",
+ "favorite.reorderError": "Не удалось сохранить порядок избранного. Попробуйте еще раз.",
+ "favorite.section": "Избранное",
+ "favorite.updateError": "Не удалось обновить избранное. Попробуйте еще раз.",
"feedback": "Обратная связь",
"feedback.emailContact": "Вы также можете написать нам на <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "Файл превышает 5 МБ",
diff --git a/locales/ru-RU/hotkey.json b/locales/ru-RU/hotkey.json
index ae1b6ce7278..2cfb722323b 100644
--- a/locales/ru-RU/hotkey.json
+++ b/locales/ru-RU/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Быстрое переключение агента",
"switchTab.desc": "Переход к определенной вкладке по ее позиции (1–9) на панели вкладок приложения для рабочего стола",
"switchTab.title": "Переключиться на вкладку по номеру",
+ "toggleFavorite.desc": "Добавить открытую страницу в раздел Избранное на боковой панели или удалить её",
+ "toggleFavorite.title": "Добавить в Избранное / Удалить из Избранного",
"toggleLeftPanel.desc": "Показать или скрыть левую панель",
"toggleLeftPanel.title": "Переключить левую панель",
"toggleRightPanel.desc": "Показать или скрыть правую панель",
diff --git a/locales/ru-RU/topic.json b/locales/ru-RU/topic.json
index acc26ce2565..786e79374fe 100644
--- a/locales/ru-RU/topic.json
+++ b/locales/ru-RU/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "Вы собираетесь удалить эту тему. Это действие необратимо.",
"actions.confirmRemoveTopicFiles": "Также удалить изображения и файлы, загруженные в этой теме",
"actions.confirmRemoveTopicTitle": "Удалить эту тему?",
+ "actions.confirmRemoveUnpinnedWorkspace": "Вы собираетесь удалить все незакреплённые темы в текущем списке рабочей области, включая темы других участников. Закреплённые темы останутся. Удалённые темы перемещаются в корзину, и их можно восстановить в течение 30 дней.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Я понимаю, что это переместит незакреплённые темы других участников в корзину.",
"actions.confirmRemoveUnstarred": "Вы собираетесь удалить все неотмеченные темы. Это действие необратимо.",
"actions.confirmRemoveUnstarredOwn": "Вы собираетесь удалить темы без звёзд, которые вы создали. Темы, созданные другими участниками Рабочего пространства, останутся. Это действие нельзя отменить.",
- "actions.confirmRemoveUnstarredWorkspace": "Вы собираетесь удалить все темы без звёздочек в текущем списке Рабочей области, включая темы, созданные другими участниками. Темы со звёздочками останутся. Это действие нельзя отменить.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Я понимаю, что это действие навсегда удалит темы без звёздочек, созданные другими участниками.",
"actions.copyLink": "Копировать ссылку",
"actions.copyLinkSuccess": "Ссылка скопирована",
"actions.copySessionId": "Копировать ID сессии",
@@ -31,23 +31,23 @@
"actions.diagnose": "Проверить цепочку сообщений",
"actions.duplicate": "Дублировать",
"actions.export": "Экспорт тем",
- "actions.favorite": "Избранное",
"actions.forwardToAgent": "Перенаправить другому агенту",
"actions.import": "Импорт беседы",
"actions.markCompleted": "Отметить как выполнено",
"actions.moveToAgent": "Переместить к другому ассистенту",
"actions.openInNewTab": "Открыть в новой вкладке",
"actions.openInNewWindow": "Открыть в новом окне",
+ "actions.pin": "Закрепить",
"actions.removeAll": "Удалить все темы",
"actions.removeAllOwn": "Удалить все темы, которые я создал",
"actions.removeAllWorkspace": "Удалить все темы Рабочего пространства",
"actions.removeTopic": "Удалить тему",
+ "actions.removeUnpinnedWorkspace": "Удалить все незакреплённые темы",
"actions.removeUnstarred": "Удалить неотмеченные темы",
"actions.removeUnstarredOwn": "Удалить мои темы без звёзд",
- "actions.removeUnstarredWorkspace": "Удалить все темы без звёздочек",
"actions.reportProblem": "Сообщить о проблеме",
- "actions.unfavorite": "Удалить из избранного",
"actions.unmarkCompleted": "Отметить как активное",
+ "actions.unpin": "Открепить",
"defaultTitle": "Тема по умолчанию",
"displayItems": "Отображаемые элементы",
"doctor.checkFailed": "Проверка не была завершена.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Копирование темы...",
"duplicateSuccess": "Тема успешно скопирована",
"failedStatusTip": "Этот запуск завершился ошибкой — откройте его, чтобы узнать подробности.",
- "favorite": "Избранное",
"filter.allTopics": "Все",
"filter.byDevice": "Устройство: {{value}}",
"filter.byStatus": "Статус: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Удалить",
"management.bulk.deleteConfirm": "Вы собираетесь удалить {{count}} тем. Это действие нельзя отменить.",
"management.bulk.deleteTitle": "Удалить темы?",
- "management.bulk.favorite": "Избранное",
"management.bulk.move": "Переместить к ассистенту",
"management.bulk.moveEmpty": "Нет других ассистентов",
"management.bulk.moveSearchPlaceholder": "Искать ассистентов…",
+ "management.bulk.pin": "Закрепить",
"management.bulk.selectedCount_one": "Выбрано: {{count}}",
"management.bulk.selectedCount_other": "Выбрано: {{count}}",
"management.card.noPreview": "Предпросмотр недоступен",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI выполняется",
"metaCard.ci.success": "CI успешно пройден",
"metaCard.detached": "Отключённая HEAD на {{sha}}",
+ "metaCard.goal": "Связанная цель",
"metaCard.pr.closed": "Закрыто",
"metaCard.pr.merged": "Слито",
"metaCard.pr.open": "Открыто",
"newTopic": "Новая тема",
+ "pinned": "Закреплённые",
"projectStatus.failed_one": "{{count}} неудачная тема",
"projectStatus.failed_other": "{{count}} неудачных тем",
"projectStatus.loading_one": "{{count}} загружаемая тема",
diff --git a/locales/tr-TR/common.json b/locales/tr-TR/common.json
index ecf04a959e5..3e3a751e45c 100644
--- a/locales/tr-TR/common.json
+++ b/locales/tr-TR/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Tüm Ajan Ayarlarını Dışa Aktar",
"exportType.allAgentWithMessage": "Tüm Ajanları ve Mesajları Dışa Aktar",
"exportType.globalSetting": "Genel Ayarları Dışa Aktar",
+ "favorite.add": "Favorilere Ekle",
+ "favorite.limitReached": "Favoriler en fazla {{count}} öğe tutabilir. Başka birini eklemek için birini kaldırın.",
+ "favorite.remove": "Favorilerden Kaldır",
+ "favorite.reorderError": "Favorilerinizin sırasını kaydedemedik. Tekrar deneyin.",
+ "favorite.section": "Favoriler",
+ "favorite.updateError": "Favorilerinizi güncelleyemedik. Tekrar deneyin.",
"feedback": "Geri Bildirim",
"feedback.emailContact": "Bize ayrıca <email>{{email}}</email> adresinden e-posta gönderebilirsiniz",
"feedback.errors.fileTooLarge": "Dosya boyutu 5MB'ı aşıyor",
diff --git a/locales/tr-TR/hotkey.json b/locales/tr-TR/hotkey.json
index 5d3ac18a6ce..bc2fb27b9c4 100644
--- a/locales/tr-TR/hotkey.json
+++ b/locales/tr-TR/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Hızlı Ajan Değiştir",
"switchTab.desc": "Masaüstü uygulamasındaki sekme çubuğunda konumuna (1–9) göre belirli bir sekmeye geç",
"switchTab.title": "Numaraya Göre Sekmeye Geç",
+ "toggleFavorite.desc": "Açık sayfayı kenar çubuğundaki Favoriler bölümüne ekleyin veya kaldırın",
+ "toggleFavorite.title": "Favorilere Ekle / Favorilerden Kaldır",
"toggleLeftPanel.desc": "Sol paneli göster veya gizle",
"toggleLeftPanel.title": "Sol Paneli Aç/Kapat",
"toggleRightPanel.desc": "Sağ paneli göster veya gizle",
diff --git a/locales/tr-TR/topic.json b/locales/tr-TR/topic.json
index 60e8757ab1d..07ac5d25c17 100644
--- a/locales/tr-TR/topic.json
+++ b/locales/tr-TR/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "Bu konuyu silmek üzeresiniz. Bu işlem geri alınamaz.",
"actions.confirmRemoveTopicFiles": "Bu konudaki yüklenmiş resim ve dosyaları da sil",
"actions.confirmRemoveTopicTitle": "Bu konuyu silmek istiyor musunuz?",
+ "actions.confirmRemoveUnpinnedWorkspace": "Mevcut Çalışma Alanı listesindeki, diğer üyelerin oluşturdukları da dahil olmak üzere sabitlenmemiş tüm konuları silmek üzeresiniz. Sabitlenen konular kalacaktır. Silinen konular çöp kutusuna taşınır ve 30 gün içinde geri yüklenebilir.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Bunun diğer üyelerin sabitlenmemiş konularını çöp kutusuna taşıyacağını anlıyorum.",
"actions.confirmRemoveUnstarred": "Yıldızlanmamış konuları silmek üzeresiniz. Bu işlem geri alınamaz.",
"actions.confirmRemoveUnstarredOwn": "Yıldızsız olarak oluşturduğunuz konuları silmek üzeresiniz. Diğer Çalışma Alanı üyeleri tarafından oluşturulan konular kalacaktır. Bu işlem geri alınamaz.",
- "actions.confirmRemoveUnstarredWorkspace": "Mevcut Çalışma Alanı listesindeki tüm yıldızsız konuları, diğer üyeler tarafından oluşturulan konular dahil silmek üzeresiniz. Yıldızlı konular kalacaktır. Bu işlem geri alınamaz.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Diğer üyelerin yıldızsız konularını kalıcı olarak sileceğimi anlıyorum.",
"actions.copyLink": "Bağlantıyı Kopyala",
"actions.copyLinkSuccess": "Bağlantı kopyalandı",
"actions.copySessionId": "Oturum Kimliğini Kopyala",
@@ -31,23 +31,23 @@
"actions.diagnose": "Mesaj Zincirini Kontrol Et",
"actions.duplicate": "Kopyala",
"actions.export": "Konuları Dışa Aktar",
- "actions.favorite": "Favori",
"actions.forwardToAgent": "Başka bir ajana yönlendir",
"actions.import": "Konuşmayı İçe Aktar",
"actions.markCompleted": "Tamamlandı olarak işaretle",
"actions.moveToAgent": "Başka bir ajana taşı",
"actions.openInNewTab": "Yeni Sekmede Aç",
"actions.openInNewWindow": "Yeni pencerede aç",
+ "actions.pin": "Sabitle",
"actions.removeAll": "Tüm Konuları Sil",
"actions.removeAllOwn": "Oluşturduğum Tüm Konuları Sil",
"actions.removeAllWorkspace": "Tüm Çalışma Alanı Konularını Sil",
"actions.removeTopic": "Konuyu Sil",
+ "actions.removeUnpinnedWorkspace": "Sabitlenmemiş Tüm Konuları Sil",
"actions.removeUnstarred": "Yıldızlanmamış Konuları Sil",
"actions.removeUnstarredOwn": "Yıldızsız Kendi Konularımı Sil",
- "actions.removeUnstarredWorkspace": "Tüm Yıldızsız Konuları Sil",
"actions.reportProblem": "Bir Sorun Bildir",
- "actions.unfavorite": "Favoriyi Kaldır",
"actions.unmarkCompleted": "Aktif olarak işaretle",
+ "actions.unpin": "Sabitlemeyi kaldır",
"defaultTitle": "Varsayılan Konu",
"displayItems": "Öğeleri Göster",
"doctor.checkFailed": "Kontrol tamamlanamadı.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Konu Kopyalanıyor...",
"duplicateSuccess": "Konu Başarıyla Kopyalandı",
"failedStatusTip": "Bu çalışmada bir hata oluştu — incelemek için açın.",
- "favorite": "Favori",
"filter.allTopics": "Tümü",
"filter.byDevice": "Cihaz: {{value}}",
"filter.byStatus": "Durum: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Sil",
"management.bulk.deleteConfirm": "{{count}} konuyu silmek üzeresiniz. Bu işlem geri alınamaz.",
"management.bulk.deleteTitle": "Konuları sil?",
- "management.bulk.favorite": "Favori",
"management.bulk.move": "Ajana taşı",
"management.bulk.moveEmpty": "Başka ajan yok",
"management.bulk.moveSearchPlaceholder": "Ajanları ara…",
+ "management.bulk.pin": "Sabitle",
"management.bulk.selectedCount_one": "{{count}} seçildi",
"management.bulk.selectedCount_other": "{{count}} seçildi",
"management.card.noPreview": "Önizleme mevcut değil",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI çalışıyor",
"metaCard.ci.success": "CI başarılı",
"metaCard.detached": "{{sha}} üzerinde ayrılmış HEAD",
+ "metaCard.goal": "Bağlantılı hedef",
"metaCard.pr.closed": "Kapalı",
"metaCard.pr.merged": "Birleştirildi",
"metaCard.pr.open": "Açık",
"newTopic": "Yeni Konu",
+ "pinned": "Sabitlenenler",
"projectStatus.failed_one": "{{count}} başarısız konu",
"projectStatus.failed_other": "{{count}} başarısız konu",
"projectStatus.loading_one": "{{count}} yükleniyor konu",
diff --git a/locales/vi-VN/common.json b/locales/vi-VN/common.json
index 421e92c6e66..7b74d581d75 100644
--- a/locales/vi-VN/common.json
+++ b/locales/vi-VN/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "Xuất tất cả cài đặt Tác nhân",
"exportType.allAgentWithMessage": "Xuất tất cả Tác nhân và Tin nhắn",
"exportType.globalSetting": "Xuất cài đặt toàn cục",
+ "favorite.add": "Thêm vào Mục yêu thích",
+ "favorite.limitReached": "Mục yêu thích có thể chứa tối đa {{count}} mục. Hãy xóa một mục để thêm mục khác.",
+ "favorite.remove": "Xóa khỏi Mục yêu thích",
+ "favorite.reorderError": "Không thể lưu thứ tự của các mục yêu thích. Vui lòng thử lại.",
+ "favorite.section": "Mục yêu thích",
+ "favorite.updateError": "Không thể cập nhật mục yêu thích của bạn. Vui lòng thử lại.",
"feedback": "Phản hồi",
"feedback.emailContact": "Bạn cũng có thể gửi email cho chúng tôi tại <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "Tệp vượt quá 5MB",
diff --git a/locales/vi-VN/hotkey.json b/locales/vi-VN/hotkey.json
index 31185888dc6..bbb42bb6290 100644
--- a/locales/vi-VN/hotkey.json
+++ b/locales/vi-VN/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "Chuyển Nhanh Tác Nhân",
"switchTab.desc": "Chuyển đến một tab cụ thể theo vị trí của nó (1–9) trên thanh tab của ứng dụng Desktop",
"switchTab.title": "Chuyển Đến Tab Theo Số",
+ "toggleFavorite.desc": "Thêm trang đang mở vào mục Yêu thích trong thanh bên, hoặc xóa nó",
+ "toggleFavorite.title": "Thêm vào / Xóa khỏi Yêu thích",
"toggleLeftPanel.desc": "Hiện hoặc ẩn bảng bên trái",
"toggleLeftPanel.title": "Bật/Tắt Bảng Bên Trái",
"toggleRightPanel.desc": "Hiện hoặc ẩn bảng bên phải",
diff --git a/locales/vi-VN/topic.json b/locales/vi-VN/topic.json
index 8f5d413574d..0d11a7dcd71 100644
--- a/locales/vi-VN/topic.json
+++ b/locales/vi-VN/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "Bạn sắp xóa chủ đề này. Hành động này không thể hoàn tác.",
"actions.confirmRemoveTopicFiles": "Cũng xóa hình ảnh và tệp đã tải lên trong chủ đề này",
"actions.confirmRemoveTopicTitle": "Xóa chủ đề này?",
+ "actions.confirmRemoveUnpinnedWorkspace": "Bạn sắp xóa tất cả chủ đề chưa ghim trong danh sách Workspace hiện tại, bao gồm cả chủ đề do thành viên khác tạo. Các chủ đề đã ghim sẽ được giữ lại. Chủ đề đã xóa sẽ được chuyển vào thùng rác và có thể khôi phục trong vòng 30 ngày.",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "Tôi hiểu rằng thao tác này sẽ chuyển các chủ đề chưa ghim của thành viên khác vào thùng rác.",
"actions.confirmRemoveUnstarred": "Bạn sắp xóa các chủ đề chưa đánh dấu sao. Hành động này không thể hoàn tác.",
"actions.confirmRemoveUnstarredOwn": "Bạn sắp xóa các chủ đề không được đánh dấu sao mà bạn đã tạo. Các chủ đề được tạo bởi các thành viên khác trong Không gian làm việc sẽ được giữ lại. Hành động này không thể hoàn tác.",
- "actions.confirmRemoveUnstarredWorkspace": "Bạn sắp xóa tất cả các chủ đề chưa được gắn sao trong danh sách Workspace hiện tại, bao gồm cả các chủ đề được tạo bởi các thành viên khác. Các chủ đề đã được gắn sao sẽ được giữ lại. Hành động này không thể hoàn tác.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "Tôi hiểu rằng hành động này sẽ xóa vĩnh viễn các chủ đề chưa được gắn sao của các thành viên khác.",
"actions.copyLink": "Sao chép liên kết",
"actions.copyLinkSuccess": "Đã sao chép liên kết",
"actions.copySessionId": "Sao chép Session ID",
@@ -31,23 +31,23 @@
"actions.diagnose": "Kiểm tra Chuỗi Tin nhắn",
"actions.duplicate": "Nhân bản",
"actions.export": "Xuất chủ đề",
- "actions.favorite": "Yêu thích",
"actions.forwardToAgent": "Chuyển tiếp đến một nhân viên khác",
"actions.import": "Nhập cuộc trò chuyện",
"actions.markCompleted": "Đánh dấu hoàn thành",
"actions.moveToAgent": "Chuyển đến trợ lý khác",
"actions.openInNewTab": "Mở trong tab mới",
"actions.openInNewWindow": "Mở trong cửa sổ mới",
+ "actions.pin": "Ghim",
"actions.removeAll": "Xóa tất cả chủ đề",
"actions.removeAllOwn": "Xóa Tất cả Chủ đề Tôi Đã Tạo",
"actions.removeAllWorkspace": "Xóa Tất cả Chủ đề trong Không gian làm việc",
"actions.removeTopic": "Xóa Chủ đề",
+ "actions.removeUnpinnedWorkspace": "Xóa tất cả chủ đề chưa ghim",
"actions.removeUnstarred": "Xóa chủ đề chưa đánh dấu sao",
"actions.removeUnstarredOwn": "Xóa Các Chủ đề Không Được Đánh Dấu Sao của Tôi",
- "actions.removeUnstarredWorkspace": "Xóa tất cả các chủ đề chưa được gắn sao",
"actions.reportProblem": "Báo cáo sự cố",
- "actions.unfavorite": "Bỏ yêu thích",
"actions.unmarkCompleted": "Đánh dấu là đang hoạt động",
+ "actions.unpin": "Bỏ ghim",
"defaultTitle": "Chủ đề mặc định",
"displayItems": "Hiển thị mục",
"doctor.checkFailed": "Không thể hoàn thành kiểm tra.",
@@ -69,7 +69,6 @@
"duplicateLoading": "Đang sao chép chủ đề...",
"duplicateSuccess": "Sao chép chủ đề thành công",
"failedStatusTip": "Lần chạy này gặp lỗi — mở để xem chi tiết.",
- "favorite": "Yêu thích",
"filter.allTopics": "Tất cả",
"filter.byDevice": "Thiết bị: {{value}}",
"filter.byStatus": "Trạng thái: {{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "Xóa",
"management.bulk.deleteConfirm": "Bạn sắp xóa {{count}} chủ đề. Hành động này không thể hoàn tác.",
"management.bulk.deleteTitle": "Xóa các chủ đề?",
- "management.bulk.favorite": "Yêu thích",
"management.bulk.move": "Chuyển đến trợ lý",
"management.bulk.moveEmpty": "Không có trợ lý nào khác",
"management.bulk.moveSearchPlaceholder": "Tìm kiếm trợ lý…",
+ "management.bulk.pin": "Ghim",
"management.bulk.selectedCount_one": "{{count}} đã chọn",
"management.bulk.selectedCount_other": "{{count}} đã chọn",
"management.card.noPreview": "Không có bản xem trước",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI đang chạy",
"metaCard.ci.success": "CI thành công",
"metaCard.detached": "HEAD tách rời tại {{sha}}",
+ "metaCard.goal": "Mục tiêu liên kết",
"metaCard.pr.closed": "Đã đóng",
"metaCard.pr.merged": "Đã hợp nhất",
"metaCard.pr.open": "Đang mở",
"newTopic": "Chủ đề mới",
+ "pinned": "Đã ghim",
"projectStatus.failed_one": "{{count}} chủ đề thất bại",
"projectStatus.failed_other": "{{count}} chủ đề thất bại",
"projectStatus.loading_one": "{{count}} chủ đề đang tải",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index 0a4930d58c3..fca5b81ae47 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -211,6 +211,12 @@
"exportType.allAgent": "导出所有助理设定",
"exportType.allAgentWithMessage": "导出所有助理和消息",
"exportType.globalSetting": "导出全局设置",
+ "favorite.add": "加入收藏夹",
+ "favorite.limitReached": "收藏夹最多 {{count}} 项,请先移除一项再添加",
+ "favorite.remove": "移出收藏夹",
+ "favorite.reorderError": "收藏夹排序保存失败,请重试",
+ "favorite.section": "收藏夹",
+ "favorite.updateError": "收藏夹更新失败,请重试",
"feedback": "反馈与建议",
"feedback.emailContact": "您也可以发送邮件至 <email>{{email}}</email>",
"feedback.errors.fileTooLarge": "文件大小超过 5MB 限制",
diff --git a/locales/zh-CN/hotkey.json b/locales/zh-CN/hotkey.json
index ac8035cc0f0..599c7a7783b 100644
--- a/locales/zh-CN/hotkey.json
+++ b/locales/zh-CN/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "快捷切换助理",
"switchTab.desc": "通过按住 ⌘/Ctrl 加数字 1~9 跳转到对应位置的标签页",
"switchTab.title": "按编号切换标签页",
+ "toggleFavorite.desc": "将当前页面加入侧边栏收藏夹,或从中移出",
+ "toggleFavorite.title": "加入 / 移出收藏夹",
"toggleLeftPanel.desc": "显示或隐藏左侧面板",
"toggleLeftPanel.title": "显示/隐藏左侧面板",
"toggleRightPanel.desc": "显示或隐藏右侧面板",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index 611e59cbed1..7e71d840fce 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "即将删除此话题。它会移入回收站,30 天内可以恢复。",
"actions.confirmRemoveTopicFiles": "同时删除此话题中上传的图片和文件",
"actions.confirmRemoveTopicTitle": "删除此话题?",
+ "actions.confirmRemoveUnpinnedWorkspace": "即将删除当前 Workspace 列表中的全部未置顶话题,包括其他成员创建的话题;已置顶的话题会保留。已删除的话题会移入回收站,30 天内可以恢复。",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "我知道这会把其他成员未置顶的话题移入回收站。",
"actions.confirmRemoveUnstarred": "即将删除未收藏的话题。它们会移入回收站,30 天内可以恢复。",
"actions.confirmRemoveUnstarredOwn": "即将删除你创建的未收藏话题,其他 Workspace 成员创建的话题会保留。已删除的话题会移入回收站,30 天内可以恢复。",
- "actions.confirmRemoveUnstarredWorkspace": "即将删除当前 Workspace 列表中的全部未收藏话题,包括其他成员创建的话题;已收藏的话题会保留。已删除的话题会移入回收站,30 天内可以恢复。",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "我知道这会把其他成员未收藏的话题移入回收站。",
"actions.copyLink": "复制链接",
"actions.copyLinkSuccess": "链接已复制",
"actions.copySessionId": "复制话题 ID",
@@ -31,23 +31,23 @@
"actions.diagnose": "检查消息链路",
"actions.duplicate": "拷贝",
"actions.export": "导出话题",
- "actions.favorite": "收藏",
"actions.forwardToAgent": "转发给其他助手",
"actions.import": "导入对话",
"actions.markCompleted": "归档",
"actions.moveToAgent": "移动到其他助手",
"actions.openInNewTab": "在新标签页中打开",
"actions.openInNewWindow": "打开独立窗口",
+ "actions.pin": "置顶",
"actions.removeAll": "删除全部话题",
"actions.removeAllOwn": "删除我的话题",
"actions.removeAllWorkspace": "删除全部话题",
"actions.removeTopic": "删除话题",
+ "actions.removeUnpinnedWorkspace": "删除全部未置顶话题",
"actions.removeUnstarred": "删除未收藏话题",
"actions.removeUnstarredOwn": "删除我创建的未收藏话题",
- "actions.removeUnstarredWorkspace": "删除全部未收藏话题",
"actions.reportProblem": "报告问题",
- "actions.unfavorite": "取消收藏",
"actions.unmarkCompleted": "取消归档",
+ "actions.unpin": "取消置顶",
"defaultTitle": "默认话题",
"displayItems": "显示条目",
"doctor.checkFailed": "检查未能完成。",
@@ -69,7 +69,6 @@
"duplicateLoading": "话题复制中…",
"duplicateSuccess": "话题复制成功",
"failedStatusTip": "当前执行遇到了错误,点击查看详情",
- "favorite": "收藏",
"filter.allTopics": "全部",
"filter.byDevice": "设备:{{value}}",
"filter.byStatus": "状态:{{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "删除",
"management.bulk.deleteConfirm": "即将删除 {{count}} 个话题。它们会移入回收站,30 天内可以恢复。",
"management.bulk.deleteTitle": "删除话题?",
- "management.bulk.favorite": "收藏",
"management.bulk.move": "移动到助手",
"management.bulk.moveEmpty": "没有其他助手",
"management.bulk.moveSearchPlaceholder": "搜索助手…",
+ "management.bulk.pin": "置顶",
"management.bulk.selectedCount_one": "已选 {{count}} 项",
"management.bulk.selectedCount_other": "已选 {{count}} 项",
"management.card.noPreview": "暂无预览内容",
@@ -258,6 +257,7 @@
"metaCard.pr.merged": "已合并",
"metaCard.pr.open": "开放中",
"newTopic": "新话题",
+ "pinned": "已置顶",
"projectStatus.failed_one": "{{count}} 个错误话题",
"projectStatus.failed_other": "{{count}} 个错误话题",
"projectStatus.loading_one": "{{count}} 个加载中话题",
diff --git a/locales/zh-TW/common.json b/locales/zh-TW/common.json
index 02e6b10edb8..960c1f69d6e 100644
--- a/locales/zh-TW/common.json
+++ b/locales/zh-TW/common.json
@@ -209,6 +209,12 @@
"exportType.allAgent": "匯出所有助手設定",
"exportType.allAgentWithMessage": "匯出所有助手和訊息",
"exportType.globalSetting": "匯出全域設定",
+ "favorite.add": "新增至我的最愛",
+ "favorite.limitReached": "我的最愛最多可容納 {{count}} 項。請移除一項以新增其他項目。",
+ "favorite.remove": "從我的最愛中移除",
+ "favorite.reorderError": "無法儲存我的最愛的排序。請再試一次。",
+ "favorite.section": "我的最愛",
+ "favorite.updateError": "無法更新我的最愛。請再試一次。",
"feedback": "回饋與建議",
"feedback.emailContact": "您也可以通過 <email>{{email}}</email> 給我們發送電子郵件",
"feedback.errors.fileTooLarge": "檔案超過 5MB",
diff --git a/locales/zh-TW/hotkey.json b/locales/zh-TW/hotkey.json
index 2aa3f8d13ad..ff754a3cbc5 100644
--- a/locales/zh-TW/hotkey.json
+++ b/locales/zh-TW/hotkey.json
@@ -43,6 +43,8 @@
"switchAgent.title": "快捷切換助手",
"switchTab.desc": "根據其在桌面應用程式標籤列中的位置(1–9)跳轉到特定標籤頁",
"switchTab.title": "按編號切換到標籤頁",
+ "toggleFavorite.desc": "將打開的頁面添加到側邊欄的收藏夾部分,或將其移除",
+ "toggleFavorite.title": "添加到收藏夾 / 從收藏夾移除",
"toggleLeftPanel.desc": "顯示或隱藏左側面板",
"toggleLeftPanel.title": "顯示/隱藏左側面板",
"toggleRightPanel.desc": "顯示或隱藏右側面板",
diff --git a/locales/zh-TW/topic.json b/locales/zh-TW/topic.json
index d50a739327a..09742f8a778 100644
--- a/locales/zh-TW/topic.json
+++ b/locales/zh-TW/topic.json
@@ -16,10 +16,10 @@
"actions.confirmRemoveTopic": "您即將刪除此主題。此操作無法復原。",
"actions.confirmRemoveTopicFiles": "同時刪除此主題中上傳的圖片和文件",
"actions.confirmRemoveTopicTitle": "刪除此主題?",
+ "actions.confirmRemoveUnpinnedWorkspace": "即將刪除目前 Workspace 列表中所有未置頂的主題,包括其他成員建立的主題;已置頂的主題會保留。已刪除的主題會移至垃圾桶,30 天內可以復原。",
+ "actions.confirmRemoveUnpinnedWorkspaceAcknowledge": "我了解這會把其他成員未置頂的主題移至垃圾桶。",
"actions.confirmRemoveUnstarred": "您即將刪除未加星號的主題。此操作無法復原。",
"actions.confirmRemoveUnstarredOwn": "您即將刪除未加星標的您創建的主題。其他工作區成員創建的主題將保留。此操作無法撤銷。",
- "actions.confirmRemoveUnstarredWorkspace": "您即將刪除當前工作區列表中所有未加星標的主題,包括其他成員創建的主題。加星標的主題將保留。此操作無法撤銷。",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "我了解此操作將永久刪除其他成員的未加星標主題。",
"actions.copyLink": "複製連結",
"actions.copyLinkSuccess": "連結已複製",
"actions.copySessionId": "複製 Session ID",
@@ -31,23 +31,23 @@
"actions.diagnose": "檢查訊息鏈",
"actions.duplicate": "建立副本",
"actions.export": "匯出話題",
- "actions.favorite": "收藏",
"actions.forwardToAgent": "轉接至其他客服人員",
"actions.import": "匯入對話",
"actions.markCompleted": "標記為已完成",
"actions.moveToAgent": "移至另一位助理",
"actions.openInNewTab": "在新分頁中開啟",
"actions.openInNewWindow": "在新視窗中開啟",
+ "actions.pin": "置頂",
"actions.removeAll": "刪除全部話題",
"actions.removeAllOwn": "刪除我創建的所有主題",
"actions.removeAllWorkspace": "刪除所有工作區主題",
"actions.removeTopic": "刪除主題",
+ "actions.removeUnpinnedWorkspace": "刪除所有未置頂的主題",
"actions.removeUnstarred": "刪除未收藏話題",
"actions.removeUnstarredOwn": "刪除我未加星標的主題",
- "actions.removeUnstarredWorkspace": "刪除所有未加星標的主題",
"actions.reportProblem": "回報問題",
- "actions.unfavorite": "取消收藏",
"actions.unmarkCompleted": "標記為進行中",
+ "actions.unpin": "取消置頂",
"defaultTitle": "預設話題",
"displayItems": "顯示項目",
"doctor.checkFailed": "檢查無法完成。",
@@ -69,7 +69,6 @@
"duplicateLoading": "話題複製中...",
"duplicateSuccess": "話題複製成功",
"failedStatusTip": "此執行遇到錯誤 — 點擊查看詳細資訊。",
- "favorite": "收藏",
"filter.allTopics": "全部",
"filter.byDevice": "設備:{{value}}",
"filter.byStatus": "狀態:{{value}}",
@@ -175,10 +174,10 @@
"management.bulk.delete": "刪除",
"management.bulk.deleteConfirm": "您即將刪除 {{count}} 個主題。此操作無法撤銷。",
"management.bulk.deleteTitle": "刪除主題?",
- "management.bulk.favorite": "收藏",
"management.bulk.move": "移至助理",
"management.bulk.moveEmpty": "沒有其他助理",
"management.bulk.moveSearchPlaceholder": "搜尋助理…",
+ "management.bulk.pin": "置頂",
"management.bulk.selectedCount_one": "已選擇 {{count}} 個",
"management.bulk.selectedCount_other": "已選擇 {{count}} 個",
"management.card.noPreview": "無可用預覽",
@@ -253,10 +252,12 @@
"metaCard.ci.pending": "CI 執行中",
"metaCard.ci.success": "CI 通過",
"metaCard.detached": "分離的 HEAD 位於 {{sha}}",
+ "metaCard.goal": "連結目標",
"metaCard.pr.closed": "已關閉",
"metaCard.pr.merged": "已合併",
"metaCard.pr.open": "開啟",
"newTopic": "新主題",
+ "pinned": "已置頂",
"projectStatus.failed_one": "{{count}} 個失敗的主題",
"projectStatus.failed_other": "{{count}} 個失敗的主題",
"projectStatus.loading_one": "{{count}} 個正在載入的主題",
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index 5d3f22b66e5..4ef42ea1c75 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -232,6 +232,8 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
expertise: rw('agent:read', 'agent:write'),
// whole-account backup dump (settings incl. market tokens, providers, agents)
exporter: 'blocked',
+ // Personal sidebar shortcuts, like other per-user preferences.
+ favorite: rw('user:read', 'user:write'),
file: rw('file:read', 'file:write'),
followUpAction: rw('chat:read', 'chat:write'),
generation: { any: 'model:invoke' },
diff --git a/packages/const/src/hotkeys.ts b/packages/const/src/hotkeys.ts
index 882836d0ff2..79a1329bc2a 100644
--- a/packages/const/src/hotkeys.ts
+++ b/packages/const/src/hotkeys.ts
@@ -58,6 +58,7 @@ export const HotkeyEnum = {
ShowApp: 'showApp',
SwitchAgent: 'switchAgent',
SwitchTab: 'switchTab',
+ ToggleFavorite: 'toggleFavorite',
ToggleLeftPanel: 'toggleLeftPanel',
ToggleRightPanel: 'toggleRightPanel',
ToggleTerminalPanel: 'toggleTerminalPanel',
@@ -142,6 +143,12 @@ export const HOTKEYS_REGISTRATION: HotkeyRegistration = [
keys: combineKeys([KeyEnum.Ctrl, KeyEnum.Shift, KeyEnum.QuestionMark]),
scopes: [HotkeyScopeEnum.Global],
},
+ {
+ group: HotkeyGroupEnum.Essential,
+ id: HotkeyEnum.ToggleFavorite,
+ keys: combineKeys([KeyEnum.Alt, 'f']),
+ scopes: [HotkeyScopeEnum.Global],
+ },
// Chat
{
group: HotkeyGroupEnum.Conversation,
diff --git a/packages/database/src/models/__tests__/favorite.test.ts b/packages/database/src/models/__tests__/favorite.test.ts
new file mode 100644
index 00000000000..9adafadc953
--- /dev/null
+++ b/packages/database/src/models/__tests__/favorite.test.ts
@@ -0,0 +1,173 @@
+// @vitest-environment node
+import { FAVORITE_LIMIT } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { userFavorites, users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { FavoriteLimitError, FavoriteModel } from '../favorite';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'favorite-test-user';
+const otherUserId = 'favorite-test-user-2';
+const workspaceId = 'favorite-test-ws';
+
+const personalModel = new FavoriteModel(serverDB, userId);
+const workspaceModel = new FavoriteModel(serverDB, userId, workspaceId);
+
+const topic = (id: string, title = id) => ({
+ path: `/agent/agt_a/${id}`,
+ targetId: id,
+ title,
+ type: 'topic' as const,
+});
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.delete(workspaces);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB
+ .insert(workspaces)
+ .values([{ id: workspaceId, name: 'Test WS', primaryOwnerId: userId, slug: 'favorite-ws' }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(userFavorites);
+ await serverDB.delete(users);
+ await serverDB.delete(workspaces);
+});
+
+describe('FavoriteModel', () => {
+ it('appends new favorites in the order they were added', async () => {
+ await personalModel.add(topic('tpc_1'));
+ await personalModel.add(topic('tpc_2'));
+ await personalModel.add({
+ path: '/projects',
+ targetId: '/projects',
+ title: 'Projects',
+ type: 'route',
+ });
+
+ const items = await personalModel.query();
+ expect(items.map((item) => item.targetId)).toEqual(['tpc_1', 'tpc_2', '/projects']);
+ expect(items[0]).toMatchObject({ icon: null, path: '/agent/agt_a/tpc_1', type: 'topic' });
+ });
+
+ it('refreshes an existing favorite in place instead of duplicating it', async () => {
+ await personalModel.add(topic('tpc_1', 'Old'));
+ await personalModel.add(topic('tpc_2'));
+ await personalModel.add({ ...topic('tpc_1', 'New'), icon: '🚀', path: '/group/cg_a/tpc_1' });
+
+ const items = await personalModel.query();
+ expect(items).toHaveLength(2);
+ expect(items[0]).toMatchObject({
+ icon: '🚀',
+ path: '/group/cg_a/tpc_1',
+ targetId: 'tpc_1',
+ title: 'New',
+ });
+ });
+
+ it('keeps personal, workspace and other members’ favorites apart', async () => {
+ await personalModel.add(topic('tpc_personal'));
+ await workspaceModel.add(topic('tpc_ws'));
+ // The same target can be favorited in both sidebars.
+ await workspaceModel.add(topic('tpc_personal'));
+ await new FavoriteModel(serverDB, otherUserId, workspaceId).add(topic('tpc_other'));
+
+ expect((await personalModel.query()).map((item) => item.targetId)).toEqual(['tpc_personal']);
+ expect((await workspaceModel.query()).map((item) => item.targetId)).toEqual([
+ 'tpc_ws',
+ 'tpc_personal',
+ ]);
+ });
+
+ it('removes only rows in the caller’s scope', async () => {
+ const own = await workspaceModel.add(topic('tpc_1'));
+ const other = await new FavoriteModel(serverDB, otherUserId, workspaceId).add(topic('tpc_1'));
+
+ await workspaceModel.remove(other.id);
+ expect(await new FavoriteModel(serverDB, otherUserId, workspaceId).query()).toHaveLength(1);
+
+ await workspaceModel.remove(own.id);
+ expect(await workspaceModel.query()).toHaveLength(0);
+ });
+
+ it('stops adding at the limit a reorder can still carry, but keeps refreshing existing rows', async () => {
+ await serverDB.insert(userFavorites).values(
+ Array.from({ length: FAVORITE_LIMIT }, (_, index) => ({
+ path: `/page/docs_${index}`,
+ sortOrder: index,
+ targetId: `docs_${index}`,
+ title: `Page ${index}`,
+ type: 'page' as const,
+ userId,
+ })),
+ );
+
+ await expect(personalModel.add(topic('tpc_over'))).rejects.toBeInstanceOf(FavoriteLimitError);
+ await personalModel.add({
+ path: '/page/docs_0',
+ targetId: 'docs_0',
+ title: 'Renamed',
+ type: 'page',
+ });
+ // Another sidebar has its own allowance.
+ await workspaceModel.add(topic('tpc_ws'));
+
+ const items = await personalModel.query();
+ expect(items).toHaveLength(FAVORITE_LIMIT);
+ expect(items[0].title).toBe('Renamed');
+ });
+
+ it('lets only one of two concurrent adds take the last free slot', async () => {
+ await serverDB.insert(userFavorites).values(
+ Array.from({ length: FAVORITE_LIMIT - 1 }, (_, index) => ({
+ path: `/page/docs_${index}`,
+ sortOrder: index,
+ targetId: `docs_${index}`,
+ title: `Page ${index}`,
+ type: 'page' as const,
+ userId,
+ })),
+ );
+
+ const results = await Promise.allSettled([
+ personalModel.add(topic('tpc_first')),
+ personalModel.add(topic('tpc_second')),
+ ]);
+
+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);
+ expect(await personalModel.query()).toHaveLength(FAVORITE_LIMIT);
+ });
+
+ it('removes by target', async () => {
+ await personalModel.add(topic('tpc_1'));
+ await personalModel.add(topic('tpc_2'));
+
+ await personalModel.removeByTarget('topic', 'tpc_1');
+
+ expect((await personalModel.query()).map((item) => item.targetId)).toEqual(['tpc_2']);
+ });
+
+ it('reorders, keeping unlisted favorites after the listed ones', async () => {
+ const a = await personalModel.add(topic('tpc_a'));
+ const b = await personalModel.add(topic('tpc_b'));
+ const c = await personalModel.add(topic('tpc_c'));
+ const foreign = await workspaceModel.add(topic('tpc_ws'));
+
+ await personalModel.reorder([c.id, foreign.id, a.id]);
+
+ expect((await personalModel.query()).map((item) => item.id)).toEqual([c.id, a.id, b.id]);
+ expect((await workspaceModel.query()).map((item) => item.id)).toEqual([foreign.id]);
+ });
+
+ it('updates the snapshot of a favorite in scope', async () => {
+ const item = await personalModel.add(topic('tpc_1', 'Old'));
+
+ await personalModel.update(item.id, { icon: '📄', title: 'Renamed' });
+
+ expect((await personalModel.query())[0]).toMatchObject({ icon: '📄', title: 'Renamed' });
+ });
+});
diff --git a/packages/database/src/models/favorite.ts b/packages/database/src/models/favorite.ts
new file mode 100644
index 00000000000..75be5980b94
--- /dev/null
+++ b/packages/database/src/models/favorite.ts
@@ -0,0 +1,182 @@
+import {
+ type AddFavoriteParams,
+ FAVORITE_LIMIT,
+ type FavoriteItem,
+ type FavoriteType,
+} from '@lobechat/types';
+import { and, asc, eq, inArray, isNull, type SQL, sql } from 'drizzle-orm';
+
+import { userFavorites } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { normalizeWorkspaceId } from '../utils/workspace';
+
+/** Adding another favorite would exceed {@link FAVORITE_LIMIT}. */
+export class FavoriteLimitError extends Error {
+ constructor() {
+ super(`A sidebar holds at most ${FAVORITE_LIMIT} favorites`);
+ this.name = 'FavoriteLimitError';
+ }
+}
+
+export interface UpdateFavoriteParams {
+ icon?: string | null;
+ path?: string;
+ title?: string;
+}
+
+const toFavoriteItem = (row: typeof userFavorites.$inferSelect): FavoriteItem => ({
+ icon: row.icon,
+ id: row.id,
+ path: row.path,
+ targetId: row.targetId,
+ title: row.title,
+ type: row.type,
+});
+
+/**
+ * A member's sidebar favorites. Favorites are personal in every scope: inside
+ * a workspace they are still filtered by `user_id`, never shared with other
+ * members the way `buildWorkspaceWhere` shares content rows.
+ */
+export class FavoriteModel {
+ private db: LobeChatDatabase;
+ private userId: string;
+ private workspaceId: string | null;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string | null) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = normalizeWorkspaceId(workspaceId);
+ }
+
+ private scope = (): SQL =>
+ and(
+ eq(userFavorites.userId, this.userId),
+ this.workspaceId
+ ? eq(userFavorites.workspaceId, this.workspaceId)
+ : isNull(userFavorites.workspaceId),
+ ) as SQL;
+
+ query = async (): Promise<FavoriteItem[]> => {
+ const rows = await this.db
+ .select()
+ .from(userFavorites)
+ .where(this.scope())
+ .orderBy(asc(userFavorites.sortOrder), asc(userFavorites.createdAt));
+
+ return rows.map(toFavoriteItem);
+ };
+
+ /**
+ * Favorite a target, appending it to the end of the section. Favoriting a
+ * target that is already there refreshes its link and snapshot in place and
+ * keeps its position.
+ */
+ add = async (params: AddFavoriteParams): Promise<FavoriteItem> =>
+ // The limit check and the insert run under one per-sidebar lock, so two
+ // concurrent adds cannot both see room for one more row.
+ this.db.transaction(async (tx) => {
+ await tx.execute(
+ sql`SELECT pg_advisory_xact_lock(hashtext(${`user-favorites:${this.userId}:${this.workspaceId ?? 'personal'}`}))`,
+ );
+
+ const [{ count, existing }] = await tx
+ .select({
+ count: sql<number>`count(*)::int`,
+ existing: sql<number>`count(*) FILTER (WHERE ${userFavorites.type} = ${params.type} AND ${userFavorites.targetId} = ${params.targetId})::int`,
+ })
+ .from(userFavorites)
+ .where(this.scope());
+ // Refreshing an existing favorite never grows the list.
+ if (existing === 0 && count >= FAVORITE_LIMIT) throw new FavoriteLimitError();
+
+ const nextSortOrder = sql<number>`(
+ SELECT COALESCE(MAX(${userFavorites.sortOrder}) + 1, 0)
+ FROM ${userFavorites}
+ WHERE ${this.scope()}
+ )`;
+
+ const [row] = await tx
+ .insert(userFavorites)
+ .values({
+ icon: params.icon ?? null,
+ path: params.path,
+ sortOrder: nextSortOrder,
+ targetId: params.targetId,
+ title: params.title,
+ type: params.type,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ })
+ .onConflictDoUpdate({
+ set: {
+ icon: params.icon ?? null,
+ path: params.path,
+ title: params.title,
+ updatedAt: new Date(),
+ },
+ target: this.workspaceId
+ ? [
+ userFavorites.userId,
+ userFavorites.workspaceId,
+ userFavorites.type,
+ userFavorites.targetId,
+ ]
+ : [userFavorites.userId, userFavorites.type, userFavorites.targetId],
+ targetWhere: this.workspaceId
+ ? sql`${userFavorites.workspaceId} IS NOT NULL`
+ : sql`${userFavorites.workspaceId} IS NULL`,
+ })
+ .returning();
+
+ return toFavoriteItem(row);
+ });
+
+ remove = async (id: string): Promise<void> => {
+ await this.db.delete(userFavorites).where(and(eq(userFavorites.id, id), this.scope()));
+ };
+
+ removeByTarget = async (type: FavoriteType, targetId: string): Promise<void> => {
+ await this.db
+ .delete(userFavorites)
+ .where(and(eq(userFavorites.type, type), eq(userFavorites.targetId, targetId), this.scope()));
+ };
+
+ /**
+ * Store the order the member arranged. Ids outside this sidebar are ignored;
+ * favorites missing from `ids` keep their position after the listed ones.
+ */
+ reorder = async (ids: string[]): Promise<void> => {
+ await this.db.transaction(async (tx) => {
+ const rows = await tx
+ .select({ id: userFavorites.id })
+ .from(userFavorites)
+ .where(this.scope())
+ .orderBy(asc(userFavorites.sortOrder), asc(userFavorites.createdAt));
+
+ const existing = rows.map((row) => row.id);
+ const listed = new Set(ids);
+ const order = [
+ ...ids.filter((id) => existing.includes(id)),
+ ...existing.filter((id) => !listed.has(id)),
+ ];
+ if (order.length === 0) return;
+
+ const position = sql.join(
+ order.map((id, index) => sql`WHEN ${id} THEN ${index}`),
+ sql` `,
+ );
+ await tx
+ .update(userFavorites)
+ .set({ sortOrder: sql`(CASE ${userFavorites.id} ${position} END)::integer` })
+ .where(and(inArray(userFavorites.id, order), this.scope()));
+ });
+ };
+
+ update = async (id: string, value: UpdateFavoriteParams): Promise<void> => {
+ await this.db
+ .update(userFavorites)
+ .set({ ...value, updatedAt: new Date() })
+ .where(and(eq(userFavorites.id, id), this.scope()));
+ };
+}
diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.ts
index d5cef1f1ad0..7c57badd64b 100644
--- a/packages/locales/src/default/common.ts
+++ b/packages/locales/src/default/common.ts
@@ -294,6 +294,12 @@ export default {
'exportType.allAgent': 'Export All Agent Settings',
'exportType.allAgentWithMessage': 'Export All Agents and Messages',
'exportType.globalSetting': 'Export Global Settings',
+ 'favorite.add': 'Add to Favorites',
+ 'favorite.limitReached': 'Favorites can hold up to {{count}} items. Remove one to add another.',
+ 'favorite.remove': 'Remove from Favorites',
+ 'favorite.reorderError': "Couldn't save the order of your favorites. Try again.",
+ 'favorite.section': 'Favorites',
+ 'favorite.updateError': "Couldn't update your favorites. Try again.",
'feedback': 'Feedback',
'feedback.emailContact': 'You can also email us at <email>{{email}}</email>',
'feedback.errors.fileTooLarge': 'File exceeds 5MB',
diff --git a/packages/locales/src/default/hotkey.ts b/packages/locales/src/default/hotkey.ts
index 9a336ce3f27..2a60db55cd1 100644
--- a/packages/locales/src/default/hotkey.ts
+++ b/packages/locales/src/default/hotkey.ts
@@ -46,6 +46,8 @@ export default {
'switchAgent.title': 'Quick Switch Agent',
'switchTab.desc': 'Jump to a specific tab by its position (1–9) in the Desktop app tab bar',
'switchTab.title': 'Switch to Tab by Number',
+ 'toggleFavorite.desc': 'Add the open page to the Favorites section of the sidebar, or remove it',
+ 'toggleFavorite.title': 'Add to / Remove from Favorites',
'toggleLeftPanel.desc': 'Show or hide the left panel',
'toggleLeftPanel.title': 'Toggle Left Panel',
'toggleRightPanel.desc': 'Show or hide the right panel',
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index 07e5b88aa10..2d2254c5bcc 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -37,10 +37,10 @@ export default {
'You are about to delete unstarred topics. They will be moved to the trash and can be restored within 30 days.',
'actions.confirmRemoveUnstarredOwn':
'You are about to delete unstarred topics you created. Topics created by other Workspace members will remain. Deleted topics move to the trash and can be restored within 30 days.',
- 'actions.confirmRemoveUnstarredWorkspace':
- 'You are about to delete all unstarred topics in the current Workspace list, including topics created by other members. Starred topics will remain. Deleted topics move to the trash and can be restored within 30 days.',
- 'actions.confirmRemoveUnstarredWorkspaceAcknowledge':
- "I understand that this moves other members' unstarred topics to the trash.",
+ 'actions.confirmRemoveUnpinnedWorkspace':
+ 'You are about to delete all unpinned topics in the current Workspace list, including topics created by other members. Pinned topics will remain. Deleted topics move to the trash and can be restored within 30 days.',
+ 'actions.confirmRemoveUnpinnedWorkspaceAcknowledge':
+ "I understand that this moves other members' unpinned topics to the trash.",
'actions.copyLink': 'Copy Link',
'actions.copyLinkSuccess': 'Link copied',
'actions.copySessionId': 'Copy Topic ID',
@@ -53,8 +53,8 @@ export default {
'actions.duplicate': 'Duplicate',
'actions.moveToAgent': 'Move to another agent',
'actions.forwardToAgent': 'Forward to another agent',
- 'actions.favorite': 'Favorite',
- 'actions.unfavorite': 'Unfavorite',
+ 'actions.pin': 'Pin',
+ 'actions.unpin': 'Unpin',
'actions.markCompleted': 'Archive',
'actions.unmarkCompleted': 'Unarchive',
'actions.export': 'Export Topics',
@@ -67,7 +67,7 @@ export default {
'actions.removeTopic': 'Delete Topic',
'actions.removeUnstarred': 'Delete Unstarred Topics',
'actions.removeUnstarredOwn': 'Delete My Unstarred Topics',
- 'actions.removeUnstarredWorkspace': 'Delete All Unstarred Topics',
+ 'actions.removeUnpinnedWorkspace': 'Delete All Unpinned Topics',
'defaultTitle': 'Default Topic',
'doctor.checkFailed': 'The check could not be completed.',
'doctor.healthy': 'Every message in this topic is showing. Nothing to fix.',
@@ -94,7 +94,7 @@ export default {
'duplicateLoading': 'Copying Topic...',
'duplicateSuccess': 'Topic Copied Successfully',
'failedStatusTip': 'This run hit an error — open it to take a look.',
- 'favorite': 'Favorite',
+ 'pinned': 'Pinned',
'forkFailed': 'Failed to fork the topic',
'forkLoading': 'Creating a new topic...',
'forkSuccess': 'Forked to a new topic',
@@ -229,7 +229,7 @@ export default {
'management.bulk.deleteConfirm':
'You are about to delete {{count}} topics. They will be moved to the trash and can be restored within 30 days.',
'management.bulk.deleteTitle': 'Delete topics?',
- 'management.bulk.favorite': 'Favorite',
+ 'management.bulk.pin': 'Pin',
'management.bulk.move': 'Move to agent',
'management.bulk.moveEmpty': 'No other agents',
'management.bulk.moveSearchPlaceholder': 'Search agents…',
diff --git a/packages/types/src/favorite.ts b/packages/types/src/favorite.ts
index 77f575131b8..f46ee360ff0 100644
--- a/packages/types/src/favorite.ts
+++ b/packages/types/src/favorite.ts
@@ -23,6 +23,13 @@ export type FavoriteType = (typeof FAVORITE_TYPES)[number];
*/
export const FAVORITE_LIMIT = 1000;
+/** Longest title a favorite keeps. Longer page titles are cut rather than refused. */
+export const FAVORITE_TITLE_MAX_LENGTH = 512;
+
+/** A title as a favorite stores it: trimmed, then cut on a code point so an emoji is never split. */
+export const toFavoriteTitle = (title: string): string =>
+ Array.from(title.trim()).slice(0, FAVORITE_TITLE_MAX_LENGTH).join('');
+
export interface FavoriteItem {
/** Emoji or avatar URL captured when the item was favorited; null falls back to the type icon. */
icon: string | null;
diff --git a/packages/types/src/hotkey.ts b/packages/types/src/hotkey.ts
index 2c9262c55a3..1f2fd136742 100644
--- a/packages/types/src/hotkey.ts
+++ b/packages/types/src/hotkey.ts
@@ -17,6 +17,7 @@ export type HotkeyId =
| 'showApp'
| 'switchAgent'
| 'switchTab'
+ | 'toggleFavorite'
| 'toggleLeftPanel'
| 'toggleRightPanel'
| 'toggleTerminalPanel';
diff --git a/src/features/AgentGoals/GoalDetailPage.test.tsx b/src/features/AgentGoals/GoalDetailPage.test.tsx
index 93d2b7cf800..fa84bce7ec8 100644
--- a/src/features/AgentGoals/GoalDetailPage.test.tsx
+++ b/src/features/AgentGoals/GoalDetailPage.test.tsx
@@ -114,6 +114,11 @@ vi.mock('./GoalSupervisorToggle', () => ({
vi.mock('@/features/Portal/router', () => ({
PortalContent: () => <div data-testid="goal-portal-content" />,
}));
+vi.mock('@/features/Favorites', () => ({
+ FavoriteButton: () => null,
+ useCurrentFavoritePath: () => '/favorite-path',
+ useFavoriteMenuItem: () => null,
+}));
vi.mock('@/features/NavHeader', () => ({
default: ({ left, right }: { left: ReactNode; right: ReactNode }) => (
<div>
diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsx
index 12f76359544..a75e7fb9a10 100644
--- a/src/features/AgentGoals/GoalDetailPage.tsx
+++ b/src/features/AgentGoals/GoalDetailPage.tsx
@@ -11,6 +11,7 @@ import ConversationSkeleton from '@/components/Skeleton/Conversation/List';
import GoalDetailSkeleton from '@/components/Skeleton/GoalDetail';
import AgentBreadcrumb from '@/features/AgentBreadcrumb';
import { useAgentRoutePath } from '@/features/AgentBreadcrumb/useAgentRoutePath';
+import { FavoriteButton, useCurrentFavoritePath } from '@/features/Favorites';
import NavHeader from '@/features/NavHeader';
import { PortalContent } from '@/features/Portal/router';
import { usePortalPanelWidth } from '@/features/Portal/usePortalPanelWidth';
@@ -83,6 +84,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
const canStart = useResourceManageable(snapshot?.goal.userId);
const buildAgentPath = useAgentRoutePath(agentId ?? '');
+ const favoritePath = useCurrentFavoritePath();
const showPortal = useChatStore(chatPortalSelectors.showPortal);
const currentViewType = useChatStore(chatPortalSelectors.currentViewType);
@@ -257,6 +259,12 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
) : (
<GoalWorkspaceBreadcrumb title={goal.title} />
)}
+ <FavoriteButton
+ path={favoritePath}
+ targetId={goal.id}
+ title={goal.title}
+ type={'goal'}
+ />
{/* Not nested under the breadcrumb: an agent-less goal still has to
be deletable, and this menu is the only place that can do it. */}
<GoalDetailActions agentId={agentId} goalId={goal.id} projectId={goal.projectId} />
diff --git a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
index 6e75a246f9c..dad76d93f52 100644
--- a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -16,8 +16,9 @@ import {
PanelRight,
PanelTop,
PencilLine,
+ Pin,
+ PinOff,
Share,
- Star,
Stethoscope,
Trash,
Wand2,
@@ -164,14 +165,14 @@ export const useTopicItemDropdownMenu = ({
},
{
disabled: !canEditTopic,
- icon: <Icon icon={Star} />,
+ icon: <Icon icon={fav ? PinOff : Pin} />,
key: 'favorite',
- label: fav ? t('actions.unfavorite') : t('actions.favorite'),
+ label: fav ? t('actions.unpin') : t('actions.pin'),
onClick: async () => {
await favoriteTopic(id, !fav);
if (scope) await refresh();
},
- sfSymbol: fav ? 'star.slash' : 'star',
+ sfSymbol: fav ? 'pin.slash' : 'pin',
},
{
type: 'divider' as const,
diff --git a/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx b/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
index d39eebd2f6f..7c2f2b3a490 100644
--- a/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
+++ b/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
@@ -228,16 +228,16 @@ describe('useTopicActionsDropdownMenu', () => {
});
expect(workspaceUnstarredItem).toMatchObject({
- label: 'actions.removeUnstarredWorkspace',
+ label: 'actions.removeUnpinnedWorkspace',
});
if (workspaceUnstarredItem && 'onClick' in workspaceUnstarredItem) {
workspaceUnstarredItem.onClick?.({} as never);
}
expect(openWorkspaceDeleteAllModalMock).toHaveBeenLastCalledWith(
expect.objectContaining({
- acknowledgeText: 'actions.confirmRemoveUnstarredWorkspaceAcknowledge',
- description: 'actions.confirmRemoveUnstarredWorkspace',
- title: 'actions.removeUnstarredWorkspace',
+ acknowledgeText: 'actions.confirmRemoveUnpinnedWorkspaceAcknowledge',
+ description: 'actions.confirmRemoveUnpinnedWorkspace',
+ title: 'actions.removeUnpinnedWorkspace',
}),
);
await openWorkspaceDeleteAllModalMock.mock.calls[0][0].onConfirm();
diff --git a/src/features/AgentSidebar/Topic/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
index 721b82b114a..35e0b301833 100644
--- a/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
+++ b/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
@@ -199,15 +199,15 @@ export const useTopicActionsDropdownMenu = (
disabled: !canEditTopic,
icon: <Icon icon={Trash} />,
key: 'deleteUnstarredWorkspace',
- label: t('actions.removeUnstarredWorkspace'),
+ label: t('actions.removeUnpinnedWorkspace'),
onClick: () => {
openWorkspaceDeleteAllModal({
- acknowledgeText: t('actions.confirmRemoveUnstarredWorkspaceAcknowledge'),
+ acknowledgeText: t('actions.confirmRemoveUnpinnedWorkspaceAcknowledge'),
cancelText: t('cancel', { ns: 'common' }),
- confirmText: t('actions.removeUnstarredWorkspace'),
- description: t('actions.confirmRemoveUnstarredWorkspace'),
+ confirmText: t('actions.removeUnpinnedWorkspace'),
+ description: t('actions.confirmRemoveUnpinnedWorkspace'),
onConfirm: () => removeUnstarredTopic({ onlyOwn: false }),
- title: t('actions.removeUnstarredWorkspace'),
+ title: t('actions.removeUnpinnedWorkspace'),
});
},
},
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
index ad1ac7eabdb..ca532ebe6e1 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
@@ -80,6 +80,11 @@ vi.mock('@/business/client/hooks/useIsWorkspaceOwner', () => ({
useIsWorkspaceOwner: () => mocks.isWorkspaceOwner,
}));
+vi.mock('@/features/Favorites', () => ({
+ FavoriteButton: () => null,
+ useCurrentFavoritePath: () => '/favorite-path',
+ useFavoriteMenuItem: () => null,
+}));
vi.mock('@/features/VisibilityConfirmContent', () => ({
default: () => <div />,
}));
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
index 395f3447683..f7e509d1b11 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
@@ -22,6 +22,7 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useTaskTransferMenuItem } from '@/business/client/hooks/useTaskTransferMenuItem';
+import { FavoriteButton, useFavoriteMenuItem } from '@/features/Favorites';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
@@ -33,6 +34,7 @@ import { userProfileSelectors } from '@/store/user/selectors';
import { getArchiveErrorKey } from '../features/archiveErrorKey';
import { useTaskArchiveGate } from '../features/useTaskArchiveGate';
import { useTaskCopyActions } from './useTaskCopyActions';
+import { useTaskFavoriteTarget } from './useTaskFavoriteTarget';
const TaskDetailHeaderActions = memo(() => {
const { t } = useTranslation(['chat', 'common']);
@@ -54,6 +56,8 @@ const TaskDetailHeaderActions = memo(() => {
});
const updateTaskVisibility = useTaskStore((s) => s.updateTaskVisibility);
const transferItems = useTaskTransferMenuItem(taskId) as DropdownItem[] | null;
+ const favoriteTarget = useTaskFavoriteTarget();
+ const favoriteMenuItem = useFavoriteMenuItem(favoriteTarget);
const triggerDelete = useCallback(() => {
if (!canEditTask) return;
@@ -158,6 +162,7 @@ const TaskDetailHeaderActions = memo(() => {
onClick: copyContent,
},
{ type: 'divider' },
+ ...(favoriteMenuItem ? [favoriteMenuItem, { type: 'divider' as const }] : []),
{
desc: archiveDeniedKey && t(archiveDeniedKey),
disabled: !canArchive,
@@ -229,6 +234,7 @@ const TaskDetailHeaderActions = memo(() => {
];
}, [
taskId,
+ favoriteMenuItem,
copyId,
copyLink,
copyContent,
@@ -252,9 +258,12 @@ const TaskDetailHeaderActions = memo(() => {
if (!taskId) return null;
return (
- <DropdownMenu items={menuItems}>
- <ActionIcon icon={MoreHorizontal} size={'small'} />
- </DropdownMenu>
+ <>
+ {favoriteTarget && <FavoriteButton {...favoriteTarget} />}
+ <DropdownMenu items={menuItems}>
+ <ActionIcon icon={MoreHorizontal} size={'small'} />
+ </DropdownMenu>
+ </>
);
});
diff --git a/src/features/AgentTasks/AgentTaskDetail/useTaskFavoriteTarget.ts b/src/features/AgentTasks/AgentTaskDetail/useTaskFavoriteTarget.ts
new file mode 100644
index 00000000000..a442689d09f
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/useTaskFavoriteTarget.ts
@@ -0,0 +1,24 @@
+import type { FavoriteTarget } from '@/features/Favorites';
+import { useTaskStore } from '@/store/task';
+import { taskDetailSelectors } from '@/store/task/selectors';
+
+import { taskDetailPath } from '../shared/taskDetailPath';
+
+/** The open task as a sidebar favorite, keyed by its database id so a renumbered link still matches. */
+export const useTaskFavoriteTarget = (): FavoriteTarget | undefined => {
+ const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
+ const databaseId = useTaskStore(taskDetailSelectors.activeTaskDatabaseId);
+ const agentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);
+ const name = useTaskStore(taskDetailSelectors.activeTaskName);
+
+ if (!taskId || !databaseId) return undefined;
+
+ // The database id arrives with the detail, so the name here is the task's own,
+ // even when empty; an unnamed task is shown, and favorited, by its identifier.
+ return {
+ path: taskDetailPath(taskId, agentId ?? undefined, name),
+ targetId: databaseId,
+ title: name || taskId,
+ type: 'task',
+ };
+};
diff --git a/src/features/AgentTopicManager/BulkActionBar.tsx b/src/features/AgentTopicManager/BulkActionBar.tsx
index b03b09dccdd..78822050856 100644
--- a/src/features/AgentTopicManager/BulkActionBar.tsx
+++ b/src/features/AgentTopicManager/BulkActionBar.tsx
@@ -1,7 +1,7 @@
'use client';
import { ActionIcon, createStaticStyles, cssVar, Flexbox, Text } from '@lobehub/ui';
-import { Archive, FolderInput, Star, Trash2, X } from 'lucide-react';
+import { Archive, FolderInput, Pin, Trash2, X } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -96,9 +96,9 @@ const BulkActionBar = memo(() => {
{t('management.bulk.selectedCount', { count: selectedIds.length })}
</Text>
<ActionIcon
- icon={Star}
+ icon={Pin}
size={'small'}
- title={t('management.bulk.favorite')}
+ title={t('management.bulk.pin')}
onClick={handleBatchFavorite}
/>
<ActionIcon
diff --git a/src/features/AgentTopicManager/TopicCard.tsx b/src/features/AgentTopicManager/TopicCard.tsx
index 95e9ed9838f..64f4949b1f1 100644
--- a/src/features/AgentTopicManager/TopicCard.tsx
+++ b/src/features/AgentTopicManager/TopicCard.tsx
@@ -3,14 +3,7 @@
import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
import { formatPrice, formatTokenNumber } from '@lobechat/utils/format';
import { Block, Checkbox, createStaticStyles, cssVar, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
-import {
- CircleDollarSign,
- FolderIcon,
- GitBranchIcon,
- MessageSquare,
- Star,
- Zap,
-} from 'lucide-react';
+import { CircleDollarSign, FolderIcon, GitBranchIcon, MessageSquare, Pin, Zap } from 'lucide-react';
import { memo, type MouseEvent, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -171,7 +164,7 @@ const TopicCard = memo<TopicCardProps>(({ topic, agentId }) => {
<Flexbox horizontal align={'center'} className={styles.titleRow} gap={6}>
{topic.favorite && (
- <Icon icon={Star} size={13} style={{ color: cssVar.colorWarning, flexShrink: 0 }} />
+ <Icon icon={Pin} size={13} style={{ color: cssVar.colorTextTertiary, flexShrink: 0 }} />
)}
{BotPlatformIcon && (
<BotPlatformIcon
diff --git a/src/features/AgentTopicManager/TopicListView.tsx b/src/features/AgentTopicManager/TopicListView.tsx
index 07e06015dc5..5fc382ff72f 100644
--- a/src/features/AgentTopicManager/TopicListView.tsx
+++ b/src/features/AgentTopicManager/TopicListView.tsx
@@ -13,7 +13,7 @@ import {
Tag,
Text,
} from '@lobehub/ui';
-import { FolderIcon, MoreHorizontal, Star } from 'lucide-react';
+import { FolderIcon, MoreHorizontal, Pin } from 'lucide-react';
import { Fragment, memo, type MouseEvent, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -207,7 +207,7 @@ const Row = memo<RowProps>(({ topic, agentId }) => {
<div className={styles.cell}>
<Flexbox horizontal align={'center'} gap={6}>
{topic.favorite && (
- <Icon icon={Star} size={12} style={{ color: cssVar.colorWarning, flexShrink: 0 }} />
+ <Icon icon={Pin} size={12} style={{ color: cssVar.colorTextTertiary, flexShrink: 0 }} />
)}
{BotPlatformIcon && (
<BotPlatformIcon
diff --git a/src/features/Dashboard/BoardPage.tsx b/src/features/Dashboard/BoardPage.tsx
index f29618aaabe..7d0fe9d8ef8 100644
--- a/src/features/Dashboard/BoardPage.tsx
+++ b/src/features/Dashboard/BoardPage.tsx
@@ -6,6 +6,7 @@ import { ChevronLeftIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { FavoriteButton, useCurrentFavoritePath } from '@/features/Favorites';
import NavHeader from '@/features/NavHeader';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
@@ -15,6 +16,7 @@ import DashboardBoard from './Board';
import DashboardActionsMenu from './DashboardActionsMenu';
import DashboardAvatar from './DashboardAvatar';
import { dashboardPageStyles as styles } from './pageStyles';
+import { getDashboardPath } from './utils/path';
interface DashboardBoardPageProps {
/** The board list this page returns to, e.g. `/dashboard` or a project's dashboards. */
@@ -30,6 +32,10 @@ const BoardPageHeader = memo<DashboardBoardPageProps>(
const { t } = useTranslation('dashboard');
const navigate = useWorkspaceAwareNavigate();
const detail = useDashboardStore(dashboardSelectors.dashboardDetail(dashboardId));
+ const currentPath = useCurrentFavoritePath();
+ // A project board opened by slug would save a link that breaks when the
+ // project is renamed, so it is favorited under the project id.
+ const favoritePath = detail?.projectId ? getDashboardPath(detail) : currentPath;
return (
<NavHeader
@@ -48,6 +54,14 @@ const BoardPageHeader = memo<DashboardBoardPageProps>(
<Text ellipsis weight={500}>
{detail?.title ?? ''}
</Text>
+ {detail?.title && (
+ <FavoriteButton
+ path={favoritePath}
+ targetId={dashboardId}
+ title={detail.title}
+ type={'dashboard'}
+ />
+ )}
</Flexbox>
}
right={
diff --git a/src/features/Favorites/FavoriteButton.tsx b/src/features/Favorites/FavoriteButton.tsx
new file mode 100644
index 00000000000..575928479f5
--- /dev/null
+++ b/src/features/Favorites/FavoriteButton.tsx
@@ -0,0 +1,59 @@
+'use client';
+
+import { HotkeyEnum } from '@lobechat/const/hotkeys';
+import { ActionIcon, type ActionIconSize, cssVar } from '@lobehub/ui';
+import { StarIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { useHotkeyById } from '@/hooks/useHotkeys/useHotkeyById';
+import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/selectors';
+
+import { useOwnsFavoriteHotkey } from './hotkeyOwner';
+import { type FavoriteTarget, useFavoriteToggle } from './useFavoriteToggle';
+
+interface FavoriteButtonProps extends FavoriteTarget {
+ size?: ActionIconSize;
+}
+
+/**
+ * Header star that adds the open page to the sidebar Favorites. The most
+ * recently mounted star also answers the favorite hotkey.
+ */
+const FavoriteButton = memo<FavoriteButtonProps>(
+ ({ size = DESKTOP_HEADER_ICON_SMALL_SIZE, ...target }) => {
+ const { t } = useTranslation('common');
+ const { isFavorite, isReady, toggle } = useFavoriteToggle(target);
+ const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ToggleFavorite));
+ const ownsHotkey = useOwnsFavoriteHotkey();
+
+ // Typing in a field must not toggle the favorite, so the hotkey stays out of form tags.
+ useHotkeyById(HotkeyEnum.ToggleFavorite, () => void toggle(), {
+ enableOnFormTags: false,
+ enabled: ownsHotkey,
+ });
+
+ const label = t(isFavorite ? 'favorite.remove' : 'favorite.add');
+
+ return (
+ <ActionIcon
+ aria-label={label}
+ aria-pressed={isFavorite}
+ color={isFavorite ? cssVar.colorWarning : undefined}
+ disabled={!isReady}
+ fill={isFavorite ? cssVar.colorWarning : 'none'}
+ icon={StarIcon}
+ size={size}
+ title={label}
+ tooltipProps={{ hotkey, placement: 'bottom' }}
+ onClick={() => void toggle()}
+ />
+ );
+ },
+);
+
+FavoriteButton.displayName = 'FavoriteButton';
+
+export default FavoriteButton;
diff --git a/src/features/Favorites/FavoriteIcon.tsx b/src/features/Favorites/FavoriteIcon.tsx
new file mode 100644
index 00000000000..c093811a5fe
--- /dev/null
+++ b/src/features/Favorites/FavoriteIcon.tsx
@@ -0,0 +1,49 @@
+'use client';
+
+import type { FavoriteType } from '@lobechat/types';
+import { Avatar, cssVar, Icon } from '@lobehub/ui';
+import {
+ BotIcon,
+ FileTextIcon,
+ HashIcon,
+ LayoutDashboardIcon,
+ LinkIcon,
+ ListTodoIcon,
+ type LucideIcon,
+ PackageIcon,
+ TargetIcon,
+ UsersIcon,
+} from 'lucide-react';
+import { memo } from 'react';
+
+const TYPE_ICONS: Record<FavoriteType, LucideIcon> = {
+ agent: BotIcon,
+ dashboard: LayoutDashboardIcon,
+ goal: TargetIcon,
+ group: UsersIcon,
+ page: FileTextIcon,
+ project: PackageIcon,
+ route: LinkIcon,
+ task: ListTodoIcon,
+ topic: HashIcon,
+};
+
+interface FavoriteIconProps {
+ /** Emoji or avatar URL snapshot; falls back to the type icon. */
+ icon?: string | null;
+ size?: number;
+ title?: string;
+ type: FavoriteType;
+}
+
+const FavoriteIcon = memo<FavoriteIconProps>(({ icon, size = 16, title, type }) => {
+ if (icon) return <Avatar avatar={icon} shape={'square'} size={size + 2} title={title} />;
+
+ return (
+ <Icon icon={TYPE_ICONS[type]} size={size} style={{ color: cssVar.colorTextDescription }} />
+ );
+});
+
+FavoriteIcon.displayName = 'FavoriteIcon';
+
+export default FavoriteIcon;
diff --git a/src/features/Favorites/hotkeyOwner.ts b/src/features/Favorites/hotkeyOwner.ts
new file mode 100644
index 00000000000..335bb26958b
--- /dev/null
+++ b/src/features/Favorites/hotkeyOwner.ts
@@ -0,0 +1,36 @@
+import { useEffect, useId, useSyncExternalStore } from 'react';
+
+/**
+ * A page can show two favorite stars at once (a chat header and a task opened
+ * in its side panel). The favorite hotkey belongs to the star mounted last —
+ * the surface the member opened most recently — so one press never toggles
+ * two favorites.
+ */
+let owners: string[] = [];
+const listeners = new Set<() => void>();
+
+const emit = () => {
+ for (const listener of listeners) listener();
+};
+
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+};
+
+const getOwner = () => owners.at(-1);
+
+export const useOwnsFavoriteHotkey = (): boolean => {
+ const id = useId();
+
+ useEffect(() => {
+ owners = [...owners, id];
+ emit();
+ return () => {
+ owners = owners.filter((owner) => owner !== id);
+ emit();
+ };
+ }, [id]);
+
+ return useSyncExternalStore(subscribe, getOwner, getOwner) === id;
+};
diff --git a/src/features/Favorites/index.ts b/src/features/Favorites/index.ts
new file mode 100644
index 00000000000..f715edb5462
--- /dev/null
+++ b/src/features/Favorites/index.ts
@@ -0,0 +1,6 @@
+export { default as FavoriteButton } from './FavoriteButton';
+export { default as FavoriteIcon } from './FavoriteIcon';
+export { useCurrentFavoritePath } from './useCurrentFavoritePath';
+export { useFavoriteMenuItem } from './useFavoriteMenuItem';
+export { type FavoriteTarget, useFavoriteToggle } from './useFavoriteToggle';
+export { useFetchFavorites } from './useFetchFavorites';
diff --git a/src/features/Favorites/path.test.ts b/src/features/Favorites/path.test.ts
new file mode 100644
index 00000000000..01f914e9605
--- /dev/null
+++ b/src/features/Favorites/path.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { toFavoritePath } from './path';
+
+describe('toFavoritePath', () => {
+ it('keeps a personal path as is', () => {
+ expect(toFavoritePath('/agent/agt_a/tpc_b', null)).toBe('/agent/agt_a/tpc_b');
+ });
+
+ it('drops the active workspace slug', () => {
+ expect(toFavoritePath('/acme/agent/agt_a/tpc_b', 'acme')).toBe('/agent/agt_a/tpc_b');
+ expect(toFavoritePath('/acme', 'acme')).toBe('/');
+ });
+
+ it('only strips a whole leading segment', () => {
+ expect(toFavoritePath('/acme-labs/page/docs_a', 'acme')).toBe('/acme-labs/page/docs_a');
+ });
+
+ it('drops a trailing slash', () => {
+ expect(toFavoritePath('/acme/projects/', 'acme')).toBe('/projects');
+ });
+});
diff --git a/src/features/Favorites/path.ts b/src/features/Favorites/path.ts
new file mode 100644
index 00000000000..a5c72343ff1
--- /dev/null
+++ b/src/features/Favorites/path.ts
@@ -0,0 +1,13 @@
+/**
+ * The in-app path a favorite stores: the location without the workspace slug,
+ * so the client can add whichever workspace prefix is active when it
+ * navigates (`useWorkspaceAwareNavigate` / `WorkspaceLink`).
+ */
+export const toFavoritePath = (pathname: string, workspaceSlug: string | null): string => {
+ const path = pathname.replace(/\/+$/, '') || '/';
+ if (!workspaceSlug) return path;
+
+ const prefix = `/${workspaceSlug}`;
+ if (path === prefix) return '/';
+ return path.startsWith(`${prefix}/`) ? path.slice(prefix.length) : path;
+};
diff --git a/src/features/Favorites/useCurrentFavoritePath.ts b/src/features/Favorites/useCurrentFavoritePath.ts
new file mode 100644
index 00000000000..0476790f65e
--- /dev/null
+++ b/src/features/Favorites/useCurrentFavoritePath.ts
@@ -0,0 +1,8 @@
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { useActiveLocation } from '@/hooks/useActiveLocation';
+
+import { toFavoritePath } from './path';
+
+/** The open page as a favorite link, for targets reached at more than one URL. */
+export const useCurrentFavoritePath = (): string =>
+ toFavoritePath(useActiveLocation().pathname, useActiveWorkspaceSlug());
diff --git a/src/features/Favorites/useFavoriteMenuItem.tsx b/src/features/Favorites/useFavoriteMenuItem.tsx
new file mode 100644
index 00000000000..fad839ab3f4
--- /dev/null
+++ b/src/features/Favorites/useFavoriteMenuItem.tsx
@@ -0,0 +1,38 @@
+import { HotkeyEnum } from '@lobechat/const/hotkeys';
+import { type DropdownItem, Hotkey, Icon } from '@lobehub/ui';
+import { StarIcon, StarOffIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/selectors';
+
+import { type FavoriteTarget, useFavoriteToggle } from './useFavoriteToggle';
+
+interface FavoriteMenuItemOptions {
+ /**
+ * Show the favorite hotkey beside the item. Only a menu of the open page
+ * should: the hotkey toggles the page, not a row in a list.
+ */
+ showHotkey?: boolean;
+}
+
+/** "Add to Favorites" / "Remove from Favorites" for a ⋯ menu. */
+export const useFavoriteMenuItem = (
+ target: FavoriteTarget | undefined,
+ { showHotkey = true }: FavoriteMenuItemOptions = {},
+): DropdownItem | null => {
+ const { t } = useTranslation('common');
+ const { isFavorite, isReady, toggle } = useFavoriteToggle(target);
+ const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ToggleFavorite));
+
+ if (!target) return null;
+
+ return {
+ disabled: !isReady,
+ extra: showHotkey && hotkey ? <Hotkey keys={hotkey} variant={'borderless'} /> : undefined,
+ icon: <Icon icon={isFavorite ? StarOffIcon : StarIcon} />,
+ key: 'toggleFavorite',
+ label: t(isFavorite ? 'favorite.remove' : 'favorite.add'),
+ onClick: () => void toggle(),
+ };
+};
diff --git a/src/features/Favorites/useFavoriteToggle.test.ts b/src/features/Favorites/useFavoriteToggle.test.ts
new file mode 100644
index 00000000000..bc41b50e888
--- /dev/null
+++ b/src/features/Favorites/useFavoriteToggle.test.ts
@@ -0,0 +1,202 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { FAVORITE_LIMIT } from '@lobechat/types';
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ FAVORITE_SNAPSHOT_SYNC_ATTEMPTS,
+ FAVORITE_SNAPSHOT_SYNC_DELAY,
+ type FavoriteTarget,
+ useFavoriteToggle,
+} from './useFavoriteToggle';
+
+const store = vi.hoisted(() => ({
+ favoriteId: undefined as string | undefined,
+ listLoaded: true,
+ listSize: 0,
+ storedTitle: 'Stored',
+ syncFavoriteSnapshot: vi.fn(),
+ toggleFavorite: vi.fn(),
+ toastError: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui', () => ({ toast: { error: store.toastError } }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('./useFetchFavorites', () => ({ useFetchFavorites: () => ({}) }));
+vi.mock('@/store/home/selectors', () => ({
+ favoriteSelectors: {
+ favoriteList: () => (store.listLoaded ? Array.from({ length: store.listSize }) : undefined),
+ getFavorite: () => () =>
+ store.favoriteId
+ ? { icon: null, id: store.favoriteId, path: '/page/docs_a', title: store.storedTitle }
+ : undefined,
+ },
+}));
+vi.mock('@/store/home', () => ({
+ useHomeStore: (selector: (s: unknown) => unknown) =>
+ selector({
+ syncFavoriteSnapshot: store.syncFavoriteSnapshot,
+ toggleFavorite: store.toggleFavorite,
+ }),
+}));
+
+const target = (title: string): FavoriteTarget => ({
+ path: '/page/docs_a',
+ targetId: 'docs_a',
+ title,
+ type: 'page',
+});
+
+describe('useFavoriteToggle snapshot sync', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ store.favoriteId = 'fav_a';
+ store.storedTitle = 'Stored';
+ store.listLoaded = true;
+ store.toggleFavorite.mockReset().mockResolvedValue(undefined);
+ store.syncFavoriteSnapshot.mockReset().mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('writes a title typed character by character once it settles', () => {
+ const { rerender } = renderHook(({ title }) => useFavoriteToggle(target(title)), {
+ initialProps: { title: 'S' },
+ });
+ for (const title of ['Sp', 'Spe', 'Spec']) {
+ act(() => vi.advanceTimersByTime(100));
+ rerender({ title });
+ }
+
+ act(() => vi.advanceTimersByTime(FAVORITE_SNAPSHOT_SYNC_DELAY));
+
+ expect(store.syncFavoriteSnapshot).toHaveBeenCalledTimes(1);
+ expect(store.syncFavoriteSnapshot).toHaveBeenLastCalledWith(
+ 'page',
+ 'docs_a',
+ expect.objectContaining({ title: 'Spec' }),
+ );
+ });
+
+ it('replays a rename made while the add was pending once the add is confirmed', () => {
+ store.favoriteId = 'optimistic:page:docs_a';
+ const { rerender } = renderHook(({ title }) => useFavoriteToggle(target(title)), {
+ initialProps: { title: 'Renamed' },
+ });
+ act(() => vi.advanceTimersByTime(FAVORITE_SNAPSHOT_SYNC_DELAY));
+ store.syncFavoriteSnapshot.mockClear();
+
+ // The confirmed row arrives with the snapshot sent at add time.
+ store.favoriteId = 'fav_a';
+ rerender({ title: 'Renamed' });
+ act(() => vi.advanceTimersByTime(FAVORITE_SNAPSHOT_SYNC_DELAY));
+
+ expect(store.syncFavoriteSnapshot).toHaveBeenCalledWith(
+ 'page',
+ 'docs_a',
+ expect.objectContaining({ title: 'Renamed' }),
+ );
+ });
+
+ it('retries a write that failed and was rolled back', async () => {
+ store.syncFavoriteSnapshot.mockRejectedValueOnce(new Error('offline'));
+ const { rerender } = renderHook(({ title }) => useFavoriteToggle(target(title)), {
+ initialProps: { title: 'Spec' },
+ });
+ await act(async () => vi.advanceTimersByTime(FAVORITE_SNAPSHOT_SYNC_DELAY));
+
+ // The optimistic title, then the rollback to the stored one.
+ store.storedTitle = 'Spec';
+ rerender({ title: 'Spec' });
+ store.storedTitle = 'Stored';
+ rerender({ title: 'Spec' });
+ await act(async () => vi.advanceTimersByTime(FAVORITE_SNAPSHOT_SYNC_DELAY));
+
+ expect(store.syncFavoriteSnapshot).toHaveBeenCalledTimes(2);
+ });
+
+ it('stops retrying a snapshot that keeps failing', async () => {
+ store.syncFavoriteSnapshot.mockRejectedValue(new Error('offline'));
+ const { rerender } = renderHook(({ title }) => useFavoriteToggle(target(title)), {
+ initialProps: { title: 'Spec' },
+ });
+
+ for (let attempt = 0; attempt < FAVORITE_SNAPSHOT_SYNC_ATTEMPTS + 2; attempt++) {
+ await act(async () => vi.advanceTimersByTime(FAVORITE_SNAPSHOT_SYNC_DELAY));
+ store.storedTitle = attempt % 2 ? 'Stored' : 'Spec';
+ rerender({ title: 'Spec' });
+ }
+
+ expect(store.syncFavoriteSnapshot).toHaveBeenCalledTimes(FAVORITE_SNAPSHOT_SYNC_ATTEMPTS);
+ });
+
+ it('does not write a placeholder title over a saved favorite', () => {
+ renderHook(() => useFavoriteToggle({ ...target('New Topic'), snapshotReady: false }));
+
+ act(() => vi.advanceTimersByTime(FAVORITE_SNAPSHOT_SYNC_DELAY * 2));
+
+ expect(store.syncFavoriteSnapshot).not.toHaveBeenCalled();
+ });
+});
+
+describe('useFavoriteToggle before the list loads', () => {
+ it('does not toggle while it cannot tell whether the target is favorited', async () => {
+ store.listLoaded = false;
+ store.favoriteId = undefined;
+ store.toggleFavorite.mockReset().mockResolvedValue(undefined);
+ const { result } = renderHook(() => useFavoriteToggle(target('Spec')));
+
+ expect(result.current.isReady).toBe(false);
+ await act(() => result.current.toggle());
+
+ expect(store.toggleFavorite).not.toHaveBeenCalled();
+ });
+});
+
+describe('useFavoriteToggle adding', () => {
+ beforeEach(() => {
+ store.favoriteId = undefined;
+ store.listLoaded = true;
+ store.listSize = 0;
+ store.toggleFavorite.mockReset().mockResolvedValue(undefined);
+ store.toastError.mockReset();
+ });
+
+ it("waits for the target's own title before adding it", async () => {
+ const { result, rerender } = renderHook(
+ ({ ready }) => useFavoriteToggle({ ...target('New Topic'), snapshotReady: ready }),
+ { initialProps: { ready: false } },
+ );
+
+ expect(result.current.isReady).toBe(false);
+ await act(() => result.current.toggle());
+ expect(store.toggleFavorite).not.toHaveBeenCalled();
+
+ rerender({ ready: true });
+ await act(() => result.current.toggle());
+ expect(store.toggleFavorite).toHaveBeenCalledTimes(1);
+ });
+
+ it('still removes a favorite whose target has not loaded', () => {
+ store.favoriteId = 'fav_a';
+ const { result } = renderHook(() =>
+ useFavoriteToggle({ ...target('New Topic'), snapshotReady: false }),
+ );
+
+ expect(result.current.isReady).toBe(true);
+ });
+
+ it('explains a full sidebar instead of sending an add that must fail', async () => {
+ store.listSize = FAVORITE_LIMIT;
+ const { result } = renderHook(() => useFavoriteToggle(target('Spec')));
+
+ await act(() => result.current.toggle());
+
+ expect(store.toggleFavorite).not.toHaveBeenCalled();
+ expect(store.toastError).toHaveBeenCalledWith('favorite.limitReached');
+ });
+});
diff --git a/src/features/Favorites/useFavoriteToggle.ts b/src/features/Favorites/useFavoriteToggle.ts
new file mode 100644
index 00000000000..6dbb7850f98
--- /dev/null
+++ b/src/features/Favorites/useFavoriteToggle.ts
@@ -0,0 +1,121 @@
+import { type AddFavoriteParams, FAVORITE_LIMIT, type FavoriteType } from '@lobechat/types';
+import { toast } from '@lobehub/ui';
+import { useCallback, useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useHomeStore } from '@/store/home';
+import { favoriteSelectors } from '@/store/home/selectors';
+
+import { useFetchFavorites } from './useFetchFavorites';
+
+/** Quiet period before a changed title or icon is written back to its favorite. */
+export const FAVORITE_SNAPSHOT_SYNC_DELAY = 800;
+
+/** Failed writes of one snapshot before the hook stops retrying it. */
+export const FAVORITE_SNAPSHOT_SYNC_ATTEMPTS = 3;
+
+export interface FavoriteTarget {
+ /** Emoji or avatar URL of the target; omitted renders the type icon. */
+ icon?: string | null;
+ /** In-app link without the workspace slug; `useCurrentFavoritePath` gives the open page's. */
+ path: string;
+ /**
+ * Whether `title` and `icon` are the target's own data. Pass `false` while
+ * they are still placeholders (a topic whose detail has not loaded), so a
+ * placeholder is never written over a saved favorite.
+ */
+ snapshotReady?: boolean;
+ targetId: string;
+ title: string;
+ type: FavoriteType;
+}
+
+/**
+ * Favorite state and toggle for one target. While the target is favorited
+ * and mounted, a renamed title, new icon or moved link is written back to the
+ * favorite so the sidebar row does not go stale.
+ */
+export const useFavoriteToggle = (target: FavoriteTarget | undefined) => {
+ const { t } = useTranslation('common');
+ useFetchFavorites();
+
+ const type = target?.type;
+ const targetId = target?.targetId;
+ const favoriteId = useHomeStore((s) =>
+ type && targetId ? favoriteSelectors.getFavorite(type, targetId)(s)?.id : undefined,
+ );
+ const isFavorite = !!favoriteId;
+ const favoriteCount = useHomeStore((s) => favoriteSelectors.favoriteList(s)?.length);
+ const snapshotReady = target?.snapshotReady ?? true;
+ // Until the list loads, "not in the list" is unknown, not "not favorited": a
+ // toggle then would add a row the member meant to remove. An add also waits
+ // for the target's own title, so a placeholder is never saved; removing does not.
+ const isReady = favoriteCount !== undefined && (isFavorite || snapshotReady);
+ // The stored copy, so a write rolled back after a failure runs the sync again.
+ const storedSnapshot = useHomeStore((s) => {
+ const item = type && targetId ? favoriteSelectors.getFavorite(type, targetId)(s) : undefined;
+ return item ? JSON.stringify([item.icon, item.path, item.title]) : undefined;
+ });
+ const failures = useRef({ count: 0, snapshot: '' });
+ const [toggleFavorite, syncFavoriteSnapshot] = useHomeStore((s) => [
+ s.toggleFavorite,
+ s.syncFavoriteSnapshot,
+ ]);
+
+ const title = target?.title;
+ const icon = target?.icon;
+ const path = target?.path;
+ // Titles change on every keystroke, so write once the target settles. The
+ // favorite id is a dependency too: a rename made while the add was pending is
+ // replayed once the confirmed row (and its real id) replaces the optimistic one.
+ // A failed write rolls the stored copy back, which reruns this effect; a
+ // snapshot that keeps failing stops after a few attempts instead of looping.
+ useEffect(() => {
+ if (!favoriteId || !snapshotReady || !type || !targetId || !title) return;
+ const snapshot = JSON.stringify([icon ?? null, path, title]);
+ if (failures.current.snapshot !== snapshot) failures.current = { count: 0, snapshot };
+ if (failures.current.count >= FAVORITE_SNAPSHOT_SYNC_ATTEMPTS) return;
+
+ const timer = setTimeout(() => {
+ syncFavoriteSnapshot(type, targetId, { icon, path, title }).catch((error) => {
+ if (failures.current.snapshot === snapshot) failures.current.count += 1;
+ console.error('[favorite] failed to refresh the snapshot', error);
+ });
+ }, FAVORITE_SNAPSHOT_SYNC_DELAY);
+ return () => clearTimeout(timer);
+ }, [
+ favoriteId,
+ snapshotReady,
+ storedSnapshot,
+ type,
+ targetId,
+ title,
+ icon,
+ path,
+ syncFavoriteSnapshot,
+ ]);
+
+ const toggle = useCallback(async () => {
+ if (!target || !isReady) return;
+ // A full sidebar rejects every add, so say how to make room instead of offering a retry.
+ if (!isFavorite && (favoriteCount ?? 0) >= FAVORITE_LIMIT) {
+ toast.error(t('favorite.limitReached', { count: FAVORITE_LIMIT }));
+ return;
+ }
+ const params: AddFavoriteParams = {
+ icon: target.icon ?? null,
+ path: target.path,
+ targetId: target.targetId,
+ title: target.title,
+ type: target.type,
+ };
+ try {
+ await toggleFavorite(params);
+ } catch (error) {
+ console.error('[favorite] toggle failed', error);
+ toast.error(t('favorite.updateError'));
+ }
+ }, [favoriteCount, isFavorite, isReady, t, target, toggleFavorite]);
+
+ return { isFavorite, isReady, toggle };
+};
diff --git a/src/features/Favorites/useFetchFavorites.ts b/src/features/Favorites/useFetchFavorites.ts
new file mode 100644
index 00000000000..b1a960c2cba
--- /dev/null
+++ b/src/features/Favorites/useFetchFavorites.ts
@@ -0,0 +1,15 @@
+import { useHomeStore } from '@/store/home';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/slices/auth/selectors';
+
+/**
+ * Sync the member's favorites into the home store. Mounted by the sidebar
+ * section and every favorite toggle; the replica dedupes concurrent mounts and
+ * swaps the list when the workspace changes.
+ */
+export const useFetchFavorites = () => {
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const useFetch = useHomeStore((s) => s.useFetchFavorites);
+
+ return useFetch(isLogin === true);
+};
diff --git a/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx b/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
index 8c3eddd2ade..0f5ee5a53a0 100644
--- a/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
+++ b/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
@@ -68,6 +68,7 @@ const ALL_SIDEBAR_ITEMS: SidebarItemConfig[] = [
{ id: 'tasks', labelKey: 'tab.tasks', routeId: 'tasks' },
{ id: 'goals', labelKey: 'tab.goals', routeId: 'goals' },
{ id: 'dashboard', labelKey: 'tab.dashboard', routeId: 'dashboard' },
+ { id: 'favorites', labelKey: 'favorite.section' },
{ id: 'recents', labelKey: 'recents' },
{ id: 'project', labelKey: 'project:sidebar.title' },
{ id: 'private', labelKey: 'navPanel.privateAgents' },
diff --git a/src/features/HomeSidebar/Body/Favorites/FavoriteItem.tsx b/src/features/HomeSidebar/Body/Favorites/FavoriteItem.tsx
new file mode 100644
index 00000000000..c0b84674019
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Favorites/FavoriteItem.tsx
@@ -0,0 +1,61 @@
+'use client';
+
+import type { FavoriteItem as FavoriteItemType } from '@lobechat/types';
+import { ActionIcon, type DropdownItem, DropdownMenu, Icon, toast } from '@lobehub/ui';
+import { MoreHorizontalIcon, StarOffIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { FavoriteIcon } from '@/features/Favorites';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+import { useHomeStore } from '@/store/home';
+
+interface FavoriteItemProps {
+ active?: boolean;
+ item: FavoriteItemType;
+}
+
+const FavoriteItem = memo<FavoriteItemProps>(({ active, item }) => {
+ const { t } = useTranslation('common');
+ const removeFavorite = useHomeStore((s) => s.removeFavorite);
+
+ const menuItems = (): DropdownItem[] => [
+ {
+ icon: <Icon icon={StarOffIcon} />,
+ key: 'removeFavorite',
+ label: t('favorite.remove'),
+ onClick: () => {
+ removeFavorite(item.type, item.targetId).catch((error) => {
+ console.error('[favorite] remove failed', error);
+ toast.error(t('favorite.updateError'));
+ });
+ },
+ },
+ ];
+
+ return (
+ <WorkspaceLink to={item.path}>
+ <NavItem
+ active={active}
+ contextMenuItems={menuItems}
+ icon={<FavoriteIcon icon={item.icon} title={item.title} type={item.type} />}
+ title={item.title}
+ actions={() => (
+ <DropdownMenu items={menuItems()}>
+ <ActionIcon
+ aria-label={t('more')}
+ icon={MoreHorizontalIcon}
+ size={'small'}
+ style={{ flex: 'none' }}
+ />
+ </DropdownMenu>
+ )}
+ />
+ </WorkspaceLink>
+ );
+});
+
+FavoriteItem.displayName = 'FavoriteItem';
+
+export default FavoriteItem;
diff --git a/src/features/HomeSidebar/Body/Favorites/SortableFavoriteList.tsx b/src/features/HomeSidebar/Body/Favorites/SortableFavoriteList.tsx
new file mode 100644
index 00000000000..4a7c26dd202
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Favorites/SortableFavoriteList.tsx
@@ -0,0 +1,155 @@
+'use client';
+
+import {
+ closestCenter,
+ DndContext,
+ type DragEndEvent,
+ DragOverlay,
+ type DragStartEvent,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import {
+ arrayMove,
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import type { FavoriteItem as FavoriteItemType } from '@lobechat/types';
+import { toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo, useMemo, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { FavoriteIcon } from '@/features/Favorites';
+import { toFavoritePath } from '@/features/Favorites/path';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { useActiveLocation } from '@/hooks/useActiveLocation';
+import { useHomeStore } from '@/store/home';
+import { isOptimisticId } from '@/store/home/slices/favorite/action';
+
+import {
+ RowKeyboardSensor,
+ RowMouseSensor,
+ RowTouchSensor,
+ sortableRowDropAnimation,
+ suppressNextClick,
+} from '../sortableRow';
+import FavoriteItem from './FavoriteItem';
+
+const styles = stylex.create({
+ overlay: {
+ backgroundColor: cssVar.colorBgElevated,
+ borderRadius: cssVar.borderRadius,
+ boxShadow: cssVar.boxShadowSecondary,
+ cursor: 'grabbing',
+ },
+});
+
+const SortableFavoriteItem = memo<{ active: boolean; item: FavoriteItemType }>(
+ ({ active, item }) => {
+ const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({
+ // A row still being added has no server id, so its position could not be saved.
+ disabled: isOptimisticId(item.id),
+ id: item.id,
+ });
+
+ return (
+ <div
+ ref={setNodeRef}
+ style={{
+ // The floating copy follows the pointer; the row itself marks where it will land.
+ opacity: isDragging ? 0.4 : undefined,
+ transform: CSS.Translate.toString(transform),
+ transition,
+ // Holding the press before the drag starts would otherwise select the title.
+ userSelect: 'none',
+ }}
+ {...attributes}
+ {...listeners}
+ // Stop the browser's native link drag from hijacking the pointer.
+ onDragStart={(e) => e.preventDefault()}
+ >
+ <FavoriteItem active={active} item={item} />
+ </div>
+ );
+ },
+);
+
+SortableFavoriteItem.displayName = 'SortableFavoriteItem';
+
+const SortableFavoriteList = memo<{ items: FavoriteItemType[] }>(({ items }) => {
+ const { t } = useTranslation('common');
+ const reorderFavorites = useHomeStore((s) => s.reorderFavorites);
+ const { pathname } = useActiveLocation();
+ const currentPath = toFavoritePath(pathname, useActiveWorkspaceSlug());
+
+ const [activeId, setActiveId] = useState<string>();
+ const ids = useMemo(() => items.map((item) => item.id), [items]);
+
+ const sensors = useSensors(
+ useSensor(RowMouseSensor, { activationConstraint: { distance: 5 } }),
+ // A press-and-hold picks a row up on touch, so a vertical swipe still scrolls the sidebar.
+ useSensor(RowTouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),
+ useSensor(RowKeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ );
+
+ const activeItem = activeId ? items.find((item) => item.id === activeId) : undefined;
+
+ const handleDragStart = ({ active }: DragStartEvent) => setActiveId(String(active.id));
+
+ const handleDragEnd = async ({ active, over }: DragEndEvent) => {
+ setActiveId(undefined);
+ suppressNextClick();
+ if (!over || active.id === over.id) return;
+
+ try {
+ await reorderFavorites(
+ arrayMove(ids, ids.indexOf(String(active.id)), ids.indexOf(String(over.id))),
+ );
+ } catch (error) {
+ console.error('[favorite] failed to save the order', error);
+ toast.error(t('favorite.reorderError'));
+ }
+ };
+
+ return (
+ <DndContext
+ collisionDetection={closestCenter}
+ sensors={sensors}
+ onDragCancel={() => setActiveId(undefined)}
+ onDragEnd={handleDragEnd}
+ onDragStart={handleDragStart}
+ >
+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>
+ {items.map((item) => (
+ <SortableFavoriteItem active={item.path === currentPath} item={item} key={item.id} />
+ ))}
+ </SortableContext>
+ {createPortal(
+ <DragOverlay dropAnimation={sortableRowDropAnimation}>
+ {activeItem ? (
+ <div {...stylex.props(styles.overlay)}>
+ <NavItem
+ icon={<FavoriteIcon icon={activeItem.icon} type={activeItem.type} />}
+ // The card itself is the surface: no hover tint on top of the white.
+ style={{ backgroundColor: 'transparent' }}
+ title={activeItem.title}
+ />
+ </div>
+ ) : null}
+ </DragOverlay>,
+ document.body,
+ )}
+ </DndContext>
+ );
+});
+
+SortableFavoriteList.displayName = 'SortableFavoriteList';
+
+export default SortableFavoriteList;
diff --git a/src/features/HomeSidebar/Body/Favorites/index.test.tsx b/src/features/HomeSidebar/Body/Favorites/index.test.tsx
new file mode 100644
index 00000000000..e9b14539868
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Favorites/index.test.tsx
@@ -0,0 +1,67 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { AccordionRoot } from '@lobehub/ui';
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import Favorites from './index';
+
+const state = vi.hoisted(() => ({
+ error: undefined as Error | undefined,
+ list: undefined as unknown[] | undefined,
+ revalidate: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/features/Favorites', () => ({
+ useFetchFavorites: () => ({ error: state.error, revalidate: state.revalidate }),
+}));
+vi.mock('@/store/home', () => ({
+ useHomeStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/home/selectors', () => ({
+ favoriteSelectors: { favoriteList: () => state.list },
+}));
+vi.mock('@/components/AsyncError', () => ({
+ default: ({ onRetry }: { onRetry: () => void }) => (
+ <button type="button" onClick={onRetry}>
+ retry
+ </button>
+ ),
+}));
+vi.mock('./SortableFavoriteList', () => ({ default: () => <div data-testid="favorite-list" /> }));
+
+const renderSection = () =>
+ render(
+ <AccordionRoot defaultValue={['favorites']}>
+ <Favorites itemKey="favorites" />
+ </AccordionRoot>,
+ );
+
+describe('Favorites sidebar section', () => {
+ beforeEach(() => {
+ state.error = undefined;
+ state.list = undefined;
+ state.revalidate.mockReset();
+ });
+
+ afterEach(cleanup);
+
+ it('shows a failed first load with a retry instead of disappearing', () => {
+ state.error = new Error('offline');
+ renderSection();
+
+ expect(screen.getByText('favorite.section')).toBeTruthy();
+ screen.getByText('retry').click();
+
+ expect(state.revalidate).toHaveBeenCalled();
+ });
+
+ it('stays hidden while there is nothing favorited', () => {
+ state.list = [];
+ renderSection();
+
+ expect(screen.queryByText('favorite.section')).toBeNull();
+ });
+});
diff --git a/src/features/HomeSidebar/Body/Favorites/index.tsx b/src/features/HomeSidebar/Body/Favorites/index.tsx
new file mode 100644
index 00000000000..0be232dade8
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Favorites/index.tsx
@@ -0,0 +1,61 @@
+'use client';
+
+import {
+ AccordionHeader,
+ AccordionItem,
+ AccordionPanel,
+ AccordionTrigger,
+ Text,
+} from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { useFetchFavorites } from '@/features/Favorites';
+import { useHomeStore } from '@/store/home';
+import { favoriteSelectors } from '@/store/home/selectors';
+
+import SortableFavoriteList from './SortableFavoriteList';
+
+interface FavoritesProps {
+ itemKey: string;
+}
+
+/**
+ * Pages the member starred, in the order they arranged. The section only
+ * appears once something is favorited: an empty one would be a heading with
+ * nothing to act on, and the star on each page is the way in. A failed first
+ * load still shows the section, with the error and a retry: the stars stay
+ * disabled until the list is known, so the member needs a way back.
+ */
+const Favorites = memo<FavoritesProps>(({ itemKey }) => {
+ const { t } = useTranslation('common');
+ const { error, revalidate } = useFetchFavorites();
+ const list = useHomeStore(favoriteSelectors.favoriteList);
+ const loadFailed = list === undefined && !!error;
+
+ if (!loadFailed && (!list || list.length === 0)) return null;
+
+ return (
+ <AccordionItem value={itemKey}>
+ <AccordionHeader>
+ <AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>
+ <Text ellipsis fontSize={12} type="secondary" weight={500}>
+ {t('favorite.section')}
+ </Text>
+ </AccordionTrigger>
+ </AccordionHeader>
+ <AccordionPanel>
+ {loadFailed ? (
+ <AsyncError error={error} variant="inline" onRetry={() => revalidate()} />
+ ) : (
+ list && <SortableFavoriteList items={list} />
+ )}
+ </AccordionPanel>
+ </AccordionItem>
+ );
+});
+
+Favorites.displayName = 'Favorites';
+
+export default Favorites;
diff --git a/src/features/HomeSidebar/Body/Project/ProjectItem.test.tsx b/src/features/HomeSidebar/Body/Project/ProjectItem.test.tsx
index 25be05019e3..daa1b5b6f78 100644
--- a/src/features/HomeSidebar/Body/Project/ProjectItem.test.tsx
+++ b/src/features/HomeSidebar/Body/Project/ProjectItem.test.tsx
@@ -1,11 +1,24 @@
import { render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type * as FavoritesModule from '@/features/Favorites';
import type { ProjectListItem } from '@/store/project';
import ProjectItem from './ProjectItem';
const permission = vi.hoisted(() => ({ allowed: true }));
+const favorite = vi.hoisted(() => ({ path: undefined as string | undefined }));
+
+vi.mock('@/features/Favorites', async (importOriginal) => {
+ const actual = await importOriginal<typeof FavoritesModule>();
+ return {
+ ...actual,
+ useFavoriteMenuItem: (...args: Parameters<typeof actual.useFavoriteMenuItem>) => {
+ favorite.path = args[0]?.path;
+ return actual.useFavoriteMenuItem(...args);
+ },
+ };
+});
vi.mock('@/features/Workspace/WorkspaceLink', () => ({
default: ({ children }: { children: React.ReactNode }) => <>{children}</>,
@@ -48,10 +61,17 @@ describe('ProjectItem', () => {
expect(container.querySelector('.nav-item-actions')).not.toBeNull();
});
- it('hides the actions menu from members without edit permission', () => {
+ it('keeps the actions menu for members without edit permission, who can still favorite', () => {
permission.allowed = false;
const { container } = render(<ProjectItem project={project} />);
- expect(container.querySelector('.nav-item-actions')).toBeNull();
+ expect(container.querySelector('.nav-item-actions')).not.toBeNull();
+ });
+
+ // A slug can be renamed from Project Settings, so the favorite keeps the id link.
+ it('favorites the project under its id, not its renameable slug', () => {
+ render(<ProjectItem project={project} />);
+
+ expect(favorite.path).toBe('/project/proj_1');
});
});
diff --git a/src/features/HomeSidebar/Body/Project/ProjectItem.tsx b/src/features/HomeSidebar/Body/Project/ProjectItem.tsx
index 3212830e469..27b304f4575 100644
--- a/src/features/HomeSidebar/Body/Project/ProjectItem.tsx
+++ b/src/features/HomeSidebar/Body/Project/ProjectItem.tsx
@@ -6,6 +6,7 @@ import { MoreHorizontalIcon, PencilIcon, TrashIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useFavoriteMenuItem } from '@/features/Favorites';
import NavItem from '@/features/NavPanel/components/NavItem';
import ProjectAvatar from '@/features/Projects/ProjectAvatar';
import { openRenameProjectModal } from '@/features/Projects/RenameProjectModal';
@@ -29,6 +30,19 @@ const ProjectItem = memo<ProjectItemProps>(({ project }) => {
const [deleting, setDeleting] = useState(false);
const deleteProject = useProjectStore((s) => s.deleteProject);
const canManage = useCanManageProject();
+ const projectPath = `/project/${project.slug ?? project.id}`;
+ const favoriteMenuItem = useFavoriteMenuItem(
+ {
+ icon: project.avatar ?? null,
+ // The slug can be renamed from Project Settings, where this row is not
+ // mounted to refresh the snapshot; the id link always resolves.
+ path: `/project/${project.id}`,
+ targetId: project.id,
+ title: project.name,
+ type: 'project',
+ },
+ { showHotkey: false },
+ );
const handleDelete = async () => {
setDeleting(true);
@@ -42,46 +56,48 @@ const ProjectItem = memo<ProjectItemProps>(({ project }) => {
}
};
- const menuItems: DropdownItem[] = canManage
- ? [
- {
- icon: <Icon icon={PencilIcon} />,
- key: 'rename',
- label: t('rename.action'),
- onClick: () => openRenameProjectModal(project),
- },
- { type: 'divider' },
- {
- danger: true,
- icon: <Icon icon={TrashIcon} />,
- key: 'delete',
- label: t('list.deleteAction'),
- onClick: () =>
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('list.deleteConfirmDescription', { name: project.name }),
- okButtonProps: { danger: true },
- okText: t('delete', { ns: 'common' }),
- onOk: () => void handleDelete(),
- title: t('list.deleteConfirmTitle'),
- }),
- },
- ]
- : [];
+ const menuItems: DropdownItem[] = [
+ ...(favoriteMenuItem ? [favoriteMenuItem] : []),
+ ...(canManage
+ ? ([
+ { type: 'divider' },
+ {
+ icon: <Icon icon={PencilIcon} />,
+ key: 'rename',
+ label: t('rename.action'),
+ onClick: () => openRenameProjectModal(project),
+ },
+ { type: 'divider' },
+ {
+ danger: true,
+ icon: <Icon icon={TrashIcon} />,
+ key: 'delete',
+ label: t('list.deleteAction'),
+ onClick: () =>
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('list.deleteConfirmDescription', { name: project.name }),
+ okButtonProps: { danger: true },
+ okText: t('delete', { ns: 'common' }),
+ onOk: () => void handleDelete(),
+ title: t('list.deleteConfirmTitle'),
+ }),
+ },
+ ] satisfies DropdownItem[])
+ : []),
+ ];
return (
- <WorkspaceLink to={`/project/${project.slug ?? project.id}`}>
+ <WorkspaceLink to={projectPath}>
<NavItem
- contextMenuItems={canManage ? menuItems : undefined}
+ contextMenuItems={menuItems}
disabled={deleting}
icon={projectIcon(project)}
title={project.name}
actions={
- canManage ? (
- <DropdownMenu items={menuItems}>
- <ActionIcon icon={MoreHorizontalIcon} loading={deleting} size={'small'} />
- </DropdownMenu>
- ) : undefined
+ <DropdownMenu items={menuItems}>
+ <ActionIcon icon={MoreHorizontalIcon} loading={deleting} size={'small'} />
+ </DropdownMenu>
}
/>
</WorkspaceLink>
diff --git a/src/features/HomeSidebar/Body/Project/SortableProjectList.tsx b/src/features/HomeSidebar/Body/Project/SortableProjectList.tsx
index de2332b64e2..9ba09032444 100644
--- a/src/features/HomeSidebar/Body/Project/SortableProjectList.tsx
+++ b/src/features/HomeSidebar/Body/Project/SortableProjectList.tsx
@@ -2,14 +2,10 @@
import {
closestCenter,
- defaultDropAnimationSideEffects,
DndContext,
type DragEndEvent,
DragOverlay,
type DragStartEvent,
- KeyboardSensor,
- MouseSensor,
- TouchSensor,
useSensor,
useSensors,
} from '@dnd-kit/core';
@@ -35,6 +31,13 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import type { ProjectListItem } from '@/store/project';
import { useProjectStore } from '@/store/project';
+import {
+ RowKeyboardSensor,
+ RowMouseSensor,
+ RowTouchSensor,
+ sortableRowDropAnimation,
+ suppressNextClick,
+} from '../sortableRow';
import ProjectItem, { projectIcon } from './ProjectItem';
import { sortProjects } from './sortProjects';
@@ -47,60 +50,6 @@ const styles = stylex.create({
},
});
-const dropAnimation = {
- sideEffects: defaultDropAnimationSideEffects({ styles: { active: { opacity: '0.4' } } }),
-};
-
-// The row is a link: a click fires on pointerup after a drag, so swallow the
-// one click that follows a drop instead of navigating to the dragged project.
-const suppressNextClick = () => {
- const swallow = (event: MouseEvent) => {
- event.preventDefault();
- event.stopPropagation();
- };
- window.addEventListener('click', swallow, { capture: true, once: true });
- // A drop that lands off the row produces no click; don't eat a later one.
- setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
-};
-
-// Pressing on a row's own buttons (the ⋯ menu) must never pick the row up.
-const startsOnRowAction = (event: Event) =>
- event.target instanceof Element && !!event.target.closest('.nav-item-actions');
-
-class RowMouseSensor extends MouseSensor {
- static activators = [
- {
- eventName: 'onMouseDown' as const,
- handler: ({ nativeEvent }: { nativeEvent: MouseEvent }) =>
- nativeEvent.button === 0 && !startsOnRowAction(nativeEvent),
- },
- ];
-}
-
-// A keyboard drag starts only from the focused row itself. Enter / Space on
-// anything inside it — the project link, the ⋯ button — keeps its own meaning
-// (open the project, open the menu).
-const isRowItself = (event: Event) =>
- event.target instanceof Element &&
- event.target.getAttribute('aria-roledescription') === 'sortable';
-
-class RowKeyboardSensor extends KeyboardSensor {
- static activators = KeyboardSensor.activators.map((activator) => ({
- ...activator,
- handler: (...args: Parameters<typeof activator.handler>) =>
- isRowItself(args[0].nativeEvent) && activator.handler(...args),
- }));
-}
-
-class RowTouchSensor extends TouchSensor {
- static activators = [
- {
- eventName: 'onTouchStart' as const,
- handler: ({ nativeEvent }: { nativeEvent: TouchEvent }) => !startsOnRowAction(nativeEvent),
- },
- ];
-}
-
const SortableProjectItem = memo<{ project: ProjectListItem }>(({ project }) => {
const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({
id: project.id,
@@ -184,7 +133,7 @@ const SortableProjectList = memo<{ projects: ProjectListItem[] }>(({ projects })
))}
</SortableContext>
{createPortal(
- <DragOverlay dropAnimation={dropAnimation}>
+ <DragOverlay dropAnimation={sortableRowDropAnimation}>
{activeProject ? (
<div {...stylex.props(styles.overlay)}>
<NavItem
diff --git a/src/features/HomeSidebar/Body/index.tsx b/src/features/HomeSidebar/Body/index.tsx
index e93cc7ec272..b93dbbdbe79 100644
--- a/src/features/HomeSidebar/Body/index.tsx
+++ b/src/features/HomeSidebar/Body/index.tsx
@@ -26,6 +26,7 @@ import { isModifierClick } from '@/utils/navigation';
import Agent from './Agent';
import { openCustomizeSidebarModal } from './CustomizeSidebarModal';
+import Favorites from './Favorites';
import Private from './Private';
import Project from './Project';
import { useSyncWorkspaceSidebarPreference } from './useSyncWorkspaceSidebarPreference';
@@ -33,6 +34,7 @@ import { useSyncWorkspaceSidebarPreference } from './useSyncWorkspaceSidebarPref
export enum GroupKey {
Agent = 'agent',
Community = 'community',
+ Favorites = 'favorites',
Pages = 'pages',
Private = 'private',
Project = 'project',
@@ -41,6 +43,7 @@ export enum GroupKey {
}
const ACCORDION_KEYS = new Set<string>([
+ GroupKey.Favorites,
GroupKey.Project,
GroupKey.Recents,
GroupKey.Agent,
@@ -53,6 +56,7 @@ const HEADER_KEYS = new Set<string>(['home', 'search']);
const accordionComponents: Record<string, (key: string) => ReactElement> = {
[GroupKey.Agent]: (key) => <Agent itemKey={key} key={key} />,
+ [GroupKey.Favorites]: (key) => <Favorites itemKey={key} key={key} />,
[GroupKey.Private]: (key) => <Private itemKey={key} key={key} />,
[GroupKey.Project]: (key) => <Project itemKey={key} key={key} />,
[GroupKey.Recents]: (key) => <Recents itemKey={key} key={key} />,
diff --git a/src/features/HomeSidebar/Body/sortableRow.ts b/src/features/HomeSidebar/Body/sortableRow.ts
new file mode 100644
index 00000000000..b67c6ad7b85
--- /dev/null
+++ b/src/features/HomeSidebar/Body/sortableRow.ts
@@ -0,0 +1,60 @@
+import {
+ defaultDropAnimationSideEffects,
+ KeyboardSensor,
+ MouseSensor,
+ TouchSensor,
+} from '@dnd-kit/core';
+
+export const sortableRowDropAnimation = {
+ sideEffects: defaultDropAnimationSideEffects({ styles: { active: { opacity: '0.4' } } }),
+};
+
+// The row is a link: a click fires on pointerup after a drag, so swallow the
+// one click that follows a drop instead of navigating to the dragged row.
+export const suppressNextClick = () => {
+ const swallow = (event: MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ };
+ window.addEventListener('click', swallow, { capture: true, once: true });
+ // A drop that lands off the row produces no click; don't eat a later one.
+ setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
+};
+
+// Pressing on a row's own buttons (the ⋯ menu) must never pick the row up.
+const startsOnRowAction = (event: Event) =>
+ event.target instanceof Element && !!event.target.closest('.nav-item-actions');
+
+export class RowMouseSensor extends MouseSensor {
+ static activators = [
+ {
+ eventName: 'onMouseDown' as const,
+ handler: ({ nativeEvent }: { nativeEvent: MouseEvent }) =>
+ nativeEvent.button === 0 && !startsOnRowAction(nativeEvent),
+ },
+ ];
+}
+
+// A keyboard drag starts only from the focused row itself. Enter / Space on
+// anything inside it — the row link, the ⋯ button — keeps its own meaning
+// (open the row, open the menu).
+const isRowItself = (event: Event) =>
+ event.target instanceof Element &&
+ event.target.getAttribute('aria-roledescription') === 'sortable';
+
+export class RowKeyboardSensor extends KeyboardSensor {
+ static activators = KeyboardSensor.activators.map((activator) => ({
+ ...activator,
+ handler: (...args: Parameters<typeof activator.handler>) =>
+ isRowItself(args[0].nativeEvent) && activator.handler(...args),
+ }));
+}
+
+export class RowTouchSensor extends TouchSensor {
+ static activators = [
+ {
+ eventName: 'onTouchStart' as const,
+ handler: ({ nativeEvent }: { nativeEvent: TouchEvent }) => !startsOnRowAction(nativeEvent),
+ },
+ ];
+}
diff --git a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx
index 828850e3904..462c574ad89 100644
--- a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx
+++ b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx
@@ -11,8 +11,9 @@ import {
LucideCopy,
PanelTop,
PencilLine,
+ Pin,
+ PinOff,
Share2,
- Star,
Trash,
Wand2,
} from 'lucide-react';
@@ -109,15 +110,13 @@ export const useDropdownMenu = ({
},
{
disabled: !canEditTopic,
- icon: <Icon icon={Star} />,
+ icon: <Icon icon={fav ? PinOff : Pin} />,
key: 'favorite',
- label: fav
- ? t('actions.unfavorite', { ns: 'topic' })
- : t('actions.favorite', { ns: 'topic' }),
+ label: fav ? t('actions.unpin', { ns: 'topic' }) : t('actions.pin', { ns: 'topic' }),
onClick: () => {
favoriteTopic(topicId, !fav);
},
- sfSymbol: fav ? 'star.slash' : 'star',
+ sfSymbol: fav ? 'pin.slash' : 'pin',
},
{
type: 'divider' as const,
diff --git a/src/features/PageEditor/Header/index.tsx b/src/features/PageEditor/Header/index.tsx
index 1383c8299fa..186bb6abe49 100644
--- a/src/features/PageEditor/Header/index.tsx
+++ b/src/features/PageEditor/Header/index.tsx
@@ -24,6 +24,7 @@ import { useTranslation } from 'react-i18next';
import ShareButton from '@/business/client/features/PageShare/ShareButton';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { AutoSaveHint } from '@/features/EditorCanvas';
+import { FavoriteButton } from '@/features/Favorites';
import NavHeader from '@/features/NavHeader';
import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';
import { usePermission } from '@/hooks/usePermission';
@@ -90,6 +91,17 @@ const Header = memo(() => {
</Text>
</>
)}
+ {documentId && (
+ <FavoriteButton
+ icon={emoji ?? null}
+ path={`/page/${documentId}`}
+ // An untitled page is loaded too; only `undefined` means still loading.
+ snapshotReady={title !== undefined}
+ targetId={documentId}
+ title={title || t('pageEditor.titlePlaceholder')}
+ type={'page'}
+ />
+ )}
{/* An artifact's body is never edited here, so a save status would only
ever read "latest version"; name what the page is instead. */}
{isHtmlPage ? (
diff --git a/src/features/PageEditor/Header/useMenu.test.tsx b/src/features/PageEditor/Header/useMenu.test.tsx
index 4b3a0123540..510e27a1a8c 100644
--- a/src/features/PageEditor/Header/useMenu.test.tsx
+++ b/src/features/PageEditor/Header/useMenu.test.tsx
@@ -16,6 +16,8 @@ const resourcePermissionMock = vi.hoisted(() => ({
workspaceId: undefined as string | undefined,
}));
const wsNavigateMock = vi.hoisted(() => vi.fn());
+const favoriteMenuItemMock = vi.hoisted(() => vi.fn(() => null));
+const pageEditorState = vi.hoisted(() => ({ title: undefined as string | undefined }));
const documentStoreMock = vi.hoisted(() => ({ state: {} as Record<string, unknown> }));
const menuActionMocks = vi.hoisted(() => ({
handleCopyLink: vi.fn(),
@@ -72,6 +74,11 @@ vi.mock('@/business/client/hooks/useDocumentTransferMenuItem', () => ({
useDocumentTransferMenuItem: () => null,
}));
+vi.mock('@/features/Favorites', () => ({
+ FavoriteButton: () => null,
+ useCurrentFavoritePath: () => '/favorite-path',
+ useFavoriteMenuItem: favoriteMenuItemMock,
+}));
vi.mock('@/features/VisibilityConfirmContent', () => ({
default: () => null,
}));
@@ -155,6 +162,7 @@ vi.mock('../store', () => ({
selector({
documentId: 'doc-1',
setRightPanelMode: menuActionMocks.setRightPanelMode,
+ title: pageEditorState.title,
}),
useStoreApi: () => ({
getState: () => ({
@@ -178,9 +186,31 @@ describe('PageEditor header menu', () => {
resourcePermissionMock.canManage = false;
resourcePermissionMock.workspaceId = undefined;
documentStoreMock.state = { documentDetailMap: {} };
+ pageEditorState.title = undefined;
vi.clearAllMocks();
});
+ it('lets a loaded untitled page be favorited, but waits while the title is loading', () => {
+ renderHook(() => useMenu());
+ expect(favoriteMenuItemMock).toHaveBeenLastCalledWith(
+ expect.objectContaining({ snapshotReady: false }),
+ );
+
+ pageEditorState.title = '';
+ renderHook(() => useMenu());
+ expect(favoriteMenuItemMock).toHaveBeenLastCalledWith(
+ expect.objectContaining({ snapshotReady: true, title: 'pageEditor.titlePlaceholder' }),
+ );
+ });
+
+ it('favorites the page under its canonical link, not the location underneath a modal', () => {
+ renderHook(() => useMenu());
+
+ expect(favoriteMenuItemMock).toHaveBeenCalledWith(
+ expect.objectContaining({ path: '/page/doc-1', targetId: 'doc-1', type: 'page' }),
+ );
+ });
+
it('exports an HTML page as HTML and offers no editor history', () => {
const exportChildren = (items: ReturnType<typeof useMenu>['menuItems']) =>
(getMenuItem(items, 'export') as { children: { key: string }[] }).children.map(
diff --git a/src/features/PageEditor/Header/useMenu.tsx b/src/features/PageEditor/Header/useMenu.tsx
index 9c6276836f7..7f2eb51d210 100644
--- a/src/features/PageEditor/Header/useMenu.tsx
+++ b/src/features/PageEditor/Header/useMenu.tsx
@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useAuthorInfo } from '@/business/client/hooks/useAuthorInfo';
import { useDocumentTransferMenuItem } from '@/business/client/hooks/useDocumentTransferMenuItem';
+import { useFavoriteMenuItem } from '@/features/Favorites';
import { useResourcePermission } from '@/features/ResourcePermission/useResourcePermission';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
@@ -52,7 +53,25 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {
const { lg = true } = useResponsive();
const dateLocale = i18n.resolvedLanguage || i18n.language;
- const documentId = usePageEditorStore((s) => s.documentId);
+ const [documentId, pageTitle, pageEmoji] = usePageEditorStore((s) => [
+ s.documentId,
+ s.title,
+ s.emoji,
+ ]);
+ const favoriteMenuItem = useFavoriteMenuItem(
+ documentId
+ ? {
+ icon: pageEmoji ?? null,
+ // The canonical link: this menu also opens in the document modal,
+ // which leaves the location on whatever page is underneath.
+ path: `/page/${documentId}`,
+ targetId: documentId,
+ snapshotReady: pageTitle !== undefined,
+ title: pageTitle || t('pageEditor.titlePlaceholder'),
+ type: 'page',
+ }
+ : undefined,
+ );
// An HTML page has no rich-text body: it exports as HTML and has no editor history.
const isHtmlPage = useIsHtmlPage(documentId);
const { allowed: canCreatePage } = usePermission('create_content');
@@ -256,6 +275,7 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {
{ type: 'divider' as const },
]
: []),
+ ...(favoriteMenuItem ? [favoriteMenuItem] : []),
{
disabled: !canCreatePage,
icon: <Icon icon={CopyPlus} />,
@@ -369,6 +389,7 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {
}
return items;
}, [
+ favoriteMenuItem,
isHtmlPage,
lastUpdatedTime,
authorName,
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
index e41c8d80e58..7207741fe72 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
@@ -18,7 +18,8 @@ import {
Hash,
Maximize2,
PencilLine,
- Star,
+ Pin,
+ PinOff,
Trash,
Wand2,
} from 'lucide-react';
@@ -236,9 +237,9 @@ export const useMenu = (): { menuHeader?: ReactNode; menuItems: () => DropdownIt
if (topicId) {
items.push(
{
- icon: <Icon icon={Star} />,
+ icon: <Icon icon={isFavorite ? PinOff : Pin} />,
key: 'favorite',
- label: t(isFavorite ? 'actions.unfavorite' : 'actions.favorite', { ns: 'topic' }),
+ label: t(isFavorite ? 'actions.unpin' : 'actions.pin', { ns: 'topic' }),
onClick: () => {
favoriteTopic(topicId, !isFavorite);
},
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
index 8a2fe491b78..76ab70f17ca 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
@@ -194,16 +194,16 @@ describe('group useTopicActionsDropdownMenu', () => {
});
expect(workspaceUnstarredItem).toMatchObject({
- label: 'actions.removeUnstarredWorkspace',
+ label: 'actions.removeUnpinnedWorkspace',
});
if (workspaceUnstarredItem && 'onClick' in workspaceUnstarredItem) {
workspaceUnstarredItem.onClick?.({} as never);
}
expect(openWorkspaceDeleteAllModalMock).toHaveBeenLastCalledWith(
expect.objectContaining({
- acknowledgeText: 'actions.confirmRemoveUnstarredWorkspaceAcknowledge',
- description: 'actions.confirmRemoveUnstarredWorkspace',
- title: 'actions.removeUnstarredWorkspace',
+ acknowledgeText: 'actions.confirmRemoveUnpinnedWorkspaceAcknowledge',
+ description: 'actions.confirmRemoveUnpinnedWorkspace',
+ title: 'actions.removeUnpinnedWorkspace',
}),
);
await openWorkspaceDeleteAllModalMock.mock.calls[0][0].onConfirm();
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
index bc9c7cea287..a429bce12b8 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
@@ -199,15 +199,15 @@ export const useTopicActionsDropdownMenu = (
disabled: !canEditTopic,
icon: <Icon icon={Trash} />,
key: 'deleteUnstarredWorkspace',
- label: t('actions.removeUnstarredWorkspace'),
+ label: t('actions.removeUnpinnedWorkspace'),
onClick: () => {
openWorkspaceDeleteAllModal({
- acknowledgeText: t('actions.confirmRemoveUnstarredWorkspaceAcknowledge'),
+ acknowledgeText: t('actions.confirmRemoveUnpinnedWorkspaceAcknowledge'),
cancelText: t('cancel', { ns: 'common' }),
- confirmText: t('actions.removeUnstarredWorkspace'),
- description: t('actions.confirmRemoveUnstarredWorkspace'),
+ confirmText: t('actions.removeUnpinnedWorkspace'),
+ description: t('actions.confirmRemoveUnpinnedWorkspace'),
onConfirm: () => removeUnstarredTopic({ onlyOwn: false }),
- title: t('actions.removeUnstarredWorkspace'),
+ title: t('actions.removeUnpinnedWorkspace'),
});
},
},
diff --git a/src/services/favorite/index.ts b/src/services/favorite/index.ts
new file mode 100644
index 00000000000..58c3092d859
--- /dev/null
+++ b/src/services/favorite/index.ts
@@ -0,0 +1,31 @@
+import type { AddFavoriteParams, FavoriteItem, FavoriteType } from '@lobechat/types';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+class FavoriteService {
+ add = (params: AddFavoriteParams): Promise<FavoriteItem> =>
+ lambdaClient.favorite.add.mutate(params);
+
+ list = (): Promise<FavoriteItem[]> => lambdaClient.favorite.list.query();
+
+ remove = async (id: string): Promise<void> => {
+ await lambdaClient.favorite.remove.mutate({ id });
+ };
+
+ removeByTarget = async (type: FavoriteType, targetId: string): Promise<void> => {
+ await lambdaClient.favorite.removeByTarget.mutate({ targetId, type });
+ };
+
+ reorder = async (ids: string[]): Promise<void> => {
+ await lambdaClient.favorite.reorder.mutate({ ids });
+ };
+
+ update = async (
+ id: string,
+ value: Partial<Pick<FavoriteItem, 'icon' | 'path' | 'title'>>,
+ ): Promise<void> => {
+ await lambdaClient.favorite.update.mutate({ id, value });
+ };
+}
+
+export const favoriteService = new FavoriteService();
diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.ts
index 369ff344986..708c455a602 100644
--- a/src/store/chat/slices/topic/selectors.test.ts
+++ b/src/store/chat/slices/topic/selectors.test.ts
@@ -512,7 +512,7 @@ describe('topicSelectors', () => {
// Check favorite group
expect(grouped[0]).toEqual({
id: 'favorite',
- title: 'favorite', // This matches the mocked t function return
+ title: 'pinned', // This matches the mocked t function return
children: topics.filter((t) => t.favorite),
});
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index 75b126d687d..1640414de0a 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -430,7 +430,7 @@ const buildGroupedTopics = (
{
children: favTopics,
id: 'favorite',
- title: t('favorite', { ns: 'topic' }),
+ title: t('pinned', { ns: 'topic' }),
},
...groupFn(unfavTopics),
]
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index f4216b15ffb..a4e4426648c 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -154,7 +154,7 @@ export type TaskViewMode = 'kanban' | 'list';
/** How topics inside one byProject sidebar group are sectioned. */
export type ProjectTopicSubGroupMode = 'none' | 'byDevice' | 'byTime' | 'byStatus';
-export const DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS = ['recents', 'agent', 'private'];
+export const DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS = ['favorites', 'recents', 'agent', 'private'];
/** How the agent document tree orders sibling rows. */
export interface AgentDocumentSort {
diff --git a/src/store/global/selectors/systemStatus.test.ts b/src/store/global/selectors/systemStatus.test.ts
index a90dad719b9..55b716f5a2d 100644
--- a/src/store/global/selectors/systemStatus.test.ts
+++ b/src/store/global/selectors/systemStatus.test.ts
@@ -276,10 +276,11 @@ describe('systemStatusSelectors', () => {
status: { sidebarItems: stored },
});
expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual([
- // Defaults missing from a saved layout (here the newer `goals` and
- // `dashboard`) are backfilled.
+ // Defaults missing from a saved layout (here the newer `goals`,
+ // `dashboard` and `favorites`) are backfilled.
'goals',
'dashboard',
+ 'favorites',
'private',
'agent',
'recents',
@@ -299,6 +300,7 @@ describe('systemStatusSelectors', () => {
'pages',
'goals',
'dashboard',
+ 'favorites',
'project',
'recents',
'private',
@@ -339,6 +341,7 @@ describe('systemStatusSelectors', () => {
'pages',
'goals',
'dashboard',
+ 'favorites',
'recents',
'project',
'private',
@@ -351,6 +354,41 @@ describe('systemStatusSelectors', () => {
]);
});
+ it('should backfill favorites at the head of a saved accordion block', () => {
+ const stored = [
+ 'tasks',
+ 'goals',
+ 'dashboard',
+ 'resource',
+ 'recents',
+ 'project',
+ 'private',
+ 'agent',
+ SIDEBAR_SPACER_ID,
+ 'image',
+ 'community',
+ 'memory',
+ ];
+ const s: GlobalState = merge(initialState, {
+ status: { sidebarItems: stored },
+ });
+ expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual([
+ 'tasks',
+ 'goals',
+ 'dashboard',
+ 'resource',
+ 'favorites',
+ 'recents',
+ 'project',
+ 'private',
+ 'agent',
+ SIDEBAR_SPACER_ID,
+ 'image',
+ 'community',
+ 'memory',
+ ]);
+ });
+
it('should slot missing top-group defaults before the accordion block', () => {
const s: GlobalState = merge(initialState, {
status: { sidebarItems: ['agent', 'recents'] },
@@ -387,6 +425,7 @@ describe('systemStatusSelectors', () => {
'goals',
'dashboard',
'resource',
+ 'favorites',
'private',
'agent',
'recents',
@@ -410,6 +449,7 @@ describe('systemStatusSelectors', () => {
'goals',
'dashboard',
'resource',
+ 'favorites',
'private',
'recents',
'project',
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index 609573b5324..bf040e25c47 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -214,6 +214,7 @@ export const DEFAULT_SIDEBAR_ITEMS: string[] = [
'goals',
'dashboard',
'resource',
+ 'favorites',
'recents',
'project',
'private',
@@ -227,7 +228,13 @@ export const DEFAULT_SIDEBAR_ITEMS: string[] = [
/** Items that must stay contiguous in the sidebar list (accordion block).
* `private` sits above `agent` so workspace users see their personal items
* first, with the workspace-shared agents right below. */
-export const SIDEBAR_ACCORDION_KEYS = new Set(['recents', 'project', 'private', 'agent']);
+export const SIDEBAR_ACCORDION_KEYS = new Set([
+ 'favorites',
+ 'recents',
+ 'project',
+ 'private',
+ 'agent',
+]);
const DEFAULT_BOTTOM_KEYS = new Set(
DEFAULT_SIDEBAR_ITEMS.slice(DEFAULT_SIDEBAR_ITEMS.indexOf(SIDEBAR_SPACER_ID) + 1),
diff --git a/src/store/home/initialState.ts b/src/store/home/initialState.ts
index f6d40f883de..01dac89aca6 100644
--- a/src/store/home/initialState.ts
+++ b/src/store/home/initialState.ts
@@ -1,5 +1,7 @@
import { type AgentListState } from './slices/agentList/initialState';
import { initialAgentListState } from './slices/agentList/initialState';
+import { type FavoriteState } from './slices/favorite/initialState';
+import { initialFavoriteState } from './slices/favorite/initialState';
import { type HomeInputState } from './slices/homeInput/initialState';
import { initialHomeInputState } from './slices/homeInput/initialState';
import { type HomeInboxState } from './slices/inbox/initialState';
@@ -12,10 +14,18 @@ import { type SidebarUIState } from './slices/sidebarUI/initialState';
import { initialSidebarUIState } from './slices/sidebarUI/initialState';
export interface HomeStoreState
- extends AgentListState, RecentState, HomeInboxState, HomeInputState, LabelState, SidebarUIState {}
+ extends
+ AgentListState,
+ FavoriteState,
+ RecentState,
+ HomeInboxState,
+ HomeInputState,
+ LabelState,
+ SidebarUIState {}
export const initialState: HomeStoreState = {
...initialAgentListState,
+ ...initialFavoriteState,
...initialRecentState,
...initialHomeInboxState,
...initialHomeInputState,
diff --git a/src/store/home/selectors.ts b/src/store/home/selectors.ts
index 6fed15d3812..1213af18370 100644
--- a/src/store/home/selectors.ts
+++ b/src/store/home/selectors.ts
@@ -1,4 +1,5 @@
export * from './slices/agentList/selectors';
+export * from './slices/favorite/selectors';
export * from './slices/inbox/selectors';
export * from './slices/label/selectors';
export * from './slices/recent/selectors';
diff --git a/src/store/home/slices/favorite/action.test.ts b/src/store/home/slices/favorite/action.test.ts
new file mode 100644
index 00000000000..69231b4c97d
--- /dev/null
+++ b/src/store/home/slices/favorite/action.test.ts
@@ -0,0 +1,282 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * Sidebar favorites are a replica list. A star click shows up in the sidebar
+ * before the server answers, a refused write puts the list back, and a
+ * renamed target rewrites its snapshot only when something changed.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { FavoriteItem } from '@lobechat/types';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { favoriteService } from '@/services/favorite';
+import { useHomeStore } from '@/store/home';
+import { favoriteSelectors } from '@/store/home/selectors';
+
+import { initialFavoriteState } from './initialState';
+import { favoriteListResource } from './projection';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const favorite = (targetId: string, overrides: Partial<FavoriteItem> = {}): FavoriteItem => ({
+ icon: null,
+ id: `fav_${targetId}`,
+ path: `/page/${targetId}`,
+ targetId,
+ title: targetId,
+ type: 'page',
+ ...overrides,
+});
+
+const STORAGE_KEY = favoriteListResource.storageKey({});
+
+const renderSync = () =>
+ renderHook(() => useHomeStore((s) => s.useFetchFavorites)(true), { wrapper });
+
+const list = () => favoriteSelectors.favorites(useHomeStore.getState());
+
+describe('favorite slice', () => {
+ const scopes = new Set<string>();
+
+ beforeEach(() => {
+ const scope = `favorite-user-${randomUUID()}:personal`;
+ scopes.add(scope);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ useHomeStore.setState({ ...initialFavoriteState });
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].map((scope) =>
+ favoriteListResource.storage!.remove({ queryKey: STORAGE_KEY, scope }),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ });
+
+ const loadWith = async (items: FavoriteItem[]) => {
+ vi.spyOn(favoriteService, 'list').mockResolvedValue(items);
+ renderSync();
+ await waitFor(() =>
+ expect(favoriteSelectors.favoriteList(useHomeStore.getState())).toBeDefined(),
+ );
+ };
+
+ it('shows a new favorite before the server answers, then keeps the saved row', async () => {
+ await loadWith([favorite('a')]);
+ let resolveAdd!: (item: FavoriteItem) => void;
+ const add = vi
+ .spyOn(favoriteService, 'add')
+ .mockImplementation(() => new Promise((resolve) => (resolveAdd = resolve)));
+
+ let toggled!: Promise<void>;
+ act(() => {
+ toggled = useHomeStore
+ .getState()
+ .toggleFavorite({ path: '/page/b', targetId: 'b', title: 'B', type: 'page' });
+ });
+
+ expect(list().map((item) => item.targetId)).toEqual(['a', 'b']);
+
+ await waitFor(() => expect(add).toHaveBeenCalled());
+ await act(async () => {
+ resolveAdd(favorite('b', { title: 'B' }));
+ await toggled;
+ });
+ expect(list()[1]).toEqual(favorite('b', { title: 'B' }));
+ });
+
+ it('puts a removed favorite back when the server refuses', async () => {
+ await loadWith([favorite('a'), favorite('b')]);
+ vi.spyOn(favoriteService, 'removeByTarget').mockRejectedValue(new Error('offline'));
+
+ await act(async () => {
+ await expect(
+ useHomeStore
+ .getState()
+ .toggleFavorite({ path: '/page/a', targetId: 'a', title: 'a', type: 'page' }),
+ ).rejects.toThrow('offline');
+ });
+
+ expect(list().map((item) => item.targetId)).toEqual(['a', 'b']);
+ });
+
+ it('reorders right away and sends the new order', async () => {
+ await loadWith([favorite('a'), favorite('b'), favorite('c')]);
+ const reorder = vi.spyOn(favoriteService, 'reorder').mockResolvedValue();
+
+ await act(() => useHomeStore.getState().reorderFavorites(['fav_c', 'fav_a', 'fav_b']));
+
+ expect(list().map((item) => item.targetId)).toEqual(['c', 'a', 'b']);
+ expect(reorder).toHaveBeenCalledWith(['fav_c', 'fav_a', 'fav_b']);
+ });
+
+ it('sends overlapping reorders in drag order, so the last drag wins', async () => {
+ await loadWith([favorite('a'), favorite('b'), favorite('c')]);
+ const sent: string[][] = [];
+ const settle: (() => void)[] = [];
+ vi.spyOn(favoriteService, 'reorder').mockImplementation(async (ids) => {
+ sent.push(ids);
+ await new Promise<void>((resolve) => settle.push(resolve));
+ });
+
+ let first!: Promise<void>;
+ let second!: Promise<void>;
+ act(() => {
+ first = useHomeStore.getState().reorderFavorites(['fav_b', 'fav_a', 'fav_c']);
+ second = useHomeStore.getState().reorderFavorites(['fav_c', 'fav_b', 'fav_a']);
+ });
+
+ await waitFor(() => expect(sent).toHaveLength(1));
+ // The second drag waits for the first request instead of racing it.
+ expect(sent).toEqual([['fav_b', 'fav_a', 'fav_c']]);
+
+ await act(async () => {
+ settle[0]();
+ await first;
+ });
+ await waitFor(() => expect(sent).toHaveLength(2));
+ await act(async () => {
+ settle[1]();
+ await second;
+ });
+
+ expect(sent[1]).toEqual(['fav_c', 'fav_b', 'fav_a']);
+ expect(list().map((item) => item.targetId)).toEqual(['c', 'b', 'a']);
+ });
+
+ it('leaves a row still being added out of the persisted order', async () => {
+ await loadWith([favorite('a'), favorite('b')]);
+ const reorder = vi.spyOn(favoriteService, 'reorder').mockResolvedValue();
+
+ await act(() =>
+ useHomeStore.getState().reorderFavorites(['fav_b', 'optimistic:page:c', 'fav_a']),
+ );
+
+ expect(reorder).toHaveBeenCalledWith(['fav_b', 'fav_a']);
+ });
+
+ it('keeps the dragged order across a row whose add is still pending', async () => {
+ await loadWith([favorite('a'), favorite('b')]);
+ let resolveAdd!: (item: FavoriteItem) => void;
+ const add = vi
+ .spyOn(favoriteService, 'add')
+ .mockImplementation(() => new Promise((resolve) => (resolveAdd = resolve)));
+ const reorder = vi.spyOn(favoriteService, 'reorder').mockResolvedValue();
+
+ let added!: Promise<void>;
+ let reordered!: Promise<void>;
+ act(() => {
+ added = useHomeStore
+ .getState()
+ .addFavorite({ path: '/page/c', targetId: 'c', title: 'c', type: 'page' });
+ });
+ act(() => {
+ reordered = useHomeStore.getState().reorderFavorites(['fav_b', 'optimistic:page:c', 'fav_a']);
+ });
+ expect(list().map((item) => item.targetId)).toEqual(['b', 'c', 'a']);
+
+ await waitFor(() => expect(add).toHaveBeenCalled());
+ // The reorder waits for the add instead of dropping the pending row.
+ expect(reorder).not.toHaveBeenCalled();
+ await act(async () => {
+ resolveAdd(favorite('c'));
+ await added;
+ await reordered;
+ });
+
+ expect(reorder).toHaveBeenCalledWith(['fav_b', 'fav_c', 'fav_a']);
+ expect(list().map((item) => item.id)).toEqual(['fav_b', 'fav_c', 'fav_a']);
+ });
+
+ it('rewrites a snapshot only when the target changed', async () => {
+ await loadWith([favorite('a', { title: 'Old' })]);
+ const update = vi.spyOn(favoriteService, 'update').mockResolvedValue();
+
+ await act(() =>
+ useHomeStore.getState().syncFavoriteSnapshot('page', 'a', { icon: null, title: 'Old' }),
+ );
+ expect(update).not.toHaveBeenCalled();
+
+ await act(() => useHomeStore.getState().syncFavoriteSnapshot('page', 'a', { title: 'New' }));
+ expect(update).toHaveBeenCalledWith('fav_a', { title: 'New' });
+ expect(list()[0].title).toBe('New');
+ });
+
+ it('updates the saved row on the server when the list has not loaded here', async () => {
+ vi.spyOn(favoriteService, 'list').mockResolvedValue([
+ favorite('p1', { title: 'Old', type: 'project' }),
+ ]);
+ const update = vi.spyOn(favoriteService, 'update').mockResolvedValue();
+
+ await act(() =>
+ useHomeStore.getState().syncFavoriteSnapshot('project', 'p1', { icon: null, title: 'New' }),
+ );
+ expect(update).toHaveBeenCalledWith('fav_p1', { title: 'New' });
+
+ update.mockClear();
+ await act(() =>
+ useHomeStore.getState().syncFavoriteSnapshot('project', 'p2', { title: 'Other' }),
+ );
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it('retries a server-side snapshot update after a brief outage', async () => {
+ vi.useFakeTimers();
+ try {
+ vi.spyOn(favoriteService, 'list')
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValue([favorite('p1', { title: 'Old', type: 'project' })]);
+ const update = vi.spyOn(favoriteService, 'update').mockResolvedValue();
+
+ const sync = useHomeStore.getState().syncFavoriteSnapshot('project', 'p1', { title: 'New' });
+ await vi.advanceTimersByTimeAsync(1000);
+ await sync;
+
+ expect(update).toHaveBeenCalledWith('fav_p1', { title: 'New' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('stores a long page title cut to the favorite limit', async () => {
+ await loadWith([]);
+ const add = vi
+ .spyOn(favoriteService, 'add')
+ .mockImplementation(async (params) => favorite(params.targetId, { title: params.title }));
+ const longTitle = '📄'.repeat(600);
+
+ await act(() =>
+ useHomeStore
+ .getState()
+ .addFavorite({ path: '/page/long', targetId: 'long', title: longTitle, type: 'page' }),
+ );
+
+ const sent = add.mock.calls[0][0].title;
+ expect(Array.from(sent)).toHaveLength(512);
+ expect(sent.startsWith('📄')).toBe(true);
+ expect(list()[0].title).toBe(sent);
+ });
+});
diff --git a/src/store/home/slices/favorite/action.ts b/src/store/home/slices/favorite/action.ts
new file mode 100644
index 00000000000..e8491f0d0f9
--- /dev/null
+++ b/src/store/home/slices/favorite/action.ts
@@ -0,0 +1,241 @@
+import {
+ type AddFavoriteParams,
+ type FavoriteItem,
+ type FavoriteType,
+ toFavoriteTitle,
+} from '@lobechat/types';
+
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import { favoriteService } from '@/services/favorite';
+import type { HomeStore } from '@/store/home/store';
+import type { StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { FAVORITE_LIST_KEY, favoriteListResource } from './projection';
+import { favoriteSelectors } from './selectors';
+
+const n = setNamespace('favorite');
+
+const LIST_PARAMS = {} as Record<string, never>;
+
+type FavoriteSnapshot = Partial<Pick<FavoriteItem, 'icon' | 'path' | 'title'>>;
+
+/** Rows added on the client before the server confirmed them. */
+export const isOptimisticId = (id: string) => id.startsWith('optimistic:');
+
+/**
+ * The row an id from the list points at. A client id names its target, so it
+ * still finds the row after the server confirmed it under a real id.
+ */
+const findRow = (items: FavoriteItem[], id: string): FavoriteItem | undefined => {
+ const byId = items.find((item) => item.id === id);
+ if (byId || !isOptimisticId(id)) return byId;
+ const [, type, ...rest] = id.split(':');
+ const targetId = rest.join(':');
+ return items.find((item) => item.type === type && item.targetId === targetId);
+};
+
+const isTarget = (item: FavoriteItem, type: FavoriteType, targetId: string) =>
+ item.type === type && item.targetId === targetId;
+
+/** Insert or refresh `item` in place, the way the server upserts by target. */
+const upsert = (items: FavoriteItem[], item: FavoriteItem): FavoriteItem[] => {
+ const index = items.findIndex((row) => isTarget(row, item.type, item.targetId));
+ if (index === -1) return [...items, item];
+ const next = [...items];
+ next[index] = { ...item, id: items[index].id };
+ return next;
+};
+
+const RETRY_DELAYS_MS = [1000, 3000];
+
+/** Run a background write, retrying after each delay before giving up. */
+const withRetry = async (run: () => Promise<void>): Promise<void> => {
+ for (const delay of [...RETRY_DELAYS_MS, undefined]) {
+ try {
+ return await run();
+ } catch (error) {
+ if (delay === undefined) throw error;
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ }
+ }
+};
+
+/** The snapshot fields that differ from the saved row, or undefined when none do. */
+const snapshotChanges = (
+ item: FavoriteItem,
+ snapshot: FavoriteSnapshot,
+): FavoriteSnapshot | undefined => {
+ const changes = Object.fromEntries(
+ Object.entries(snapshot).filter(
+ ([key, value]) => value !== undefined && item[key as keyof FavoriteSnapshot] !== value,
+ ),
+ ) as FavoriteSnapshot;
+ return Object.keys(changes).length > 0 ? changes : undefined;
+};
+
+type Setter = StoreSetter<HomeStore>;
+export const createFavoriteSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
+ new FavoriteActionImpl(set, get, _api);
+
+export class FavoriteActionImpl {
+ readonly #get: () => HomeStore;
+ readonly #list;
+ /** Writes per target reach the server in order, so a quick re-toggle cannot land reversed. */
+ readonly #targetQueues = new Map<string, Promise<unknown>>();
+ /** Reorders reach the server in drag order, so the last drag wins. */
+ #reorderQueue: Promise<unknown> = Promise.resolve();
+ /** Adds still waiting for the server; a reorder waits for them to learn their ids. */
+ readonly #pendingAdds = new Set<Promise<unknown>>();
+
+ constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
+ void _api;
+ this.#get = get;
+ this.#list = createReplicaSlice(favoriteListResource, {
+ actionPrefix: n('favoriteList'),
+ fetcher: () => favoriteService.list(),
+ get,
+ set,
+ stateKey: 'favoriteListReplica',
+ view: recordLens<HomeStore, FavoriteItem[]>('favoriteListMap'),
+ });
+ }
+
+ #enqueue = async <T>(type: FavoriteType, targetId: string, run: () => Promise<T>) => {
+ const key = `${type}:${targetId}`;
+ const previous = this.#targetQueues.get(key) ?? Promise.resolve();
+ const operation = previous.catch(() => undefined).then(run);
+ this.#targetQueues.set(key, operation);
+ try {
+ return await operation;
+ } finally {
+ if (this.#targetQueues.get(key) === operation) this.#targetQueues.delete(key);
+ }
+ };
+
+ addFavorite = async (input: AddFavoriteParams): Promise<void> => {
+ // The server stores the cut title; keep the optimistic row and later
+ // snapshot comparisons on the same value.
+ const params = { ...input, title: toFavoriteTitle(input.title) };
+ const optimisticItem: FavoriteItem = {
+ icon: params.icon ?? null,
+ id: `optimistic:${params.type}:${params.targetId}`,
+ path: params.path,
+ targetId: params.targetId,
+ title: params.title,
+ type: params.type,
+ };
+
+ const operation = this.#list.optimistic(
+ FAVORITE_LIST_KEY,
+ (items = []) => upsert(items, optimisticItem),
+ () => this.#enqueue(params.type, params.targetId, () => favoriteService.add(params)),
+ {
+ confirm:
+ (saved) =>
+ (items = []) => {
+ const index = items.findIndex((row) => isTarget(row, saved.type, saved.targetId));
+ if (index === -1) return [...items, saved];
+ const next = [...items];
+ next[index] = saved;
+ return next;
+ },
+ },
+ );
+ // Settles once the confirmed row (with its real id) is in the list.
+ this.#pendingAdds.add(operation);
+ try {
+ await operation;
+ } finally {
+ this.#pendingAdds.delete(operation);
+ }
+ };
+
+ refreshFavorites = async (): Promise<void> => {
+ await this.#list.revalidate();
+ };
+
+ removeFavorite = async (type: FavoriteType, targetId: string): Promise<void> => {
+ await this.#list.optimistic(
+ FAVORITE_LIST_KEY,
+ (items = []) => items.filter((item) => !isTarget(item, type, targetId)),
+ () => this.#enqueue(type, targetId, () => favoriteService.removeByTarget(type, targetId)),
+ );
+ };
+
+ reorderFavorites = async (ids: string[]): Promise<void> => {
+ await this.#list.optimistic(
+ FAVORITE_LIST_KEY,
+ (items = []) => {
+ const listed = ids.flatMap((id) => findRow(items, id) ?? []);
+ const rest = items.filter((item) => !listed.includes(item));
+ return [...listed, ...rest];
+ },
+ () => {
+ const operation = this.#reorderQueue
+ .catch(() => undefined)
+ .then(async () => {
+ // A row being added has no server id yet: wait for its add, then
+ // send the whole order with real ids so the server keeps its slot.
+ await Promise.allSettled(this.#pendingAdds);
+ const items = favoriteSelectors.favorites(this.#get());
+ const persistedIds = ids
+ .map((id) => findRow(items, id)?.id)
+ .filter((id): id is string => !!id && !isOptimisticId(id));
+ await favoriteService.reorder(persistedIds);
+ });
+ this.#reorderQueue = operation;
+ return operation;
+ },
+ );
+ };
+
+ toggleFavorite = async (params: AddFavoriteParams): Promise<void> => {
+ const isFavorite = favoriteSelectors.isFavorite(params.type, params.targetId)(this.#get());
+ if (isFavorite) await this.removeFavorite(params.type, params.targetId);
+ else await this.addFavorite(params);
+ };
+
+ /**
+ * Keep the snapshot of a favorite in step with the page it points at (a
+ * renamed topic, a new page emoji). A no-op when nothing changed or the
+ * target is not a favorite. Before the list has loaded in this session (a
+ * project renamed from its own settings, with the home sidebar never shown)
+ * the row is looked up on the server, so the saved title still follows.
+ */
+ syncFavoriteSnapshot = async (
+ type: FavoriteType,
+ targetId: string,
+ input: FavoriteSnapshot,
+ ): Promise<void> => {
+ const snapshot =
+ input.title === undefined ? input : { ...input, title: toFavoriteTitle(input.title) };
+
+ if (favoriteSelectors.favoriteList(this.#get()) === undefined) {
+ // Nothing mounted here retries a missed write, so ride out a brief outage.
+ await withRetry(async () => {
+ const remote = (await favoriteService.list()).find((row) => isTarget(row, type, targetId));
+ const changes = remote && snapshotChanges(remote, snapshot);
+ if (remote && changes) await favoriteService.update(remote.id, changes);
+ });
+ return;
+ }
+
+ const item = favoriteSelectors.getFavorite(type, targetId)(this.#get());
+ if (!item || isOptimisticId(item.id)) return;
+
+ const changes = snapshotChanges(item, snapshot);
+ if (!changes) return;
+
+ await this.#list.optimistic(
+ FAVORITE_LIST_KEY,
+ (items = []) => items.map((row) => (row.id === item.id ? { ...row, ...changes } : row)),
+ () => this.#enqueue(type, targetId, () => favoriteService.update(item.id, changes)),
+ );
+ };
+
+ useFetchFavorites = (enabled: boolean): ReplicaSyncResult =>
+ this.#list.useSync(LIST_PARAMS, { enabled });
+}
+
+export type FavoriteAction = Pick<FavoriteActionImpl, keyof FavoriteActionImpl>;
diff --git a/src/store/home/slices/favorite/initialState.ts b/src/store/home/slices/favorite/initialState.ts
new file mode 100644
index 00000000000..d3adaa787fc
--- /dev/null
+++ b/src/store/home/slices/favorite/initialState.ts
@@ -0,0 +1,14 @@
+import type { FavoriteItem } from '@lobechat/types';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+export interface FavoriteState {
+ /** Favorites of the current scope, the view of the `favoriteList` replica. */
+ favoriteListMap: Record<string, FavoriteItem[]>;
+ favoriteListReplica: ReplicaState<FavoriteItem[]>;
+}
+
+export const initialFavoriteState: FavoriteState = {
+ favoriteListMap: {},
+ favoriteListReplica: createReplicaState(),
+};
diff --git a/src/store/home/slices/favorite/projection.ts b/src/store/home/slices/favorite/projection.ts
new file mode 100644
index 00000000000..1eb9c97e8cd
--- /dev/null
+++ b/src/store/home/slices/favorite/projection.ts
@@ -0,0 +1,17 @@
+import type { FavoriteItem } from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+
+/** One list per cache scope: the replica scope already carries user and workspace. */
+export const FAVORITE_LIST_KEY = 'list';
+
+/**
+ * The member's sidebar favorites. The persisted copy paints the section on a
+ * cold start instead of popping it in after the request answers.
+ */
+export const favoriteListResource = defineReplica<Record<string, never>, FavoriteItem[]>({
+ key: () => FAVORITE_LIST_KEY,
+ name: 'favoriteList',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/home/slices/favorite/selectors.ts b/src/store/home/slices/favorite/selectors.ts
new file mode 100644
index 00000000000..8b7ceae26aa
--- /dev/null
+++ b/src/store/home/slices/favorite/selectors.ts
@@ -0,0 +1,28 @@
+import type { FavoriteItem, FavoriteType } from '@lobechat/types';
+
+import type { HomeStoreState } from '@/store/home/initialState';
+
+import { FAVORITE_LIST_KEY } from './projection';
+
+const EMPTY: FavoriteItem[] = [];
+
+/** `undefined` until the list has loaded (or hydrated) for this scope. */
+const favoriteList = (s: HomeStoreState): FavoriteItem[] | undefined =>
+ s.favoriteListMap[FAVORITE_LIST_KEY];
+
+const favorites = (s: HomeStoreState): FavoriteItem[] => favoriteList(s) ?? EMPTY;
+
+const getFavorite =
+ (type: FavoriteType, targetId: string) =>
+ (s: HomeStoreState): FavoriteItem | undefined =>
+ favorites(s).find((item) => item.type === type && item.targetId === targetId);
+
+const isFavorite = (type: FavoriteType, targetId: string) => (s: HomeStoreState) =>
+ !!getFavorite(type, targetId)(s);
+
+export const favoriteSelectors = {
+ favoriteList,
+ favorites,
+ getFavorite,
+ isFavorite,
+};
diff --git a/src/store/home/store.ts b/src/store/home/store.ts
index 4a552fc13ca..99350bcb2b8 100644
--- a/src/store/home/store.ts
+++ b/src/store/home/store.ts
@@ -13,6 +13,8 @@ import { type HomeStoreState } from './initialState';
import { initialState } from './initialState';
import { type AgentListAction } from './slices/agentList/action';
import { createAgentListSlice } from './slices/agentList/action';
+import { type FavoriteAction } from './slices/favorite/action';
+import { createFavoriteSlice } from './slices/favorite/action';
import { type GroupAction } from './slices/group/action';
import { createGroupSlice } from './slices/group/action';
import { type HomeInputAction } from './slices/homeInput/action';
@@ -31,6 +33,7 @@ import { createSidebarUISlice } from './slices/sidebarUI/action';
export interface HomeStore
extends
AgentListAction,
+ FavoriteAction,
GroupAction,
RecentAction,
HomeInboxAction,
@@ -41,6 +44,7 @@ export interface HomeStore
HomeStoreState {}
type HomeStoreAction = AgentListAction &
+ FavoriteAction &
GroupAction &
RecentAction &
HomeInboxAction &
@@ -59,6 +63,7 @@ const createStore: StateCreator<HomeStore, [['zustand/devtools', never]]> = (
...initialState,
...flattenActions<HomeStoreAction>([
createAgentListSlice(...parameters),
+ createFavoriteSlice(...parameters),
createGroupSlice(...parameters),
createRecentSlice(...parameters),
createHomeInboxSlice(...parameters),
diff --git a/src/store/project/store.test.ts b/src/store/project/store.test.ts
index d981e432d5d..e0bbdc89634 100644
--- a/src/store/project/store.test.ts
+++ b/src/store/project/store.test.ts
@@ -29,6 +29,7 @@ import {
const mocks = vi.hoisted(() => ({
activeWorkspaceId: null as string | null,
refreshProjectTopics: vi.fn(),
+ syncFavoriteSnapshot: vi.fn(),
}));
vi.mock('@/store/projectWorkingDirectory', () => ({
@@ -42,6 +43,10 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => mocks.activeWorkspaceId,
}));
+vi.mock('@/store/home', () => ({
+ useHomeStore: { getState: () => ({ syncFavoriteSnapshot: mocks.syncFavoriteSnapshot }) },
+}));
+
vi.mock('@/services/project', () => ({
projectService: {
addAgent: vi.fn(),
@@ -459,5 +464,28 @@ describe('project store replicas', () => {
);
expect(useProjectStore.getState().projectListMap.all[0].id).toBe('p3');
});
+ it('refreshes a favorited project when its name or logo changes', async () => {
+ seed();
+ await waitSeeded();
+ const renamed = { ...project('p1', 'Renamed'), avatar: '🚀' };
+ vi.mocked(projectService.update).mockResolvedValue(ok(renamed) as any);
+
+ await act(async () => {
+ await useProjectStore.getState().updateProject('p1', { avatar: '🚀', name: 'Renamed' });
+ });
+ await waitFor(() =>
+ expect(mocks.syncFavoriteSnapshot).toHaveBeenCalledWith('project', 'p1', {
+ icon: '🚀',
+ title: 'Renamed',
+ }),
+ );
+
+ mocks.syncFavoriteSnapshot.mockClear();
+ vi.mocked(projectService.update).mockResolvedValue(ok(project('p1', 'Renamed')) as any);
+ await act(async () => {
+ await useProjectStore.getState().updateProject('p1', { description: 'Plan' } as any);
+ });
+ expect(mocks.syncFavoriteSnapshot).not.toHaveBeenCalled();
+ });
});
});
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
index 753b5b4af27..5969320ec8a 100644
--- a/src/store/project/store.ts
+++ b/src/store/project/store.ts
@@ -95,6 +95,24 @@ const LIST_PARAMS = {} as Record<string, never>;
const devtools = createDevtools('project');
+/**
+ * A favorited project keeps a title and icon snapshot in the sidebar. Renames
+ * and logo changes come from Project Settings, where no favorites row is
+ * mounted to refresh it, so every save pushes the new values.
+ */
+const syncProjectFavorite = (project: Pick<ProjectListItem, 'avatar' | 'id' | 'name'>): void => {
+ // Loaded on demand: a static import would pull the home store, and through
+ // it the chat store, into every chunk that touches projects.
+ void import('@/store/home')
+ .then(({ useHomeStore }) =>
+ useHomeStore.getState().syncFavoriteSnapshot('project', project.id, {
+ icon: project.avatar ?? null,
+ title: project.name,
+ }),
+ )
+ .catch((error) => console.error('[project] failed to sync the favorite snapshot', error));
+};
+
export const useProjectStore = createWithEqualityFn<ProjectStore>()(
devtools((set, get) => {
const list = createReplicaSlice(projectListResource, {
@@ -300,6 +318,7 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(
// Server-owned fields (updatedAt, slug normalisation) land in every copy.
projectEntity.update(id, (project) => ({ ...project, ...response.data }));
void refreshList();
+ if ('name' in input || 'avatar' in input) syncProjectFavorite(response.data);
return response.data;
},
useFetchProjectDetail: (idOrSlug) => detail.useSync(idOrSlug || null),