🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(brief): open self-review skill cards in a skill viewer (#21393)
LiJiane6916553649c
diff --git a/apps/server/src/routers/lambda/__tests__/agentDocument.getSkill.test.ts b/apps/server/src/routers/lambda/__tests__/agentDocument.getSkill.test.tsnew file mode 100644index 00000000000..3430e7bde76--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentDocument.getSkill.test.ts@@ -0,0 +1,73 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as AgentDocumentModels from '@/database/models/agentDocuments';+import { createCallerFactory } from '@/libs/trpc/lambda';+import { createContextInner } from '@/libs/trpc/lambda/context';+import { SkillManagementDocumentService } from '@/server/services/skillManagement';++import { agentDocumentRouter } from '../agentDocument';++const mocks = vi.hoisted(() => ({+ getServerDB: vi.fn(),+ getSkill: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: mocks.getServerDB,+}));++vi.mock('@/database/models/agentDocuments', async (importOriginal) => {+ const actual = await importOriginal<typeof AgentDocumentModels>();++ return { ...actual, AgentDocumentModel: vi.fn() };+});++vi.mock('@/database/models/topic', () => ({ TopicModel: vi.fn() }));+vi.mock('@/database/models/topicDocument', () => ({ TopicDocumentModel: vi.fn() }));+vi.mock('@/server/services/agentDocuments', () => ({ AgentDocumentsService: vi.fn() }));+vi.mock('@/server/services/agentDocumentVfs', () => ({ AgentDocumentVfsService: vi.fn() }));+vi.mock('@/server/services/skillManagement', () => ({ SkillManagementDocumentService: vi.fn() }));++const createCaller = createCallerFactory(agentDocumentRouter);++describe('agentDocumentRouter.getSkill', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getServerDB.mockResolvedValue({ kind: 'server-db' });++ vi.mocked(SkillManagementDocumentService).mockImplementation(function () {+ return { getSkill: mocks.getSkill } as unknown as SkillManagementDocumentService;+ });+ });++ it('reads the managed skill with its SKILL.md for this agent', async () => {+ const skill = {+ bundle: { agentDocumentId: 'agd-bundle', documentId: 'docs_bundle' },+ content: '---\nname: lobe-marker-cleanup\n---\nBody',+ index: { agentDocumentId: 'agd-index', documentId: 'docs_index' },+ name: 'lobe-marker-cleanup',+ };+ mocks.getSkill.mockResolvedValue(skill);++ const caller = createCaller(await createContextInner({ userId: 'user-1' }));+ const result = await caller.getSkill({ agentDocumentId: 'agd-bundle', agentId: 'agent-1' });++ expect(mocks.getSkill).toHaveBeenCalledWith({+ agentDocumentId: 'agd-bundle',+ agentId: 'agent-1',+ includeContent: true,+ });+ expect(result).toEqual(skill);+ });++ it('answers null once the skill is gone', async () => {+ mocks.getSkill.mockResolvedValue(undefined);++ const caller = createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(+ caller.getSkill({ agentDocumentId: 'agd-deleted', agentId: 'agent-1' }),+ ).resolves.toBeNull();+ });+});diff --git a/apps/server/src/routers/lambda/agentDocument/index.procedures.test.ts b/apps/server/src/routers/lambda/agentDocument/index.procedures.test.tsindex 4c33e770707..017522711a9 100644--- a/apps/server/src/routers/lambda/agentDocument/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/agentDocument/index.procedures.test.ts@@ -47,6 +47,7 @@ function expected(): Array<['getDocumentsMap', 'query', 12],['getOrCreateChatTopic', 'mutation', 12],['getReaderDocument', 'query', 12],+ ['getSkill', 'query', 12],['getTemplates', 'query', 11],['hasDocuments', 'query', 12],['importFile', 'mutation', 13],diff --git a/apps/server/src/routers/lambda/agentDocument/skills.ts b/apps/server/src/routers/lambda/agentDocument/skills.tsindex c128f11c124..90259b0b7ed 100644--- a/apps/server/src/routers/lambda/agentDocument/skills.ts+++ b/apps/server/src/routers/lambda/agentDocument/skills.ts@@ -9,7 +9,11 @@ import type { AgentDocumentsService } from '@/server/services/agentDocuments';import { getUnifiedSkillNamespaceRootPath } from '@/server/services/agentDocumentVfs/mounts/skills/path';import { safeMatterOptions } from '@/server/utils/safeMatterOptions';-import { agentDocumentProcedureWrite, handleAgentDocumentVfsError } from './procedures';+import {+ agentDocumentProcedure,+ agentDocumentProcedureWrite,+ handleAgentDocumentVfsError,+} from './procedures';const mountedSkillNamespaceSchema = z.literal('agent');@@ -102,6 +106,25 @@ const resolveConvertibleDocumentBody = async (};export const skillsRouter = router({+ /**+ * Reads one managed skill with its `SKILL.md`, for read-only viewers such as+ * the skill card on a self-review brief.+ *+ * `agentDocumentId` is either the skill bundle row or its `SKILL.md` index row;+ * both resolve to the same skill. Returns `null` when the skill no longer+ * exists for this agent, so a viewer can show it as gone instead of erroring.+ */+ getSkill: agentDocumentProcedure+ .input(z.object({ agentDocumentId: z.string(), agentId: z.string() }))+ .query(async ({ ctx, input }) => {+ const skill = await ctx.skillManagementService.getSkill({+ agentDocumentId: input.agentDocumentId,+ agentId: input.agentId,+ includeContent: true,+ });++ return skill ?? null;+ }),createSkillByPath: agentDocumentProcedureWrite.input(createMountedSkillSchema).mutation(async ({ ctx, input }) => {diff --git a/locales/ar/chat.json b/locales/ar/chat.jsonindex c27c441a24f..c4616ef9d86 100644--- a/locales/ar/chat.json+++ b/locales/ar/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "الإجمالي: {{count}} دفعات · {{nodes}} عقد","goalBatch.planPanel.compare": "قارن مع","goalBatch.planPanel.compareTitle": "مقارنة إصدارات الخطة",- "goalBatch.planPanel.files": "الملفات",- "goalBatch.planPanel.foldFiles": "إخفاء الملفات","goalBatch.planPanel.forked": "خطة متفرعة: تبدأ مرة أخرى من مخطط الدفعة الأصلي بدلاً من مراجعة الإصدار السابق","goalBatch.planPanel.latest": "الإصدار {{revision}} · الأحدث","goalBatch.planPanel.same": "نفس الإصدار {{base}}",- "goalBatch.planPanel.unfoldFiles": "عرض الملفات","goalBatch.probes.attemptNext": "التشغيل التالي","goalBatch.probes.attemptOf": "تشغيل {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "التشغيل السابق",diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.jsonindex 75bbd13b5ff..22b25dbbd69 100644--- a/locales/bg-BG/chat.json+++ b/locales/bg-BG/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Общо: {{count}} партиди · {{nodes}} възли","goalBatch.planPanel.compare": "Сравни с","goalBatch.planPanel.compareTitle": "Сравнете версии на плана",- "goalBatch.planPanel.files": "Файлове",- "goalBatch.planPanel.foldFiles": "Скрий файловете","goalBatch.planPanel.forked": "Разклонен план: започва отново от оригиналния контур на партидата, вместо да преработва предишната версия","goalBatch.planPanel.latest": "v{{revision}} · последна","goalBatch.planPanel.same": "Същото като v{{base}}",- "goalBatch.planPanel.unfoldFiles": "Покажи файловете","goalBatch.probes.attemptNext": "Следващо изпълнение","goalBatch.probes.attemptOf": "Изпълнение {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Предишно изпълнение",diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.jsonindex fb9a58361c1..5237bcf05b4 100644--- a/locales/de-DE/chat.json+++ b/locales/de-DE/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Gesamt: {{count}} Chargen · {{nodes}} Knoten","goalBatch.planPanel.compare": "Vergleichen mit","goalBatch.planPanel.compareTitle": "Planversionen vergleichen",- "goalBatch.planPanel.files": "Dateien",- "goalBatch.planPanel.foldFiles": "Dateien ausblenden","goalBatch.planPanel.forked": "Ein verzweigter Plan: Er beginnt erneut mit der ursprünglichen Struktur der Charge, anstatt die vorherige Version zu überarbeiten","goalBatch.planPanel.latest": "v{{revision}} · neueste","goalBatch.planPanel.same": "Gleich wie v{{base}}",- "goalBatch.planPanel.unfoldFiles": "Dateien anzeigen","goalBatch.probes.attemptNext": "Nächster Durchlauf","goalBatch.probes.attemptOf": "Durchlauf {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Vorheriger Durchlauf",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 28ffe197099..cc2bd3b18c4 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -65,6 +65,9 @@"agentSignal.receipts.revert.unsupported": "Unsupported","agentSignal.receipts.skill.detail": "Self-refined how this agent handles similar requests","agentSignal.receipts.skill.title": "Auto-learned a new skill",+ "agentSkillModal.loadFailed": "Couldn't load this skill",+ "agentSkillModal.notFound": "This skill no longer exists. It may have been deleted.",+ "agentSkillModal.openDocument": "Open in documents","agents": "Agents","ampInstallGuide.actions.openDocs": "Open Install Guide","ampInstallGuide.actions.openSystemTools": "Open System Tools",@@ -521,12 +524,9 @@"goalBatch.overviewCount": "Total: {{count}} batches · {{nodes}} nodes","goalBatch.planPanel.compare": "Compare versions","goalBatch.planPanel.compareTitle": "Compare plan versions",- "goalBatch.planPanel.files": "Files",- "goalBatch.planPanel.foldFiles": "Hide files","goalBatch.planPanel.forked": "A forked plan: it starts again from the batch’s original outline instead of revising the previous version","goalBatch.planPanel.latest": "v{{revision}} · latest","goalBatch.planPanel.same": "Same as v{{base}}",- "goalBatch.planPanel.unfoldFiles": "Show files","goalBatch.probes.attemptNext": "Next run","goalBatch.probes.attemptOf": "Run {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Previous run",@@ -2205,6 +2205,9 @@"signalCallbacks.empty": "No callback messages","signalCallbacks.expand": "Show details","signalCallbacks.title": "{{tool}} · {{count}} callback updates",+ "skillViewer.files": "Files",+ "skillViewer.foldFiles": "Hide files",+ "skillViewer.unfoldFiles": "Show files","steer.tag": "Steered","stt.action": "Voice Input","stt.loading": "Recognizing...",diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.jsonindex b6f034faa8b..8e9363e177f 100644--- a/locales/es-ES/chat.json+++ b/locales/es-ES/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Total: {{count}} lotes · {{nodes}} nodos","goalBatch.planPanel.compare": "Comparar con","goalBatch.planPanel.compareTitle": "Comparar versiones del plan",- "goalBatch.planPanel.files": "Archivos",- "goalBatch.planPanel.foldFiles": "Ocultar archivos","goalBatch.planPanel.forked": "Un plan bifurcado: comienza de nuevo desde el esquema original del lote en lugar de revisar la versión anterior","goalBatch.planPanel.latest": "v{{revision}} · más reciente","goalBatch.planPanel.same": "Igual que v{{base}}",- "goalBatch.planPanel.unfoldFiles": "Mostrar archivos","goalBatch.probes.attemptNext": "Siguiente ejecución","goalBatch.probes.attemptOf": "Ejecución {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Ejecución anterior",diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.jsonindex 2caf086f964..5fbb95e1cc1 100644--- a/locales/fa-IR/chat.json+++ b/locales/fa-IR/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "مجموع: {{count}} دسته · {{nodes}} گره","goalBatch.planPanel.compare": "مقایسه با","goalBatch.planPanel.compareTitle": "مقایسه نسخههای برنامه",- "goalBatch.planPanel.files": "فایلها",- "goalBatch.planPanel.foldFiles": "پنهان کردن فایلها","goalBatch.planPanel.forked": "یک برنامه منشعب: از طرح اصلی دسته شروع میشود به جای بازبینی نسخه قبلی","goalBatch.planPanel.latest": "نسخه {{revision}} · آخرین","goalBatch.planPanel.same": "همانند نسخه {{base}}",- "goalBatch.planPanel.unfoldFiles": "نمایش فایلها","goalBatch.probes.attemptNext": "اجرای بعدی","goalBatch.probes.attemptOf": "اجرا {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "اجرای قبلی",diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.jsonindex b90e8ad9d49..67dd40f6261 100644--- a/locales/fr-FR/chat.json+++ b/locales/fr-FR/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Total : {{count}} lots · {{nodes}} nœuds","goalBatch.planPanel.compare": "Comparer avec","goalBatch.planPanel.compareTitle": "Comparer les versions du plan",- "goalBatch.planPanel.files": "Fichiers",- "goalBatch.planPanel.foldFiles": "Masquer les fichiers","goalBatch.planPanel.forked": "Un plan dérivé : il repart de l'ébauche originale du lot au lieu de réviser la version précédente","goalBatch.planPanel.latest": "v{{revision}} · dernier","goalBatch.planPanel.same": "Identique à v{{base}}",- "goalBatch.planPanel.unfoldFiles": "Afficher les fichiers","goalBatch.probes.attemptNext": "Exécution suivante","goalBatch.probes.attemptOf": "Exécution {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Exécution précédente",diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.jsonindex 336275aabec..91127e054ac 100644--- a/locales/it-IT/chat.json+++ b/locales/it-IT/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Totale: {{count}} batch · {{nodes}} nodi","goalBatch.planPanel.compare": "Confronta con","goalBatch.planPanel.compareTitle": "Confronta versioni del piano",- "goalBatch.planPanel.files": "File",- "goalBatch.planPanel.foldFiles": "Nascondi file","goalBatch.planPanel.forked": "Un piano derivato: ricomincia dallo schema originale del batch invece di rivedere la versione precedente","goalBatch.planPanel.latest": "v{{revision}} · ultimo","goalBatch.planPanel.same": "Uguale a v{{base}}",- "goalBatch.planPanel.unfoldFiles": "Mostra file","goalBatch.probes.attemptNext": "Esegui successivo","goalBatch.probes.attemptOf": "Esecuzione {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Esegui precedente",diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.jsonindex bbf01e7d244..b17190bd216 100644--- a/locales/ja-JP/chat.json+++ b/locales/ja-JP/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "合計: {{count}} バッチ · {{nodes}} ノード","goalBatch.planPanel.compare": "比較する","goalBatch.planPanel.compareTitle": "計画バージョンを比較",- "goalBatch.planPanel.files": "ファイル",- "goalBatch.planPanel.foldFiles": "ファイルを隠す","goalBatch.planPanel.forked": "分岐した計画: バッチの元のアウトラインから再開し、以前のバージョンを修正する代わりに開始します","goalBatch.planPanel.latest": "v{{revision}} · 最新","goalBatch.planPanel.same": "v{{base}} と同じ",- "goalBatch.planPanel.unfoldFiles": "ファイルを表示","goalBatch.probes.attemptNext": "次の実行","goalBatch.probes.attemptOf": "実行 {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "前の実行",diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.jsonindex 12fa6ceead2..e87d089d9cf 100644--- a/locales/ko-KR/chat.json+++ b/locales/ko-KR/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "총계: {{count}} 배치 · {{nodes}} 노드","goalBatch.planPanel.compare": "비교","goalBatch.planPanel.compareTitle": "계획 버전 비교",- "goalBatch.planPanel.files": "파일",- "goalBatch.planPanel.foldFiles": "파일 숨기기","goalBatch.planPanel.forked": "분기된 계획: 이전 버전을 수정하는 대신 배치의 원래 개요에서 다시 시작","goalBatch.planPanel.latest": "v{{revision}} · 최신","goalBatch.planPanel.same": "v{{base}}와 동일",- "goalBatch.planPanel.unfoldFiles": "파일 표시","goalBatch.probes.attemptNext": "다음 실행","goalBatch.probes.attemptOf": "실행 {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "이전 실행",diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.jsonindex 56dc98ceedb..9db08118f43 100644--- a/locales/nl-NL/chat.json+++ b/locales/nl-NL/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Totaal: {{count}} batches · {{nodes}} knooppunten","goalBatch.planPanel.compare": "Vergelijken met","goalBatch.planPanel.compareTitle": "Vergelijk planversies",- "goalBatch.planPanel.files": "Bestanden",- "goalBatch.planPanel.foldFiles": "Bestanden verbergen","goalBatch.planPanel.forked": "Een gesplitst plan: het begint opnieuw vanuit de oorspronkelijke opzet van de batch in plaats van de vorige versie te herzien","goalBatch.planPanel.latest": "v{{revision}} · nieuwste","goalBatch.planPanel.same": "Hetzelfde als v{{base}}",- "goalBatch.planPanel.unfoldFiles": "Bestanden tonen","goalBatch.probes.attemptNext": "Volgende run","goalBatch.probes.attemptOf": "Run {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Vorige run",diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.jsonindex 4648249d2da..d98e7a74163 100644--- a/locales/pl-PL/chat.json+++ b/locales/pl-PL/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Łącznie: {{count}} partii · {{nodes}} węzłów","goalBatch.planPanel.compare": "Porównaj z","goalBatch.planPanel.compareTitle": "Porównaj wersje planu",- "goalBatch.planPanel.files": "Pliki",- "goalBatch.planPanel.foldFiles": "Ukryj pliki","goalBatch.planPanel.forked": "Rozgałęziony plan: zaczyna od pierwotnego zarysu partii zamiast poprawiać poprzednią wersję","goalBatch.planPanel.latest": "v{{revision}} · najnowsza","goalBatch.planPanel.same": "Taka sama jak wersja {{base}}",- "goalBatch.planPanel.unfoldFiles": "Pokaż pliki","goalBatch.probes.attemptNext": "Następne uruchomienie","goalBatch.probes.attemptOf": "Uruchomienie {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Poprzednie uruchomienie",diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.jsonindex d17135a97ee..f3368a15a58 100644--- a/locales/pt-BR/chat.json+++ b/locales/pt-BR/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Total: {{count}} lotes · {{nodes}} nós","goalBatch.planPanel.compare": "Comparar com","goalBatch.planPanel.compareTitle": "Comparar versões do plano",- "goalBatch.planPanel.files": "Arquivos",- "goalBatch.planPanel.foldFiles": "Ocultar arquivos","goalBatch.planPanel.forked": "Um plano bifurcado: começa novamente a partir do esboço original do lote em vez de revisar a versão anterior","goalBatch.planPanel.latest": "v{{revision}} · mais recente","goalBatch.planPanel.same": "Igual a v{{base}}",- "goalBatch.planPanel.unfoldFiles": "Mostrar arquivos","goalBatch.probes.attemptNext": "Próxima execução","goalBatch.probes.attemptOf": "Execução {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Execução anterior",diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.jsonindex 2460193a6ef..9564938f659 100644--- a/locales/ru-RU/chat.json+++ b/locales/ru-RU/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Всего: {{count}} партий · {{nodes}} узлов","goalBatch.planPanel.compare": "Сравнить с","goalBatch.planPanel.compareTitle": "Сравнить версии плана",- "goalBatch.planPanel.files": "Файлы",- "goalBatch.planPanel.foldFiles": "Скрыть файлы","goalBatch.planPanel.forked": "Разветвленный план: начинается с оригинального контура партии, а не с пересмотра предыдущей версии","goalBatch.planPanel.latest": "v{{revision}} · последняя","goalBatch.planPanel.same": "То же, что и v{{base}}",- "goalBatch.planPanel.unfoldFiles": "Показать файлы","goalBatch.probes.attemptNext": "Следующий запуск","goalBatch.probes.attemptOf": "Запуск {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Предыдущий запуск",diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.jsonindex 5a6af48d799..66da3f2dd82 100644--- a/locales/tr-TR/chat.json+++ b/locales/tr-TR/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Toplam: {{count}} toplu işlem · {{nodes}} düğüm","goalBatch.planPanel.compare": "Karşılaştır","goalBatch.planPanel.compareTitle": "Plan sürümlerini karşılaştır",- "goalBatch.planPanel.files": "Dosyalar",- "goalBatch.planPanel.foldFiles": "Dosyaları gizle","goalBatch.planPanel.forked": "Çatallanmış bir plan: önceki sürümü revize etmek yerine toplu işlemin orijinal taslağından yeniden başlar","goalBatch.planPanel.latest": "v{{revision}} · en son","goalBatch.planPanel.same": "v{{base}} ile aynı",- "goalBatch.planPanel.unfoldFiles": "Dosyaları göster","goalBatch.probes.attemptNext": "Sonraki çalıştırma","goalBatch.probes.attemptOf": "Çalıştırma {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Önceki çalıştırma",diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.jsonindex 8b199178a47..b981794485a 100644--- a/locales/vi-VN/chat.json+++ b/locales/vi-VN/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "Tổng cộng: {{count}} lô · {{nodes}} nút","goalBatch.planPanel.compare": "So sánh với","goalBatch.planPanel.compareTitle": "So sánh các phiên bản kế hoạch",- "goalBatch.planPanel.files": "Tệp",- "goalBatch.planPanel.foldFiles": "Ẩn tệp","goalBatch.planPanel.forked": "Một kế hoạch phân nhánh: nó bắt đầu lại từ phác thảo ban đầu của lô thay vì sửa đổi phiên bản trước","goalBatch.planPanel.latest": "v{{revision}} · mới nhất","goalBatch.planPanel.same": "Giống như v{{base}}",- "goalBatch.planPanel.unfoldFiles": "Hiển thị tệp","goalBatch.probes.attemptNext": "Lần chạy tiếp theo","goalBatch.probes.attemptOf": "Lần chạy {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "Lần chạy trước",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex aa782211c62..ceabdafbd8c 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -65,6 +65,9 @@"agentSignal.receipts.revert.unsupported": "不支持撤销","agentSignal.receipts.skill.detail": "已自主优化处理相似请求的方式","agentSignal.receipts.skill.title": "已自动习得新技能",+ "agentSkillModal.loadFailed": "技能加载失败",+ "agentSkillModal.notFound": "这个技能已不存在,可能已被删除。",+ "agentSkillModal.openDocument": "在文档中打开","agents": "助理","ampInstallGuide.actions.openDocs": "打开安装指南","ampInstallGuide.actions.openSystemTools": "打开系统工具",@@ -521,12 +524,9 @@"goalBatch.overviewCount": "共 {{count}} 个批次 · {{nodes}} 个节点","goalBatch.planPanel.compare": "对比版本","goalBatch.planPanel.compareTitle": "对比方案版本",- "goalBatch.planPanel.files": "文件",- "goalBatch.planPanel.foldFiles": "收起文件","goalBatch.planPanel.forked": "另起的方案:不沿用上一版的修订,从批次最初的方案出发","goalBatch.planPanel.latest": "v{{revision}} · 最新","goalBatch.planPanel.same": "与 v{{base}} 相同",- "goalBatch.planPanel.unfoldFiles": "展开文件","goalBatch.probes.attemptNext": "下一次","goalBatch.probes.attemptOf": "第 {{current}} / {{total}} 次","goalBatch.probes.attemptPrevious": "上一次",@@ -2205,6 +2205,9 @@"signalCallbacks.empty": "没有回调消息","signalCallbacks.expand": "显示详情","signalCallbacks.title": "{{tool}} · {{count}} 条回调更新",+ "skillViewer.files": "文件",+ "skillViewer.foldFiles": "收起文件",+ "skillViewer.unfoldFiles": "展开文件","steer.tag": "追加指令","stt.action": "语音输入","stt.loading": "识别中…",diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.jsonindex a7d9f9bf56f..f677b44ce63 100644--- a/locales/zh-TW/chat.json+++ b/locales/zh-TW/chat.json@@ -520,12 +520,9 @@"goalBatch.overviewCount": "總計:{{count}} 批次 · {{nodes}} 節點","goalBatch.planPanel.compare": "比較","goalBatch.planPanel.compareTitle": "比較計劃版本",- "goalBatch.planPanel.files": "檔案",- "goalBatch.planPanel.foldFiles": "隱藏檔案","goalBatch.planPanel.forked": "分叉計劃:從批次的原始大綱重新開始,而不是修訂上一版本","goalBatch.planPanel.latest": "v{{revision}} · 最新","goalBatch.planPanel.same": "與 v{{base}} 相同",- "goalBatch.planPanel.unfoldFiles": "顯示檔案","goalBatch.probes.attemptNext": "下一次運行","goalBatch.probes.attemptOf": "運行 {{current}} / {{total}}","goalBatch.probes.attemptPrevious": "上一次運行",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex c311ea7aaad..81a2bb5e7d4 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -57,13 +57,10 @@ export default {'goalBatch.enter': 'Open','goalBatch.planPanel.compare': 'Compare versions','goalBatch.planPanel.compareTitle': 'Compare plan versions',- 'goalBatch.planPanel.files': 'Files',- 'goalBatch.planPanel.foldFiles': 'Hide files','goalBatch.planPanel.forked':'A forked plan: it starts again from the batch’s original outline instead of revising the previous version','goalBatch.planPanel.latest': 'v{{revision}} · latest','goalBatch.planPanel.same': 'Same as v{{base}}',- 'goalBatch.planPanel.unfoldFiles': 'Show files','goalBatch.probes.attemptNext': 'Next run','goalBatch.probes.attemptOf': 'Run {{current}} / {{total}}','goalBatch.probes.attemptPrevious': 'Previous run',@@ -279,6 +276,9 @@ export default {'permission.configAccess.groupRoleRestricted':'Your workspace role cannot configure Agent Groups. You were returned to chat.','agentNotFound.title': 'Agent Unavailable',+ 'agentSkillModal.loadFailed': "Couldn't load this skill",+ 'agentSkillModal.notFound': 'This skill no longer exists. It may have been deleted.',+ 'agentSkillModal.openDocument': 'Open in documents','groupNotFound.desc':'This group does not exist or is no longer accessible — it may have been deleted or set to private by its owner.','groupNotFound.title': 'Group Unavailable',@@ -1858,6 +1858,9 @@ export default {'signalCallbacks.empty': 'No callback messages','signalCallbacks.expand': 'Show details','signalCallbacks.title': '{{tool}} · {{count}} callback updates',+ 'skillViewer.files': 'Files',+ 'skillViewer.foldFiles': 'Hide files',+ 'skillViewer.unfoldFiles': 'Show files','stt.action': 'Voice Input','stt.loading': 'Recognizing...','stt.prettifying': 'Polishing...',diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.jsonindex 15ce05767f2..da3a98f6f0a 100644--- a/scripts/stylexMigration/legacyFiles.json+++ b/scripts/stylexMigration/legacyFiles.json@@ -412,7 +412,6 @@"src/features/AgentGoals/ProcessControl/BatchGate/GateChecksHint.tsx","src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx","src/features/AgentGoals/ProcessControl/BatchPlan/PlanCompareModal.tsx",- "src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx","src/features/AgentGoals/ProcessControl/DeliverableReader.tsx","src/features/AgentGoals/ProcessControl/Deliverables.tsx","src/features/AgentGoals/ProcessControl/Findings.tsx",diff --git a/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsx b/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsxindex 5f967b86676..db6665c9543 100644--- a/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsx+++ b/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsx@@ -4,12 +4,10 @@ import { createStaticStyles, cssVar, Flexbox, Highlighter, Markdown } from '@lobimport { memo, useMemo, useState } from 'react';import Loading from '@/components/Loading/CircleLoading';-import {- skillFileTree,- skillVersionContent,-} from '@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions';+import { skillVersionContent } from '@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions';import { getLanguage } from '@/features/AgentSkillDetail/ContentViewer';import FileTree from '@/features/FileTree';+import { skillFileTree } from '@/features/SkillViewer/skillFileTree';import { useClientDataSWR } from '@/libs/swr';import { userSkillService } from '@/services/userSkill';import { parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsxindex ab4e20296bb..e68b14c7123 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx@@ -1,54 +1,22 @@-import { useEditor } from '@lobehub/editor/react';-import { ActionIcon, createStaticStyles, cssVar, cx, Flexbox, Text } from '@lobehub/ui';-import { PanelRightCloseIcon, PanelRightOpenIcon } from 'lucide-react';-import { memo, useMemo, useState } from 'react';+import { Text } from '@lobehub/ui';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import Loading from '@/components/Loading/CircleLoading';-import ContentViewer from '@/features/AgentSkillDetail/ContentViewer';-import { EditorCanvas } from '@/features/EditorCanvas';-import FileTree from '@/features/FileTree';-import SkillFrontmatterCard from '@/features/Portal/Document/SkillFrontmatterCard';-import { parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';+import SkillViewer from '@/features/SkillViewer';import type { GoalGraphView } from '../goalGraphViewModel';import type { BatchModel, BatchRound } from '../Graph/batchModel';import { usePlanVersions, usePlanVersionSelection } from './planVersion';-import { skillFileTree } from './skillVersions';/**- * A batch's plan, opened from its node, read the way the product reads a- * skill document: its frontmatter card (folded — the plan is what one comes- * to read), then the selected file of the skill on the left — `SKILL.md` on- * the same canvas documents render on, read-only since a version is a record- * of a round — and the skill's files on the right.+ * A batch's plan, opened from its node, read as the skill it is kept as: the+ * selected version's `SKILL.md` and the skill's files, read-only since a+ * version is a record of a round.* Which version shows, and comparing two, live in the panel's header* (`PlanHeaderActions`), out of the document.*/-const SKILL_INDEX = 'SKILL.md';--const styles = createStaticStyles(({ css }) => ({- files: css`- overflow-y: auto;- display: flex;- flex: none;- flex-direction: column;-- width: 180px;- padding: 8px;- border-inline-start: 1px solid ${cssVar.colorBorderSecondary};- `,- filesFolded: css`- width: auto;- padding-inline: 4px;- `,- filesHead: css`- padding-block: 2px 6px;- padding-inline: 8px 0;- `,-}));-interface PlanDetailProps {graph: GoalGraphView;model: BatchModel;@@ -57,92 +25,28 @@ interface PlanDetailProps {const PlanDetail = memo<PlanDetailProps>(({ graph, model, round }) => {const { t } = useTranslation('chat');- const editor = useEditor();- const [selectedFile, setSelectedFile] = useState(SKILL_INDEX);- const [filesOpen, setFilesOpen] = useState(true);const { selected } = usePlanVersionSelection();const { files, isLoading, versions } = usePlanVersions(graph, model);- const resourceTree = useMemo(() => skillFileTree(files), [files]);- const contentMap = useMemo(- () => Object.fromEntries(files.map((file) => [file.path, file.content])),- [files],- );if (isLoading) return <Loading />;const revision = selected ?? round.planVersion;const current = versions.find((version) => version.revision === revision);const forked = model.rounds.find((item) => item.planVersion === revision)?.forked;- const { body, frontmatter } = parseSkillMarkdownFrontmatter(current?.content);return (- <Flexbox data-plan-detail flex={1} style={{ minHeight: 0 }}>- {(forked || frontmatter) && (- <Flexbox paddingInline={16} style={{ flex: 'none' }}>- {forked && (- <Text fontSize={12} style={{ paddingBlockStart: 12 }} type={'secondary'}>- {t('goalBatch.planPanel.forked')}- </Text>- )}- {frontmatter && <SkillFrontmatterCard defaultCollapsed frontmatter={frontmatter} />}- </Flexbox>- )}- <Flexbox horizontal flex={1} style={{ minHeight: 0 }}>- <div style={{ flex: 1, minWidth: 0, overflowY: 'auto', paddingBlockEnd: 24 }}>- {selectedFile === SKILL_INDEX ? (- <div style={{ paddingInline: 16 }}>- <EditorCanvas- editable={false}- editor={editor}- editorData={{ content: body }}- entityId={`${model.planSkill?.id ?? model.batchId}:${revision}`}- floatingToolbar={false}- />- </div>- ) : (- <ContentViewer contentMap={contentMap} key={selectedFile} selectedFile={selectedFile} />- )}- </div>- {/* The skill's files: folds to a rail so the document can take the width. */}- <div- className={cx(styles.files, !filesOpen && styles.filesFolded)}- data-plan-files={filesOpen ? 'open' : 'folded'}- >- {filesOpen ? (- <>- <Flexbox- horizontal- align={'center'}- className={styles.filesHead}- justify={'space-between'}- >- <Text fontSize={12} type={'secondary'} weight={500}>- {t('goalBatch.planPanel.files')}- </Text>- <ActionIcon- icon={PanelRightCloseIcon}- size={'small'}- title={t('goalBatch.planPanel.foldFiles')}- onClick={() => setFilesOpen(false)}- />- </Flexbox>- <FileTree- resourceTree={resourceTree}- selectedFile={selectedFile}- onSelectFile={setSelectedFile}- />- </>- ) : (- <ActionIcon- icon={PanelRightOpenIcon}- size={'small'}- title={t('goalBatch.planPanel.unfoldFiles')}- onClick={() => setFilesOpen(true)}- />- )}- </div>- </Flexbox>- </Flexbox>+ <SkillViewer+ content={current?.content}+ entityId={`${model.planSkill?.id ?? model.batchId}:${revision}`}+ files={files}+ notice={+ forked && (+ <Text fontSize={12} style={{ paddingBlockStart: 12 }} type={'secondary'}>+ {t('goalBatch.planPanel.forked')}+ </Text>+ )+ }+ />);});diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.tsindex 60944ec487d..e3400a4cc4e 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { skillFileTree, skillVersionContent } from './skillVersions';+import { skillVersionContent } from './skillVersions';describe('skillVersionContent', () => {it('reads a kept version whole, frontmatter included', () => {@@ -13,30 +13,3 @@ describe('skillVersionContent', () => {expect(skillVersionContent(undefined, 1)).toBeUndefined();});});--describe('skillFileTree', () => {- it('nests a skill’s files into folders, folders first', () => {- expect(- skillFileTree([- { content: 'b', path: 'scripts/rollback.sql' },- { content: 'notes', path: 'README.md' },- { content: 'a', path: 'scripts/check.sh' },- ]),- ).toEqual([- {- children: [- { content: 'a', name: 'check.sh', path: 'scripts/check.sh', type: 'file' },- { content: 'b', name: 'rollback.sql', path: 'scripts/rollback.sql', type: 'file' },- ],- name: 'scripts',- path: 'scripts',- type: 'directory',- },- { content: 'notes', name: 'README.md', path: 'README.md', type: 'file' },- ]);- });-- it('is empty for a skill with no files', () => {- expect(skillFileTree(undefined)).toEqual([]);- });-});diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.tsindex b9dbeaaab9d..087b71c3504 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts@@ -1,5 +1,3 @@-import type { SkillResourceTreeNode } from '@lobechat/types';-/*** One version's `SKILL.md` as a plan skill kept it — frontmatter included, as* the document view shows it. A payload without `versions` (an older server)@@ -9,38 +7,3 @@ export const skillVersionContent = (versions: readonly { content: string; version: number }[] | null | undefined,revision: number,): string | undefined => (versions ?? []).find((version) => version.version === revision)?.content;--/**- * A skill's files as the file tree takes them: `scripts/check.sh` becomes a- * `scripts` folder holding `check.sh`. Folders first, then files, by name.- * `SKILL.md` itself is the tree's root entry, not one of these.- */-export const skillFileTree = (- files: readonly { content: string; path: string }[] | null | undefined,-): SkillResourceTreeNode[] => {- const root: SkillResourceTreeNode[] = [];- for (const file of files ?? []) {- const parts = file.path.split('/').filter(Boolean);- let level = root;- parts.forEach((name, index) => {- const path = parts.slice(0, index + 1).join('/');- if (index === parts.length - 1) {- level.push({ content: file.content, name, path, type: 'file' });- return;- }- let folder = level.find((node) => node.type === 'directory' && node.name === name);- if (!folder) {- folder = { children: [], name, path, type: 'directory' };- level.push(folder);- }- level = folder.children!;- });- }- const sort = (nodes: SkillResourceTreeNode[]): SkillResourceTreeNode[] =>- nodes- .map((node) => (node.children ? { ...node, children: sort(node.children) } : node))- .sort((a, b) =>- a.type === b.type ? a.name.localeCompare(b.name) : a.type === 'directory' ? -1 : 1,- );- return sort(root);-};diff --git a/src/features/AgentSkillModal/AgentSkillModalContent.tsx b/src/features/AgentSkillModal/AgentSkillModalContent.tsxnew file mode 100644index 00000000000..d8e69cc38dc--- /dev/null+++ b/src/features/AgentSkillModal/AgentSkillModalContent.tsx@@ -0,0 +1,55 @@+'use client';++import { Button, Center, Empty } from '@lobehub/ui';+import { SkillsIcon } from '@lobehub/ui/icons';+import { FileWarningIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import Loading from '@/components/Loading/CircleLoading';+import SkillViewer from '@/features/SkillViewer';++import { useAgentSkill } from './useAgentSkill';++export interface AgentSkillModalContentProps {+ /** The skill bundle row or its `SKILL.md` index row, from `agent_documents.id`. */+ agentDocumentId: string;+ agentId: string;+}++// Managed skills keep `SKILL.md` alone, so the tree lists just that file.+const NO_OTHER_FILES: { content: string; path: string }[] = [];++/**+ * One of an agent's managed skills, read-only: its file tree beside the+ * selected file. Editing happens on the skill's own document page, which the+ * modal title opens.+ */+const AgentSkillModalContent = ({ agentDocumentId, agentId }: AgentSkillModalContentProps) => {+ const { t } = useTranslation(['chat', 'common']);+ const { data: skill, error, isLoading, mutate } = useAgentSkill(agentId, agentDocumentId);++ if (isLoading) return <Loading />;++ if (error || !skill) {+ return (+ <Center flex={1} gap={12}>+ <Empty+ description={t(error ? 'agentSkillModal.loadFailed' : 'agentSkillModal.notFound')}+ icon={error ? FileWarningIcon : SkillsIcon}+ />+ {error && <Button onClick={() => void mutate()}>{t('retry', { ns: 'common' })}</Button>}+ </Center>+ );+ }++ return (+ <SkillViewer+ content={skill.content}+ entityId={`agent-skill:${skill.index.documentId}`}+ files={NO_OTHER_FILES}+ filesPosition={'start'}+ />+ );+};++export default AgentSkillModalContent;diff --git a/src/features/AgentSkillModal/AgentSkillModalTitle.tsx b/src/features/AgentSkillModal/AgentSkillModalTitle.tsxnew file mode 100644index 00000000000..29ec7c32110--- /dev/null+++ b/src/features/AgentSkillModal/AgentSkillModalTitle.tsx@@ -0,0 +1,52 @@+'use client';++import { ActionIcon, Flexbox, useModalContext } from '@lobehub/ui';+import { Maximize2Icon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { buildAgentDocumentPath } from '@/features/AgentDocumentPage/navigation';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';++import { useAgentSkill } from './useAgentSkill';++export interface AgentSkillModalTitleProps {+ agentDocumentId: string;+ agentId: string;+ /** The name the opener already knows, shown until the skill loads. */+ title: string;+}++/**+ * The skill's name, and beside it the way out to its full document page — where+ * it can be edited. The action waits for the skill, since that page is+ * addressed by its `SKILL.md` document.+ */+const AgentSkillModalTitle = ({ agentDocumentId, agentId, title }: AgentSkillModalTitleProps) => {+ const { t } = useTranslation('chat');+ const { close } = useModalContext();+ const navigate = useWorkspaceAwareNavigate();+ const { data: skill } = useAgentSkill(agentId, agentDocumentId);++ return (+ <Flexbox horizontal align={'center'} gap={4} style={{ minWidth: 0 }}>+ <span+ style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}+ >+ {skill?.title || title}+ </span>+ {skill && (+ <ActionIcon+ icon={Maximize2Icon}+ size={'small'}+ title={t('agentSkillModal.openDocument')}+ onClick={() => {+ close();+ navigate(buildAgentDocumentPath(agentId, skill.index.documentId));+ }}+ />+ )}+ </Flexbox>+ );+};++export default AgentSkillModalTitle;diff --git a/src/features/AgentSkillModal/index.tsx b/src/features/AgentSkillModal/index.tsxnew file mode 100644index 00000000000..55e2aec6b9c--- /dev/null+++ b/src/features/AgentSkillModal/index.tsx@@ -0,0 +1,35 @@+'use client';++import { createModal } from '@lobehub/ui';+import { t } from 'i18next';++import AgentSkillModalContent, { type AgentSkillModalContentProps } from './AgentSkillModalContent';+import AgentSkillModalTitle from './AgentSkillModalTitle';++export interface AgentSkillModalOptions extends AgentSkillModalContentProps {+ /** The skill's name as the opener already knows it, shown while it loads. */+ title?: string | null;+}++export const createAgentSkillModal = ({ title, ...props }: AgentSkillModalOptions) =>+ createModal({+ content: <AgentSkillModalContent {...props} />,+ footer: null,+ maskClosable: true,+ styles: {+ content: {+ display: 'flex',+ flexDirection: 'column',+ height: 'min(80vh, 800px)',+ overflow: 'hidden',+ padding: 0,+ },+ },+ title: (+ <AgentSkillModalTitle+ {...props}+ title={title || t('workingPanel.skills.detail.title', { ns: 'chat' })}+ />+ ),+ width: 'min(90vw, 960px)',+ });diff --git a/src/features/AgentSkillModal/loader.ts b/src/features/AgentSkillModal/loader.tsnew file mode 100644index 00000000000..77f84e9a477--- /dev/null+++ b/src/features/AgentSkillModal/loader.ts@@ -0,0 +1,17 @@+import type { AgentSkillModalOptions } from '.';++const importAgentSkillModal = () => import('.');++let agentSkillModalPromise: ReturnType<typeof importAgentSkillModal> | undefined;++export const preloadAgentSkillModal = (): ReturnType<typeof importAgentSkillModal> =>+ (agentSkillModalPromise ??= importAgentSkillModal().catch((error) => {+ agentSkillModalPromise = undefined;+ throw error;+ }));++export const openAgentSkillModal = async (options: AgentSkillModalOptions) => {+ const { createAgentSkillModal } = await preloadAgentSkillModal();++ return createAgentSkillModal(options);+};diff --git a/src/features/AgentSkillModal/useAgentSkill.ts b/src/features/AgentSkillModal/useAgentSkill.tsnew file mode 100644index 00000000000..7edf6bf7f29--- /dev/null+++ b/src/features/AgentSkillModal/useAgentSkill.ts@@ -0,0 +1,12 @@+import { useClientDataSWR } from '@/libs/swr';+import { agentDocumentService } from '@/services/agentDocument';++/**+ * One managed skill of an agent, with its `SKILL.md`. `agentDocumentId` is the+ * skill bundle row or its `SKILL.md` index row. `data` is `null` once the skill+ * no longer exists for this agent.+ */+export const useAgentSkill = (agentId: string, agentDocumentId: string) =>+ useClientDataSWR(['agent-managed-skill', agentId, agentDocumentId], () =>+ agentDocumentService.getSkill({ agentDocumentId, agentId }),+ );diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsxindex 3392cb4aba8..2f8bbcfd101 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx@@ -105,7 +105,10 @@ const TaskBriefCard = memo<TaskBriefCardProps>({showFull && (<><BriefCardSummary summary={brief.summary} />- <BriefCardArtifacts artifacts={brief.artifacts} />+ <BriefCardArtifacts+ agentId={brief.agentId ?? brief.agent?.id}+ artifacts={brief.artifacts}+ /><BriefCardActionsactions={brief.actions}agentId={brief.agentId ?? brief.agent?.id}diff --git a/src/features/DailyBrief/BriefCardArtifacts.tsx b/src/features/DailyBrief/BriefCardArtifacts.tsxindex 49ec9786b2b..1830fa8e6e9 100644--- a/src/features/DailyBrief/BriefCardArtifacts.tsx+++ b/src/features/DailyBrief/BriefCardArtifacts.tsx@@ -1,10 +1,15 @@import type { BriefArtifactDocument, BriefArtifacts } from '@lobechat/types';-import { Block, createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';-import { ChevronRightIcon, FileTextIcon } from 'lucide-react';-import { memo } from 'react';+import { Block, createStaticStyles, cssVar, Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';+import { SkillsIcon } from '@lobehub/ui/icons';+import { ChevronRightIcon, FileTextIcon, type LucideIcon } from 'lucide-react';+import { memo, type ReactNode } from 'react';+import { openAgentSkillModal, preloadAgentSkillModal } from '@/features/AgentSkillModal/loader';+import { useAgentSkill } from '@/features/AgentSkillModal/useAgentSkill';import { openDocumentModal, preloadDocumentModal } from '@/features/DocumentModal/loader';+import { resolveBriefArtifactTarget } from './briefArtifactTarget';+const styles = createStaticStyles(({ css, cssVar }) => ({iconWrap: css`display: flex;@@ -20,54 +25,137 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-const BriefArtifactCard = memo<{ doc: BriefArtifactDocument }>(({ doc }) => {- const title = doc.title || 'Untitled';+interface BriefArtifactCardProps {+ /** A second line under the title, e.g. what a skill is for. */+ description?: ReactNode;+ icon: LucideIcon;+ onOpen: () => void;+ onPreload: () => void;+ title: string;+}- return (- <Block- clickable- horizontal- align={'center'}- gap={12}- paddingBlock={10}- paddingInline={12}- variant={'filled'}- onClick={() => void openDocumentModal(doc.id)}- onFocus={preloadDocumentModal}- onPointerEnter={preloadDocumentModal}- >- <div className={styles.iconWrap}>- <Icon- color={cssVar.colorTextSecondary}- icon={FileTextIcon}- size={{ size: 20, strokeWidth: 1.5 }}- />- </div>- <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={500}>+const BriefArtifactCard = ({+ description,+ icon,+ onOpen,+ onPreload,+ title,+}: BriefArtifactCardProps) => (+ <Block+ clickable+ horizontal+ align={'center'}+ gap={12}+ paddingBlock={10}+ paddingInline={12}+ variant={'filled'}+ onClick={onOpen}+ onFocus={onPreload}+ onPointerEnter={onPreload}+ >+ <div className={styles.iconWrap}>+ <Icon color={cssVar.colorTextSecondary} icon={icon} size={{ size: 20, strokeWidth: 1.5 }} />+ </div>+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Text ellipsis weight={500}>{title}</Text>- <Icon- color={cssVar.colorTextQuaternary}- icon={ChevronRightIcon}- size={16}- style={{ flexShrink: 0 }}+ {description}+ </Flexbox>+ <Icon+ color={cssVar.colorTextQuaternary}+ icon={ChevronRightIcon}+ size={16}+ style={{ flexShrink: 0 }}+ />+ </Block>+);++const SKILL_ICON = SkillsIcon as unknown as LucideIcon;++/**+ * A skill reads as its title and what it is for. The description comes from+ * the skill itself, through the same request the skill modal makes, so opening+ * it right after shows the skill at once.+ */+const SkillArtifactCard = ({+ agentDocumentId,+ agentId,+ title,+}: {+ agentDocumentId: string;+ agentId: string;+ title: string | null;+}) => {+ const { data: skill, isLoading } = useAgentSkill(agentId, agentDocumentId);++ return (+ <BriefArtifactCard+ icon={SKILL_ICON}+ title={skill?.title || title || 'Untitled'}+ description={+ isLoading ? (+ <Skeleton.Text fontSize={12} rows={1} width={240} />+ ) : (+ skill?.description && (+ <Text ellipsis fontSize={12} type={'secondary'}>+ {skill.description}+ </Text>+ )+ )+ }+ onOpen={() => void openAgentSkillModal({ agentDocumentId, agentId, title })}+ onPreload={preloadAgentSkillModal}+ />+ );+};++const BriefArtifact = ({+ agentId,+ doc,+}: {+ agentId?: string | null;+ doc: BriefArtifactDocument;+}) => {+ const target = resolveBriefArtifactTarget(doc, agentId);+ if (!target) return null;++ const title = doc.title || 'Untitled';++ if (target.type === 'skill') {+ return (+ <SkillArtifactCard+ agentDocumentId={target.agentDocumentId}+ agentId={target.agentId}+ title={doc.title}/>- </Block>+ );+ }++ return (+ <BriefArtifactCard+ icon={FileTextIcon}+ title={title}+ onOpen={() => void openDocumentModal(target.documentId)}+ onPreload={preloadDocumentModal}+ />);-});+};interface BriefCardArtifactsProps {+ /** The agent the brief is about; a skill artifact is one of its skills. */+ agentId?: string | null;artifacts?: BriefArtifacts | null;}-const BriefCardArtifacts = memo<BriefCardArtifactsProps>(({ artifacts }) => {+const BriefCardArtifacts = memo<BriefCardArtifactsProps>(({ agentId, artifacts }) => {const docs = artifacts?.documents;if (!docs?.length) return null;return (<Flexbox gap={8}>{docs.map((doc) => (- <BriefArtifactCard doc={doc} key={doc.id} />+ <BriefArtifact agentId={agentId} doc={doc} key={doc.id} />))}</Flexbox>);diff --git a/src/features/DailyBrief/__tests__/briefArtifactTarget.test.ts b/src/features/DailyBrief/__tests__/briefArtifactTarget.test.tsnew file mode 100644index 00000000000..2ef3c8b4a41--- /dev/null+++ b/src/features/DailyBrief/__tests__/briefArtifactTarget.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { resolveBriefArtifactTarget } from '../briefArtifactTarget';++const SKILL_AGENT_DOCUMENT_ID = '5b0f0a9e-6c3c-4d55-9f3a-1b2c3d4e5f60';++describe('resolveBriefArtifactTarget', () => {+ it('opens a skill artifact as the agent skill, not as a page', () => {+ // The id is an `agent_documents` id: opened as a page it is a 404.+ expect(+ resolveBriefArtifactTarget(+ { id: SKILL_AGENT_DOCUMENT_ID, kind: 'skill', title: 'LOBE Marker Cleanup' },+ 'agt_reviewed',+ ),+ ).toEqual({ agentDocumentId: SKILL_AGENT_DOCUMENT_ID, agentId: 'agt_reviewed', type: 'skill' });+ });++ it('has nothing to open for a skill artifact without its agent', () => {+ expect(+ resolveBriefArtifactTarget({ id: SKILL_AGENT_DOCUMENT_ID, kind: 'skill', title: null }),+ ).toBeUndefined();+ });++ it('opens any other artifact as the page it names', () => {+ expect(+ resolveBriefArtifactTarget(+ { id: 'docs_report', kind: 'text/markdown', title: 'Report' },+ 'agt_reviewed',+ ),+ ).toEqual({ documentId: 'docs_report', type: 'page' });+ expect(resolveBriefArtifactTarget({ id: 'docs_note', kind: null, title: null })).toEqual({+ documentId: 'docs_note',+ type: 'page',+ });+ });+});diff --git a/src/features/DailyBrief/briefArtifactTarget.ts b/src/features/DailyBrief/briefArtifactTarget.tsnew file mode 100644index 00000000000..693d739d1cc--- /dev/null+++ b/src/features/DailyBrief/briefArtifactTarget.ts@@ -0,0 +1,23 @@+import type { BriefArtifactDocument } from '@lobechat/types';++/** What opening one brief artifact shows. */+export type BriefArtifactTarget =+ | { agentDocumentId: string; agentId: string; type: 'skill' }+ | { documentId: string; type: 'page' };++/**+ * A `skill` artifact names one of the agent's managed skills by its+ * `agent_documents` id — not a page id — so it opens as that skill. Without+ * its agent such a skill can't be resolved, and there is nothing to open.+ * Every other artifact is the page it names.+ */+export const resolveBriefArtifactTarget = (+ doc: BriefArtifactDocument,+ agentId?: string | null,+): BriefArtifactTarget | undefined => {+ if (doc.kind === 'skill') {+ return agentId ? { agentDocumentId: doc.id, agentId, type: 'skill' } : undefined;+ }++ return { documentId: doc.id, type: 'page' };+};diff --git a/src/features/HomeInbox/InboxBriefCard.tsx b/src/features/HomeInbox/InboxBriefCard.tsxindex 2901566e5d3..accd8db3753 100644--- a/src/features/HomeInbox/InboxBriefCard.tsx+++ b/src/features/HomeInbox/InboxBriefCard.tsx@@ -166,7 +166,10 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {) : (<BriefCardSummary summary={brief.summary} />)}- <BriefCardArtifacts artifacts={brief.artifacts} />+ <BriefCardArtifacts+ agentId={brief.agentId ?? brief.agent?.id}+ artifacts={brief.artifacts}+ /></Flexbox></Flexbox>diff --git a/src/features/HomeInbox/NewsList.tsx b/src/features/HomeInbox/NewsList.tsxindex 877ddea1e0c..752bd6964c8 100644--- a/src/features/HomeInbox/NewsList.tsx+++ b/src/features/HomeInbox/NewsList.tsx@@ -174,7 +174,7 @@ const NewsItem = memo<NewsItemProps>(({ bare, brief, showTime }) => {</Suspense>))}- <BriefCardArtifacts artifacts={brief.artifacts} />+ <BriefCardArtifacts agentId={agentId} artifacts={brief.artifacts} />{agentId && topicId && (<NewsChatActionsagentId={agentId}diff --git a/src/features/SkillViewer/index.tsx b/src/features/SkillViewer/index.tsxnew file mode 100644index 00000000000..52b184a8876--- /dev/null+++ b/src/features/SkillViewer/index.tsx@@ -0,0 +1,194 @@+'use client';++import { useEditor } from '@lobehub/editor/react';+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import {+ PanelLeftCloseIcon,+ PanelLeftOpenIcon,+ PanelRightCloseIcon,+ PanelRightOpenIcon,+} from 'lucide-react';+import { type ReactNode, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import ContentViewer from '@/features/AgentSkillDetail/ContentViewer';+import { EditorCanvas } from '@/features/EditorCanvas';+import FileTree from '@/features/FileTree';+import SkillFrontmatterCard from '@/features/Portal/Document/SkillFrontmatterCard';+import { parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';++import { skillFileTree } from './skillFileTree';++const SKILL_INDEX = 'SKILL.md';++const styles = stylex.create({+ body: {+ flex: '1',+ minWidth: 0,+ overflowY: 'auto',+ paddingBlockEnd: 24,+ },+ files: {+ display: 'flex',+ flex: 'none',+ flexDirection: 'column',+ overflowY: 'auto',+ padding: 8,+ width: 180,+ },+ filesAtEnd: {+ borderInlineStartColor: cssVar.colorBorderSecondary,+ borderInlineStartStyle: 'solid',+ borderInlineStartWidth: 1,+ },+ filesAtStart: {+ borderInlineEndColor: cssVar.colorBorderSecondary,+ borderInlineEndStyle: 'solid',+ borderInlineEndWidth: 1,+ },+ filesFolded: {+ paddingInline: 4,+ width: 'auto',+ },+ filesHead: {+ paddingBlockEnd: 6,+ paddingBlockStart: 2,+ paddingInlineEnd: 0,+ paddingInlineStart: 8,+ },+ index: {+ paddingInline: 16,+ },+});++export interface SkillViewerProps {+ /** The skill's `SKILL.md`, frontmatter included. */+ content?: string;+ /** Identifies what the canvas shows, e.g. a skill id and its revision. */+ entityId: string;+ /**+ * The skill's other files, keyed by path. Passed, a rail lists them beside+ * `SKILL.md`; left out, the skill reads as its `SKILL.md` alone.+ */+ files?: readonly { content: string; path: string }[];+ /**+ * Which side the file tree sits on. At the start it runs the full height+ * beside the selected file, frontmatter included, the way a file browser+ * reads; at the end it is a rail beside the document. Defaults to the end.+ */+ filesPosition?: 'end' | 'start';+ /** A line above the frontmatter card, e.g. how this version came about. */+ notice?: ReactNode;+}++/**+ * A skill read the way the product reads a skill document: its frontmatter+ * card (folded — the instructions are what one comes to read), then the+ * selected file — `SKILL.md` on the same canvas documents render on,+ * read-only — and, when files are passed, the skill's file tree beside it.+ *+ * The caller loads the skill; this only presents it.+ */+const SkillViewer = ({+ content,+ entityId,+ files,+ filesPosition = 'end',+ notice,+}: SkillViewerProps) => {+ const { t } = useTranslation('chat');+ const editor = useEditor();+ const [selectedFile, setSelectedFile] = useState(SKILL_INDEX);+ const [filesOpen, setFilesOpen] = useState(true);+ const resourceTree = useMemo(() => skillFileTree(files), [files]);+ const contentMap = useMemo(+ () => Object.fromEntries((files ?? []).map((file) => [file.path, file.content])),+ [files],+ );++ const { body, frontmatter } = parseSkillMarkdownFrontmatter(content);++ const atStart = filesPosition === 'start';++ const intro = (notice || frontmatter) && (+ <Flexbox paddingInline={16} style={{ flex: 'none' }}>+ {notice}+ {frontmatter && <SkillFrontmatterCard defaultCollapsed frontmatter={frontmatter} />}+ </Flexbox>+ );++ // The skill's files: folds to a rail so the document can take the width.+ const fileTree = files && (+ <div+ data-skill-files={filesOpen ? 'open' : 'folded'}+ {...stylex.props(+ styles.files,+ atStart ? styles.filesAtStart : styles.filesAtEnd,+ !filesOpen && styles.filesFolded,+ )}+ >+ {filesOpen ? (+ <>+ <Flexbox+ horizontal+ align={'center'}+ justify={'space-between'}+ {...stylex.props(styles.filesHead)}+ >+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('skillViewer.files')}+ </Text>+ <ActionIcon+ icon={atStart ? PanelLeftCloseIcon : PanelRightCloseIcon}+ size={'small'}+ title={t('skillViewer.foldFiles')}+ onClick={() => setFilesOpen(false)}+ />+ </Flexbox>+ <FileTree+ resourceTree={resourceTree}+ selectedFile={selectedFile}+ onSelectFile={setSelectedFile}+ />+ </>+ ) : (+ <ActionIcon+ icon={atStart ? PanelLeftOpenIcon : PanelRightOpenIcon}+ size={'small'}+ title={t('skillViewer.unfoldFiles')}+ onClick={() => setFilesOpen(true)}+ />+ )}+ </div>+ );++ return (+ <Flexbox data-skill-viewer flex={1} style={{ minHeight: 0 }}>+ {!atStart && intro}+ <Flexbox horizontal flex={1} style={{ minHeight: 0 }}>+ {atStart && fileTree}+ <div {...stylex.props(styles.body)}>+ {atStart && intro}+ {selectedFile === SKILL_INDEX ? (+ <div {...stylex.props(styles.index)}>+ <EditorCanvas+ editable={false}+ editor={editor}+ editorData={{ content: body }}+ entityId={entityId}+ floatingToolbar={false}+ />+ </div>+ ) : (+ <ContentViewer contentMap={contentMap} key={selectedFile} selectedFile={selectedFile} />+ )}+ </div>+ {!atStart && fileTree}+ </Flexbox>+ </Flexbox>+ );+};++export default SkillViewer;diff --git a/src/features/SkillViewer/skillFileTree.test.ts b/src/features/SkillViewer/skillFileTree.test.tsnew file mode 100644index 00000000000..b15e16d4a4e--- /dev/null+++ b/src/features/SkillViewer/skillFileTree.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { skillFileTree } from './skillFileTree';++describe('skillFileTree', () => {+ it('nests a skill’s files into folders, folders first', () => {+ expect(+ skillFileTree([+ { content: 'b', path: 'scripts/rollback.sql' },+ { content: 'notes', path: 'README.md' },+ { content: 'a', path: 'scripts/check.sh' },+ ]),+ ).toEqual([+ {+ children: [+ { content: 'a', name: 'check.sh', path: 'scripts/check.sh', type: 'file' },+ { content: 'b', name: 'rollback.sql', path: 'scripts/rollback.sql', type: 'file' },+ ],+ name: 'scripts',+ path: 'scripts',+ type: 'directory',+ },+ { content: 'notes', name: 'README.md', path: 'README.md', type: 'file' },+ ]);+ });++ it('is empty for a skill with no files', () => {+ expect(skillFileTree(undefined)).toEqual([]);+ });+});diff --git a/src/features/SkillViewer/skillFileTree.ts b/src/features/SkillViewer/skillFileTree.tsnew file mode 100644index 00000000000..edb8f8f8a8b--- /dev/null+++ b/src/features/SkillViewer/skillFileTree.ts@@ -0,0 +1,36 @@+import type { SkillResourceTreeNode } from '@lobechat/types';++/**+ * A skill's files as the file tree takes them: `scripts/check.sh` becomes a+ * `scripts` folder holding `check.sh`. Folders first, then files, by name.+ * `SKILL.md` itself is the tree's root entry, not one of these.+ */+export const skillFileTree = (+ files: readonly { content: string; path: string }[] | null | undefined,+): SkillResourceTreeNode[] => {+ const root: SkillResourceTreeNode[] = [];+ for (const file of files ?? []) {+ const parts = file.path.split('/').filter(Boolean);+ let level = root;+ parts.forEach((name, index) => {+ const path = parts.slice(0, index + 1).join('/');+ if (index === parts.length - 1) {+ level.push({ content: file.content, name, path, type: 'file' });+ return;+ }+ let folder = level.find((node) => node.type === 'directory' && node.name === name);+ if (!folder) {+ folder = { children: [], name, path, type: 'directory' };+ level.push(folder);+ }+ level = folder.children!;+ });+ }+ const sort = (nodes: SkillResourceTreeNode[]): SkillResourceTreeNode[] =>+ nodes+ .map((node) => (node.children ? { ...node, children: sort(node.children) } : node))+ .sort((a, b) =>+ a.type === b.type ? a.name.localeCompare(b.name) : a.type === 'directory' ? -1 : 1,+ );+ return sort(root);+};diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.tsindex 693058ec467..f6445e14a0b 100644--- a/src/services/agentDocument.ts+++ b/src/services/agentDocument.ts@@ -81,6 +81,11 @@ class AgentDocumentService {return lambdaClient.agentDocument.getReaderDocument.query(params);};+ /** A managed skill and its `SKILL.md`; `null` once it no longer exists. */+ getSkill = async (params: { agentDocumentId: string; agentId: string }) => {+ return lambdaClient.agentDocument.getSkill.query(params);+ };+associateDocument = async (params: { agentId: string; documentId: string }) => {const result = await lambdaClient.agentDocument.associateDocument.mutate(params);await invalidateDocumentMutation({