🤯 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
✨ feat(dashboard): card-first widget approvals, board settings, in-place editing and shared don't-ask-again (#21600)
LiJian4215d3865131
diff --git a/apps/server/src/routers/lambda/widget.ts b/apps/server/src/routers/lambda/widget.tsindex 735b76144d7..50e7a31ce0e 100644--- a/apps/server/src/routers/lambda/widget.ts+++ b/apps/server/src/routers/lambda/widget.ts@@ -318,6 +318,21 @@ export const widgetRouter = router({}}),+ /**+ * From the dry-run approval card: stop asking before dry runs that need no+ * more access than this version (its connectors and hosts, on its level).+ */+ grantDryRunAccess: widgetWriteProcedure+ .input(z.object({ versionId: uuid, widgetId: uuid }))+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetService.grantDryRunAccess(input.widgetId, input.versionId);+ return { data, success: true };+ } catch (error) {+ fail(error, 'grant dry-run access');+ }+ }),+/** Set (cron pattern) or clear (null) the refresh schedule. */setSchedule: widgetWriteProcedure.input(diff --git a/apps/server/src/services/widget/__tests__/dryRunAudit.test.ts b/apps/server/src/services/widget/__tests__/dryRunAudit.test.tsindex a8cbae95a58..425c13dabff 100644--- a/apps/server/src/services/widget/__tests__/dryRunAudit.test.ts+++ b/apps/server/src/services/widget/__tests__/dryRunAudit.test.ts@@ -5,9 +5,11 @@ import { getTestDB } from '@lobechat/database/test-utils';import { inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { UserModel } from '@/database/models/user';import { WidgetModel } from '@/database/models/widget';import { createWidgetDryRunAudit } from '../dryRunAudit';+import { WidgetService } from '../index';const userId = 'dry-run-audit-user';const otherUserId = 'dry-run-audit-other';@@ -62,4 +64,40 @@ describe('createWidgetDryRunAudit', () => {const foreign = await draftOf(otherUserId, null);expect(await createWidgetDryRunAudit(db, userId)(foreign)).toBe(true);});++ it('stops asking once the creator granted that access, and only for that access', async () => {+ const githubManifest = {+ env: [{ connector: 'github', name: 'GITHUB_TOKEN' }],+ network: { allow: ['api.github.com'] },+ };+ const approved = await draftOf(userId, githubManifest);+ const grant = await new WidgetService(db, userId).grantDryRunAccess(+ approved.widgetId,+ approved.versionId,+ );+ expect(grant).toMatchObject({+ connectors: ['github'],+ hosts: ['api.github.com'],+ workspaceId: null,+ });++ const audit = createWidgetDryRunAudit(db, userId);+ // Another widget asking for the same access runs unattended…+ expect(await audit(await draftOf(userId, githubManifest))).toBe(false);+ // …but one more host asks again.+ const wider = await draftOf(userId, {+ ...githubManifest,+ network: { allow: ['api.github.com', 'evil.example'] },+ });+ expect(await audit(wider)).toBe(true);+ });++ it('refuses a grant from someone who cannot author the widget', async () => {+ const foreign = await draftOf(otherUserId, { network: { allow: ['api.github.com'] } });+ await expect(+ new WidgetService(db, userId).grantDryRunAccess(foreign.widgetId, foreign.versionId),+ ).rejects.toThrow();+ const settings = await new UserModel(db, userId).getUserSettings();+ expect(settings?.tool).toBeFalsy();+ });});diff --git a/apps/server/src/services/widget/dryRunAudit.ts b/apps/server/src/services/widget/dryRunAudit.tsindex 6ad8a4ee141..781f8deb0a7 100644--- a/apps/server/src/services/widget/dryRunAudit.ts+++ b/apps/server/src/services/widget/dryRunAudit.ts@@ -1,13 +1,15 @@import { createDryRunAudit } from '@lobechat/builtin-tool-dashboard';-import type { DynamicInterventionResolver } from '@lobechat/types';+import type { DynamicInterventionResolver, UserToolConfig } from '@lobechat/types';+import { UserModel } from '@/database/models/user';import { WidgetModel } from '@/database/models/widget';import type { LobeChatDatabase } from '@/database/type';/*** The `dryRunWidget` approval audit for a server agent run: reads the exact* version the call names, as the run's user, and asks for approval when it- * declares connector credentials or network hosts. Unreadable → approval.+ * declares connector credentials or network hosts that none of the user's+ * standing grants covers. Unreadable → approval.*/export const createWidgetDryRunAudit = (db: LobeChatDatabase,@@ -15,7 +17,12 @@ export const createWidgetDryRunAudit = (workspaceId?: string,): DynamicInterventionResolver => {const widgets = new WidgetModel(db, userId, workspaceId);+ const users = new UserModel(db, userId);return createDryRunAudit({+ loadGrants: async () => {+ const settings = await users.getUserSettings();+ return (settings?.tool as UserToolConfig | null | undefined)?.widgetDryRunGrants;+ },loadVersion: async (widgetId, versionId) => widgets.findVersion(widgetId, versionId),});};diff --git a/apps/server/src/services/widget/index.ts b/apps/server/src/services/widget/index.tsindex 4e2f52fb80d..1cddabfbc33 100644--- a/apps/server/src/services/widget/index.ts+++ b/apps/server/src/services/widget/index.ts@@ -1,5 +1,8 @@+import { dryRunAccessOf } from '@lobechat/builtin-tool-dashboard';+import type { WidgetDryRunGrant } from '@lobechat/types';import { validateCronPattern } from '@lobechat/utils/cronEval';+import { UserModel } from '@/database/models/user';import { type CreateWidgetVersionInput, WidgetModel } from '@/database/models/widget';import type { LobeChatDatabase } from '@/database/type';@@ -182,6 +185,31 @@ export class WidgetService {* Set or clear the refresh schedule. The next due instant is computed from* the pattern; scheduled runs only fire once a version is published.*/+ /**+ * Stop asking before dry runs that need no more access than this version:+ * record its connectors and hosts as a standing grant at the version's own+ * level. The access is read from the stored version, never taken from the+ * caller, so the grant is exactly what the approval card showed. Only the+ * widget's creator — the one who reviews its dry runs — may grant.+ */+ async grantDryRunAccess(+ widgetId: string,+ versionId: string,+ ): Promise<WidgetDryRunGrant | undefined> {+ await this.requireManageable(widgetId);+ const version = await this.requireVersion(widgetId, versionId);+ const access = dryRunAccessOf(version.manifest);+ if (access.connectors.length === 0 && access.hosts.length === 0) return undefined;++ const grant: WidgetDryRunGrant = {+ ...access,+ grantedAt: new Date().toISOString(),+ workspaceId: version.workspaceId ?? null,+ };+ await new UserModel(this.db, this.userId).appendWidgetDryRunGrant(grant);+ return grant;+ }+async setSchedule(widgetId: string, pattern: string | null, timezone?: string | null) {await this.requireManageable(widgetId);diff --git a/locales/ar/dashboard.json b/locales/ar/dashboard.jsonindex 996a545ce9b..747365ed508 100644--- a/locales/ar/dashboard.json+++ b/locales/ar/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "المزيد من الإجراءات",- "actions.rename": "إعادة تسمية","actions.trash": "نقل إلى المهملات","actions.trashConfirm": "سيتم نقل \"{{title}}\" وتخطيطه إلى المهملات. ستظل الأدوات متاحة وتحافظ على تاريخها.","actions.trashTitle": "نقل لوحة التحكم هذه إلى المهملات؟","actions.trashed": "تم نقل \"{{title}}\" إلى المهملات",- "board.empty": "لا توجد أدوات حتى الآن. اطلب من وكيل في محادثة إنشاء أداة مراقبة وإضافتها إلى لوحة التحكم هذه.","board.health.failed": "{{count}} فشل","board.health.ok": "{{count}} محدث","board.health.running": "{{count}} يتم تحديثه",@@ -56,7 +54,6 @@"detail.versionNone": "غير منشور","detail.versionPublished": "v{{version}} مباشر","dryRun.intro": "يريد الوكيل تشغيل هذه المسودة مرة واحدة لمعاينة نتائجها. يتم تشغيلها في بيئة تجريبية مع الوصول أدناه؛ لا شيء يصبح مباشرًا ولا يتم تغيير لوحة التحكم.",- "dryRun.runtime": "وقت التشغيل","error.hideDetails": "إخفاء التفاصيل","error.showDetails": "عرض التفاصيل","form.descriptionLabel": "الوصف",@@ -66,13 +63,9 @@"layout.cancel": "تجاهل التغييرات","layout.drag": "اسحب لإعادة الترتيب","layout.edit": "تعديل التخطيط",- "layout.narrower": "أضيق","layout.save": "حفظ التخطيط","layout.saveFailed": "تعذر حفظ التخطيط. تم استعادة التخطيط السابق.","layout.saved": "تم حفظ التخطيط",- "layout.shorter": "أقصر",- "layout.taller": "أطول",- "layout.wider": "أعرض","list.description": "لوحات أدوات مباشرة. كل أداة تشغل نصها الخاص وفقًا لجدول وتحافظ على تاريخها.","list.empty": "لا توجد لوحات تحكم حتى الآن","list.noDescription": "لا يوجد وصف",@@ -103,12 +96,10 @@"publish.networkNone": "لا يوجد وصول إلى الشبكة","publish.networkUnrestricted": "لا يمكن للبيئة التجريبية تقييد الوصول إلى المضيفين المدرجين — يمكن للنص الوصول إلى أي مضيف، بما في ذلك المضيفين الذين لم يعلن عنهم.","publish.noSuccessfulRun": "لم تنجح هذه المسودة في تشغيل تجريبي حتى الآن، لذا سيتم رفض نشرها.",- "publish.previewTitle": "أحدث تشغيل تجريبي","publish.schedule": "التحديث","publish.scheduleNone": "يدوي فقط","publish.scriptChanges": "التغييرات من الإصدار المباشر v{{version}}","publish.scriptNew": "النص",- "rename.title": "إعادة تسمية لوحة التحكم","review.loadFailed": "تعذر تحميل المراجعة، لذا الموافقة معلقة","review.versionMissing": "هذا الإصدار لم يعد متاحًا، لذا لا يمكن مراجعته. رفض الطلب واطلب من الوكيل المحاولة مرة أخرى.","run.empty": "هذه الأداة لم يتم تشغيلها بعد.",diff --git a/locales/bg-BG/dashboard.json b/locales/bg-BG/dashboard.jsonindex a345dbedc01..98dcb2574f7 100644--- a/locales/bg-BG/dashboard.json+++ b/locales/bg-BG/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Още действия",- "actions.rename": "Преименуване","actions.trash": "Премести в кошчето","actions.trashConfirm": "\"{{title}}\" и неговото оформление ще бъдат преместени в кошчето. Уиджетите ще останат налични и ще запазят историята си.","actions.trashTitle": "Да преместите ли това табло в кошчето?","actions.trashed": "\"{{title}}\" беше преместено в кошчето",- "board.empty": "Все още няма уиджети. Помолете агент в разговор да създаде уиджет за мониторинг и да го добави към това табло.","board.health.failed": "{{count}} неуспешни","board.health.ok": "{{count}} актуални","board.health.running": "{{count}} обновявания",@@ -56,7 +54,6 @@"detail.versionNone": "Не е публикувано","detail.versionPublished": "v{{version}} на живо","dryRun.intro": "Агентът иска да изпълни тази чернова веднъж, за да прегледа изхода ѝ. Тя се изпълнява в пясъчник с долупосочения достъп; нищо няма да бъде публикувано и таблото няма да бъде променено.",- "dryRun.runtime": "Време за изпълнение","error.hideDetails": "Скрий детайлите","error.showDetails": "Покажи детайлите","form.descriptionLabel": "Описание",@@ -66,13 +63,9 @@"layout.cancel": "Откажи промените","layout.drag": "Премести за пренареждане","layout.edit": "Редактирай оформление",- "layout.narrower": "По-тясно","layout.save": "Запази оформление","layout.saveFailed": "Неуспешно запазване на оформлението. Предишното оформление е възстановено.","layout.saved": "Оформлението е запазено",- "layout.shorter": "По-ниско",- "layout.taller": "По-високо",- "layout.wider": "По-широко","list.description": "Табла с активни уиджети. Всеки уиджет изпълнява свой собствен скрипт по график и запазва историята си.","list.empty": "Все още няма табла","list.noDescription": "Няма описание",@@ -103,12 +96,10 @@"publish.networkNone": "Няма достъп до мрежата","publish.networkUnrestricted": "Пясъчникът не може да ограничи изходящия трафик към изброените хостове — скриптът може да достигне до всеки хост, включително и до такива, които не са декларирани.","publish.noSuccessfulRun": "Тази чернова все още не е успяла в тестов режим, така че публикуването ѝ ще бъде отказано.",- "publish.previewTitle": "Последен тестов режим","publish.schedule": "Обновяване","publish.scheduleNone": "Само ръчно","publish.scriptChanges": "Промени от активна v{{version}}","publish.scriptNew": "Скрипт",- "rename.title": "Преименуване на табло","review.loadFailed": "Неуспешно зареждане на прегледа, одобрението е задържано","review.versionMissing": "Тази версия вече не е налична, така че не може да бъде прегледана. Отхвърлете заявката и помолете агента да опита отново.","run.empty": "Този уиджет все още не е изпълнен.",diff --git a/locales/de-DE/dashboard.json b/locales/de-DE/dashboard.jsonindex 40c497a7664..43f3422935f 100644--- a/locales/de-DE/dashboard.json+++ b/locales/de-DE/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Weitere Aktionen",- "actions.rename": "Umbenennen","actions.trash": "In den Papierkorb verschieben","actions.trashConfirm": "\"{{title}}\" und sein Layout werden in den Papierkorb verschoben. Widgets bleiben verfügbar und behalten ihre Historie.","actions.trashTitle": "Dieses Dashboard in den Papierkorb verschieben?","actions.trashed": "\"{{title}}\" wurde in den Papierkorb verschoben",- "board.empty": "Noch keine Widgets. Bitten Sie einen Agenten in einem Gespräch, ein Überwachungs-Widget zu erstellen und es zu diesem Dashboard hinzuzufügen.","board.health.failed": "{{count}} fehlgeschlagen","board.health.ok": "{{count}} auf dem neuesten Stand","board.health.running": "{{count}} wird aktualisiert",@@ -56,7 +54,6 @@"detail.versionNone": "Nicht veröffentlicht","detail.versionPublished": "v{{version}} live","dryRun.intro": "Der Agent möchte diesen Entwurf einmal ausführen, um seine Ausgabe vorzuschauen. Er wird in einer Sandbox mit den unten aufgeführten Zugriffsrechten ausgeführt; nichts wird live geschaltet und keine Dashboard-Änderungen vorgenommen.",- "dryRun.runtime": "Laufzeit","error.hideDetails": "Details ausblenden","error.showDetails": "Details anzeigen","form.descriptionLabel": "Beschreibung",@@ -66,13 +63,9 @@"layout.cancel": "Änderungen verwerfen","layout.drag": "Zum Neuordnen ziehen","layout.edit": "Layout bearbeiten",- "layout.narrower": "Schmaler","layout.save": "Layout speichern","layout.saveFailed": "Das Layout konnte nicht gespeichert werden. Das vorherige Layout wurde wiederhergestellt.","layout.saved": "Layout gespeichert",- "layout.shorter": "Kürzer",- "layout.taller": "Höher",- "layout.wider": "Breiter","list.description": "Boards mit Live-Widgets. Jedes Widget führt sein eigenes Skript nach einem Zeitplan aus und speichert seine Historie.","list.empty": "Noch keine Dashboards","list.noDescription": "Keine Beschreibung",@@ -103,12 +96,10 @@"publish.networkNone": "Kein Netzwerkzugriff","publish.networkUnrestricted": "Die Sandbox kann den Ausgang zu den aufgeführten Hosts nicht einschränken — das Skript kann jeden Host erreichen, einschließlich solcher, die es nicht deklariert hat.","publish.noSuccessfulRun": "Dieser Entwurf war in einem Testlauf noch nicht erfolgreich, daher wird die Veröffentlichung verweigert.",- "publish.previewTitle": "Letzter Testlauf","publish.schedule": "Aktualisieren","publish.scheduleNone": "Nur manuell","publish.scriptChanges": "Änderungen von Live v{{version}}","publish.scriptNew": "Skript",- "rename.title": "Dashboard umbenennen","review.loadFailed": "Die Überprüfung konnte nicht geladen werden, daher ist die Genehmigung ausgesetzt","review.versionMissing": "Diese Version ist nicht mehr verfügbar, daher kann sie nicht überprüft werden. Lehnen Sie die Anfrage ab und bitten Sie den Agenten, es erneut zu versuchen.","run.empty": "Dieses Widget wurde noch nicht ausgeführt.",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex b008026a8fd..05d568860c2 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2732,7 +2732,7 @@"tool.intervention.mode.autoRun": "Auto Approve","tool.intervention.mode.autoRunDesc": "Automatically approve all tool executions","tool.intervention.mode.manual": "Manual",- "tool.intervention.mode.manualDesc": "Manual approval required for each invocation",+ "tool.intervention.mode.manualDesc": "Asks before each invocation, except actions you chose not to be asked about again","tool.intervention.onboarding.agentIdentity.editHint": "You can edit the name or avatar directly below.","tool.intervention.onboarding.agentIdentity.namePlaceholder": "Agent name","tool.intervention.onboarding.agentIdentity.title": "I'll update my name and avatar",diff --git a/locales/en-US/dashboard.json b/locales/en-US/dashboard.jsonindex ec89cdff732..c7095393d7b 100644--- a/locales/en-US/dashboard.json+++ b/locales/en-US/dashboard.json@@ -1,11 +1,19 @@{"actions.more": "More actions",- "actions.rename": "Rename",+ "actions.settings": "Settings","actions.trash": "Move to trash","actions.trashConfirm": "\"{{title}}\" and its layout will move to the trash. Widgets stay available and keep their history.","actions.trashTitle": "Move this dashboard to the trash?","actions.trashed": "\"{{title}}\" moved to the trash",- "board.empty": "No widgets yet. Ask an agent in a conversation to build a monitoring widget and add it to this dashboard.",+ "board.emptyAction": "Ask an agent to build a widget",+ "board.emptyAgentUnavailable": "Couldn't open the agent. Try again in a moment.",+ "board.emptyDescription": "A widget is a small script that runs on a schedule and shows its result as a card here. Ask an agent to write and dry-run one for you; it goes live only after you approve it.",+ "board.emptyKind.list": "List",+ "board.emptyKind.series": "Trend",+ "board.emptyKind.stat": "Number",+ "board.emptyKind.table": "Table",+ "board.emptyPrompt": "Build a monitoring widget and put it on the dashboard \"{{title}}\". I want to see: ",+ "board.emptyTitle": "This dashboard has no widgets yet","board.health.failed": "{{count}} failed","board.health.ok": "{{count}} up to date","board.health.running": "{{count}} refreshing",@@ -56,7 +64,7 @@"detail.versionNone": "Not published","detail.versionPublished": "v{{version}} live","dryRun.intro": "The agent wants to run this draft once to preview its output. It runs in a sandbox with the access below; nothing goes live and no dashboard changes.",- "dryRun.runtime": "Runtime",+ "dryRun.rememberFailed": "Approved, but this access couldn't be remembered. You'll be asked again next time.","error.hideDetails": "Hide details","error.showDetails": "Show details","form.descriptionLabel": "Description",@@ -65,14 +73,11 @@"form.titlePlaceholder": "e.g. Open-source project health","layout.cancel": "Discard changes","layout.drag": "Drag to reorder",- "layout.edit": "Edit layout",- "layout.narrower": "Narrower",+ "layout.edit": "Edit dashboard",+ "layout.resize": "Drag to resize (or use the arrow keys)","layout.save": "Save layout","layout.saveFailed": "Could not save the layout. The previous layout is restored.","layout.saved": "Layout saved",- "layout.shorter": "Shorter",- "layout.taller": "Taller",- "layout.wider": "Wider","list.description": "Boards of live widgets. Each widget runs its own script on a schedule and keeps its history.","list.empty": "No dashboards yet","list.noDescription": "No description",@@ -102,13 +107,19 @@"publish.network": "Network","publish.networkNone": "No network access","publish.noSuccessfulRun": "This draft has not succeeded in a dry run yet, so publishing it will be refused.",- "publish.previewTitle": "Latest dry run","publish.schedule": "Refresh","publish.scheduleNone": "Manual only","publish.scriptChanges": "Changes from live v{{version}}","publish.scriptNew": "Script",- "rename.title": "Rename dashboard",+ "review.expected": "What it will look like",+ "review.expectedEarlier": "for reference, v{{version}}'s last result; approving runs this draft to make its own",+ "review.expectedSameVersion": "from this version's last dry run",+ "review.expectedSample": "sample data showing the card it will make; approving produces the real result","review.loadFailed": "Couldn't load the review, so approval is on hold",+ "review.sampleItem": "Sample item {{index}}",+ "review.sampleName": "Name",+ "review.sampleTag": "Sample",+ "review.sampleValue": "Value","review.versionMissing": "This version is no longer available, so it can't be reviewed. Reject the request and ask the agent to try again.","run.empty": "This widget has not run yet.","run.error": "Error",@@ -122,6 +133,29 @@"run.trigger.manual": "Manual","run.trigger.preview": "Preview","run.trigger.schedule": "Scheduled",+ "schedule.daily9": "Daily at 09:00",+ "schedule.every15m": "Every 15 minutes",+ "schedule.every30m": "Every 30 minutes",+ "schedule.every6h": "Every 6 hours",+ "schedule.hourly": "Every hour",+ "schedule.manual": "Manual refresh only",+ "settings.saved": "Settings saved",+ "settings.schedule": "Widget refresh",+ "settings.scheduleFailed_one": "Settings saved, but {{count}} widget's refresh could not be changed",+ "settings.scheduleFailed_other": "Settings saved, but {{count}} widgets' refresh could not be changed",+ "settings.scheduleHint_one": "Applies to the {{count}} widget you created on this dashboard.",+ "settings.scheduleHint_other": "Applies to the {{count}} widgets you created on this dashboard.",+ "settings.scheduleKeep": "Keep each widget's current refresh",+ "settings.scheduleKeepCustom": "Keep current ({{pattern}})",+ "settings.scheduleNoWidgets": "No widgets on this dashboard yet.",+ "settings.scheduleNotOwner": "Only a widget's creator can change its refresh, and you created none of the widgets here.",+ "settings.scheduleOthers_one": "{{count}} widget created by others keeps its own refresh.",+ "settings.scheduleOthers_other": "{{count}} widgets created by others keep their own refresh.",+ "settings.title": "Dashboard settings",+ "settings.visibility": "Who can see it",+ "settings.visibilityKeptPrivate": "Saved. The dashboard stays visible only to you because its project is private.",+ "settings.visibilityPrivate": "Only me",+ "settings.visibilityPublic": "Workspace members","version.empty": "No versions yet.","version.publishedAt": "Published {{time}}","version.script": "Script",@@ -151,5 +185,10 @@"widget.view.listEmpty": "No items","widget.view.more": "+{{count}} more","widget.view.seriesEmpty": "No data points",- "widget.view.tableEmpty": "No rows"+ "widget.view.tableEmpty": "No rows",+ "widgetEdit.action": "Edit widget",+ "widgetEdit.descriptionPlaceholder": "Data source, filters, time window and unit",+ "widgetEdit.saved": "Widget updated",+ "widgetEdit.title": "Edit widget",+ "widgetEdit.titleLabel": "Title"}diff --git a/locales/es-ES/dashboard.json b/locales/es-ES/dashboard.jsonindex abf33a969e6..b36578ffa00 100644--- a/locales/es-ES/dashboard.json+++ b/locales/es-ES/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Más acciones",- "actions.rename": "Renombrar","actions.trash": "Mover a la papelera","actions.trashConfirm": "\"{{title}}\" y su diseño se moverán a la papelera. Los widgets permanecen disponibles y conservan su historial.","actions.trashTitle": "¿Mover este tablero a la papelera?","actions.trashed": "\"{{title}}\" se movió a la papelera",- "board.empty": "Aún no hay widgets. Pide a un agente en una conversación que cree un widget de monitoreo y lo agregue a este tablero.","board.health.failed": "{{count}} fallidos","board.health.ok": "{{count}} actualizados","board.health.running": "{{count}} actualizándose",@@ -56,7 +54,6 @@"detail.versionNone": "No publicado","detail.versionPublished": "v{{version}} en vivo","dryRun.intro": "El agente quiere ejecutar este borrador una vez para previsualizar su salida. Se ejecuta en un entorno de prueba con los accesos a continuación; nada se publica y no se realizan cambios en el tablero.",- "dryRun.runtime": "Tiempo de ejecución","error.hideDetails": "Ocultar detalles","error.showDetails": "Mostrar detalles","form.descriptionLabel": "Descripción",@@ -66,13 +63,9 @@"layout.cancel": "Descartar cambios","layout.drag": "Arrastrar para reordenar","layout.edit": "Editar diseño",- "layout.narrower": "Más estrecho","layout.save": "Guardar diseño","layout.saveFailed": "No se pudo guardar el diseño. Se restauró el diseño anterior.","layout.saved": "Diseño guardado",- "layout.shorter": "Más corto",- "layout.taller": "Más alto",- "layout.wider": "Más ancho","list.description": "Tableros de widgets en vivo. Cada widget ejecuta su propio script según una programación y conserva su historial.","list.empty": "Aún no hay tableros","list.noDescription": "Sin descripción",@@ -103,12 +96,10 @@"publish.networkNone": "Sin acceso a la red","publish.networkUnrestricted": "El entorno de prueba no puede restringir el acceso a los hosts listados; el script puede acceder a cualquier host, incluidos aquellos que no declaró.","publish.noSuccessfulRun": "Este borrador aún no ha tenido éxito en una prueba, por lo que no se puede publicar.",- "publish.previewTitle": "Última prueba","publish.schedule": "Actualizar","publish.scheduleNone": "Solo manual","publish.scriptChanges": "Cambios desde la versión en vivo v{{version}}","publish.scriptNew": "Script",- "rename.title": "Renombrar tablero","review.loadFailed": "No se pudo cargar la revisión, por lo que la aprobación está en espera","review.versionMissing": "Esta versión ya no está disponible, por lo que no se puede revisar. Rechaza la solicitud y pide al agente que lo intente de nuevo.","run.empty": "Este widget aún no se ha ejecutado.",diff --git a/locales/fa-IR/dashboard.json b/locales/fa-IR/dashboard.jsonindex e5666a084e6..63ac8fd3b68 100644--- a/locales/fa-IR/dashboard.json+++ b/locales/fa-IR/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "اقدامات بیشتر",- "actions.rename": "تغییر نام","actions.trash": "انتقال به زبالهدان","actions.trashConfirm": "«{{title}}» و طرحبندی آن به زبالهدان منتقل خواهد شد. ویجتها در دسترس باقی میمانند و تاریخچه خود را حفظ میکنند.","actions.trashTitle": "آیا این داشبورد به زبالهدان منتقل شود؟","actions.trashed": "«{{title}}» به زبالهدان منتقل شد",- "board.empty": "هنوز هیچ ویجتی وجود ندارد. از یک عامل در یک مکالمه بخواهید یک ویجت نظارتی بسازد و به این داشبورد اضافه کند.","board.health.failed": "{{count}} شکست خورده","board.health.ok": "{{count}} بهروز","board.health.running": "{{count}} در حال بهروزرسانی",@@ -56,7 +54,6 @@"detail.versionNone": "منتشر نشده","detail.versionPublished": "نسخه {{version}} زنده","dryRun.intro": "عامل میخواهد این پیشنویس را یک بار اجرا کند تا خروجی آن را پیشنمایش دهد. این اجرا در یک محیط آزمایشی با دسترسیهای زیر انجام میشود؛ هیچ چیزی زنده نمیشود و هیچ تغییری در داشبورد ایجاد نمیشود.",- "dryRun.runtime": "زمان اجرا","error.hideDetails": "پنهان کردن جزئیات","error.showDetails": "نمایش جزئیات","form.descriptionLabel": "توضیحات",@@ -66,13 +63,9 @@"layout.cancel": "لغو تغییرات","layout.drag": "برای تغییر ترتیب بکشید","layout.edit": "ویرایش طرحبندی",- "layout.narrower": "باریکتر","layout.save": "ذخیره طرحبندی","layout.saveFailed": "نتوانستیم طرحبندی را ذخیره کنیم. طرحبندی قبلی بازیابی شد.","layout.saved": "طرحبندی ذخیره شد",- "layout.shorter": "کوتاهتر",- "layout.taller": "بلندتر",- "layout.wider": "عریضتر","list.description": "تختههایی از ویجتهای زنده. هر ویجت اسکریپت خود را طبق برنامه زمانی اجرا میکند و تاریخچه خود را نگه میدارد.","list.empty": "هنوز هیچ داشبوردی وجود ندارد","list.noDescription": "بدون توضیحات",@@ -103,12 +96,10 @@"publish.networkNone": "بدون دسترسی به شبکه","publish.networkUnrestricted": "محیط آزمایشی نمیتواند خروجی به میزبانهای فهرستشده را محدود کند — اسکریپت میتواند به هر میزبانی، از جمله آنهایی که اعلام نشدهاند، دسترسی پیدا کند.","publish.noSuccessfulRun": "این پیشنویس هنوز در یک اجرای آزمایشی موفق نبوده است، بنابراین انتشار آن رد خواهد شد.",- "publish.previewTitle": "آخرین اجرای آزمایشی","publish.schedule": "تازهسازی","publish.scheduleNone": "فقط دستی","publish.scriptChanges": "تغییرات از نسخه زنده {{version}}","publish.scriptNew": "اسکریپت",- "rename.title": "تغییر نام داشبورد","review.loadFailed": "نتوانستیم بررسی را بارگذاری کنیم، بنابراین تأیید به تعویق افتاده است","review.versionMissing": "این نسخه دیگر در دسترس نیست، بنابراین نمیتوان آن را بررسی کرد. درخواست را رد کنید و از عامل بخواهید دوباره تلاش کند.","run.empty": "این ویجت هنوز اجرا نشده است.",diff --git a/locales/fr-FR/dashboard.json b/locales/fr-FR/dashboard.jsonindex 7968da0944c..c26c94456cf 100644--- a/locales/fr-FR/dashboard.json+++ b/locales/fr-FR/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Plus d'actions",- "actions.rename": "Renommer","actions.trash": "Déplacer à la corbeille","actions.trashConfirm": "\"{{title}}\" et sa mise en page seront déplacés à la corbeille. Les widgets restent disponibles et conservent leur historique.","actions.trashTitle": "Déplacer ce tableau de bord à la corbeille ?","actions.trashed": "\"{{title}}\" a été déplacé à la corbeille",- "board.empty": "Pas encore de widgets. Demandez à un agent dans une conversation de créer un widget de surveillance et de l'ajouter à ce tableau de bord.","board.health.failed": "{{count}} échoué","board.health.ok": "{{count}} à jour","board.health.running": "{{count}} en cours de rafraîchissement",@@ -56,7 +54,6 @@"detail.versionNone": "Non publié","detail.versionPublished": "v{{version}} en direct","dryRun.intro": "L'agent souhaite exécuter ce brouillon une fois pour prévisualiser son résultat. Il s'exécute dans un bac à sable avec les accès ci-dessous ; rien ne sera mis en ligne et aucun changement ne sera apporté au tableau de bord.",- "dryRun.runtime": "Durée d'exécution","error.hideDetails": "Masquer les détails","error.showDetails": "Afficher les détails","form.descriptionLabel": "Description",@@ -66,13 +63,9 @@"layout.cancel": "Annuler les modifications","layout.drag": "Glisser pour réorganiser","layout.edit": "Modifier la mise en page",- "layout.narrower": "Plus étroit","layout.save": "Enregistrer la mise en page","layout.saveFailed": "Impossible d'enregistrer la mise en page. La mise en page précédente est restaurée.","layout.saved": "Mise en page enregistrée",- "layout.shorter": "Plus court",- "layout.taller": "Plus haut",- "layout.wider": "Plus large","list.description": "Tableaux de widgets en direct. Chaque widget exécute son propre script selon un calendrier et conserve son historique.","list.empty": "Pas encore de tableaux de bord","list.noDescription": "Pas de description",@@ -103,12 +96,10 @@"publish.networkNone": "Aucun accès réseau","publish.networkUnrestricted": "Le bac à sable ne peut pas restreindre les sorties vers les hôtes listés — le script peut atteindre n'importe quel hôte, y compris ceux qu'il n'a pas déclarés.","publish.noSuccessfulRun": "Ce brouillon n'a pas encore réussi une exécution à blanc, donc sa publication sera refusée.",- "publish.previewTitle": "Dernière exécution à blanc","publish.schedule": "Rafraîchir","publish.scheduleNone": "Manuel uniquement","publish.scriptChanges": "Modifications par rapport à la version en direct v{{version}}","publish.scriptNew": "Script",- "rename.title": "Renommer le tableau de bord","review.loadFailed": "Impossible de charger la révision, donc l'approbation est en attente","review.versionMissing": "Cette version n'est plus disponible, donc elle ne peut pas être révisée. Rejetez la demande et demandez à l'agent de réessayer.","run.empty": "Ce widget n'a pas encore été exécuté.",diff --git a/locales/it-IT/dashboard.json b/locales/it-IT/dashboard.jsonindex 116dc0e2f2f..ca5eb36c559 100644--- a/locales/it-IT/dashboard.json+++ b/locales/it-IT/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Altre azioni",- "actions.rename": "Rinomina","actions.trash": "Sposta nel cestino","actions.trashConfirm": "\"{{title}}\" e il suo layout saranno spostati nel cestino. I widget rimangono disponibili e mantengono la loro cronologia.","actions.trashTitle": "Spostare questa dashboard nel cestino?","actions.trashed": "\"{{title}}\" spostato nel cestino",- "board.empty": "Nessun widget ancora. Chiedi a un agente in una conversazione di creare un widget di monitoraggio e aggiungerlo a questa dashboard.","board.health.failed": "{{count}} non riusciti","board.health.ok": "{{count}} aggiornati","board.health.running": "{{count}} in aggiornamento",@@ -56,7 +54,6 @@"detail.versionNone": "Non pubblicato","detail.versionPublished": "v{{version}} live","dryRun.intro": "L'agente vuole eseguire questa bozza una volta per visualizzarne l'output. Viene eseguita in un sandbox con i seguenti accessi; nulla va live e nessuna modifica viene apportata alla dashboard.",- "dryRun.runtime": "Runtime","error.hideDetails": "Nascondi dettagli","error.showDetails": "Mostra dettagli","form.descriptionLabel": "Descrizione",@@ -66,13 +63,9 @@"layout.cancel": "Annulla modifiche","layout.drag": "Trascina per riordinare","layout.edit": "Modifica layout",- "layout.narrower": "Più stretto","layout.save": "Salva layout","layout.saveFailed": "Impossibile salvare il layout. Il layout precedente è stato ripristinato.","layout.saved": "Layout salvato",- "layout.shorter": "Più corto",- "layout.taller": "Più alto",- "layout.wider": "Più largo","list.description": "Bacheche di widget live. Ogni widget esegue il proprio script secondo un programma e mantiene la sua cronologia.","list.empty": "Nessuna dashboard ancora","list.noDescription": "Nessuna descrizione",@@ -103,12 +96,10 @@"publish.networkNone": "Nessun accesso alla rete","publish.networkUnrestricted": "Il sandbox non può limitare l'uscita agli host elencati — lo script può raggiungere qualsiasi host, inclusi quelli non dichiarati.","publish.noSuccessfulRun": "Questa bozza non è ancora riuscita in un'esecuzione di prova, quindi la pubblicazione sarà rifiutata.",- "publish.previewTitle": "Ultima esecuzione di prova","publish.schedule": "Aggiorna","publish.scheduleNone": "Solo manuale","publish.scriptChanges": "Modifiche dalla versione live v{{version}}","publish.scriptNew": "Script",- "rename.title": "Rinomina dashboard","review.loadFailed": "Impossibile caricare la revisione, quindi l'approvazione è in sospeso","review.versionMissing": "Questa versione non è più disponibile, quindi non può essere revisionata. Rifiuta la richiesta e chiedi all'agente di riprovare.","run.empty": "Questo widget non è ancora stato eseguito.",diff --git a/locales/ja-JP/dashboard.json b/locales/ja-JP/dashboard.jsonindex 96ddf251baf..45215012a4c 100644--- a/locales/ja-JP/dashboard.json+++ b/locales/ja-JP/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "その他のアクション",- "actions.rename": "名前を変更","actions.trash": "ゴミ箱に移動","actions.trashConfirm": "「{{title}}」とそのレイアウトはゴミ箱に移動します。ウィジェットは利用可能で履歴を保持します。","actions.trashTitle": "このダッシュボードをゴミ箱に移動しますか?","actions.trashed": "「{{title}}」がゴミ箱に移動されました",- "board.empty": "まだウィジェットがありません。会話でエージェントにモニタリングウィジェットを作成して、このダッシュボードに追加するよう依頼してください。","board.health.failed": "{{count}} 失敗","board.health.ok": "{{count}} 最新","board.health.running": "{{count}} 更新中",@@ -56,7 +54,6 @@"detail.versionNone": "未公開","detail.versionPublished": "ライブ v{{version}}","dryRun.intro": "エージェントはこのドラフトを一度実行して出力をプレビューしたいと考えています。以下のアクセス権を持つサンドボックスで実行されます。ライブにはならず、ダッシュボードの変更もありません。",- "dryRun.runtime": "ランタイム","error.hideDetails": "詳細を隠す","error.showDetails": "詳細を表示","form.descriptionLabel": "説明",@@ -66,13 +63,9 @@"layout.cancel": "変更を破棄","layout.drag": "ドラッグして並べ替え","layout.edit": "レイアウトを編集",- "layout.narrower": "狭くする","layout.save": "レイアウトを保存","layout.saveFailed": "レイアウトを保存できませんでした。以前のレイアウトが復元されました。","layout.saved": "レイアウトを保存しました",- "layout.shorter": "短くする",- "layout.taller": "高くする",- "layout.wider": "広くする","list.description": "ライブウィジェットのボード。各ウィジェットは独自のスクリプトをスケジュールに従って実行し、履歴を保持します。","list.empty": "まだダッシュボードがありません","list.noDescription": "説明なし",@@ -103,12 +96,10 @@"publish.networkNone": "ネットワークアクセスなし","publish.networkUnrestricted": "サンドボックスはリストされたホストへの送信を制限できません — スクリプトは宣言されていないホストを含む任意のホストに到達できます。","publish.noSuccessfulRun": "このドラフトはまだ試行で成功していないため、公開は拒否されます。",- "publish.previewTitle": "最新の試行","publish.schedule": "更新","publish.scheduleNone": "手動のみ","publish.scriptChanges": "ライブ v{{version}} からの変更","publish.scriptNew": "スクリプト",- "rename.title": "ダッシュボードの名前を変更","review.loadFailed": "レビューを読み込めなかったため、承認は保留されています","review.versionMissing": "このバージョンはもう利用できないため、レビューできません。リクエストを拒否し、エージェントに再試行を依頼してください。","run.empty": "このウィジェットはまだ実行されていません。",diff --git a/locales/ko-KR/dashboard.json b/locales/ko-KR/dashboard.jsonindex 1495302214e..27a38cdbdc2 100644--- a/locales/ko-KR/dashboard.json+++ b/locales/ko-KR/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "추가 작업",- "actions.rename": "이름 변경","actions.trash": "휴지통으로 이동","actions.trashConfirm": "\"{{title}}\" 및 해당 레이아웃이 휴지통으로 이동합니다. 위젯은 계속 사용할 수 있으며 기록을 유지합니다.","actions.trashTitle": "이 대시보드를 휴지통으로 이동하시겠습니까?","actions.trashed": "\"{{title}}\"이(가) 휴지통으로 이동되었습니다",- "board.empty": "아직 위젯이 없습니다. 대화를 통해 에이전트에게 모니터링 위젯을 생성하고 이 대시보드에 추가하도록 요청하세요.","board.health.failed": "{{count}} 실패","board.health.ok": "{{count}} 최신 상태","board.health.running": "{{count}} 새로 고침 중",@@ -56,7 +54,6 @@"detail.versionNone": "게시되지 않음","detail.versionPublished": "v{{version}} 라이브","dryRun.intro": "에이전트가 이 초안을 한 번 실행하여 출력 결과를 미리보기로 확인하려고 합니다. 아래 액세스 권한으로 샌드박스에서 실행되며, 라이브 상태로 전환되거나 대시보드가 변경되지 않습니다.",- "dryRun.runtime": "런타임","error.hideDetails": "세부 정보 숨기기","error.showDetails": "세부 정보 보기","form.descriptionLabel": "설명",@@ -66,13 +63,9 @@"layout.cancel": "변경 사항 폐기","layout.drag": "드래그하여 순서 변경","layout.edit": "레이아웃 편집",- "layout.narrower": "더 좁게","layout.save": "레이아웃 저장","layout.saveFailed": "레이아웃을 저장할 수 없습니다. 이전 레이아웃이 복원되었습니다.","layout.saved": "레이아웃 저장됨",- "layout.shorter": "더 짧게",- "layout.taller": "더 길게",- "layout.wider": "더 넓게","list.description": "라이브 위젯의 보드입니다. 각 위젯은 자체 스크립트를 일정에 따라 실행하며 기록을 유지합니다.","list.empty": "아직 대시보드가 없습니다","list.noDescription": "설명 없음",@@ -103,12 +96,10 @@"publish.networkNone": "네트워크 액세스 없음","publish.networkUnrestricted": "샌드박스는 나열된 호스트로의 송신을 제한할 수 없습니다 — 스크립트는 선언되지 않은 호스트를 포함하여 모든 호스트에 접근할 수 있습니다.","publish.noSuccessfulRun": "이 초안은 아직 드라이 런에서 성공하지 않았으므로 게시가 거부됩니다.",- "publish.previewTitle": "최신 드라이 런","publish.schedule": "새로 고침","publish.scheduleNone": "수동만 가능","publish.scriptChanges": "라이브 v{{version}}에서 변경된 사항","publish.scriptNew": "스크립트",- "rename.title": "대시보드 이름 변경","review.loadFailed": "검토를 로드할 수 없어 승인이 보류 중입니다","review.versionMissing": "이 버전은 더 이상 사용할 수 없으므로 검토할 수 없습니다. 요청을 거부하고 에이전트에게 다시 시도하도록 요청하세요.","run.empty": "이 위젯은 아직 실행되지 않았습니다.",diff --git a/locales/nl-NL/dashboard.json b/locales/nl-NL/dashboard.jsonindex 8a4465a9448..3d538157674 100644--- a/locales/nl-NL/dashboard.json+++ b/locales/nl-NL/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Meer acties",- "actions.rename": "Hernoemen","actions.trash": "Verplaatsen naar prullenbak","actions.trashConfirm": "\"{{title}}\" en de indeling worden verplaatst naar de prullenbak. Widgets blijven beschikbaar en behouden hun geschiedenis.","actions.trashTitle": "Dit dashboard naar de prullenbak verplaatsen?","actions.trashed": "\"{{title}}\" verplaatst naar de prullenbak",- "board.empty": "Nog geen widgets. Vraag een agent in een gesprek om een monitoringwidget te maken en toe te voegen aan dit dashboard.","board.health.failed": "{{count}} mislukt","board.health.ok": "{{count}} up-to-date","board.health.running": "{{count}} aan het verversen",@@ -56,7 +54,6 @@"detail.versionNone": "Niet gepubliceerd","detail.versionPublished": "v{{version}} live","dryRun.intro": "De agent wil dit concept eenmalig uitvoeren om de output te bekijken. Het wordt uitgevoerd in een sandbox met de onderstaande toegang; niets gaat live en er worden geen dashboardwijzigingen doorgevoerd.",- "dryRun.runtime": "Runtime","error.hideDetails": "Details verbergen","error.showDetails": "Details weergeven","form.descriptionLabel": "Beschrijving",@@ -66,13 +63,9 @@"layout.cancel": "Wijzigingen annuleren","layout.drag": "Slepen om opnieuw te ordenen","layout.edit": "Indeling bewerken",- "layout.narrower": "Smaller","layout.save": "Indeling opslaan","layout.saveFailed": "Kon de indeling niet opslaan. De vorige indeling is hersteld.","layout.saved": "Indeling opgeslagen",- "layout.shorter": "Korter",- "layout.taller": "Hoger",- "layout.wider": "Breder","list.description": "Borden met live widgets. Elke widget voert zijn eigen script uit volgens een schema en behoudt zijn geschiedenis.","list.empty": "Nog geen dashboards","list.noDescription": "Geen beschrijving",@@ -103,12 +96,10 @@"publish.networkNone": "Geen netwerktoegang","publish.networkUnrestricted": "De sandbox kan uitgaande verbindingen naar de vermelde hosts niet beperken — het script kan elke host bereiken, inclusief hosts die het niet heeft gedeclareerd.","publish.noSuccessfulRun": "Dit concept is nog niet geslaagd in een proefversie, dus publicatie wordt geweigerd.",- "publish.previewTitle": "Laatste proefversie","publish.schedule": "Verversen","publish.scheduleNone": "Alleen handmatig","publish.scriptChanges": "Wijzigingen van live v{{version}}","publish.scriptNew": "Script",- "rename.title": "Dashboard hernoemen","review.loadFailed": "Kon de review niet laden, goedkeuring is uitgesteld","review.versionMissing": "Deze versie is niet langer beschikbaar, dus kan niet worden beoordeeld. Wijs het verzoek af en vraag de agent om het opnieuw te proberen.","run.empty": "Deze widget is nog niet uitgevoerd.",diff --git a/locales/pl-PL/dashboard.json b/locales/pl-PL/dashboard.jsonindex a96727c774d..1ef16d8299c 100644--- a/locales/pl-PL/dashboard.json+++ b/locales/pl-PL/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Więcej akcji",- "actions.rename": "Zmień nazwę","actions.trash": "Przenieś do kosza","actions.trashConfirm": "\"{{title}}\" i jego układ zostaną przeniesione do kosza. Widżety pozostaną dostępne i zachowają swoją historię.","actions.trashTitle": "Przenieść ten pulpit nawigacyjny do kosza?","actions.trashed": "\"{{title}}\" przeniesiono do kosza",- "board.empty": "Brak widżetów. Poproś agenta w rozmowie o utworzenie widżetu monitorującego i dodanie go do tego pulpitu nawigacyjnego.","board.health.failed": "{{count}} nieudanych","board.health.ok": "{{count}} aktualnych","board.health.running": "{{count}} odświeżających się",@@ -56,7 +54,6 @@"detail.versionNone": "Nie opublikowano","detail.versionPublished": "v{{version}} na żywo","dryRun.intro": "Agent chce uruchomić ten szkic raz, aby zobaczyć jego wynik. Uruchamia się w piaskownicy z poniższym dostępem; nic nie zostaje opublikowane, a pulpit nawigacyjny nie ulega zmianie.",- "dryRun.runtime": "Czas wykonania","error.hideDetails": "Ukryj szczegóły","error.showDetails": "Pokaż szczegóły","form.descriptionLabel": "Opis",@@ -66,13 +63,9 @@"layout.cancel": "Odrzuć zmiany","layout.drag": "Przeciągnij, aby zmienić kolejność","layout.edit": "Edytuj układ",- "layout.narrower": "Węższy","layout.save": "Zapisz układ","layout.saveFailed": "Nie udało się zapisać układu. Przywrócono poprzedni układ.","layout.saved": "Układ zapisany",- "layout.shorter": "Krótszy",- "layout.taller": "Wyższy",- "layout.wider": "Szerszy","list.description": "Tablice widżetów na żywo. Każdy widżet uruchamia swój własny skrypt zgodnie z harmonogramem i zachowuje swoją historię.","list.empty": "Brak pulpitów nawigacyjnych","list.noDescription": "Brak opisu",@@ -103,12 +96,10 @@"publish.networkNone": "Brak dostępu do sieci","publish.networkUnrestricted": "Piaskownica nie może ograniczyć ruchu wychodzącego do podanych hostów — skrypt może dotrzeć do dowolnego hosta, w tym tych, których nie zadeklarował.","publish.noSuccessfulRun": "Ten szkic nie zakończył się jeszcze sukcesem w próbie, więc jego publikacja zostanie odrzucona.",- "publish.previewTitle": "Ostatnia próba","publish.schedule": "Odśwież","publish.scheduleNone": "Tylko ręcznie","publish.scriptChanges": "Zmiany od wersji na żywo v{{version}}","publish.scriptNew": "Skrypt",- "rename.title": "Zmień nazwę pulpitu nawigacyjnego","review.loadFailed": "Nie udało się załadować przeglądu, więc zatwierdzenie jest wstrzymane","review.versionMissing": "Ta wersja nie jest już dostępna, więc nie można jej przeglądać. Odrzuć żądanie i poproś agenta o ponowną próbę.","run.empty": "Ten widżet jeszcze nie został uruchomiony.",diff --git a/locales/pt-BR/dashboard.json b/locales/pt-BR/dashboard.jsonindex 859332f16d1..decc217b2a4 100644--- a/locales/pt-BR/dashboard.json+++ b/locales/pt-BR/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Mais ações",- "actions.rename": "Renomear","actions.trash": "Mover para a lixeira","actions.trashConfirm": "\"{{title}}\" e seu layout serão movidos para a lixeira. Os widgets permanecem disponíveis e mantêm seu histórico.","actions.trashTitle": "Mover este painel para a lixeira?","actions.trashed": "\"{{title}}\" movido para a lixeira",- "board.empty": "Ainda não há widgets. Peça a um agente em uma conversa para criar um widget de monitoramento e adicioná-lo a este painel.","board.health.failed": "{{count}} falhou","board.health.ok": "{{count}} atualizado","board.health.running": "{{count}} atualizando",@@ -56,7 +54,6 @@"detail.versionNone": "Não publicado","detail.versionPublished": "v{{version}} ao vivo","dryRun.intro": "O agente deseja executar este rascunho uma vez para pré-visualizar seu resultado. Ele será executado em um sandbox com o acesso abaixo; nada será publicado e nenhuma alteração será feita no painel.",- "dryRun.runtime": "Tempo de execução","error.hideDetails": "Ocultar detalhes","error.showDetails": "Mostrar detalhes","form.descriptionLabel": "Descrição",@@ -66,13 +63,9 @@"layout.cancel": "Descartar alterações","layout.drag": "Arraste para reordenar","layout.edit": "Editar layout",- "layout.narrower": "Mais estreito","layout.save": "Salvar layout","layout.saveFailed": "Não foi possível salvar o layout. O layout anterior foi restaurado.","layout.saved": "Layout salvo",- "layout.shorter": "Mais curto",- "layout.taller": "Mais alto",- "layout.wider": "Mais largo","list.description": "Painéis de widgets ao vivo. Cada widget executa seu próprio script em uma programação e mantém seu histórico.","list.empty": "Ainda não há painéis","list.noDescription": "Sem descrição",@@ -103,12 +96,10 @@"publish.networkNone": "Sem acesso à rede","publish.networkUnrestricted": "O sandbox não pode restringir o acesso de saída aos hosts listados — o script pode alcançar qualquer host, incluindo aqueles que não declarou.","publish.noSuccessfulRun": "Este rascunho ainda não foi bem-sucedido em uma execução de teste, portanto, sua publicação será recusada.",- "publish.previewTitle": "Última execução de teste","publish.schedule": "Atualizar","publish.scheduleNone": "Apenas manual","publish.scriptChanges": "Alterações em relação à versão ao vivo v{{version}}","publish.scriptNew": "Script",- "rename.title": "Renomear painel","review.loadFailed": "Não foi possível carregar a revisão, então a aprovação está em espera","review.versionMissing": "Esta versão não está mais disponível, então não pode ser revisada. Rejeite a solicitação e peça ao agente para tentar novamente.","run.empty": "Este widget ainda não foi executado.",diff --git a/locales/ru-RU/dashboard.json b/locales/ru-RU/dashboard.jsonindex a62d05ed8e7..cc9a5009f3c 100644--- a/locales/ru-RU/dashboard.json+++ b/locales/ru-RU/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Дополнительные действия",- "actions.rename": "Переименовать","actions.trash": "Переместить в корзину","actions.trashConfirm": "\"{{title}}\" и его макет будут перемещены в корзину. Виджеты останутся доступными и сохранят свою историю.","actions.trashTitle": "Переместить эту панель в корзину?","actions.trashed": "\"{{title}}\" перемещен в корзину",- "board.empty": "Пока нет виджетов. Попросите агента в беседе создать виджет мониторинга и добавить его на эту панель.","board.health.failed": "{{count}} неудач","board.health.ok": "{{count}} актуальны","board.health.running": "{{count}} обновляются",@@ -56,7 +54,6 @@"detail.versionNone": "Не опубликовано","detail.versionPublished": "v{{version}} в работе","dryRun.intro": "Агент хочет выполнить этот черновик один раз, чтобы предварительно просмотреть его результат. Он выполняется в песочнице с указанным доступом; ничего не публикуется, и изменения на панели не вносятся.",- "dryRun.runtime": "Среда выполнения","error.hideDetails": "Скрыть детали","error.showDetails": "Показать детали","form.descriptionLabel": "Описание",@@ -66,13 +63,9 @@"layout.cancel": "Отменить изменения","layout.drag": "Перетащите для изменения порядка","layout.edit": "Редактировать макет",- "layout.narrower": "Уже","layout.save": "Сохранить макет","layout.saveFailed": "Не удалось сохранить макет. Восстановлен предыдущий макет.","layout.saved": "Макет сохранен",- "layout.shorter": "Ниже",- "layout.taller": "Выше",- "layout.wider": "Шире","list.description": "Панели с активными виджетами. Каждый виджет выполняет свой скрипт по расписанию и сохраняет свою историю.","list.empty": "Панели пока отсутствуют","list.noDescription": "Описание отсутствует",@@ -103,12 +96,10 @@"publish.networkNone": "Нет доступа к сети","publish.networkUnrestricted": "Песочница не может ограничить выход к указанным хостам — скрипт может обращаться к любым хостам, включая те, которые он не декларировал.","publish.noSuccessfulRun": "Этот черновик еще не прошел успешный тестовый запуск, поэтому его публикация будет отклонена.",- "publish.previewTitle": "Последний тестовый запуск","publish.schedule": "Обновление","publish.scheduleNone": "Только вручную","publish.scriptChanges": "Изменения с момента v{{version}}","publish.scriptNew": "Скрипт",- "rename.title": "Переименовать панель","review.loadFailed": "Не удалось загрузить обзор, поэтому утверждение приостановлено","review.versionMissing": "Эта версия больше недоступна, поэтому она не может быть проверена. Отклоните запрос и попросите агента попробовать снова.","run.empty": "Этот виджет еще не запускался.",diff --git a/locales/tr-TR/dashboard.json b/locales/tr-TR/dashboard.jsonindex d68392fd0ae..17a92931ea1 100644--- a/locales/tr-TR/dashboard.json+++ b/locales/tr-TR/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Daha fazla eylem",- "actions.rename": "Yeniden adlandır","actions.trash": "Çöpe taşı","actions.trashConfirm": "\"{{title}}\" ve düzeni çöpe taşınacak. Araçlar kullanılabilir durumda kalacak ve geçmişlerini koruyacak.","actions.trashTitle": "Bu panoyu çöpe taşımak istiyor musunuz?","actions.trashed": "\"{{title}}\" çöpe taşındı",- "board.empty": "Henüz araç yok. Bir ajanla konuşarak bir izleme aracı oluşturmasını ve bu panele eklemesini isteyin.","board.health.failed": "{{count}} başarısız","board.health.ok": "{{count}} güncel","board.health.running": "{{count}} yenileniyor",@@ -56,7 +54,6 @@"detail.versionNone": "Yayınlanmadı","detail.versionPublished": "v{{version}} canlı","dryRun.intro": "Ajan bu taslağı bir kez çalıştırarak çıktısını önizlemek istiyor. Bu işlem aşağıdaki erişimle bir sanal ortamda çalışır; hiçbir şey canlıya geçmez ve pano değişmez.",- "dryRun.runtime": "Çalışma zamanı","error.hideDetails": "Detayları gizle","error.showDetails": "Detayları göster","form.descriptionLabel": "Açıklama",@@ -66,13 +63,9 @@"layout.cancel": "Değişiklikleri iptal et","layout.drag": "Sürükleyerek yeniden sırala","layout.edit": "Düzeni düzenle",- "layout.narrower": "Daha dar","layout.save": "Düzeni kaydet","layout.saveFailed": "Düzen kaydedilemedi. Önceki düzen geri yüklendi.","layout.saved": "Düzen kaydedildi",- "layout.shorter": "Daha kısa",- "layout.taller": "Daha uzun",- "layout.wider": "Daha geniş","list.description": "Canlı araç panoları. Her araç kendi betiğini bir program dahilinde çalıştırır ve geçmişini tutar.","list.empty": "Henüz pano yok","list.noDescription": "Açıklama yok",@@ -103,12 +96,10 @@"publish.networkNone": "Ağ erişimi yok","publish.networkUnrestricted": "Sanal ortam, listelenen ana bilgisayarlara çıkışı kısıtlayamaz — betik, beyan etmediği ana bilgisayarlar da dahil olmak üzere herhangi bir ana bilgisayara ulaşabilir.","publish.noSuccessfulRun": "Bu taslak henüz bir deneme çalıştırmasında başarılı olmadı, bu nedenle yayınlanması reddedilecektir.",- "publish.previewTitle": "Son deneme çalıştırması","publish.schedule": "Yenile","publish.scheduleNone": "Sadece manuel","publish.scriptChanges": "Canlı v{{version}} sürümünden değişiklikler","publish.scriptNew": "Betik",- "rename.title": "Panoyu yeniden adlandır","review.loadFailed": "İnceleme yüklenemedi, bu nedenle onay beklemede","review.versionMissing": "Bu sürüm artık mevcut değil, bu yüzden incelenemez. Talebi reddedin ve ajandan tekrar denemesini isteyin.","run.empty": "Bu araç henüz çalıştırılmadı.",diff --git a/locales/vi-VN/dashboard.json b/locales/vi-VN/dashboard.jsonindex a7f25d88ffc..bfaa59c26eb 100644--- a/locales/vi-VN/dashboard.json+++ b/locales/vi-VN/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "Thêm hành động",- "actions.rename": "Đổi tên","actions.trash": "Chuyển vào thùng rác","actions.trashConfirm": "\"{{title}}\" và bố cục của nó sẽ được chuyển vào thùng rác. Các tiện ích vẫn khả dụng và giữ lại lịch sử của chúng.","actions.trashTitle": "Chuyển bảng điều khiển này vào thùng rác?","actions.trashed": "\"{{title}}\" đã được chuyển vào thùng rác",- "board.empty": "Chưa có tiện ích nào. Hãy yêu cầu một agent trong cuộc trò chuyện để tạo một tiện ích giám sát và thêm nó vào bảng điều khiển này.","board.health.failed": "{{count}} thất bại","board.health.ok": "{{count}} cập nhật","board.health.running": "{{count}} đang làm mới",@@ -56,7 +54,6 @@"detail.versionNone": "Chưa xuất bản","detail.versionPublished": "v{{version}} trực tiếp","dryRun.intro": "Agent muốn chạy bản nháp này một lần để xem trước kết quả của nó. Nó sẽ chạy trong môi trường thử nghiệm với quyền truy cập dưới đây; không có gì được đưa lên trực tiếp và không có thay đổi nào trên bảng điều khiển.",- "dryRun.runtime": "Thời gian chạy","error.hideDetails": "Ẩn chi tiết","error.showDetails": "Hiển thị chi tiết","form.descriptionLabel": "Mô tả",@@ -66,13 +63,9 @@"layout.cancel": "Hủy thay đổi","layout.drag": "Kéo để sắp xếp lại","layout.edit": "Chỉnh sửa bố cục",- "layout.narrower": "Hẹp hơn","layout.save": "Lưu bố cục","layout.saveFailed": "Không thể lưu bố cục. Bố cục trước đó đã được khôi phục.","layout.saved": "Bố cục đã được lưu",- "layout.shorter": "Ngắn hơn",- "layout.taller": "Cao hơn",- "layout.wider": "Rộng hơn","list.description": "Bảng các tiện ích trực tiếp. Mỗi tiện ích chạy script riêng theo lịch trình và giữ lại lịch sử của nó.","list.empty": "Chưa có bảng điều khiển nào","list.noDescription": "Không có mô tả",@@ -103,12 +96,10 @@"publish.networkNone": "Không có quyền truy cập mạng","publish.networkUnrestricted": "Môi trường thử nghiệm không thể hạn chế truy cập ra ngoài đến các máy chủ được liệt kê — script có thể truy cập bất kỳ máy chủ nào, bao gồm cả những máy chủ không được khai báo.","publish.noSuccessfulRun": "Bản nháp này chưa thành công trong lần chạy thử nào, vì vậy việc xuất bản sẽ bị từ chối.",- "publish.previewTitle": "Lần chạy thử mới nhất","publish.schedule": "Làm mới","publish.scheduleNone": "Chỉ thủ công","publish.scriptChanges": "Thay đổi từ phiên bản trực tiếp v{{version}}","publish.scriptNew": "Script",- "rename.title": "Đổi tên bảng điều khiển","review.loadFailed": "Không thể tải bản xem xét, vì vậy việc phê duyệt đang bị tạm dừng","review.versionMissing": "Phiên bản này không còn khả dụng, vì vậy không thể xem xét. Hãy từ chối yêu cầu và yêu cầu agent thử lại.","run.empty": "Tiện ích này chưa chạy lần nào.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 28fdc24aa45..641e0745649 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2732,7 +2732,7 @@"tool.intervention.mode.autoRun": "自动批准","tool.intervention.mode.autoRunDesc": "自动批准所有技能调用","tool.intervention.mode.manual": "手动批准",- "tool.intervention.mode.manualDesc": "每次调用都需要你确认",+ "tool.intervention.mode.manualDesc": "每次调用都需要你确认(已选择不再询问的操作除外)","tool.intervention.onboarding.agentIdentity.editHint": "你可以直接在下方修改名字或头像","tool.intervention.onboarding.agentIdentity.namePlaceholder": "助手名字","tool.intervention.onboarding.agentIdentity.title": "我将更新自己的名字与头像",diff --git a/locales/zh-CN/dashboard.json b/locales/zh-CN/dashboard.jsonindex 0fea6a332a6..40b4941a851 100644--- a/locales/zh-CN/dashboard.json+++ b/locales/zh-CN/dashboard.json@@ -1,11 +1,19 @@{"actions.more": "更多操作",- "actions.rename": "重命名",+ "actions.settings": "设置","actions.trash": "移到回收站","actions.trashConfirm": "「{{title}}」及其布局将移到回收站。组件仍然保留,历史记录不受影响。","actions.trashTitle": "将此看板移到回收站?","actions.trashed": "「{{title}}」已移到回收站",- "board.empty": "还没有组件。在对话中让助理编写一个监控组件,并把它添加到这个看板。",+ "board.emptyAction": "让助理创建组件",+ "board.emptyAgentUnavailable": "暂时无法打开助理,请稍后重试。",+ "board.emptyDescription": "组件是一段按计划运行的小脚本,结果会以卡片显示在这里。让助理按你的需要编写并试运行,你确认后才会上线。",+ "board.emptyKind.list": "列表",+ "board.emptyKind.series": "趋势",+ "board.emptyKind.stat": "数字",+ "board.emptyKind.table": "表格",+ "board.emptyPrompt": "帮我创建一个监控组件,并放到看板「{{title}}」上。我想看:",+ "board.emptyTitle": "这个看板还没有组件","board.health.failed": "{{count}} 个失败","board.health.ok": "{{count}} 个正常","board.health.running": "{{count}} 个刷新中",@@ -56,7 +64,7 @@"detail.versionNone": "未发布","detail.versionPublished": "v{{version}} 生效中","dryRun.intro": "智能体想先试运行一次此草稿以预览输出。它会在沙箱中以下方列出的权限运行;不会上线,也不会改动任何看板。",- "dryRun.runtime": "运行环境",+ "dryRun.rememberFailed": "已批准,但没能记住这项授权,下次仍会询问。","error.hideDetails": "隐藏详情","error.showDetails": "显示详情","form.descriptionLabel": "描述",@@ -65,14 +73,11 @@"form.titlePlaceholder": "例如:开源项目健康度","layout.cancel": "放弃修改","layout.drag": "拖动以调整顺序",- "layout.edit": "编辑布局",- "layout.narrower": "变窄",+ "layout.edit": "编辑看板",+ "layout.resize": "拖动调整大小(也可用方向键)","layout.save": "保存布局","layout.saveFailed": "布局保存失败,已恢复为之前的布局。","layout.saved": "布局已保存",- "layout.shorter": "变矮",- "layout.taller": "变高",- "layout.wider": "变宽","list.description": "由实时组件组成的看板。每个组件按计划运行自己的脚本,并保留历史记录。","list.empty": "还没有看板","list.noDescription": "暂无描述",@@ -102,13 +107,19 @@"publish.network": "网络","publish.networkNone": "无网络访问","publish.noSuccessfulRun": "该草稿尚未试运行成功,发布将被拒绝。",- "publish.previewTitle": "最近一次试运行","publish.schedule": "刷新频率","publish.scheduleNone": "仅手动","publish.scriptChanges": "相对已上线 v{{version}} 的变更","publish.scriptNew": "脚本",- "rename.title": "重命名看板",+ "review.expected": "预期效果",+ "review.expectedEarlier": "参考 v{{version}} 上次的结果,批准后会用此草稿重新生成",+ "review.expectedSameVersion": "来自此版本上次试运行",+ "review.expectedSample": "示例数据,仅示意将生成的卡片;批准后会生成真实结果","review.loadFailed": "无法加载审阅内容,暂不能批准",+ "review.sampleItem": "示例条目 {{index}}",+ "review.sampleName": "名称",+ "review.sampleTag": "示例",+ "review.sampleValue": "数值","review.versionMissing": "这个版本已不可用,无法审阅。请拒绝该请求,并让智能体重新尝试。","run.empty": "这个组件还没有运行过。","run.error": "错误",@@ -122,6 +133,29 @@"run.trigger.manual": "手动","run.trigger.preview": "预览","run.trigger.schedule": "定时",+ "schedule.daily9": "每天 09:00",+ "schedule.every15m": "每 15 分钟",+ "schedule.every30m": "每 30 分钟",+ "schedule.every6h": "每 6 小时",+ "schedule.hourly": "每小时",+ "schedule.manual": "仅手动刷新",+ "settings.saved": "设置已保存",+ "settings.schedule": "组件刷新频率",+ "settings.scheduleFailed_one": "设置已保存,但有 {{count}} 个组件的刷新频率没能修改",+ "settings.scheduleFailed_other": "设置已保存,但有 {{count}} 个组件的刷新频率没能修改",+ "settings.scheduleHint_one": "会应用到此看板上你创建的 {{count}} 个组件。",+ "settings.scheduleHint_other": "会应用到此看板上你创建的 {{count}} 个组件。",+ "settings.scheduleKeep": "保持各组件当前的刷新频率",+ "settings.scheduleKeepCustom": "保持当前({{pattern}})",+ "settings.scheduleNoWidgets": "此看板上还没有组件。",+ "settings.scheduleNotOwner": "只有组件的创建者能修改刷新频率,此看板上没有你创建的组件。",+ "settings.scheduleOthers_one": "他人创建的 {{count}} 个组件保持原有刷新频率。",+ "settings.scheduleOthers_other": "他人创建的 {{count}} 个组件保持原有刷新频率。",+ "settings.title": "看板设置",+ "settings.visibility": "可见范围",+ "settings.visibilityKeptPrivate": "已保存。所在项目是私有的,看板仍仅自己可见。",+ "settings.visibilityPrivate": "仅自己",+ "settings.visibilityPublic": "工作区成员","version.empty": "还没有版本。","version.publishedAt": "发布于 {{time}}","version.script": "脚本",@@ -151,5 +185,10 @@"widget.view.listEmpty": "没有条目","widget.view.more": "还有 {{count}} 条","widget.view.seriesEmpty": "没有数据点",- "widget.view.tableEmpty": "没有数据行"+ "widget.view.tableEmpty": "没有数据行",+ "widgetEdit.action": "编辑组件",+ "widgetEdit.descriptionPlaceholder": "数据来源、筛选条件、时间范围和单位",+ "widgetEdit.saved": "组件已更新",+ "widgetEdit.title": "编辑组件",+ "widgetEdit.titleLabel": "标题"}diff --git a/locales/zh-TW/dashboard.json b/locales/zh-TW/dashboard.jsonindex 4d548ef7724..01148d405eb 100644--- a/locales/zh-TW/dashboard.json+++ b/locales/zh-TW/dashboard.json@@ -1,11 +1,9 @@{"actions.more": "更多操作",- "actions.rename": "重新命名","actions.trash": "移至垃圾桶","actions.trashConfirm": "「{{title}}」及其佈局將移至垃圾桶。小工具仍可用並保留其歷史記錄。","actions.trashTitle": "將此儀表板移至垃圾桶?","actions.trashed": "「{{title}}」已移至垃圾桶",- "board.empty": "尚無小工具。在對話中請求代理人建立監控小工具並將其添加到此儀表板。","board.health.failed": "{{count}} 失敗","board.health.ok": "{{count}} 最新","board.health.running": "{{count}} 正在刷新",@@ -56,7 +54,6 @@"detail.versionNone": "未發布","detail.versionPublished": "v{{version}} 已上線","dryRun.intro": "代理人希望運行此草稿一次以預覽其輸出。它在具有以下訪問權限的沙盒中運行;不會上線,也不會更改儀表板。",- "dryRun.runtime": "運行時","error.hideDetails": "隱藏詳情","error.showDetails": "顯示詳情","form.descriptionLabel": "描述",@@ -66,13 +63,9 @@"layout.cancel": "放棄更改","layout.drag": "拖動以重新排序","layout.edit": "編輯佈局",- "layout.narrower": "更窄","layout.save": "保存佈局","layout.saveFailed": "無法保存佈局。已恢復到之前的佈局。","layout.saved": "佈局已保存",- "layout.shorter": "更短",- "layout.taller": "更高",- "layout.wider": "更寬","list.description": "實時小工具的面板。每個小工具按計劃運行自己的腳本並保留其歷史記錄。","list.empty": "尚無儀表板","list.noDescription": "無描述",@@ -103,12 +96,10 @@"publish.networkNone": "無網絡訪問","publish.networkUnrestricted": "沙盒無法限制到列出主機的出口 — 腳本可以訪問任何主機,包括未聲明的主機。","publish.noSuccessfulRun": "此草稿尚未成功試運行,因此發布將被拒絕。",- "publish.previewTitle": "最新試運行","publish.schedule": "刷新","publish.scheduleNone": "僅手動","publish.scriptChanges": "與已上線 v{{version}} 的變更","publish.scriptNew": "腳本",- "rename.title": "重新命名儀表板","review.loadFailed": "無法加載審核,因此批准被暫停","review.versionMissing": "此版本不再可用,因此無法審核。拒絕請求並要求代理人重試。","run.empty": "此小工具尚未運行。",diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 02fe58a70d3..73b8db4ef4b 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -278,8 +278,7 @@ export class GeneralChatAgent implements Agent {if (dynamicPolicy !== undefined) {if (dynamicPolicy === 'never') toolsToExecute.push(toolCalling);- else if (approvalMode === 'allow-list' && allowList.includes(toolKey))- toolsToExecute.push(toolCalling);+ else if (allowList.includes(toolKey)) toolsToExecute.push(toolCalling);else toolsNeedingIntervention.push(toolCalling);continue;}@@ -304,8 +303,11 @@ export class GeneralChatAgent implements Agent {continue;}- // Phase 7: User config is 'manual' (default), use tool's own config- if (staticPolicy === 'never') {+ // Phase 7: User config is 'manual' (default), use tool's own config —+ // except for tools the user approved with "don't ask again for similar+ // actions", which joined the allow-list. Calls that must always ask+ // never reach here (handled above).+ if (staticPolicy === 'never' || allowList.includes(toolKey)) {toolsToExecute.push(toolCalling);} else {toolsNeedingIntervention.push(toolCalling);diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.manualAllowList.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.manualAllowList.test.tsnew file mode 100644index 00000000000..d78b4987a06--- /dev/null+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.manualAllowList.test.ts@@ -0,0 +1,110 @@+import { type ChatToolPayload } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { type AgentRuntimeContext, type AgentState } from '../../types';+import { GeneralChatAgent } from '../GeneralChatAgent';++/**+ * "Approve, and don't ask again for similar actions" puts a tool on the+ * user's allow-list. Manual mode honours it like allow-list mode does, but a+ * call that must always ask is never skipped.+ */+describe('GeneralChatAgent — remembered tools in manual mode', () => {+ const createState = (overrides?: Partial<AgentState>): AgentState => ({+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ messages: [],+ operationId: 'test-session',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ },+ ...overrides,+ });++ const createContext = (toolsCalling: ChatToolPayload[]): AgentRuntimeContext => ({+ payload: { hasToolsCalling: true, parentMessageId: 'msg-1', toolsCalling },+ phase: 'llm_result',+ session: { messageCount: 0, sessionId: 'test-session', status: 'running', stepCount: 0 },+ });++ const createAgent = () =>+ new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },+ operationId: 'test-session',+ });++ const bash: ChatToolPayload = {+ apiName: 'bash',+ arguments: '{"command":"ls"}',+ id: 'call-1',+ identifier: 'bash',+ type: 'builtin',+ };++ it('runs a remembered tool without asking', async () => {+ const state = createState({+ toolManifestMap: { bash: { humanIntervention: 'required', identifier: 'bash' } },+ userInterventionConfig: { allowList: ['bash/bash'], approvalMode: 'manual' },+ });++ const result = await createAgent().runner(createContext([bash]), state);++ expect(result).toEqual([+ { payload: { parentMessageId: 'msg-1', toolCalling: bash }, type: 'call_tool' },+ ]);+ });++ it('still asks for a tool that is not remembered', async () => {+ const state = createState({+ toolManifestMap: { bash: { humanIntervention: 'required', identifier: 'bash' } },+ userInterventionConfig: { allowList: [], approvalMode: 'manual' },+ });++ const result = await createAgent().runner(createContext([bash]), state);++ expect(result).toEqual([+ {+ parentMessageId: 'msg-1',+ pendingToolsCalling: [bash],+ reason: 'human_intervention_required',+ type: 'request_human_approve',+ },+ ]);+ });++ it('never skips a call that must always ask, even when remembered', async () => {+ const state = createState({+ toolManifestMap: { bash: { humanIntervention: 'always', identifier: 'bash' } },+ userInterventionConfig: { allowList: ['bash/bash'], approvalMode: 'manual' },+ });++ const result = await createAgent().runner(createContext([bash]), state);++ expect(result).toEqual([+ {+ parentMessageId: 'msg-1',+ pendingToolsCalling: [bash],+ reason: 'human_intervention_required',+ type: 'request_human_approve',+ },+ ]);+ });+});diff --git a/packages/builtin-tool-dashboard/src/client/Intervention/index.tsx b/packages/builtin-tool-dashboard/src/client/Intervention/index.tsxindex ad0f4abd9b1..ba005bd7110 100644--- a/packages/builtin-tool-dashboard/src/client/Intervention/index.tsx+++ b/packages/builtin-tool-dashboard/src/client/Intervention/index.tsx@@ -60,11 +60,12 @@ const RequestPublishIntervention = memo<BuiltinInterventionProps<RequestPublishPRequestPublishIntervention.displayName = 'DashboardRequestPublishIntervention';/**- * Shown only for drafts that declare connector credentials or network hosts:- * the user approves running exactly this script with that access.+ * Shown only for drafts that declare connector credentials or network hosts+ * no standing grant covers: the user approves running exactly this script+ * with that access, and may stop being asked for the same access.*/const DryRunWidgetIntervention = memo<BuiltinInterventionProps<DryRunWidgetParams>>(- ({ args, onApprovalBlockedChange, onArgsChange }) => {+ ({ args, onApprovalBlockedChange, onArgsChange, registerRememberApproval }) => {const pinVersion = useCallback((versionId: string) => onArgsChange?.({ ...args, versionId }),[args, onArgsChange],@@ -75,6 +76,7 @@ const DryRunWidgetIntervention = memo<BuiltinInterventionProps<DryRunWidgetParamreturn (<DashboardFeatureGate><WidgetDryRunReview+ registerRememberApproval={registerRememberApproval}versionId={args.versionId}widgetId={args.widgetId}onApprovalBlockedChange={onApprovalBlockedChange}diff --git a/packages/builtin-tool-dashboard/src/index.ts b/packages/builtin-tool-dashboard/src/index.tsindex 840bc3b83ce..57425946fb1 100644--- a/packages/builtin-tool-dashboard/src/index.ts+++ b/packages/builtin-tool-dashboard/src/index.ts@@ -1,8 +1,10 @@export {createDryRunAudit,DASHBOARD_DRY_RUN_AUDIT,+ dryRunAccessOf,type DryRunAuditOptions,dryRunNeedsApproval,+ isDryRunAccessGranted,} from './interventionAudit';export { DashboardIdentifier, DashboardManifest } from './manifest';export { systemPrompt } from './systemRole';diff --git a/packages/builtin-tool-dashboard/src/interventionAudit.test.ts b/packages/builtin-tool-dashboard/src/interventionAudit.test.tsindex b97c87de369..7c862006442 100644--- a/packages/builtin-tool-dashboard/src/interventionAudit.test.ts+++ b/packages/builtin-tool-dashboard/src/interventionAudit.test.ts@@ -1,6 +1,11 @@import { describe, expect, it, vi } from 'vitest';-import { createDryRunAudit, dryRunNeedsApproval } from './interventionAudit';+import {+ createDryRunAudit,+ dryRunAccessOf,+ dryRunNeedsApproval,+ isDryRunAccessGranted,+} from './interventionAudit';describe('dryRunNeedsApproval', () => {it('lets a closed draft (no credentials, no network) run unattended', () => {@@ -53,3 +58,75 @@ describe('createDryRunAudit', () => {).toBe(true);});});++const githubDraft = {+ env: [{ connector: 'github', name: 'GITHUB_TOKEN' }],+ network: { allow: ['api.github.com'] },+};+const grant = (patch: Record<string, unknown> = {}) => ({+ connectors: ['github'],+ grantedAt: '2026-10-25T00:00:00Z',+ hosts: ['api.github.com'],+ workspaceId: null,+ ...patch,+});++describe('dryRunAccessOf', () => {+ it('lists each connector and host once, hosts case-folded', () => {+ expect(+ dryRunAccessOf({+ env: [+ { connector: 'github', name: 'A' },+ { connector: 'github', name: 'B' },+ { name: 'PLAIN' },+ ],+ network: { allow: ['API.github.com', 'api.github.com'] },+ }),+ ).toEqual({ connectors: ['github'], hosts: ['api.github.com'] });+ });+});++describe('isDryRunAccessGranted', () => {+ it('covers a draft asking for the same or less access on the same level', () => {+ expect(isDryRunAccessGranted(githubDraft, [grant()], null)).toBe(true);+ expect(isDryRunAccessGranted({ network: { allow: ['api.github.com'] } }, [grant()], null)).toBe(+ true,+ );+ });++ it('asks again for a new host, a new connector or another level', () => {+ const extraHost = { ...githubDraft, network: { allow: ['api.github.com', 'evil.example'] } };+ expect(isDryRunAccessGranted(extraHost, [grant()], null)).toBe(false);+ const extraConnector = { ...githubDraft, env: [{ connector: 'linear', name: 'LINEAR' }] };+ expect(isDryRunAccessGranted(extraConnector, [grant()], null)).toBe(false);+ expect(isDryRunAccessGranted(githubDraft, [grant()], 'ws_1')).toBe(false);+ expect(isDryRunAccessGranted(githubDraft, [grant({ workspaceId: 'ws_1' })], null)).toBe(false);+ });++ it('never pools access from separate grants', () => {+ const grants = [grant({ hosts: [] }), grant({ connectors: [], hosts: ['api.github.com'] })];+ expect(isDryRunAccessGranted(githubDraft, grants, null)).toBe(false);+ });+});++describe('createDryRunAudit with grants', () => {+ const loadVersion = vi.fn(async () => ({ manifest: githubDraft, workspaceId: null }));++ it('runs a covered draft without asking', async () => {+ const audit = createDryRunAudit({ loadGrants: () => [grant()], loadVersion });+ expect(await audit({ versionId: 'v2', widgetId: 'w1' })).toBe(false);+ });++ it('asks when no grant covers the draft or the grants cannot be read', async () => {+ const uncovered = createDryRunAudit({ loadGrants: () => [], loadVersion });+ expect(await uncovered({ versionId: 'v2', widgetId: 'w1' })).toBe(true);++ const failing = createDryRunAudit({+ loadGrants: async () => {+ throw new Error('settings unavailable');+ },+ loadVersion,+ });+ expect(await failing({ versionId: 'v2', widgetId: 'w1' })).toBe(true);+ });+});diff --git a/packages/builtin-tool-dashboard/src/interventionAudit.ts b/packages/builtin-tool-dashboard/src/interventionAudit.tsindex a79c250635a..03490e785f1 100644--- a/packages/builtin-tool-dashboard/src/interventionAudit.ts+++ b/packages/builtin-tool-dashboard/src/interventionAudit.ts@@ -1,4 +1,8 @@-import type { DynamicInterventionResolver, WidgetManifest } from '@lobechat/types';+import type {+ DynamicInterventionResolver,+ WidgetDryRunGrant,+ WidgetManifest,+} from '@lobechat/types';/** Registry key of the `dryRunWidget` approval audit (see `dynamicInterventionAudits`). */export const DASHBOARD_DRY_RUN_AUDIT = 'dashboardDryRunAudit';@@ -14,7 +18,46 @@ export const dryRunNeedsApproval = (manifest: WidgetManifest | null | undefined)((manifest.env ?? []).some((item) => !!item.connector) ||(manifest.network?.allow ?? []).length > 0);+/** The access a version asks for: the connectors it reads and the hosts it calls. */+export const dryRunAccessOf = (manifest: WidgetManifest | null | undefined) => ({+ connectors: [+ ...new Set(+ (manifest?.env ?? []).map((item) => item.connector?.trim()).filter((c): c is string => !!c),+ ),+ ].sort(),+ hosts: [+ ...new Set(+ (manifest?.network?.allow ?? []).map((host) => host.trim().toLowerCase()).filter(Boolean),+ ),+ ].sort(),+});++/**+ * Whether one standing grant of the version's own level (personal space or+ * its workspace) covers every connector and host the version asks for.+ * Access is never pooled across grants: approving GitHub-with-its-API and,+ * separately, an unrelated host must not let a script send the GitHub token+ * to that host.+ */+export const isDryRunAccessGranted = (+ manifest: WidgetManifest | null | undefined,+ grants: WidgetDryRunGrant[] | null | undefined,+ workspaceId: string | null | undefined,+) => {+ const access = dryRunAccessOf(manifest);+ const level = workspaceId ?? null;+ return (grants ?? []).some(+ (grant) =>+ (grant.workspaceId ?? null) === level &&+ access.connectors.every((connector) => grant.connectors.includes(connector)) &&+ access.hosts.every((host) => grant.hosts.includes(host)),+ );+};+export interface DryRunAuditOptions {+ /** The user's standing dry-run grants; without it every gated dry run asks. */+ loadGrants?: () =>+ Promise<WidgetDryRunGrant[] | null | undefined> | WidgetDryRunGrant[] | null | undefined;/*** The manifest of one version of a widget the caller may author;* `undefined` when the version cannot be found.@@ -22,23 +65,27 @@ export interface DryRunAuditOptions {loadVersion?: (widgetId: string,versionId: string,- ) => Promise<{ manifest?: WidgetManifest | null } | undefined>;+ ) => Promise<{ manifest?: WidgetManifest | null; workspaceId?: string | null } | undefined>;}/*** Decide whether a `dryRunWidget` call needs approval by reading the exact- * version it names. Fails closed: without a pinned version, a loader, or a- * readable version, it asks the user.+ * version it names: a closed draft, or one whose access a standing grant+ * covers, runs unattended. Fails closed: without a pinned version, a loader,+ * or a readable version — or when the grants cannot be read — it asks.*/export const createDryRunAudit =- ({ loadVersion }: DryRunAuditOptions = {}): DynamicInterventionResolver =>+ ({ loadGrants, loadVersion }: DryRunAuditOptions = {}): DynamicInterventionResolver =>async (toolArgs) => {const { versionId, widgetId } = toolArgs ?? {};if (typeof widgetId !== 'string' || typeof versionId !== 'string' || !loadVersion) return true;try {const version = await loadVersion(widgetId, versionId);if (!version) return true;- return dryRunNeedsApproval(version.manifest);+ if (!dryRunNeedsApproval(version.manifest)) return false;+ if (!loadGrants) return true;+ const grants = await loadGrants();+ return !isDryRunAccessGranted(version.manifest, grants, version.workspaceId);} catch {return true;}diff --git a/packages/database/src/models/__tests__/user.widgetDryRunGrant.test.ts b/packages/database/src/models/__tests__/user.widgetDryRunGrant.test.tsnew file mode 100644index 00000000000..90aad5a0030--- /dev/null+++ b/packages/database/src/models/__tests__/user.widgetDryRunGrant.test.ts@@ -0,0 +1,54 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { users, userSettings } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { UserModel } from '../user';++const userId = 'user-widget-dry-run-grant-test';++const serverDB: LobeChatDatabase = await getTestDB();+const userModel = new UserModel(serverDB, userId);++const grant = {+ connectors: ['github'],+ grantedAt: '2026-10-25T00:00:00.000Z',+ hosts: ['api.github.com'],+ workspaceId: null,+};++const readTool = async () =>+ (await serverDB.query.userSettings.findFirst({ where: eq(userSettings.id, userId) }))?.tool;++describe('UserModel.appendWidgetDryRunGrant', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ it('should create the settings row when none exists', async () => {+ await userModel.appendWidgetDryRunGrant(grant);++ expect(await readTool()).toEqual({ widgetDryRunGrants: [grant] });+ });++ it('should append after stored grants while preserving sibling tool keys', async () => {+ const earlier = { ...grant, hosts: ['api.linear.app'] };+ await serverDB.insert(userSettings).values({+ id: userId,+ tool: { humanIntervention: { approvalMode: 'manual' }, widgetDryRunGrants: [earlier] },+ });++ await userModel.appendWidgetDryRunGrant(grant);++ expect(await readTool()).toEqual({+ humanIntervention: { approvalMode: 'manual' },+ widgetDryRunGrants: [earlier, grant],+ });+ });+});diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex a0fd6b45c21..36cf39cddf8 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -6,6 +6,7 @@ import type {UserKeyVaults,UserPreference,UserSettings,+ WidgetDryRunGrant,} from '@lobechat/types';import { TRPCError } from '@trpc/server';import dayjs from 'dayjs';@@ -370,6 +371,28 @@ export class UserModel {});};+ /**+ * Append one standing widget dry-run grant to `tool.widgetDryRunGrants` in+ * a single statement, so a concurrent writer of another `tool` key (or of+ * another grant) is never clobbered by a stale client snapshot.+ */+ appendWidgetDryRunGrant = async (grant: WidgetDryRunGrant) => {+ const item = JSON.stringify([grant]);++ return this.db+ .insert(userSettings)+ .values({ id: this.userId, tool: { widgetDryRunGrants: [grant] } })+ .onConflictDoUpdate({+ set: {+ tool: sql`coalesce(${userSettings.tool}, '{}'::jsonb) || jsonb_build_object(+ 'widgetDryRunGrants',+ coalesce(${userSettings.tool}->'widgetDryRunGrants', '[]'::jsonb) || ${item}::jsonb+ )`,+ },+ target: userSettings.id,+ });+ };+/*** Atomically replace the uninstalled-builtin-tools list for one scope* (personal, or one workspace's slot) inside the `tool` column, leaving everydiff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 41c44911c41..fd2bbbc995e 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3164,7 +3164,8 @@ export default {'tool.intervention.mode.autoRun': 'Auto Approve','tool.intervention.mode.autoRunDesc': 'Automatically approve all tool executions','tool.intervention.mode.manual': 'Manual',- 'tool.intervention.mode.manualDesc': 'Manual approval required for each invocation',+ 'tool.intervention.mode.manualDesc':+ 'Asks before each invocation, except actions you chose not to be asked about again','tool.intervention.onboarding.agentIdentity.editHint':'You can edit the name or avatar directly below.','tool.intervention.onboarding.agentIdentity.namePlaceholder': 'Agent name',diff --git a/packages/locales/src/default/dashboard.ts b/packages/locales/src/default/dashboard.tsindex 78d5b68cd6b..31c43ea5014 100644--- a/packages/locales/src/default/dashboard.ts+++ b/packages/locales/src/default/dashboard.ts@@ -1,13 +1,10 @@export default {'actions.more': 'More actions',- 'actions.rename': 'Rename','actions.trash': 'Move to trash','actions.trashConfirm':'"{{title}}" and its layout will move to the trash. Widgets stay available and keep their history.','actions.trashTitle': 'Move this dashboard to the trash?','actions.trashed': '"{{title}}" moved to the trash',- 'board.empty':- 'No widgets yet. Ask an agent in a conversation to build a monitoring widget and add it to this dashboard.','board.health.failed': '{{count}} failed','board.health.ok': '{{count}} up to date','board.health.running': '{{count}} refreshing',@@ -60,7 +57,6 @@ export default {'detail.versionPublished': 'v{{version}} live','dryRun.intro':'The agent wants to run this draft once to preview its output. It runs in a sandbox with the access below; nothing goes live and no dashboard changes.',- 'dryRun.runtime': 'Runtime','error.hideDetails': 'Hide details','error.showDetails': 'Show details','form.descriptionLabel': 'Description',@@ -77,14 +73,6 @@ export default {'No widgets yet. Ask an agent in a conversation of this project to build a monitoring widget and it will show up here.','layout.cancel': 'Discard changes','layout.drag': 'Drag to reorder',- 'layout.edit': 'Edit layout',- 'layout.narrower': 'Narrower',- 'layout.save': 'Save layout',- 'layout.saveFailed': 'Could not save the layout. The previous layout is restored.',- 'layout.saved': 'Layout saved',- 'layout.shorter': 'Shorter',- 'layout.taller': 'Taller',- 'layout.wider': 'Wider','list.description':'Boards of live widgets. Each widget runs its own script on a schedule and keeps its history.','list.empty': 'No dashboards yet',@@ -113,12 +101,14 @@ export default {'publish.networkNone': 'No network access','publish.noSuccessfulRun':'This draft has not succeeded in a dry run yet, so publishing it will be refused.',- 'publish.previewTitle': 'Latest dry run','publish.schedule': 'Refresh','publish.scheduleNone': 'Manual only','publish.scriptChanges': 'Changes from live v{{version}}','publish.scriptNew': 'Script',- 'rename.title': 'Rename dashboard',+ 'review.expected': 'What it will look like',+ 'review.expectedEarlier':+ "for reference, v{{version}}'s last result; approving runs this draft to make its own",+ 'review.expectedSameVersion': "from this version's last dry run",'review.loadFailed': "Couldn't load the review, so approval is on hold",'review.versionMissing':"This version is no longer available, so it can't be reviewed. Reject the request and ask the agent to try again.",@@ -165,4 +155,61 @@ export default {'widget.view.more': '+{{count}} more','widget.view.seriesEmpty': 'No data points','widget.view.tableEmpty': 'No rows',+ 'actions.settings': 'Settings',+ 'settings.title': 'Dashboard settings',+ 'settings.visibility': 'Who can see it',+ 'settings.visibilityPrivate': 'Only me',+ 'settings.visibilityPublic': 'Workspace members',+ 'settings.visibilityKeptPrivate':+ 'Saved. The dashboard stays visible only to you because its project is private.',+ 'settings.schedule': 'Widget refresh',+ 'settings.scheduleHint_one': 'Applies to the {{count}} widget you created on this dashboard.',+ 'settings.scheduleHint_other': 'Applies to the {{count}} widgets you created on this dashboard.',+ 'settings.scheduleOthers_one': '{{count}} widget created by others keeps its own refresh.',+ 'settings.scheduleOthers_other': '{{count}} widgets created by others keep their own refresh.',+ 'settings.scheduleKeep': "Keep each widget's current refresh",+ 'settings.scheduleKeepCustom': 'Keep current ({{pattern}})',+ 'settings.scheduleNoWidgets': 'No widgets on this dashboard yet.',+ 'settings.scheduleNotOwner':+ "Only a widget's creator can change its refresh, and you created none of the widgets here.",+ 'settings.scheduleFailed_one':+ "Settings saved, but {{count}} widget's refresh could not be changed",+ 'settings.scheduleFailed_other':+ "Settings saved, but {{count}} widgets' refresh could not be changed",+ 'settings.saved': 'Settings saved',+ 'schedule.manual': 'Manual refresh only',+ 'schedule.every15m': 'Every 15 minutes',+ 'schedule.every30m': 'Every 30 minutes',+ 'schedule.hourly': 'Every hour',+ 'schedule.every6h': 'Every 6 hours',+ 'schedule.daily9': 'Daily at 09:00',+ 'layout.edit': 'Edit dashboard',+ 'layout.resize': 'Drag to resize (or use the arrow keys)',+ 'dryRun.rememberFailed':+ "Approved, but this access couldn't be remembered. You'll be asked again next time.",+ 'layout.save': 'Save layout',+ 'layout.saveFailed': 'Could not save the layout. The previous layout is restored.',+ 'layout.saved': 'Layout saved',+ 'review.expectedSample':+ 'sample data showing the card it will make; approving produces the real result',+ 'review.sampleTag': 'Sample',+ 'review.sampleItem': 'Sample item {{index}}',+ 'review.sampleName': 'Name',+ 'review.sampleValue': 'Value',+ 'widgetEdit.action': 'Edit widget',+ 'widgetEdit.title': 'Edit widget',+ 'widgetEdit.titleLabel': 'Title',+ 'widgetEdit.descriptionPlaceholder': 'Data source, filters, time window and unit',+ 'widgetEdit.saved': 'Widget updated',+ 'board.emptyTitle': 'This dashboard has no widgets yet',+ 'board.emptyDescription':+ 'A widget is a small script that runs on a schedule and shows its result as a card here. Ask an agent to write and dry-run one for you; it goes live only after you approve it.',+ 'board.emptyKind.stat': 'Number',+ 'board.emptyKind.list': 'List',+ 'board.emptyKind.series': 'Trend',+ 'board.emptyKind.table': 'Table',+ 'board.emptyAction': 'Ask an agent to build a widget',+ 'board.emptyPrompt':+ 'Build a monitoring widget and put it on the dashboard "{{title}}". I want to see: ',+ 'board.emptyAgentUnavailable': "Couldn't open the agent. Try again in a moment.",};diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 9a6ee921c93..db867816c7a 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -6,6 +6,8 @@ import { type RuntimeStepContext } from '../stepContext';import { type HumanInterventionConfig, type HumanInterventionPolicy } from './intervention';import { HumanInterventionConfigSchema, HumanInterventionPolicySchema } from './intervention';+export * from './builtinIntervention';+export interface Meta {/*** avatar@@ -569,55 +571,6 @@ export interface BuiltinServerRuntimeOutput {toolMessageId?: string;}-export interface BuiltinInterventionProps<Arguments = any> {- /**- * When present, a custom intervention should portal its action footer- * (submit / skip + status) into this node so it stays pinned below the- * scrollable content instead of scrolling with it. Hosts that render a fixed- * footer (e.g. the global approval card) supply this; when absent the- * component renders its footer inline.- */- actionsPortalTarget?: HTMLElement | null;- apiName?: string;- args: Arguments;- /** Keep the form visible but inert while a remote resolution awaits producer ACK. */- disabled?: boolean;- identifier?: string;- interactionMode?: 'approval' | 'custom';- messageId: string;- /**- * Hold the host's approve action while the intervention cannot show what is- * being approved — e.g. its review data is still loading or failed to load.- * Pass `true` to block approval and `false` to release it; reject / stop stay- * available. Hosts without approval controls ignore it. Only approval-mode- * interventions receive it.- */- onApprovalBlockedChange?: (blocked: boolean) => void;- /**- * Callback to update the arguments before approval- * This is called when the user modifies the intervention content- * The approve action will wait for this async callback to complete- */- onArgsChange?: (args: Arguments) => void | Promise<void>;- onInteractionAction?: (- action:- | { type: 'submit'; payload: Record<string, unknown> }- | { type: 'skip'; payload?: Record<string, unknown>; reason?: string }- | { type: 'cancel'; payload?: Record<string, unknown> },- ) => Promise<void>;- /**- * Register a callback to be called before approval- * Used by intervention components that need to flush pending saves (e.g., debounced saves)- * before the approve action proceeds- * @param id - Unique identifier for the callback (for reliable cleanup)- * @param callback - The callback to execute before approval- * @returns Cleanup function to unregister the callback- */- registerBeforeApprove?: (id: string, callback: () => void | Promise<void>) => () => void;-}--export type BuiltinIntervention = (props: BuiltinInterventionProps) => ReactNode;-// ==================== Executor Types ====================/**diff --git a/packages/types/src/tool/builtinIntervention.ts b/packages/types/src/tool/builtinIntervention.tsnew file mode 100644index 00000000000..007e8619088--- /dev/null+++ b/packages/types/src/tool/builtinIntervention.ts@@ -0,0 +1,67 @@+import { type ReactNode } from 'react';++// Props a builtin tool's approval / interaction card receives from its host.++export interface BuiltinInterventionProps<Arguments = any> {+ /**+ * When present, a custom intervention should portal its action footer+ * (submit / skip + status) into this node so it stays pinned below the+ * scrollable content instead of scrolling with it. Hosts that render a fixed+ * footer (e.g. the global approval card) supply this; when absent the+ * component renders its footer inline.+ */+ actionsPortalTarget?: HTMLElement | null;+ apiName?: string;+ args: Arguments;+ /** Keep the form visible but inert while a remote resolution awaits producer ACK. */+ disabled?: boolean;+ identifier?: string;+ interactionMode?: 'approval' | 'custom';+ messageId: string;+ /**+ * Hold the host's approve action while the intervention cannot show what is+ * being approved — e.g. its review data is still loading or failed to load.+ * Pass `true` to block approval and `false` to release it; reject / stop stay+ * available. Hosts without approval controls ignore it. Only approval-mode+ * interventions receive it.+ */+ onApprovalBlockedChange?: (blocked: boolean) => void;+ /**+ * Callback to update the arguments before approval+ * This is called when the user modifies the intervention content+ * The approve action will wait for this async callback to complete+ */+ onArgsChange?: (args: Arguments) => void | Promise<void>;+ onInteractionAction?: (+ action:+ | { type: 'submit'; payload: Record<string, unknown> }+ | { type: 'skip'; payload?: Record<string, unknown>; reason?: string }+ | { type: 'cancel'; payload?: Record<string, unknown> },+ ) => Promise<void>;+ /**+ * Register a callback to be called before approval+ * Used by intervention components that need to flush pending saves (e.g., debounced saves)+ * before the approve action proceeds+ * @param id - Unique identifier for the callback (for reliable cleanup)+ * @param callback - The callback to execute before approval+ * @returns Cleanup function to unregister the callback+ */+ registerBeforeApprove?: (id: string, callback: () => void | Promise<void>) => () => void;+ /**+ * Define what "similar" means for this tool's shared "approve, and don't+ * ask again for similar actions" choice (e.g. the same access rather than+ * the whole tool). The host runs `onRemember` right before approving when+ * the user picks that choice; a plain approve or a rejection never runs it.+ * Without it, the choice puts the whole tool on the allow-list. Only+ * approval-mode interventions receive it.+ * @returns Cleanup function that withdraws the definition+ */+ registerRememberApproval?: (option: BuiltinRememberApproval) => () => void;+}++/** A tool's own "don't ask again for similar actions" step (see `registerRememberApproval`). */+export interface BuiltinRememberApproval {+ onRemember: () => void | Promise<void>;+}++export type BuiltinIntervention = (props: BuiltinInterventionProps) => ReactNode;diff --git a/packages/types/src/user/settings/tool.ts b/packages/types/src/user/settings/tool.tsindex f8c5727c83e..002950b2cd5 100644--- a/packages/types/src/user/settings/tool.ts+++ b/packages/types/src/user/settings/tool.ts@@ -1,4 +1,5 @@import type { UserInterventionConfig } from '../../tool';+import type { WidgetDryRunGrant } from '../../widget';export interface UserToolConfig {/**@@ -34,6 +35,11 @@ export interface UserToolConfig {* default state), not the user's personal `uninstalledBuiltinTools`.*/uninstalledBuiltinToolsByWorkspace?: Record<string, string[]>;+ /**+ * Access the user approved for widget dry runs "from now on" (see+ * `WidgetDryRunGrant`). Appended from the dry-run approval card.+ */+ widgetDryRunGrants?: WidgetDryRunGrant[];}/**diff --git a/packages/types/src/widget/index.ts b/packages/types/src/widget/index.tsindex 67f1a598ef7..aa3902060c0 100644--- a/packages/types/src/widget/index.ts+++ b/packages/types/src/widget/index.ts@@ -161,6 +161,22 @@ export interface WidgetEnvInject {prefix?: string;}+/**+ * The user's standing approval to dry-run widget scripts with some access:+ * a draft whose connectors and hosts all fall inside one grant of its own+ * level runs without asking again. Stored in the user's tool settings.+ */+export interface WidgetDryRunGrant {+ /** Connectors the approved scripts may read, e.g. ['github']. */+ connectors: string[];+ /** ISO time the user gave it. */+ grantedAt: string;+ /** Hosts the approved scripts may call, exactly as declared in `network.allow`. */+ hosts: string[];+ /** Workspace the grant holds in; `null` for the personal space. */+ workspaceId: string | null;+}+/*** Declarative contract stored beside the script: what it needs to run and how* the platform should treat its output.diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsxindex 028fa2aecf5..a2aa0858680 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx@@ -1,13 +1,23 @@import { registerPendingHotkeyCard } from '@lobechat/shared-tool-ui/pending-hotkeys';+import type { BuiltinRememberApproval } from '@lobechat/types';import { Button, createStaticStyles, cx, Flexbox } from '@lobehub/ui';import { CircleStop, CornerDownLeft } from 'lucide-react';import type { KeyboardEvent as ReactKeyboardEvent } from 'react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useToolStore } from '@/store/tool';+import { toolSelectors } from '@/store/tool/selectors';+import { useConversationResourceAccess } from '../../../../../hooks/useConversationResourceAccess';import { useConversationStore } from '../../../../../store';-import { type ApprovalChoice, isChoiceSubmitBlocked } from './approvalGate';+import {+ type ApprovalChoice,+ canRememberViaAllowList,+ getApprovalChoices,+ isChoiceSubmitBlocked,+ resolveRememberAction,+} from './approvalGate';import { type ApprovalMode } from './index';import { isSubmitShortcutBlockedByTarget } from './submitShortcutGuard';@@ -28,6 +38,10 @@ interface ApprovalActionsProps {*/onBeforeApprove?: () =>Promise<Record<string, unknown> | undefined> | Record<string, unknown> | undefined;+ /** The tool's own "approve and remember" step, when its intervention defines "similar". */+ rememberOption?: BuiltinRememberApproval;+ /** The call's arguments: a call that must always ask cannot be remembered. */+ toolArgs?: Record<string, unknown>;toolCallId: string;}@@ -142,6 +156,8 @@ const ApprovalActions = memo<ApprovalActionsProps>(identifier,messageId,onBeforeApprove,+ rememberOption,+ toolArgs,}) => {const { t } = useTranslation('chat');const [choice, setChoice] = useState<Choice>('approve');@@ -150,18 +166,38 @@ const ApprovalActions = memo<ApprovalActionsProps>(const rejectInputRef = useRef<HTMLInputElement>(null);const isMessageCreating = messageId.startsWith('tmp_');- const isAllowListMode = approvalMode === 'allow-list';// Workspace topics are shared: a view-only member can be LOOKING at a// teammate's running conversation — they must not drive its tool approvals.const { canUseResource } = useConversationResourceAccess();+ // "Approve, and don't ask again for similar actions" is one shared choice+ // for every tool. A tool may define "similar" itself (its own remember+ // step); otherwise the tool joins the allow-list, which only helps when+ // this call is not one that must always ask.+ const interventionConfig = useToolStore(+ (s) =>+ toolSelectors+ .getManifestById(identifier)(s)+ ?.api?.find((api) => api.name === apiName)?.humanIntervention,+ );+ const allowListRememberable = useMemo(+ () => canRememberViaAllowList({ config: interventionConfig, toolArgs }),+ [interventionConfig, toolArgs],+ );+ const hasToolRemember = !!rememberOption;// Ordered choices drive both the numbered rows and the 1/2/3 shortcuts.- // "Approve & don't ask again" is a first-class option (allow-list only)- // rather than a checkbox nested under approve.const choices = useMemo<Choice[]>(- () => (isAllowListMode ? ['approve', 'approve-remember', 'reject'] : ['approve', 'reject']),- [isAllowListMode],+ () =>+ getApprovalChoices({+ allowListRememberable,+ approvalMode,+ toolRemember: hasToolRemember,+ }),+ [allowListRememberable, approvalMode, hasToolRemember],);+ // A tool's choice can be withdrawn while the card is open; fall back to plain approve.+ const effectiveChoice: Choice = choices.includes(choice) ? choice : 'approve';+ const rememberAction = resolveRememberAction({ toolRemember: hasToolRemember });const [approveToolCall, rejectAndContinueToolCall, stopPendingApprovalForCard] =useConversationStore((s) => [@@ -195,18 +231,22 @@ const ApprovalActions = memo<ApprovalActionsProps>(stopPendingApprovalForCard,messageId,]);- const submitBlocked = isChoiceSubmitBlocked(choice, approveDisabled);+ const submitBlocked = isChoiceSubmitBlocked(effectiveChoice, approveDisabled);const handleSubmit = useCallback(async () => {if (loading || isMessageCreating || !canUseResource || submitBlocked) return;setLoading(true);try {- if (choice === 'reject') {+ if (effectiveChoice === 'reject') {await rejectAndContinueToolCall(messageId, reason.trim() || undefined);} else {+ const remember = effectiveChoice === 'approve-remember';+ // The tool's own remember step runs first, so the very next call+ // after this approval already sees it.+ if (remember && rememberAction === 'tool') await rememberOption?.onRemember();const editedArguments = await onBeforeApprove?.();await approveToolCall(messageId, assistantGroupId ?? '', {editedArguments,- ...(isAllowListMode && choice === 'approve-remember'+ ...(remember && rememberAction === 'allow-list'? { rememberToolKey: `${identifier}/${apiName}` }: {}),});@@ -219,15 +259,16 @@ const ApprovalActions = memo<ApprovalActionsProps>(approveToolCall,assistantGroupId,canUseResource,- choice,+ effectiveChoice,identifier,- isAllowListMode,isMessageCreating,loading,messageId,onBeforeApprove,reason,rejectAndContinueToolCall,+ rememberAction,+ rememberOption,submitBlocked,]);@@ -367,9 +408,9 @@ const ApprovalActions = memo<ApprovalActionsProps>(return (<div- aria-checked={choice === c}+ aria-checked={effectiveChoice === c}aria-disabled={approveDisabled || undefined}- className={cx(styles.option, choice === c && styles.optionSelected)}+ className={cx(styles.option, effectiveChoice === c && styles.optionSelected)}key={c}role="radio"onClick={() => setChoice(c)}diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsxindex 38367f2ce81..7e849c1019b 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx@@ -179,6 +179,7 @@ const FallbackIntervention = memo<FallbackInterventionProps>(assistantGroupId={assistantGroupId}identifier={identifier}messageId={id}+ toolArgs={parsedArgs}toolCallId={toolCallId}onBeforeApprove={() => pendingEditedArgumentsRef.current}/>diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.tsindex cade3732ef2..1d9585f3844 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from 'vitest';-import { isChoiceSubmitBlocked } from './approvalGate';+import {+ canRememberViaAllowList,+ getApprovalChoices,+ isChoiceSubmitBlocked,+ resolveRememberAction,+} from './approvalGate';describe('isChoiceSubmitBlocked', () => {it('holds both approve choices while the intervention blocks approval', () => {@@ -18,3 +23,66 @@ describe('isChoiceSubmitBlocked', () => {expect(isChoiceSubmitBlocked('reject')).toBe(false);});});++describe('getApprovalChoices', () => {+ const withRemember = ['approve', 'approve-remember', 'reject'];++ it('offers the shared remember choice in manual and allow-list modes', () => {+ for (const approvalMode of ['manual', 'allow-list']) {+ expect(+ getApprovalChoices({ allowListRememberable: true, approvalMode, toolRemember: false }),+ ).toEqual(withRemember);+ }+ });++ it('hides it when remembering could never take effect', () => {+ expect(+ getApprovalChoices({+ allowListRememberable: false,+ approvalMode: 'manual',+ toolRemember: false,+ }),+ ).toEqual(['approve', 'reject']);+ expect(+ getApprovalChoices({+ allowListRememberable: true,+ approvalMode: 'auto-run',+ toolRemember: false,+ }),+ ).toEqual(['approve', 'reject']);+ });++ it("offers it whenever the tool defines its own 'similar'", () => {+ expect(+ getApprovalChoices({+ allowListRememberable: false,+ approvalMode: 'manual',+ toolRemember: true,+ }),+ ).toEqual(withRemember);+ });+});++describe('resolveRememberAction', () => {+ it("uses the tool's own remember step, else the allow-list", () => {+ expect(resolveRememberAction({ toolRemember: true })).toBe('tool');+ expect(resolveRememberAction({ toolRemember: false })).toBe('allow-list');+ });+});++describe('canRememberViaAllowList', () => {+ it('allows tools that ask by default or by rule', () => {+ expect(canRememberViaAllowList({ config: 'required' })).toBe(true);+ expect(canRememberViaAllowList({ config: undefined })).toBe(true);+ });++ it('refuses calls that must always ask', () => {+ expect(canRememberViaAllowList({ config: 'always' })).toBe(false);+ expect(+ canRememberViaAllowList({ config: { dynamic: { policy: 'always', type: 'audit' } } }),+ ).toBe(false);+ expect(canRememberViaAllowList({ config: 'required', toolArgs: { command: 'rm -rf /' } })).toBe(+ false,+ );+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.tsindex fc9636d8c7c..e487b78233e 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.ts@@ -1,3 +1,6 @@+import { DEFAULT_SECURITY_BLACKLIST, InterventionChecker } from '@lobechat/agent-runtime';+import type { HumanInterventionConfig } from '@lobechat/types';+export type ApprovalChoice = 'approve' | 'approve-remember' | 'reject';/**@@ -7,3 +10,66 @@ export type ApprovalChoice = 'approve' | 'approve-remember' | 'reject';*/export const isChoiceSubmitBlocked = (choice: ApprovalChoice, approveDisabled = false) =>approveDisabled && choice !== 'reject';++/**+ * Whether "approve, and don't ask again" can take effect for a call through+ * the allow-list (the generic remember step): the runtime skips approval for+ * allow-listed tools in manual and allow-list modes, but never for calls+ * that must always ask — an `always` policy, static or dynamic, or a+ * security-blacklist match.+ */+export const canRememberViaAllowList = ({+ config,+ toolArgs = {},+}: {+ config?: unknown;+ toolArgs?: Record<string, unknown>;+}) => {+ if (InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, toolArgs).blocked) {+ return false;+ }+ if (config && typeof config === 'object' && !Array.isArray(config) && 'dynamic' in config) {+ const dynamic = (config as { dynamic?: { policy?: string } }).dynamic;+ return dynamic?.policy !== 'always';+ }+ return (+ InterventionChecker.shouldIntervene({+ config: config as HumanInterventionConfig | undefined,+ securityBlacklist: [],+ toolArgs,+ }) !== 'always'+ );+};++/**+ * The choices an approval card lists, in order. "Approve, and don't ask again+ * for similar actions" is one shared choice for every tool: offered when the+ * tool defines its own notion of "similar" (a remember step of its own), or+ * when the allow-list can remember the tool in the current mode.+ */+export const getApprovalChoices = ({+ allowListRememberable,+ approvalMode,+ toolRemember,+}: {+ allowListRememberable: boolean;+ approvalMode: string;+ toolRemember: boolean;+}): ApprovalChoice[] => {+ const viaAllowList =+ allowListRememberable && (approvalMode === 'manual' || approvalMode === 'allow-list');+ return toolRemember || viaAllowList+ ? ['approve', 'approve-remember', 'reject']+ : ['approve', 'reject'];+};++/**+ * What "approve and don't ask again" does: a tool's own remember step (e.g.+ * a standing grant scoped to the same access) when it offers one, otherwise+ * the tool joins the allow-list.+ */+export const resolveRememberAction = ({+ toolRemember,+}: {+ toolRemember: boolean;+}): 'allow-list' | 'tool' => (toolRemember ? 'tool' : 'allow-list');diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsxindex ada3935466d..ae39d5ea596 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx@@ -1,4 +1,5 @@import { getBuiltinIntervention } from '@lobechat/builtin-tools/interventions';+import type { BuiltinRememberApproval } from '@lobechat/types';import { safeParseJSON } from '@lobechat/utils';import { Flexbox } from '@lobehub/ui';import { memo, Suspense, useCallback, useMemo, useRef, useState } from 'react';@@ -46,6 +47,12 @@ const Intervention = memo<InterventionProps>(// Raised by an intervention that cannot show what is being approved yet// (review data loading or failed); the approve action waits on it.const [approvalBlocked, setApprovalBlocked] = useState(false);+ // A tool-specific "approve and remember" choice the intervention offers.+ const [rememberOption, setRememberOption] = useState<BuiltinRememberApproval>();+ const registerRememberApproval = useCallback((option: BuiltinRememberApproval) => {+ setRememberOption(option);+ return () => setRememberOption((current) => (current === option ? undefined : current));+ }, []);const updatePluginArguments = useConversationStore((s) => s.updatePluginArguments);const message = useConversationStore((s) => dataSelectors.getDbMessageById(id)(s));const usesDurableServerClaim = Boolean(@@ -317,6 +324,8 @@ const Intervention = memo<InterventionProps>(assistantGroupId={assistantGroupId}identifier={identifier}messageId={id}+ rememberOption={rememberOption}+ toolArgs={parsedArgs}toolCallId={toolCallId}onBeforeApprove={handleBeforeApprove}/>@@ -332,6 +341,7 @@ const Intervention = memo<InterventionProps>(identifier={identifier}messageId={id}registerBeforeApprove={registerBeforeApprove}+ registerRememberApproval={registerRememberApproval}onApprovalBlockedChange={setApprovalBlocked}onArgsChange={handleArgsChange}/>diff --git a/src/features/Dashboard/Board/BoardEmpty.tsx b/src/features/Dashboard/Board/BoardEmpty.tsxnew file mode 100644index 00000000000..98816d866d5--- /dev/null+++ b/src/features/Dashboard/Board/BoardEmpty.tsx@@ -0,0 +1,92 @@+'use client';++import { AGENT_CHAT_URL } from '@lobechat/const';+import { Button, Center, Empty, Flexbox, Icon, Tag, toast } from '@lobehub/ui';+import {+ HashIcon,+ LayoutDashboardIcon,+ ListIcon,+ SparklesIcon,+ TableIcon,+ TrendingUpIcon,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { queueDraftForMainComposer } from '@/features/Conversation/composerDraftBus';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { usePermission } from '@/hooks/usePermission';+import { useAgentStore } from '@/store/agent';+import { builtinAgentSelectors } from '@/store/agent/selectors';++/** The kinds of card a widget can put on a board, shown as what this board will hold. */+const CARD_KINDS = [+ { icon: HashIcon, key: 'stat' },+ { icon: ListIcon, key: 'list' },+ { icon: TrendingUpIcon, key: 'series' },+ { icon: TableIcon, key: 'table' },+] as const;++interface BoardEmptyProps {+ /** The board's name, written into the prompt so the agent places the widget here. */+ title?: string;+}++/**+ * A board with no widgets yet: what a widget is, the cards it can show, and+ * the way to get one — asking an agent, which writes, dry-runs and (after the+ * user approves) publishes it onto this board. Users who cannot create+ * content get the explanation without the action.+ */+const BoardEmpty = ({ title }: BoardEmptyProps) => {+ const { t } = useTranslation('dashboard');+ const navigate = useWorkspaceAwareNavigate();+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);+ const { allowed: canCreate } = usePermission('create_content');++ const handleCreate = () => {+ if (!inboxAgentId) {+ toast.error(t('board.emptyAgentUnavailable'));+ return;+ }+ queueDraftForMainComposer(t('board.emptyPrompt', { title: title ?? '' }), {+ agentId: inboxAgentId,+ });+ navigate(AGENT_CHAT_URL(inboxAgentId));+ };++ return (+ <Center data-dashboard-board-empty flex={1} padding={48}>+ <Empty+ align={'center'}+ description={t('board.emptyDescription')}+ descriptionProps={{ style: { textAlign: 'center' } }}+ icon={LayoutDashboardIcon}+ style={{ maxWidth: 440 }}+ title={t('board.emptyTitle')}+ action={+ <Flexbox align={'center'} gap={16}>+ <Flexbox horizontal gap={6} justify={'center'} wrap={'wrap'}>+ {CARD_KINDS.map(({ icon, key }) => (+ <Tag icon={<Icon icon={icon} />} key={key}>+ {t(`board.emptyKind.${key}`)}+ </Tag>+ ))}+ </Flexbox>+ {canCreate && (+ <Button+ data-dashboard-board-empty-create+ icon={SparklesIcon}+ type={'primary'}+ onClick={handleCreate}+ >+ {t('board.emptyAction')}+ </Button>+ )}+ </Flexbox>+ }+ />+ </Center>+ );+};++export default BoardEmpty;diff --git a/src/features/Dashboard/Board/LayoutEditor.tsx b/src/features/Dashboard/Board/LayoutEditor.tsxindex f48d848b0f7..ce58707462c 100644--- a/src/features/Dashboard/Board/LayoutEditor.tsx+++ b/src/features/Dashboard/Board/LayoutEditor.tsx@@ -18,89 +18,126 @@ import {} from '@dnd-kit/sortable';import { CSS } from '@dnd-kit/utilities';import type { DashboardItemLayout } from '@lobechat/types';-import { ActionIcon, Button, cx, Flexbox, Icon, toast } from '@lobehub/ui';+import { ActionIcon, Button, cx, Flexbox, Icon, Text, toast } from '@lobehub/ui';+import { GripVerticalIcon, MoveDiagonal2Icon, PencilIcon } from 'lucide-react';import {- ChevronDownIcon,- ChevronLeftIcon,- ChevronRightIcon,- ChevronUpIcon,- GripVerticalIcon,-} from 'lucide-react';-import { memo, useMemo, useState } from 'react';+ type KeyboardEvent as ReactKeyboardEvent,+ memo,+ type PointerEvent as ReactPointerEvent,+ useMemo,+ useState,+} from 'react';import { useTranslation } from 'react-i18next';import type { DashboardBoardItem } from '@/services/dashboard';import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';import {- DASHBOARD_MAX_H,DASHBOARD_MIN_H,- DASHBOARD_WIDTH_PRESETS,+ DASHBOARD_STACKED_QUERY,flowLayouts,+ resizeByKey,+ resizeByPointer,} from '../utils/layout';import WidgetCard from '../WidgetCard';+import { openWidgetEditModal } from '../WidgetEditModal';import { cellStyle, gridStyles } from './style';type Size = { h: number; w: number };-const stepWidth = (w: number, direction: 1 | -1) => {- const presets = [...DASHBOARD_WIDTH_PRESETS];- if (direction > 0) return presets.find((preset) => preset > w) ?? w;- return presets.reverse().find((preset) => preset < w) ?? w;+interface ResizeHandleProps {+ layout: DashboardItemLayout;+ onResize: (size: Size) => void;+}++/** Whether the board is stacked in one column right now (narrow screen). */+const isStacked = () =>+ typeof window !== 'undefined' && window.matchMedia(DASHBOARD_STACKED_QUERY).matches;++/**+ * The card's bottom-right corner: drag to resize in whole columns and rows,+ * or focus it and use the arrow keys. On a stacked (narrow) board it resizes+ * height only, since every card spans the full width there.+ */+const ResizeHandle = ({ layout, onResize }: ResizeHandleProps) => {+ const { t } = useTranslation('dashboard');+ const [active, setActive] = useState(false);++ const handlePointerDown = (event: ReactPointerEvent<HTMLButtonElement>) => {+ if (event.button !== 0) return;+ event.preventDefault();+ event.stopPropagation();+ const handle = event.currentTarget;+ const gridWidth = handle.closest('[data-dashboard-grid]')?.getBoundingClientRect().width ?? 0;+ const start = { h: layout.h, w: layout.w };+ const origin = { x: event.clientX, y: event.clientY };+ const stacked = isStacked();++ const handleMove = (moveEvent: PointerEvent) =>+ onResize(+ resizeByPointer(+ start,+ { dx: moveEvent.clientX - origin.x, dy: moveEvent.clientY - origin.y },+ gridWidth,+ { stacked },+ ),+ );+ const handleEnd = () => {+ setActive(false);+ handle.removeEventListener('pointermove', handleMove);+ handle.removeEventListener('pointerup', handleEnd);+ handle.removeEventListener('pointercancel', handleEnd);+ };++ handle.setPointerCapture(event.pointerId);+ setActive(true);+ handle.addEventListener('pointermove', handleMove);+ handle.addEventListener('pointerup', handleEnd);+ handle.addEventListener('pointercancel', handleEnd);+ };++ const handleKeyDown = (event: ReactKeyboardEvent<HTMLButtonElement>) => {+ const next = resizeByKey(layout, event.key, { stacked: isStacked() });+ if (!next) return;+ event.preventDefault();+ onResize(next);+ };++ return (+ <button+ data-resize-handle+ aria-label={t('layout.resize')}+ className={gridStyles.resizeHandle}+ data-active={active}+ title={t('layout.resize')}+ type={'button'}+ onKeyDown={handleKeyDown}+ onPointerDown={handlePointerDown}+ >+ <Icon icon={MoveDiagonal2Icon} size={14} />+ </button>+ );};interface EditableCellProps {+ /** The user created this widget and may edit its title and metric definition. */+ editable: boolean;entry: DashboardBoardItem;layout: DashboardItemLayout;onResize: (size: Size) => void;}-const EditableCell = memo<EditableCellProps>(({ entry, layout, onResize }) => {+const EditableCell = memo<EditableCellProps>(({ entry, layout, onResize, editable }) => {const { t } = useTranslation('dashboard');const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({id: entry.item.id,});- const resizeActions = (- <>- <ActionIcon- aria-label={t('layout.narrower')}- disabled={layout.w <= DASHBOARD_WIDTH_PRESETS[0]}- icon={ChevronLeftIcon}- size={'small'}- title={t('layout.narrower')}- onClick={() => onResize({ h: layout.h, w: stepWidth(layout.w, -1) })}- />- <ActionIcon- aria-label={t('layout.wider')}- disabled={layout.w >= DASHBOARD_WIDTH_PRESETS.at(-1)!}- icon={ChevronRightIcon}- size={'small'}- title={t('layout.wider')}- onClick={() => onResize({ h: layout.h, w: stepWidth(layout.w, 1) })}- />- <ActionIcon- aria-label={t('layout.shorter')}- disabled={layout.h <= DASHBOARD_MIN_H}- icon={ChevronUpIcon}- size={'small'}- title={t('layout.shorter')}- onClick={() => onResize({ h: layout.h - 1, w: layout.w })}- />- <ActionIcon- aria-label={t('layout.taller')}- disabled={layout.h >= DASHBOARD_MAX_H}- icon={ChevronDownIcon}- size={'small'}- title={t('layout.taller')}- onClick={() => onResize({ h: layout.h + 1, w: layout.w })}- />- </>- );-return (<div- className={cx(gridStyles.cell, isDragging && gridStyles.cellDragging)}+ className={cx(gridStyles.cell, gridStyles.editCell, isDragging && gridStyles.cellDragging)}data-layout-cell={entry.item.id}ref={setNodeRef}style={{@@ -110,7 +147,6 @@ const EditableCell = memo<EditableCellProps>(({ entry, layout, onResize }) => {}}><WidgetCard- actions={resizeActions}className={gridStyles.editCard}widget={entry.widget}handle={@@ -123,7 +159,24 @@ const EditableCell = memo<EditableCellProps>(({ entry, layout, onResize }) => {<Icon icon={GripVerticalIcon} size={14} /></span>}+ title={+ <Flexbox horizontal align={'center'} gap={2} style={{ flex: 1, minWidth: 0 }}>+ <Text ellipsis title={entry.widget.title} weight={500}>+ {entry.widget.title}+ </Text>+ {editable && (+ <ActionIcon+ data-widget-edit+ icon={PencilIcon}+ size={'small'}+ title={t('widgetEdit.action')}+ onClick={() => openWidgetEditModal(entry.widget)}+ />+ )}+ </Flexbox>+ }/>+ <ResizeHandle layout={layout} onResize={onResize} /></div>);});@@ -140,13 +193,17 @@ interface LayoutEditorProps {}/**- * Edit a board's layout as a draft: drag to reorder, step width / height, then- * save every cell to `dashboard_items.layout` in one request or discard.+ * Edit a board's layout as a draft: drag cards to reorder, drag a corner to+ * resize, then save every cell to `dashboard_items.layout` in one request or+ * discard. A widget's own title and metric definition are edited from its+ * pencil icon and save on their own, outside the draft.*/const LayoutEditor = memo<LayoutEditorProps>(({ dashboardId, items, initialLayouts, onDone }) => {const { t } = useTranslation('dashboard');const saveDashboardLayout = useDashboardStore((s) => s.saveDashboardLayout);const saving = useDashboardStore(dashboardSelectors.isLayoutSaving(dashboardId));+ // Only a widget's creator may edit it; everyone else sees its title as is.+ const userId = useUserStore(userProfileSelectors.userId);const [order, setOrder] = useState(() => items.map((entry) => entry.item.id));const [sizes, setSizes] = useState<Record<string, Size>>(() =>@@ -195,7 +252,12 @@ const LayoutEditor = memo<LayoutEditorProps>(({ dashboardId, items, initialLayou<Button disabled={saving} onClick={onDone}>{t('layout.cancel')}</Button>- <Button loading={saving} type={'primary'} onClick={() => void handleSave()}>+ <Button+ data-dashboard-layout-save+ loading={saving}+ type={'primary'}+ onClick={() => void handleSave()}+ >{t('layout.save')}</Button></Flexbox>@@ -208,10 +270,17 @@ const LayoutEditor = memo<LayoutEditorProps>(({ dashboardId, items, initialLayouif (!entry || !layout) return null;return (<EditableCell+ editable={!!userId && entry.widget.userId === userId}entry={entry}key={id}layout={layout}- onResize={(size) => setSizes((current) => ({ ...current, [id]: size }))}+ onResize={(size) =>+ setSizes((current) =>+ current[id]?.w === size.w && current[id]?.h === size.h+ ? current+ : { ...current, [id]: size },+ )+ }/>);})}diff --git a/src/features/Dashboard/Board/index.tsx b/src/features/Dashboard/Board/index.tsxindex c8949ec1b00..e28cdc9467a 100644--- a/src/features/Dashboard/Board/index.tsx+++ b/src/features/Dashboard/Board/index.tsx@@ -1,7 +1,6 @@'use client';-import { Center, Empty, Flexbox, toast } from '@lobehub/ui';-import { LayoutDashboardIcon } from 'lucide-react';+import { Flexbox, toast } from '@lobehub/ui';import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -14,6 +13,7 @@ import { userProfileSelectors } from '@/store/user/selectors';import { resolveLayouts, sortByPosition } from '../utils/layout';import { isUsableRunStatus } from '../utils/widgetHealth';import WidgetDetailDrawer from '../WidgetDetail';+import BoardEmpty from './BoardEmpty';import BoardHeader from './BoardHeader';import BoardWidgetCard from './BoardWidgetCard';import LayoutEditor from './LayoutEditor';@@ -89,16 +89,10 @@ const DashboardBoard = memo<DashboardBoardProps>(({ dashboardId, empty }) => {return (<AsyncBoundarydata={data}+ empty={empty ?? <BoardEmpty title={detail?.title} />}error={error}isEmpty={responseItems.length === 0}isLoading={isLoading}- empty={- empty ?? (- <Center flex={1} padding={48}>- <Empty description={t('board.empty')} icon={LayoutDashboardIcon} />- </Center>- )- }onRetry={() => void mutate()}>{editing && canEditLayout ? (diff --git a/src/features/Dashboard/Board/style.ts b/src/features/Dashboard/Board/style.tsindex d343366d622..4bb4e931aed 100644--- a/src/features/Dashboard/Board/style.ts+++ b/src/features/Dashboard/Board/style.ts@@ -28,6 +28,15 @@ export const gridStyles = createStaticStyles(({ css, cssVar }) => ({outline: 1px dashed ${cssVar.colorBorder};outline-offset: 2px;`,+ editCell: css`+ position: relative;++ &:hover [data-resize-handle],+ & [data-resize-handle]:focus-visible,+ & [data-resize-handle][data-active='true'] {+ opacity: 1;+ }+ `,grid: css`display: grid;grid-auto-rows: ${DASHBOARD_ROW_HEIGHT}px;@@ -38,6 +47,47 @@ export const gridStyles = createStaticStyles(({ css, cssVar }) => ({grid-template-columns: minmax(0, 1fr);}`,+ resizeHandle: css`+ touch-action: none;+ cursor: nwse-resize;++ position: absolute;+ z-index: 1;+ inset-block-end: 2px;+ inset-inline-end: 2px;++ display: flex;+ align-items: center;+ justify-content: center;++ width: 20px;+ height: 20px;+ padding: 0;+ border: none;+ border-radius: ${cssVar.borderRadiusSM};++ color: ${cssVar.colorTextTertiary};++ opacity: 0.6;+ background: transparent;++ transition: opacity ${cssVar.motionDurationMid};++ &:hover,+ &[data-active='true'] {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ }++ /* Stacked cards span the full width: the handle resizes height only. */+ @media (width <= 767px) {+ cursor: ns-resize;+ }+ `,handle: css`touch-action: none;cursor: grab;diff --git a/src/features/Dashboard/BoardPage.tsx b/src/features/Dashboard/BoardPage.tsxindex 315d2e8cbd8..f77af45b3cb 100644--- a/src/features/Dashboard/BoardPage.tsx+++ b/src/features/Dashboard/BoardPage.tsx@@ -1,8 +1,8 @@'use client';import type { WidgetLevelFilter } from '@lobechat/types';-import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';-import { ChevronLeftIcon, LayoutDashboardIcon } from 'lucide-react';+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';+import { ChevronLeftIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -12,6 +12,7 @@ import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';import DashboardBoard from './Board';import DashboardActionsMenu from './DashboardActionsMenu';+import DashboardAvatar from './DashboardAvatar';import { dashboardPageStyles as styles } from './pageStyles';interface DashboardBoardPageProps {@@ -39,7 +40,7 @@ const BoardPageHeader = memo<DashboardBoardPageProps>(title={t('list.title')}onClick={() => navigate(backPath)}/>- <Icon icon={LayoutDashboardIcon} size={16} />+ {detail && <DashboardAvatar icon={detail.icon} size={20} title={detail.title} />}<Text ellipsis weight={500}>{detail?.title ?? ''}</Text>diff --git a/src/features/Dashboard/DashboardActionsMenu.tsx b/src/features/Dashboard/DashboardActionsMenu.tsxindex 2371a9c523f..c37789ad013 100644--- a/src/features/Dashboard/DashboardActionsMenu.tsx+++ b/src/features/Dashboard/DashboardActionsMenu.tsx@@ -3,26 +3,30 @@import type { WidgetLevelFilter } from '@lobechat/types';import { Icon } from '@lobehub/ui';import { ActionIcon, confirmModal, type DropdownItem, DropdownMenu, toast } from '@lobehub/ui';-import { MoreHorizontalIcon, PencilIcon, TrashIcon } from 'lucide-react';+import { MoreHorizontalIcon, Settings2Icon, TrashIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { usePermission } from '@/hooks/usePermission';+import type { DashboardListItem } from '@/services/dashboard';import { useDashboardStore } from '@/store/dashboard';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';-import { openRenameDashboardModal } from './DashboardFormModal';+import { openDashboardSettingsModal } from './DashboardSettingsModal';interface DashboardActionsMenuProps {- dashboard: { id: string; title: string; userId: string };+ dashboard: Pick<+ DashboardListItem,+ 'description' | 'id' | 'title' | 'userId' | 'visibility' | 'workspaceId'+ >;level?: WidgetLevelFilter;/** Called after the board moved to the trash, e.g. to leave its page. */onTrashed?: () => void;}/**- * Rename / trash a board. Only its creator with the create_content+ * Open a board's settings or trash it. Only its creator with the create_content* permission may change it — a demoted owner keeps ownership but the server* refuses their writes, so they get no menu either.*/@@ -36,11 +40,10 @@ const DashboardActionsMenu = memo<DashboardActionsMenuProps>(({ dashboard, levelconst items: DropdownItem[] = [{- icon: <Icon icon={PencilIcon} />,- key: 'rename',- label: t('actions.rename'),- onClick: () =>- openRenameDashboardModal({ dashboardId: dashboard.id, level, title: dashboard.title }),+ icon: <Icon icon={Settings2Icon} />,+ key: 'settings',+ label: t('actions.settings'),+ onClick: () => openDashboardSettingsModal({ dashboard, level }),},{ type: 'divider' },{diff --git a/src/features/Dashboard/DashboardAvatar.tsx b/src/features/Dashboard/DashboardAvatar.tsxnew file mode 100644index 00000000000..1075d41218d--- /dev/null+++ b/src/features/Dashboard/DashboardAvatar.tsx@@ -0,0 +1,25 @@+import { Avatar } from '@lobehub/ui';++export interface DashboardAvatarProps {+ /** The board's own icon (an emoji or image URL), when it has one. */+ icon?: string | null;+ size?: number;+ title: string;+}++/**+ * A board's icon, or the ring-style avatar `@lobehub/ui` generates from its+ * name when it has none, so every board is told apart at a glance.+ */+const DashboardAvatar = ({ icon, size = 20, title }: DashboardAvatarProps) => (+ <Avatar+ avatar={icon || undefined}+ fallbackVariant={'ring'}+ shape={'square'}+ size={size}+ style={{ flex: 'none' }}+ title={title}+ />+);++export default DashboardAvatar;diff --git a/src/features/Dashboard/DashboardFormModal.tsx b/src/features/Dashboard/DashboardFormModal.tsxindex 3b55b51e3e5..5093cbbc26f 100644--- a/src/features/Dashboard/DashboardFormModal.tsx+++ b/src/features/Dashboard/DashboardFormModal.tsx@@ -19,82 +19,76 @@ import { useTranslation } from 'react-i18next';import { useDashboardStore } from '@/store/dashboard';interface DashboardFormProps {- initialTitle?: string;onSubmit: (value: { description?: string; title: string }) => Promise<void>;- showDescription?: boolean;submitText: string;}-const DashboardForm = memo<DashboardFormProps>(- ({ initialTitle = '', onSubmit, showDescription, submitText }) => {- const { t } = useTranslation(['dashboard', 'common']);- const { close } = useModalContext();- const [title, setTitle] = useState(initialTitle);- const [description, setDescription] = useState('');- const [loading, setLoading] = useState(false);- const trimmed = title.trim();+const DashboardForm = memo<DashboardFormProps>(({ onSubmit, submitText }) => {+ const { t } = useTranslation(['dashboard', 'common']);+ const { close } = useModalContext();+ const [title, setTitle] = useState('');+ const [description, setDescription] = useState('');+ const [loading, setLoading] = useState(false);+ const trimmed = title.trim();- const handleSubmit = async () => {- if (!trimmed || loading) return;- setLoading(true);- try {- await onSubmit({ description: description.trim() || undefined, title: trimmed });- close();- } catch (error) {- console.error('[dashboard] form submit failed', error);- toast.error(t('operationFailed', { ns: 'common' }));- } finally {- setLoading(false);- }- };+ const handleSubmit = async () => {+ if (!trimmed || loading) return;+ setLoading(true);+ try {+ await onSubmit({ description: description.trim() || undefined, title: trimmed });+ close();+ } catch (error) {+ console.error('[dashboard] form submit failed', error);+ toast.error(t('operationFailed', { ns: 'common' }));+ } finally {+ setLoading(false);+ }+ };- return (- <>- <Flexbox gap={16} padding={16}>- <Flexbox gap={6}>- <Text fontSize={13} weight={500}>- {t('form.titleLabel')}- </Text>- <Input- autoFocus- data-dashboard-title-input- maxLength={200}- placeholder={t('form.titlePlaceholder')}- value={title}- onChange={(event) => setTitle(event.target.value)}- onPressEnter={() => void handleSubmit()}- />- </Flexbox>- {showDescription && (- <Flexbox gap={6}>- <Text fontSize={13} weight={500}>- {t('form.descriptionLabel')}- </Text>- <TextArea- autoSize={{ maxRows: 6, minRows: 2 }}- maxLength={2000}- placeholder={t('form.descriptionPlaceholder')}- value={description}- onChange={(event) => setDescription(event.target.value)}- />- </Flexbox>- )}+ return (+ <>+ <Flexbox gap={16} padding={16}>+ <Flexbox gap={6}>+ <Text fontSize={13} weight={500}>+ {t('form.titleLabel')}+ </Text>+ <Input+ autoFocus+ data-dashboard-title-input+ maxLength={200}+ placeholder={t('form.titlePlaceholder')}+ value={title}+ onChange={(event) => setTitle(event.target.value)}+ onPressEnter={() => void handleSubmit()}+ /></Flexbox>- <ModalFooter>- <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>- <Button- disabled={!trimmed}- loading={loading}- type={'primary'}- onClick={() => void handleSubmit()}- >- {submitText}- </Button>- </ModalFooter>- </>- );- },-);+ <Flexbox gap={6}>+ <Text fontSize={13} weight={500}>+ {t('form.descriptionLabel')}+ </Text>+ <TextArea+ autoSize={{ maxRows: 6, minRows: 2 }}+ maxLength={2000}+ placeholder={t('form.descriptionPlaceholder')}+ value={description}+ onChange={(event) => setDescription(event.target.value)}+ />+ </Flexbox>+ </Flexbox>+ <ModalFooter>+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>+ <Button+ disabled={!trimmed}+ loading={loading}+ type={'primary'}+ onClick={() => void handleSubmit()}+ >+ {submitText}+ </Button>+ </ModalFooter>+ </>+ );+});DashboardForm.displayName = 'DashboardForm';@@ -115,7 +109,6 @@ export const openCreateDashboardModal = ({createModal({content: (<DashboardForm- showDescriptionsubmitText={translate('create.submit', { ns: 'dashboard' })}onSubmit={async ({ description, title }) => {const dashboard = await useDashboardStore@@ -130,28 +123,3 @@ export const openCreateDashboardModal = ({title: translate('create.title', { ns: 'dashboard' }),width: 460,});--export const openRenameDashboardModal = ({- dashboardId,- level,- title,-}: {- dashboardId: string;- level?: WidgetLevelFilter;- title: string;-}) =>- createModal({- content: (- <DashboardForm- initialTitle={title}- submitText={translate('save', { ns: 'common' })}- onSubmit={({ title: nextTitle }) =>- useDashboardStore.getState().renameDashboard(dashboardId, nextTitle, level)- }- />- ),- footer: null,- styles: { content: { padding: 0 } },- title: translate('rename.title', { ns: 'dashboard' }),- width: 460,- });diff --git a/src/features/Dashboard/DashboardSettingsModal.tsx b/src/features/Dashboard/DashboardSettingsModal.tsxnew file mode 100644index 00000000000..115baabbcb5--- /dev/null+++ b/src/features/Dashboard/DashboardSettingsModal.tsx@@ -0,0 +1,255 @@+'use client';++import type { DashboardVisibility, WidgetLevelFilter } from '@lobechat/types';+import {+ Button,+ createModal,+ Flexbox,+ Input,+ ModalFooter,+ Segmented,+ Select,+ Skeleton,+ Text,+ TextArea,+ toast,+ useModalContext,+} from '@lobehub/ui';+import { t as translate } from 'i18next';+import { type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { DashboardListItem, DashboardSettingsPatch } from '@/services/dashboard';+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++import {+ type BoardScheduleChoice,+ boardSchedulePattern,+ initialBoardScheduleChoice,+ resolveBoardSchedule,+ SCHEDULE_PRESETS,+} from './utils/schedule';++const Field = ({+ children,+ hint,+ label,+}: {+ children: ReactNode;+ hint?: ReactNode;+ label: string;+}) => (+ <Flexbox gap={6}>+ <Text fontSize={13} weight={500}>+ {label}+ </Text>+ {children}+ {hint && (+ <Text fontSize={12} type={'secondary'}>+ {hint}+ </Text>+ )}+ </Flexbox>+);++type SettingsBoard = Pick<+ DashboardListItem,+ 'description' | 'id' | 'title' | 'visibility' | 'workspaceId'+>;++interface DashboardSettingsFormProps {+ dashboard: SettingsBoard;+ level?: WidgetLevelFilter;+}++/**+ * A board's settings: its name and description, who in the workspace sees+ * it, and one refresh cadence for the widgets on it. Cadence lives on each+ * widget and only its creator may change it, so the board-wide choice writes+ * to the user's own widgets and says how many that is.+ */+const DashboardSettingsForm = ({ dashboard, level }: DashboardSettingsFormProps) => {+ const { t } = useTranslation(['dashboard', 'common']);+ const { close } = useModalContext();+ const updateDashboard = useDashboardStore((s) => s.updateDashboard);+ const setWidgetsSchedule = useDashboardStore((s) => s.setWidgetsSchedule);+ const useFetchDashboardDetail = useDashboardStore((s) => s.useFetchDashboardDetail);+ const { data } = useFetchDashboardDetail(dashboard.id);+ const detail = useDashboardStore(dashboardSelectors.dashboardDetail(dashboard.id));+ const userId = useUserStore(userProfileSelectors.userId);++ const [title, setTitle] = useState(dashboard.title);+ const [description, setDescription] = useState(dashboard.description ?? '');+ const [visibility, setVisibility] = useState<DashboardVisibility>(dashboard.visibility);+ const [pickedSchedule, setPickedSchedule] = useState<BoardScheduleChoice>();+ const [saving, setSaving] = useState(false);++ // Home boards outside a workspace are personal: there is no one to share with.+ const showVisibility = !!dashboard.workspaceId;+ const widgets = (detail?.items ?? []).map(({ widget }) => widget);+ const ownWidgets = widgets.filter((widget) => !!userId && widget.userId === userId);+ const othersCount = widgets.length - ownWidgets.length;+ const scheduleState = resolveBoardSchedule(ownWidgets);+ const initialSchedule = initialBoardScheduleChoice(scheduleState);+ const schedule = pickedSchedule ?? initialSchedule;+ const trimmedTitle = title.trim();++ const scheduleOptions = [+ ...(initialSchedule === 'keep'+ ? [+ {+ label:+ scheduleState.kind === 'custom'+ ? t('settings.scheduleKeepCustom', { pattern: scheduleState.pattern })+ : t('settings.scheduleKeep'),+ value: 'keep',+ },+ ]+ : []),+ { label: t('schedule.manual'), value: 'manual' },+ ...SCHEDULE_PRESETS.map((preset) => ({+ label: t(`schedule.${preset.key}`),+ value: preset.key,+ })),+ ];++ const handleSave = async () => {+ if (!trimmedTitle || saving) return;+ setSaving(true);+ try {+ const patch: DashboardSettingsPatch = {};+ if (trimmedTitle !== dashboard.title) patch.title = trimmedTitle;+ const nextDescription = description.trim() || null;+ if (nextDescription !== (dashboard.description ?? null)) patch.description = nextDescription;+ if (showVisibility && visibility !== dashboard.visibility) patch.visibility = visibility;++ let keptPrivate = false;+ if (Object.keys(patch).length > 0) {+ const saved = await updateDashboard(dashboard.id, patch, level);+ keptPrivate = patch.visibility === 'public' && saved?.visibility === 'private';+ }++ let failed = 0;+ const pattern = boardSchedulePattern(schedule);+ if (schedule !== initialSchedule && pattern !== undefined && ownWidgets.length > 0) {+ ({ failed } = await setWidgetsSchedule(+ ownWidgets.map((widget) => widget.id),+ { pattern, timezone: pattern ? Intl.DateTimeFormat().resolvedOptions().timeZone : null },+ ));+ }++ if (failed > 0) toast.error(t('settings.scheduleFailed', { count: failed }));+ else if (keptPrivate) toast.info(t('settings.visibilityKeptPrivate'));+ else toast.success(t('settings.saved'));+ close();+ } catch (error) {+ console.error('[dashboard] settings save failed', error);+ toast.error(t('operationFailed', { ns: 'common' }));+ } finally {+ setSaving(false);+ }+ };++ const renderSchedule = () => {+ if (!data) return <Skeleton height={32} width={'100%'} />;+ if (ownWidgets.length === 0) {+ return (+ <Text fontSize={12} type={'secondary'}>+ {widgets.length === 0 ? t('settings.scheduleNoWidgets') : t('settings.scheduleNotOwner')}+ </Text>+ );+ }+ return (+ <Select+ data-dashboard-settings-schedule+ options={scheduleOptions}+ value={schedule}+ variant={'filled'}+ onChange={(value) => setPickedSchedule(value as BoardScheduleChoice)}+ />+ );+ };++ return (+ <>+ <Flexbox gap={20} padding={16}>+ <Field label={t('form.titleLabel')}>+ <Input+ autoFocus+ data-dashboard-title-input+ maxLength={200}+ placeholder={t('form.titlePlaceholder')}+ value={title}+ onChange={(event) => setTitle(event.target.value)}+ />+ </Field>+ <Field label={t('form.descriptionLabel')}>+ <TextArea+ autoSize={{ maxRows: 6, minRows: 2 }}+ maxLength={2000}+ placeholder={t('form.descriptionPlaceholder')}+ value={description}+ onChange={(event) => setDescription(event.target.value)}+ />+ </Field>+ {showVisibility && (+ <Field label={t('settings.visibility')}>+ <Segmented+ block+ value={visibility}+ options={[+ { label: t('settings.visibilityPrivate'), value: 'private' },+ { label: t('settings.visibilityPublic'), value: 'public' },+ ]}+ onChange={(value) => setVisibility(value as DashboardVisibility)}+ />+ </Field>+ )}+ <Field+ label={t('settings.schedule')}+ hint={+ data && ownWidgets.length > 0+ ? [+ t('settings.scheduleHint', { count: ownWidgets.length }),+ othersCount > 0 && t('settings.scheduleOthers', { count: othersCount }),+ ]+ .filter(Boolean)+ .join(' ')+ : undefined+ }+ >+ {renderSchedule()}+ </Field>+ </Flexbox>+ <ModalFooter>+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>+ <Button+ data-dashboard-settings-save+ disabled={!trimmedTitle}+ loading={saving}+ type={'primary'}+ onClick={() => void handleSave()}+ >+ {t('save', { ns: 'common' })}+ </Button>+ </ModalFooter>+ </>+ );+};++export const openDashboardSettingsModal = ({+ dashboard,+ level,+}: {+ dashboard: SettingsBoard;+ level?: WidgetLevelFilter;+}) =>+ createModal({+ content: <DashboardSettingsForm dashboard={dashboard} level={level} />,+ footer: null,+ styles: { content: { padding: 0 } },+ title: translate('settings.title', { ns: 'dashboard' }),+ width: 480,+ });diff --git a/src/features/Dashboard/List/DashboardListCard.tsx b/src/features/Dashboard/List/DashboardListCard.tsxindex 5e3ced27c14..3fb82cd1d45 100644--- a/src/features/Dashboard/List/DashboardListCard.tsx+++ b/src/features/Dashboard/List/DashboardListCard.tsx@@ -1,9 +1,8 @@'use client';import type { WidgetLevelFilter } from '@lobechat/types';-import { Center, createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar, Flexbox, Text } from '@lobehub/ui';import dayjs from 'dayjs';-import { LayoutDashboardIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -11,6 +10,7 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import type { DashboardListItem } from '@/services/dashboard';import DashboardActionsMenu from '../DashboardActionsMenu';+import DashboardAvatar from '../DashboardAvatar';export const dashboardListStyles = createStaticStyles(({ css }) => ({card: css`@@ -51,17 +51,6 @@ export const dashboardListStyles = createStaticStyles(({ css }) => ({grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));gap: 16px;`,- icon: css`- flex: none;-- width: 36px;- height: 36px;- border-radius: ${cssVar.borderRadius};-- color: ${cssVar.geekblue};-- background: color-mix(in srgb, ${cssVar.geekblue} 12%, transparent);- `,menu: css`position: absolute;inset-block-start: 12px;@@ -103,9 +92,7 @@ const DashboardListCard = memo<DashboardListCardProps>(({ dashboard, href, level<WorkspaceLink style={{ color: 'inherit', display: 'block' }} to={href}><Flexbox gap={12}><Flexbox horizontal align={'center'} gap={12} style={{ paddingInlineEnd: 24 }}>- <Center className={dashboardListStyles.icon}>- <Icon icon={LayoutDashboardIcon} size={18} />- </Center>+ <DashboardAvatar icon={dashboard.icon} size={36} title={dashboard.title} /><Text ellipsis fontSize={15} weight={600}>{dashboard.title}</Text>diff --git a/src/features/Dashboard/WidgetCard/index.tsx b/src/features/Dashboard/WidgetCard/index.tsxindex 96900efa6cc..75447e1541d 100644--- a/src/features/Dashboard/WidgetCard/index.tsx+++ b/src/features/Dashboard/WidgetCard/index.tsx@@ -103,6 +103,8 @@ export interface WidgetCardProps {onOpen?: () => void;/** A manual refresh of this widget is in flight from this client. */runningLocally?: boolean;+ /** Replaces the plain title, e.g. an inline input while editing a board. */+ title?: ReactNode;/** Long-term trend from `metric_points`, when the host loaded it. */trend?: DashboardTrendSeries[];view?: WidgetView | null;@@ -118,7 +120,7 @@ export interface WidgetCardProps {* the card says so instead of rendering an empty value.*/const WidgetCard = memo<WidgetCardProps>(- ({ widget, trend, view, actions, handle, onOpen, runningLocally, className }) => {+ ({ widget, trend, view, actions, handle, onOpen, runningLocally, className, title }) => {const { t } = useTranslation('dashboard');const health = getWidgetHealth(widget, { runningLocally });const updatedAt = getWidgetUpdatedAt(widget);@@ -170,9 +172,11 @@ const WidgetCard = memo<WidgetCardProps>(><Flexbox horizontal align={'center'} className={styles.header} gap={6}>{handle}- <Text ellipsis className={styles.title} title={widget.title} weight={500}>- {widget.title}- </Text>+ {title ?? (+ <Text ellipsis className={styles.title} title={widget.title} weight={500}>+ {widget.title}+ </Text>+ )}<StatusBadges badges={badges} health={health} />{actions && (// Header actions must not open the drill-down.diff --git a/src/features/Dashboard/WidgetDetail/index.tsx b/src/features/Dashboard/WidgetDetail/index.tsxindex ce5d4e4af6e..e82fa7dae83 100644--- a/src/features/Dashboard/WidgetDetail/index.tsx+++ b/src/features/Dashboard/WidgetDetail/index.tsx@@ -10,6 +10,7 @@ import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';import { ErrorLine } from '../ErrorLine';import { useWidgetTrend } from '../hooks/useWidgetTrend';+import { formatSchedule } from '../utils/schedule';import { getWidgetHealth, getWidgetUpdatedAt } from '../utils/widgetHealth';import HealthDot, { getHealthTone, HEALTH_TONE_COLOR } from '../WidgetCard/HealthDot';import StatusBadges from '../WidgetCard/StatusBadges';@@ -22,7 +23,7 @@ import VersionList from './VersionList';const styles = createStaticStyles(({ css }) => ({cell: css`min-width: 0;- padding-block: 10px;+ padding-block: 8px;padding-inline: 12px;background: ${cssVar.colorBgContainer};`,@@ -41,16 +42,12 @@ const styles = createStaticStyles(({ css }) => ({`,grid: css`display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));+ grid-template-columns: repeat(auto-fit, minmax(128px, 1fr));gap: 1px;background: ${cssVar.colorBorderSecondary};`,- hint: css`- font-size: 12px;- color: ${cssVar.colorTextTertiary};- `,status: css`- padding-block: 10px;+ padding-block: 6px;padding-inline: 12px;border-block-end: 1px solid ${cssVar.colorBorderSecondary};`,@@ -61,20 +58,25 @@ const styles = createStaticStyles(({ css }) => ({`,}));-/** One fact of the summary grid: a quiet label over its value, with an optional second line. */+/**+ * One fact of the summary row: a quiet label over a short value. The exact+ * detail (full timestamps, next run) sits in the value's tooltip so the row+ * stays two lines tall.+ */const Cell = ({- hint,+ detail,label,children,}: {children: ReactNode;- hint?: ReactNode;+ detail?: string;label: string;}) => (<Flexbox className={styles.cell} gap={2}><span className={styles.cellLabel}>{label}</span>- <span className={styles.cellValue}>{children}</span>- {hint && <span className={styles.hint}>{hint}</span>}+ <span className={styles.cellValue} title={detail}>+ {children}+ </span></Flexbox>);@@ -114,38 +116,37 @@ const WidgetSummary = memo<{ widget: DashboardWidgetItem }>(({ widget }) => {<WidgetRefreshButton widget={widget} /></Flexbox><div className={styles.grid}>- <Cell hint={fromNow(updatedAt)} label={t('detail.updatedAt')}>- {formatTime(updatedAt) ?? '—'}+ <Cell detail={formatTime(updatedAt)} label={t('detail.updatedAt')}>+ {fromNow(updatedAt) ?? '—'}</Cell>- <Cell- label={t('detail.lastRunAt')}- hint={- widget.lastRunAt ? t(`run.status.${widget.lastRunStatus ?? 'running'}`) : undefined- }- >- {formatTime(widget.lastRunAt) ?? '—'}+ <Cell detail={formatTime(widget.lastRunAt)} label={t('detail.lastRunAt')}>+ {widget.lastRunAt+ ? `${fromNow(widget.lastRunAt)} · ${t(`run.status.${widget.lastRunStatus ?? 'running'}`)}`+ : '—'}</Cell><Celllabel={t('detail.schedule')}- hint={+ detail={widget.nextRunAt? `${t('detail.nextRunAt')} ${formatTime(widget.nextRunAt)}`: undefined}>{widget.schedulePattern- ? [widget.schedulePattern, widget.scheduleTimezone].filter(Boolean).join(' · ')+ ? formatSchedule(t, widget.schedulePattern, widget.scheduleTimezone): t('detail.manualOnly')}</Cell>- <Cell- hint={draft ? t('detail.versionDraft', { version: draft.version }) : undefined}- label={t('detail.version')}- >- {published- ? t('detail.versionPublished', { version: published.version })- : widget.publishedVersionId- ? '…'- : t('detail.versionNone')}+ <Cell label={t('detail.version')}>+ {[+ published+ ? t('detail.versionPublished', { version: published.version })+ : widget.publishedVersionId+ ? '…'+ : t('detail.versionNone'),+ draft && t('detail.versionDraft', { version: draft.version }),+ ]+ .filter(Boolean)+ .join(' · ')}</Cell></div></div>@@ -253,7 +254,7 @@ const WidgetDetailDrawer = memo<WidgetDetailDrawerProps>(({ widget, onClose }) =>{widget && (<Flexbox gap={16}>- {widget.description && <Text type={'secondary'}>{widget.description}</Text>}+ {widget.description && <Text>{widget.description}</Text>}<WidgetDetailPanel widget={widget} /></Flexbox>)}diff --git a/src/features/Dashboard/WidgetEditModal.tsx b/src/features/Dashboard/WidgetEditModal.tsxnew file mode 100644index 00000000000..1cb864f9426--- /dev/null+++ b/src/features/Dashboard/WidgetEditModal.tsx@@ -0,0 +1,115 @@+'use client';++import {+ Button,+ createModal,+ Flexbox,+ Input,+ ModalFooter,+ Text,+ TextArea,+ toast,+ useModalContext,+} from '@lobehub/ui';+import { t as translate } from 'i18next';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useDashboardStore } from '@/store/dashboard';++/** Longest widget title and metric definition the API accepts. */+const TITLE_MAX_LENGTH = 200;+const DESCRIPTION_MAX_LENGTH = 2000;++interface WidgetEditFormProps {+ widget: { description?: string | null; id: string; title: string };+}++/** A widget's own name and metric definition (口径), saved on their own. */+const WidgetEditForm = ({ widget }: WidgetEditFormProps) => {+ const { t } = useTranslation(['dashboard', 'common']);+ const { close } = useModalContext();+ const updateWidget = useDashboardStore((s) => s.updateWidget);+ const [title, setTitle] = useState(widget.title);+ const [description, setDescription] = useState(widget.description ?? '');+ const [saving, setSaving] = useState(false);+ const trimmedTitle = title.trim();++ const handleSave = async () => {+ if (!trimmedTitle || saving) return;+ const nextDescription = description.trim() || null;+ const patch = {+ ...(trimmedTitle !== widget.title ? { title: trimmedTitle } : {}),+ ...(nextDescription !== (widget.description ?? null) ? { description: nextDescription } : {}),+ };+ if (Object.keys(patch).length === 0) {+ close();+ return;+ }+ setSaving(true);+ try {+ await updateWidget(widget.id, patch);+ toast.success(t('widgetEdit.saved'));+ close();+ } catch (error) {+ console.error('[dashboard] widget edit failed', error);+ toast.error(t('operationFailed', { ns: 'common' }));+ } finally {+ setSaving(false);+ }+ };++ return (+ <>+ <Flexbox gap={16} padding={16}>+ <Flexbox gap={6}>+ <Text fontSize={13} weight={500}>+ {t('widgetEdit.titleLabel')}+ </Text>+ <Input+ autoFocus+ data-widget-edit-title+ maxLength={TITLE_MAX_LENGTH}+ value={title}+ onChange={(event) => setTitle(event.target.value)}+ onPressEnter={() => void handleSave()}+ />+ </Flexbox>+ <Flexbox gap={6}>+ <Text fontSize={13} weight={500}>+ {t('chat.definition')}+ </Text>+ <TextArea+ data-widget-edit-description+ autoSize={{ maxRows: 6, minRows: 2 }}+ maxLength={DESCRIPTION_MAX_LENGTH}+ placeholder={t('widgetEdit.descriptionPlaceholder')}+ value={description}+ onChange={(event) => setDescription(event.target.value)}+ />+ </Flexbox>+ </Flexbox>+ <ModalFooter>+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>+ <Button+ data-widget-edit-save+ disabled={!trimmedTitle}+ loading={saving}+ type={'primary'}+ onClick={() => void handleSave()}+ >+ {t('save', { ns: 'common' })}+ </Button>+ </ModalFooter>+ </>+ );+};++export const openWidgetEditModal = (widget: WidgetEditFormProps['widget']) =>+ createModal({+ content: <WidgetEditForm widget={widget} />,+ footer: null,+ styles: { content: { padding: 0 } },+ title: translate('widgetEdit.title', { ns: 'dashboard' }),+ width: 460,+ });diff --git a/src/features/Dashboard/WidgetPreview/DryRunReview.tsx b/src/features/Dashboard/WidgetPreview/DryRunReview.tsxindex 1e299284949..df6e297f45d 100644--- a/src/features/Dashboard/WidgetPreview/DryRunReview.tsx+++ b/src/features/Dashboard/WidgetPreview/DryRunReview.tsx@@ -1,13 +1,86 @@'use client';-import { Flexbox, Highlighter, Skeleton, Text } from '@lobehub/ui';-import { memo } from 'react';+import type { BuiltinRememberApproval } from '@lobechat/types';+import { Flexbox, Highlighter, Skeleton, Text, toast } from '@lobehub/ui';+import { memo, useEffect } from 'react';import { useTranslation } from 'react-i18next';+import type { DashboardWidgetDetail, DashboardWidgetVersionItem } from '@/services/dashboard';+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';+import { RUNTIME_LANGUAGE } from '../WidgetDetail/diffContent';-import { AccessFacts, Fact, reviewStyles, ReviewUnavailable } from './ReviewFacts';+import { findExpectedRun, sampleOutputFor } from './previewWidget';+import {+ AccessFacts,+ Fact,+ FoldedSection,+ ReviewPreviewCard,+ ReviewSampleCard,+ ReviewSection,+ reviewStyles,+ ReviewUnavailable,+} from './ReviewFacts';import { useWidgetReview } from './useWidgetReview';+interface ExpectedPreviewProps {+ target: DashboardWidgetVersionItem;+ versions: DashboardWidgetVersionItem[];+ widget: DashboardWidgetDetail;+}++/**+ * The card the dry run is expected to produce, before it runs: this+ * version's last usable result, else an earlier version's for reference,+ * else a sample-valued card of the same shape. Informational only — it never+ * holds approval, which is about access.+ */+const ExpectedPreview = ({ target, versions, widget }: ExpectedPreviewProps) => {+ const { t } = useTranslation('dashboard');+ const useFetchWidgetRuns = useDashboardStore((s) => s.useFetchWidgetRuns);+ const { data, isLoading } = useFetchWidgetRuns(widget.id);+ const runs = useDashboardStore(dashboardSelectors.widgetRuns(widget.id));++ const title = t('review.expected');+ if (!data && isLoading) {+ return (+ <ReviewSection title={title}>+ <Skeleton height={150} width={'100%'} />+ </ReviewSection>+ );+ }++ const expected = findExpectedRun(runs, target);+ if (!expected) {+ const sample = sampleOutputFor(target.outputType, target.view, {+ item: (index) => t('review.sampleItem', { index }),+ name: t('review.sampleName'),+ series: t('review.sampleTag'),+ value: t('review.sampleValue'),+ });+ return (+ <ReviewSection note={t('review.expectedSample')} title={title}>+ <ReviewSampleCard output={sample} view={target.view} widget={widget} />+ </ReviewSection>+ );+ }++ const source = versions.find((version) => version.id === expected.run.versionId);+ return (+ <ReviewSection+ title={title}+ note={+ expected.sameVersion+ ? t('review.expectedSameVersion')+ : t('review.expectedEarlier', { version: source?.version ?? '?' })+ }+ >+ <ReviewPreviewCard run={expected.run} view={target.view} widget={widget} />+ </ReviewSection>+ );+};+interface DryRunReviewProps {/** Holds the host's approve action until the version that will run is on screen. */onApprovalBlockedChange?: (blocked: boolean) => void;@@ -17,6 +90,8 @@ interface DryRunReviewProps {* version reviewed here.*/onPinVersion?: (versionId: string) => void;+ /** The host's hook to offer an "approve and stop asking for this access" choice. */+ registerRememberApproval?: (option: BuiltinRememberApproval) => () => void;/** The version that will run; when absent the current draft is shown and pinned. */versionId?: string;widgetId: string;@@ -24,15 +99,43 @@ interface DryRunReviewProps {/*** Approval for running an agent-written draft that reads credentials or- * reaches the network: the exact script, its runtime, and what it may touch.+ * reaches the network: the card it is expected to produce, what it measures+ * and may touch, and — folded — the exact script.*/const DryRunReview = memo<DryRunReviewProps>(- ({ widgetId, versionId, onApprovalBlockedChange, onPinVersion }) => {+ ({ widgetId, versionId, onApprovalBlockedChange, onPinVersion, registerRememberApproval }) => {const { t } = useTranslation('dashboard');- const { error, retry, status, target, widget } = useWidgetReview(widgetId, versionId, {- onApprovalBlockedChange,- onPinVersion,- });+ const { error, retry, status, target, versions, widget } = useWidgetReview(+ widgetId,+ versionId,+ {+ onApprovalBlockedChange,+ onPinVersion,+ },+ );+ const grantDryRunAccess = useDashboardStore((s) => s.grantDryRunAccess);+ const userId = useUserStore(userProfileSelectors.userId);+ // Only the widget's creator reviews its dry runs and may grant standing access.+ const canRemember = !!widget && !!userId && widget.userId === userId;+ const targetId = target?.id;++ // "Similar" for a dry run means the same connectors and hosts: picking the+ // shared "approve, and don't ask again for similar actions" choice records+ // a standing grant of this version's access — never a plain approve or a+ // rejection. A failed grant does not hold the approval itself.+ useEffect(() => {+ if (!canRemember || !targetId || !registerRememberApproval) return;+ return registerRememberApproval({+ onRemember: async () => {+ try {+ await grantDryRunAccess(widgetId, targetId);+ } catch (grantError) {+ console.error('[dashboard] dry-run grant failed', grantError);+ toast.error(t('dryRun.rememberFailed'));+ }+ },+ });+ }, [canRemember, grantDryRunAccess, registerRememberApproval, t, targetId, widgetId]);if (status === 'error' || status === 'missing') {return <ReviewUnavailable error={error} missing={status === 'missing'} onRetry={retry} />;@@ -49,24 +152,22 @@ const DryRunReview = memo<DryRunReviewProps>(return (<Flexbox data-widget-dry-run-review={widgetId} gap={12}>- <Flexbox gap={4}>- <Text weight={600}>{`${widget.title} · v${target.version}`}</Text>- <Text fontSize={12} type={'secondary'}>- {t('dryRun.intro')}- </Text>- </Flexbox>+ <Text weight={600}>{`${widget.title} · v${target.version}`}</Text>+ <ExpectedPreview target={target} versions={versions} widget={widget} />++ {/* The intro introduces the access facts it sits above. */}+ <Text fontSize={12} type={'secondary'}>+ {t('dryRun.intro')}+ </Text><Flexbox className={reviewStyles.section} gap={6}>- <Fact label={t('dryRun.runtime')}>- <Text fontSize={12}>{target.runtime}</Text>+ <Fact label={t('chat.definition')}>+ <Text fontSize={12}>{widget.description || t('chat.noDefinition')}</Text></Fact><AccessFacts manifest={target.manifest} /></Flexbox>- <Flexbox gap={6}>- <Text fontSize={12} type={'secondary'} weight={500}>- {t('publish.scriptNew')}- </Text>+ <FoldedSection title={`${t('publish.scriptNew')} · ${target.runtime}`}><Highlighterlanguage={RUNTIME_LANGUAGE[target.runtime] ?? 'plaintext'}style={{ maxHeight: 360, overflow: 'auto' }}@@ -74,7 +175,7 @@ const DryRunReview = memo<DryRunReviewProps>(>{target.script}</Highlighter>- </Flexbox>+ </FoldedSection></Flexbox>);},diff --git a/src/features/Dashboard/WidgetPreview/PublishReview.tsx b/src/features/Dashboard/WidgetPreview/PublishReview.tsxindex cac32388f08..59b373672fe 100644--- a/src/features/Dashboard/WidgetPreview/PublishReview.tsx+++ b/src/features/Dashboard/WidgetPreview/PublishReview.tsx@@ -4,10 +4,18 @@ import { Alert, Flexbox, Skeleton, Text } from '@lobehub/ui';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import WidgetCard from '../WidgetCard';+import { formatSchedule } from '../utils/schedule';import { ScriptDiff } from '../WidgetDetail/VersionDiff';-import { resolvePublishSchedule, toPreviewWidget } from './previewWidget';-import { AccessFacts, Fact, reviewStyles, ReviewUnavailable } from './ReviewFacts';+import { resolvePublishSchedule } from './previewWidget';+import {+ AccessFacts,+ Fact,+ FoldedSection,+ ReviewPreviewCard,+ ReviewSection,+ reviewStyles,+ ReviewUnavailable,+} from './ReviewFacts';import { useWidgetReview } from './useWidgetReview';interface PublishReviewProps {@@ -27,9 +35,10 @@ interface PublishReviewProps {}/**- * Everything a user needs to approve making a widget live: what it showed in- * its dry run, what it means, what it may touch (network, credentials), how- * often it runs, and exactly how its code differs from what is live now.+ * Everything a user needs to approve making a widget live: the card its dry+ * run produced, what it means, what it may touch (network, credentials), how+ * often it runs, and — folded — exactly how its code differs from what is+ * live now.*/const PublishReview = memo<PublishReviewProps>(({ widgetId, versionId, summary, onApprovalBlockedChange, onPinVersion }) => {@@ -65,24 +74,21 @@ const PublishReview = memo<PublishReviewProps>(<Flexbox gap={4}><Text weight={600}>{`${widget.title} · v${target.version}`}</Text>{summary && <Text fontSize={13}>{summary}</Text>}- <Text fontSize={12} type={'secondary'}>- {t('publish.intro')}- </Text></Flexbox>{run ? (- <Flexbox gap={6}>- <Text fontSize={12} type={'secondary'} weight={500}>- {t('publish.previewTitle')}- </Text>- <div style={{ height: run.output?.type === 'stat' ? 150 : 240 }}>- <WidgetCard view={target.view} widget={toPreviewWidget(widget, run)} />- </div>- </Flexbox>+ <ReviewSection title={t('review.expected')}>+ <ReviewPreviewCard run={run} view={target.view} widget={widget} />+ </ReviewSection>) : (<Alert showIcon title={t('publish.noSuccessfulRun')} type={'warning'} />)}+ {/* The intro introduces the credentials and schedule it sits above. */}+ <Text fontSize={12} type={'secondary'}>+ {t('publish.intro')}+ </Text>+<Flexbox className={reviewStyles.section} gap={6}><Fact label={t('chat.definition')}><Text fontSize={12}>{widget.description || t('chat.noDefinition')}</Text>@@ -90,21 +96,22 @@ const PublishReview = memo<PublishReviewProps>(<Fact label={t('publish.schedule')}><Text fontSize={12}>{schedule.pattern- ? [schedule.pattern, schedule.timezone].filter(Boolean).join(' · ')+ ? formatSchedule(t, schedule.pattern, schedule.timezone): t('publish.scheduleNone')}</Text></Fact><AccessFacts manifest={manifest} /></Flexbox>- <Flexbox gap={6}>- <Text fontSize={12} type={'secondary'} weight={500}>- {live && live.id !== target.id+ <FoldedSection+ title={+ live && live.id !== target.id? t('publish.scriptChanges', { version: live.version })- : t('publish.scriptNew')}- </Text>+ : t('publish.scriptNew')+ }+ ><ScriptDiff base={live && live.id !== target.id ? live : undefined} target={target} />- </Flexbox>+ </FoldedSection></Flexbox>);},diff --git a/src/features/Dashboard/WidgetPreview/ReviewFacts.tsx b/src/features/Dashboard/WidgetPreview/ReviewFacts.tsxindex 8d4080e9fc2..eab9580a308 100644--- a/src/features/Dashboard/WidgetPreview/ReviewFacts.tsx+++ b/src/features/Dashboard/WidgetPreview/ReviewFacts.tsx@@ -1,11 +1,16 @@'use client';-import type { WidgetManifest } from '@lobechat/types';-import { createStaticStyles, cssVar, Flexbox, Tag, Text } from '@lobehub/ui';-import { memo, type ReactNode } from 'react';+import type { WidgetManifest, WidgetOutput, WidgetView } from '@lobechat/types';+import { Button, createStaticStyles, cssVar, Flexbox, Tag, Text } from '@lobehub/ui';+import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';+import { memo, type ReactNode, useState } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';+import type { DashboardWidgetDetail } from '@/services/dashboard';++import WidgetCard from '../WidgetCard';+import { toPreviewWidget, toSampleWidget } from './previewWidget';export const reviewStyles = createStaticStyles(({ css }) => ({label: css`@@ -20,6 +25,112 @@ export const reviewStyles = createStaticStyles(({ css }) => ({`,}));+/**+ * A titled block of the review: the card a version produces leads, the facts+ * and the script follow.+ */+export const ReviewSection = ({+ children,+ note,+ title,+}: {+ children: ReactNode;+ /** Where the block's content comes from, read beside the title. */+ note?: ReactNode;+ title: ReactNode;+}) => (+ <Flexbox gap={6}>+ <Flexbox horizontal align={'baseline'} gap={6} wrap={'wrap'}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {title}+ </Text>+ {note && (+ <Text fontSize={12} type={'secondary'}>+ {'· '}+ {note}+ </Text>+ )}+ </Flexbox>+ {children}+ </Flexbox>+);++/**+ * Approvers judge a widget by the card it puts on their dashboard, not by its+ * code, so the script sits folded under its heading until asked for.+ */+export const FoldedSection = ({ children, title }: { children: ReactNode; title: ReactNode }) => {+ const [open, setOpen] = useState(false);++ return (+ <Flexbox gap={6}>+ <Button+ data-review-fold+ aria-expanded={open}+ icon={open ? ChevronDownIcon : ChevronRightIcon}+ size={'small'}+ style={{ alignSelf: 'flex-start', paddingInline: 4 }}+ type={'text'}+ onClick={() => setOpen((value) => !value)}+ >+ <Text fontSize={12} type={'secondary'} weight={500}>+ {title}+ </Text>+ </Button>+ {open && children}+ </Flexbox>+ );+};++type PreviewRun = Parameters<typeof toPreviewWidget>[1];++/** The dashboard card a run produces, at the size it takes on a board. */+export const ReviewPreviewCard = ({+ run,+ view,+ widget,+}: {+ run: PreviewRun;+ view?: WidgetView | null;+ widget: DashboardWidgetDetail;+}) => (+ <div data-review-preview-card style={{ height: run.output?.type === 'stat' ? 150 : 240 }}>+ <WidgetCard view={view} widget={toPreviewWidget(widget, run)} />+ </div>+);++/**+ * The card a version that never ran would make, filled with sample values+ * and tagged as such in its title so nobody reads them as data.+ */+export const ReviewSampleCard = ({+ output,+ view,+ widget,+}: {+ output: WidgetOutput;+ view?: WidgetView | null;+ widget: DashboardWidgetDetail;+}) => {+ const { t } = useTranslation('dashboard');+ return (+ <div data-review-sample-card style={{ height: output.type === 'stat' ? 150 : 240 }}>+ <WidgetCard+ view={view}+ widget={toSampleWidget(widget, output)}+ title={+ <Flexbox horizontal align={'center'} gap={6} style={{ flex: 1, minWidth: 0 }}>+ <Text ellipsis weight={500}>+ {widget.title}+ </Text>+ <Tag size={'small'}>{t('review.sampleTag')}</Tag>+ </Flexbox>+ }+ />+ </div>+ );+};+export const Fact = ({ label, children }: { children: ReactNode; label: string }) => (<Flexbox horizontal align={'baseline'} gap={8}><Text className={reviewStyles.label} fontSize={12}>diff --git a/src/features/Dashboard/WidgetPreview/previewWidget.test.ts b/src/features/Dashboard/WidgetPreview/previewWidget.test.tsindex 0e4d5f36df7..3f2aacc6494 100644--- a/src/features/Dashboard/WidgetPreview/previewWidget.test.ts+++ b/src/features/Dashboard/WidgetPreview/previewWidget.test.ts@@ -4,12 +4,15 @@ import {canCreateDashboardFromPreview,canPreviewPublish,defaultDiffPair,+ findExpectedRun,findSucceededPreviewRun,getPreviewPublishState,placeableDashboards,placementBoards,resolvePublishSchedule,+ sampleOutputFor,toPreviewWidget,+ toSampleWidget,} from './previewWidget';const widget = {@@ -233,6 +236,44 @@ describe('findSucceededPreviewRun', () => {});});+describe('findExpectedRun', () => {+ const stat = { type: 'stat', value: 1 };+ const table = { columns: [], rows: [], type: 'table' };++ it("prefers the reviewed version's own latest usable run", () => {+ const runs = [+ { id: 'r3', output: null, status: 'failed', versionId: 'v2' },+ { id: 'r2', output: stat, status: 'partial', versionId: 'v2' },+ { id: 'r1', output: stat, status: 'succeeded', versionId: 'v1' },+ ] as any[];+ expect(findExpectedRun(runs, { id: 'v2', outputType: 'stat' })).toEqual({+ run: runs[1],+ sameVersion: true,+ });+ });++ it('falls back to an earlier version with the same output type', () => {+ const runs = [+ { id: 'r3', output: null, status: 'failed', versionId: 'v3' },+ { id: 'r2', output: table, status: 'succeeded', versionId: 'v2' },+ { id: 'r1', output: stat, status: 'succeeded', versionId: 'v1' },+ ] as any[];+ expect(findExpectedRun(runs, { id: 'v3', outputType: 'stat' })).toEqual({+ run: runs[2],+ sameVersion: false,+ });+ });++ it('predicts nothing without a usable run of the same shape', () => {+ const runs = [+ { id: 'r2', output: table, status: 'succeeded', versionId: 'v1' },+ { id: 'r1', output: null, status: 'timeout', versionId: 'v2' },+ ] as any[];+ expect(findExpectedRun(runs, { id: 'v2', outputType: 'stat' })).toBeUndefined();+ expect(findExpectedRun([], { id: 'v2', outputType: 'stat' })).toBeUndefined();+ });+});+describe('defaultDiffPair', () => {const versions = [{ id: 'v3', parentVersionId: 'v2', status: 'draft' as const },@@ -250,3 +291,51 @@ describe('defaultDiffPair', () => {expect(defaultDiffPair([])).toEqual({});});});++describe('sampleOutputFor', () => {+ const labels = {+ item: (index: number) => `Item ${index}`,+ name: 'Name',+ series: 'Sample',+ value: 'Value',+ };+ const now = Date.parse('2026-10-25T08:00:00Z');++ it('shapes the sample like the output type the version declares', () => {+ expect(sampleOutputFor('stat', null, labels).type).toBe('stat');+ const list = sampleOutputFor('list', null, labels);+ expect(list).toMatchObject({+ items: [{ title: 'Item 1' }, { title: 'Item 2' }, { title: 'Item 3' }],+ });+ const series = sampleOutputFor('series', null, labels, now);+ expect(series.type === 'series' && series.series[0].points.at(-1)).toEqual({+ t: '2026-10-25',+ v: 19,+ });+ });++ it("uses a table's chosen columns, numbering the last one", () => {+ const table = sampleOutputFor('table', { columns: ['repo', 'stars'] }, labels);+ expect(table).toMatchObject({+ columns: [+ { key: 'repo', title: 'repo', type: 'string' },+ { key: 'stars', title: 'stars', type: 'number' },+ ],+ rows: [+ { repo: 'Item 1', stars: 30 },+ { repo: 'Item 2', stars: 20 },+ { repo: 'Item 3', stars: 10 },+ ],+ });+ });+});++describe('toSampleWidget', () => {+ it('shows the sample without run times or a schedule', () => {+ const sample = toSampleWidget(widget, { type: 'stat', value: 128 });+ expect(sample.latestOutput).toEqual({ type: 'stat', value: 128 });+ expect(sample.latestOutputAt).toBeNull();+ expect(sample.lastRunAt).toBeNull();+ expect(sample.schedulePattern).toBeNull();+ });+});diff --git a/src/features/Dashboard/WidgetPreview/previewWidget.ts b/src/features/Dashboard/WidgetPreview/previewWidget.tsindex 9def2c8cdbb..ef5354f75f0 100644--- a/src/features/Dashboard/WidgetPreview/previewWidget.ts+++ b/src/features/Dashboard/WidgetPreview/previewWidget.ts@@ -1,4 +1,4 @@-import type { WidgetManifest } from '@lobechat/types';+import type { WidgetManifest, WidgetOutput, WidgetOutputType, WidgetView } from '@lobechat/types';import { validateCronPattern } from '@lobechat/utils/cronEval';import type {@@ -44,6 +44,105 @@ export const findSucceededPreviewRun = <T extends PreviewRun & { trigger: string): undefined;+export interface ExpectedRun<T> {+ run: T;+ /** The run is of the version under review, not an earlier one shown for reference. */+ sameVersion: boolean;+}++/**+ * The run whose card best predicts what a version will show, from a+ * newest-first run list: that version's latest usable run, else the widget's+ * latest usable run of another version with the same output type — a stat+ * run says nothing about how a table will look.+ */+export const findExpectedRun = <T extends Pick<PreviewRun, 'output' | 'status' | 'versionId'>>(+ runs: T[],+ target: Pick<DashboardWidgetVersionItem, 'id' | 'outputType'>,+): ExpectedRun<T> | undefined => {+ const usable = runs.filter((run) => isUsableRunStatus(run.status) && !!run.output);+ const own = usable.find((run) => run.versionId === target.id);+ if (own) return { run: own, sameVersion: true };+ const earlier = usable.find((run) => run.output?.type === target.outputType);+ return earlier ? { run: earlier, sameVersion: false } : undefined;+};++/** Words a sample card shows, in the reader's language. */+export interface SampleLabels {+ item: (index: number) => string;+ name: string;+ series: string;+ value: string;+}++const SAMPLE_SERIES = [12, 15, 11, 18, 16, 21, 19];+const DAY_MS = 24 * 60 * 60 * 1000;++/**+ * Illustrative output for a version that has never produced a result, shaped+ * like its output type (and a table's chosen columns) so the approver sees the+ * kind of card it will make. The values are placeholders; the review labels+ * the card as sample data.+ */+export const sampleOutputFor = (+ outputType: WidgetOutputType,+ view: WidgetView | null | undefined,+ labels: SampleLabels,+ now = Date.now(),+): WidgetOutput => {+ switch (outputType) {+ case 'list': {+ return {+ items: [1, 2, 3].map((index) => ({ title: labels.item(index), value: 4 - index })),+ type: 'list',+ };+ }+ case 'series': {+ const points = SAMPLE_SERIES.map((v, index) => ({+ t: new Date(now - (SAMPLE_SERIES.length - 1 - index) * DAY_MS).toISOString().slice(0, 10),+ v,+ }));+ return { series: [{ name: labels.series, points }], type: 'series' };+ }+ case 'table': {+ const keys = view?.columns?.length ? view.columns : ['name', 'value'];+ const last = keys.length - 1;+ const columns = keys.map((key, index) => ({+ key,+ title: key === 'name' ? labels.name : key === 'value' ? labels.value : key,+ type: index === last && keys.length > 1 ? ('number' as const) : ('string' as const),+ }));+ const rows = [1, 2, 3].map((row) =>+ Object.fromEntries(+ keys.map((key, index) => [+ key,+ index === last && keys.length > 1 ? (4 - row) * 10 : labels.item(row),+ ]),+ ),+ );+ return { columns, rows, type: 'table' };+ }+ default: {+ return { delta: 12, trend: 'up', type: 'stat', value: 128 };+ }+ }+};++/**+ * The card model for sample output: no run times, so the card shows no+ * "updated" footer and no freshness state that the sample does not have.+ */+export const toSampleWidget = <T extends object>(widget: T, output: WidgetOutput) => ({+ ...widget,+ lastRunAt: null,+ lastRunError: null,+ lastRunStatus: null,+ latestOutput: output,+ latestOutputAt: null,+ nextRunAt: null,+ schedulePattern: null,+});+export type PreviewPublishState =/** This run's version is live. */| 'live'diff --git a/src/features/Dashboard/utils/layout.test.ts b/src/features/Dashboard/utils/layout.test.tsindex 353ec5b317e..d8ab77513b6 100644--- a/src/features/Dashboard/utils/layout.test.ts+++ b/src/features/Dashboard/utils/layout.test.ts@@ -6,6 +6,8 @@ import {DASHBOARD_ROW_HEIGHT,defaultWidgetSize,flowLayouts,+ resizeByKey,+ resizeByPointer,resolveLayouts,sortByPosition,} from './layout';@@ -85,3 +87,56 @@ describe('sortByPosition', () => {).toEqual(['c', 'a', 'b']);});});++describe('resizeByPointer', () => {+ // 12 columns of 64px with 16px gaps: one column plus its gap is 80px.+ const gridWidth = 12 * 64 + 11 * DASHBOARD_GRID_GAP;+ const rowStep = DASHBOARD_ROW_HEIGHT + DASHBOARD_GRID_GAP;++ it('snaps the dragged size to whole columns and rows', () => {+ expect(resizeByPointer({ h: 3, w: 4 }, { dx: 160, dy: rowStep }, gridWidth)).toEqual({+ h: 4,+ w: 6,+ });+ // Less than half a step does not move the edge.+ expect(resizeByPointer({ h: 3, w: 4 }, { dx: 30, dy: -30 }, gridWidth)).toEqual({+ h: 3,+ w: 4,+ });+ });++ it('stays within the board limits', () => {+ expect(resizeByPointer({ h: 3, w: 4 }, { dx: -2000, dy: -2000 }, gridWidth)).toEqual({+ h: 2,+ w: 3,+ });+ expect(resizeByPointer({ h: 3, w: 4 }, { dx: 5000, dy: 5000 }, gridWidth)).toEqual({+ h: 12,+ w: DASHBOARD_GRID_COLUMNS,+ });+ });++ it('changes only the height on a stacked board, keeping the saved width', () => {+ expect(+ resizeByPointer({ h: 3, w: 4 }, { dx: 400, dy: rowStep }, 360, { stacked: true }),+ ).toEqual({ h: 4, w: 4 });+ });++ it('keeps the size while the grid has no width yet', () => {+ expect(resizeByPointer({ h: 3, w: 4 }, { dx: 100, dy: 100 }, 0)).toEqual({ h: 3, w: 4 });+ });+});++describe('resizeByKey', () => {+ it('steps one column or row per arrow and ignores other keys', () => {+ expect(resizeByKey({ h: 3, w: 4 }, 'ArrowRight')).toEqual({ h: 3, w: 5 });+ expect(resizeByKey({ h: 3, w: 4 }, 'ArrowUp')).toEqual({ h: 2, w: 4 });+ expect(resizeByKey({ h: 2, w: 3 }, 'ArrowUp')).toEqual({ h: 2, w: 3 });+ expect(resizeByKey({ h: 3, w: 4 }, 'Enter')).toBeUndefined();+ });++ it('steps only the height on a stacked board', () => {+ expect(resizeByKey({ h: 3, w: 4 }, 'ArrowDown', { stacked: true })).toEqual({ h: 4, w: 4 });+ expect(resizeByKey({ h: 3, w: 4 }, 'ArrowRight', { stacked: true })).toBeUndefined();+ });+});diff --git a/src/features/Dashboard/utils/layout.ts b/src/features/Dashboard/utils/layout.tsindex a6683c372e3..d1352849b6f 100644--- a/src/features/Dashboard/utils/layout.ts+++ b/src/features/Dashboard/utils/layout.ts@@ -135,3 +135,82 @@ export const sortByPosition = <T extends { id: string }>(export const isSameLayout = (a?: DashboardItemLayout | null, b?: DashboardItemLayout | null) =>!!a && !!b && a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;++/** Narrowest a card may be resized to, in columns. */+export const DASHBOARD_MIN_W = DASHBOARD_WIDTH_PRESETS[0];++const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));++/**+ * The media query under which the board stacks its cards in one column.+ * Keep in sync with the `@media` rules in `Board/style.ts`.+ */+export const DASHBOARD_STACKED_QUERY = '(width <= 767px)';++interface ResizeOptions {+ /**+ * The board is stacked (narrow screen): every card spans the full width,+ * so only height can change; the saved width — what wider screens use —+ * is kept as it is.+ */+ stacked?: boolean;+}++/**+ * The size a card snaps to while its resize handle is dragged by `dx` / `dy`+ * pixels on a grid `gridWidth` pixels wide: the dragged pixel size rounded to+ * whole columns and rows (gaps included), within the board's limits.+ */+export const resizeByPointer = (+ start: { h: number; w: number },+ delta: { dx: number; dy: number },+ gridWidth: number,+ { stacked = false }: ResizeOptions = {},+): { h: number; w: number } => {+ const h = clamp(+ Math.round(+ (start.h * DASHBOARD_ROW_HEIGHT ++ (start.h - 1) * DASHBOARD_GRID_GAP ++ delta.dy ++ DASHBOARD_GRID_GAP) /+ (DASHBOARD_ROW_HEIGHT + DASHBOARD_GRID_GAP),+ ),+ DASHBOARD_MIN_H,+ DASHBOARD_MAX_H,+ );+ if (stacked) return { h, w: start.w };++ const columnWidth =+ (gridWidth - DASHBOARD_GRID_GAP * (DASHBOARD_GRID_COLUMNS - 1)) / DASHBOARD_GRID_COLUMNS;+ if (!(columnWidth > 0)) return start;++ const startWidth = start.w * columnWidth + (start.w - 1) * DASHBOARD_GRID_GAP;+ const w = Math.round(+ (startWidth + delta.dx + DASHBOARD_GRID_GAP) / (columnWidth + DASHBOARD_GRID_GAP),+ );++ return { h, w: clamp(w, DASHBOARD_MIN_W, DASHBOARD_GRID_COLUMNS) };+};++/**+ * One keyboard step of the resize handle: arrows grow or shrink by a column+ * or a row. On a stacked board only up / down apply.+ */+export const resizeByKey = (+ size: { h: number; w: number },+ key: string,+ { stacked = false }: ResizeOptions = {},+): { h: number; w: number } | undefined => {+ const step: Record<string, { dh: number; dw: number }> = {+ ArrowDown: { dh: 1, dw: 0 },+ ArrowLeft: { dh: 0, dw: -1 },+ ArrowRight: { dh: 0, dw: 1 },+ ArrowUp: { dh: -1, dw: 0 },+ };+ const move = step[key];+ if (!move || (stacked && move.dw !== 0)) return undefined;+ return {+ h: clamp(size.h + move.dh, DASHBOARD_MIN_H, DASHBOARD_MAX_H),+ w: clamp(size.w + move.dw, DASHBOARD_MIN_W, DASHBOARD_GRID_COLUMNS),+ };+};diff --git a/src/features/Dashboard/utils/schedule.test.ts b/src/features/Dashboard/utils/schedule.test.tsnew file mode 100644index 00000000000..a382a054523--- /dev/null+++ b/src/features/Dashboard/utils/schedule.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';++import {+ boardSchedulePattern,+ findSchedulePreset,+ formatSchedule,+ initialBoardScheduleChoice,+ resolveBoardSchedule,+ scheduleShowsTimezone,+} from './schedule';++describe('findSchedulePreset', () => {+ it('names a preset regardless of spacing', () => {+ expect(findSchedulePreset('0 * * * *')).toBe('hourly');+ expect(findSchedulePreset(' */15 * * * * ')).toBe('every15m');+ });++ it('names nothing for other patterns or no schedule', () => {+ expect(findSchedulePreset('5 4 * * 1')).toBeUndefined();+ expect(findSchedulePreset(null)).toBeUndefined();+ });+});++describe('scheduleShowsTimezone', () => {+ it('drops the timezone for intervals only', () => {+ expect(scheduleShowsTimezone('0 * * * *')).toBe(false);+ expect(scheduleShowsTimezone('0 9 * * *')).toBe(true);+ expect(scheduleShowsTimezone('5 4 * * 1')).toBe(true);+ });+});++describe('resolveBoardSchedule', () => {+ it('has nothing to set without widgets the user can change', () => {+ expect(resolveBoardSchedule([])).toEqual({ kind: 'none' });+ });++ it('reads one shared cadence as a preset or as manual', () => {+ expect(+ resolveBoardSchedule([{ schedulePattern: '0 * * * *' }, { schedulePattern: '0 * * * *' }]),+ ).toEqual({ choice: 'hourly', kind: 'uniform' });+ expect(resolveBoardSchedule([{ schedulePattern: null }, {}])).toEqual({+ choice: 'manual',+ kind: 'uniform',+ });+ });++ it('keeps a shared custom pattern and differing cadences as they are', () => {+ const custom = resolveBoardSchedule([{ schedulePattern: '5 4 * * 1' }]);+ expect(custom).toEqual({ kind: 'custom', pattern: '5 4 * * 1' });+ expect(initialBoardScheduleChoice(custom)).toBe('keep');++ const mixed = resolveBoardSchedule([+ { schedulePattern: '0 * * * *' },+ { schedulePattern: null },+ ]);+ expect(mixed).toEqual({ kind: 'mixed' });+ expect(initialBoardScheduleChoice(mixed)).toBe('keep');+ });+});++describe('boardSchedulePattern', () => {+ it('writes a preset pattern, clears for manual and writes nothing to keep', () => {+ expect(boardSchedulePattern('every6h')).toBe('0 */6 * * *');+ expect(boardSchedulePattern('manual')).toBeNull();+ expect(boardSchedulePattern('keep')).toBeUndefined();+ });+});++describe('formatSchedule', () => {+ const translate = (key: string) => `t:${key}`;++ it('names presets and keeps the timezone only where it changes the run time', () => {+ expect(formatSchedule(translate, '0 * * * *', 'Asia/Shanghai')).toBe('t:schedule.hourly');+ expect(formatSchedule(translate, '0 9 * * *', 'Asia/Shanghai')).toBe(+ 't:schedule.daily9 · Asia/Shanghai',+ );+ expect(formatSchedule(translate, '5 4 * * 1', null)).toBe('5 4 * * 1');+ });+});diff --git a/src/features/Dashboard/utils/schedule.ts b/src/features/Dashboard/utils/schedule.tsnew file mode 100644index 00000000000..ba36eb6c64b--- /dev/null+++ b/src/features/Dashboard/utils/schedule.ts@@ -0,0 +1,88 @@+/**+ * Refresh cadences offered by name. A widget may carry any cron pattern (an+ * agent picks one from its script's manifest); these are the ones a person+ * picks from a list and reads back as words.+ */+export const SCHEDULE_PRESETS = [+ { key: 'every15m', pattern: '*/15 * * * *' },+ { key: 'every30m', pattern: '*/30 * * * *' },+ { key: 'hourly', pattern: '0 * * * *' },+ { key: 'every6h', pattern: '0 */6 * * *' },+ { key: 'daily9', pattern: '0 9 * * *' },+] as const;++export type SchedulePresetKey = (typeof SCHEDULE_PRESETS)[number]['key'];++/** Presets whose run time depends on the timezone (fixed clock time, not an interval). */+const CLOCK_PRESETS = new Set<SchedulePresetKey>(['daily9']);++const normalizePattern = (pattern: string) => pattern.trim().split(/\s+/).join(' ');++/** The preset a cron pattern is, if it is one. */+export const findSchedulePreset = (pattern?: string | null): SchedulePresetKey | undefined => {+ if (!pattern) return undefined;+ const normalized = normalizePattern(pattern);+ return SCHEDULE_PRESETS.find((preset) => preset.pattern === normalized)?.key;+};++/** Whether a schedule's timezone changes when it runs (and so belongs beside its label). */+export const scheduleShowsTimezone = (pattern: string) => {+ const preset = findSchedulePreset(pattern);+ return !preset || CLOCK_PRESETS.has(preset);+};++/** A board-wide schedule choice: no schedule, a preset, or leave every widget as it is. */+export type BoardScheduleChoice = 'keep' | 'manual' | SchedulePresetKey;++/**+ * What the board's widgets refresh on today, as the settings form reads it:+ * - `none` — the user can change no widget here (only creators may);+ * - `uniform` — every widget they can change shares one cadence, shown as `choice`;+ * - `custom` — they share one cron pattern that is not a preset;+ * - `mixed` — the widgets differ.+ */+export type BoardScheduleState =+ | { kind: 'none' }+ | { choice: Exclude<BoardScheduleChoice, 'keep'>; kind: 'uniform' }+ | { kind: 'custom'; pattern: string }+ | { kind: 'mixed' };++export const resolveBoardSchedule = (+ widgets: { schedulePattern?: string | null }[],+): BoardScheduleState => {+ if (widgets.length === 0) return { kind: 'none' };++ const patterns = new Set(+ widgets.map(({ schedulePattern }) =>+ schedulePattern ? normalizePattern(schedulePattern) : null,+ ),+ );+ if (patterns.size > 1) return { kind: 'mixed' };++ const [pattern] = patterns;+ if (!pattern) return { choice: 'manual', kind: 'uniform' };+ const preset = findSchedulePreset(pattern);+ return preset ? { choice: preset, kind: 'uniform' } : { kind: 'custom', pattern };+};++/** The choice the form starts on: what is set today, or "keep" when no single preset says it. */+export const initialBoardScheduleChoice = (state: BoardScheduleState): BoardScheduleChoice =>+ state.kind === 'uniform' ? state.choice : 'keep';++/** The cron pattern a choice writes; `undefined` when it writes nothing. */+export const boardSchedulePattern = (choice: BoardScheduleChoice): string | null | undefined => {+ if (choice === 'keep') return undefined;+ if (choice === 'manual') return null;+ return SCHEDULE_PRESETS.find((preset) => preset.key === choice)?.pattern;+};++/** A cadence as a person reads it: the preset's name, else the cron pattern, with its timezone when it matters. */+export const formatSchedule = (+ translate: (key: `schedule.${SchedulePresetKey}`) => string,+ pattern: string,+ timezone?: string | null,+) => {+ const preset = findSchedulePreset(pattern);+ const label = preset ? translate(`schedule.${preset}`) : pattern;+ return timezone && scheduleShowsTimezone(pattern) ? `${label} · ${timezone}` : label;+};diff --git a/src/services/dashboard.ts b/src/services/dashboard.tsindex 452bf93daef..fdbf54f284a 100644--- a/src/services/dashboard.ts+++ b/src/services/dashboard.ts@@ -1,4 +1,4 @@-import type { DashboardItemLayout, WidgetLevelFilter } from '@lobechat/types';+import type { DashboardItemLayout, DashboardVisibility, WidgetLevelFilter } from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';@@ -18,6 +18,13 @@ export type DashboardWidgetVersionItem = QueryData<WidgetRouter['listVersions']>export type DashboardWidgetRunItem = QueryData<WidgetRouter['listRuns']>[number];export type DashboardWidgetRunDetail = QueryData<WidgetRouter['getRun']>;+/** The board fields its settings edit. */+export interface DashboardSettingsPatch {+ description?: string | null;+ title?: string;+ visibility?: DashboardVisibility;+}+export interface DashboardLayoutPatch {id: string;layout?: DashboardItemLayout | null;@@ -73,8 +80,11 @@ class DashboardService {return data;};- rename = async (id: string, title: string) =>- lambdaClient.dashboard.update.mutate({ id, value: { title } });+ /** Returns the saved row: the server may keep a board private that asked to be public. */+ update = async (id: string, value: DashboardSettingsPatch) => {+ const { data } = await lambdaClient.dashboard.update.mutate({ id, value });+ return data;+ };trash = async (id: string) => lambdaClient.dashboard.trash.mutate({ id });@@ -121,6 +131,33 @@ class DashboardService {return data;};+ updateWidget = async (+ widgetId: string,+ value: { description?: string | null; title?: string },+ ) => {+ const { data } = await lambdaClient.widget.update.mutate({ id: widgetId, value });+ return data;+ };++ /** Stop asking before dry runs that need no more access than this version. */+ grantDryRunAccess = async (widgetId: string, versionId: string) => {+ const { data } = await lambdaClient.widget.grantDryRunAccess.mutate({ versionId, widgetId });+ return data;+ };++ setWidgetSchedule = async (+ widgetId: string,+ pattern: string | null,+ timezone?: string | null,+ ) => {+ const { data } = await lambdaClient.widget.setSchedule.mutate({+ id: widgetId,+ pattern,+ timezone,+ });+ return data;+ };+publish = async (widgetId: string, versionId: string) => {const { data } = await lambdaClient.widget.publish.mutate({ versionId, widgetId });return data;diff --git a/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.ts b/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.tsnew file mode 100644index 00000000000..c707781e285--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.ts@@ -0,0 +1,27 @@+import { createDryRunAudit, DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';+import { createPathScopeAudit } from '@lobechat/builtin-tool-local-system';+import { isDesktop } from '@lobechat/const';++import { dashboardService } from '@/services/dashboard';+import { localFileService } from '@/services/electron/localFileService';+import { getUserStoreState } from '@/store/user/store';++/**+ * Dynamic intervention audits for runs driven by this client: each reads what+ * the call would touch through the client's own services and the signed-in+ * user's settings.+ */+export const clientInterventionAudits = {+ [DASHBOARD_DRY_RUN_AUDIT]: createDryRunAudit({+ loadGrants: () => getUserStoreState().settings.tool?.widgetDryRunGrants,+ loadVersion: (widgetId, versionId) => dashboardService.getVersion(widgetId, versionId),+ }),+ pathScopeAudit: createPathScopeAudit({+ areAllPathsSafe: async ({ paths, resolveAgainstScope }) => {+ if (!isDesktop) return false;++ const result = await localFileService.auditSafePaths({ paths, resolveAgainstScope });+ return result.allSafe;+ },+ }),+};diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 6c3b1c7e82a..281ffb677e2 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -12,9 +12,7 @@ import {getLlmCallCount,isParkedStatus,} from '@lobechat/agent-runtime';-import { createDryRunAudit, DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';-import { createPathScopeAudit } from '@lobechat/builtin-tool-local-system';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';import {@@ -41,8 +39,6 @@ import { aiAgentService } from '@/services/aiAgent';import { isCanUseAudio, isCanUseVideo, isCanUseVision } from '@/services/chat/helper';import { type ResolvedAgentConfig } from '@/services/chat/mecha';import { composeEnabledTools, resolveAgentConfig } from '@/services/chat/mecha';-import { dashboardService } from '@/services/dashboard';-import { localFileService } from '@/services/electron/localFileService';import { messageService } from '@/services/message';import { hydrateProjectedConversation } from '@/services/message/hydrateProjectedTools';import { workService } from '@/services/work';@@ -74,23 +70,10 @@ import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';import type { RunParkedReason, RunScope } from '../../lifecycle/types';import { buildViewedTaskPrompt } from '../viewedTaskPrompt';import { buildRunManifestMap } from './discoverableManifests';+import { clientInterventionAudits } from './interventionAudits';const log = debug('lobe-store:streaming-executor');-const dynamicInterventionAudits = {- [DASHBOARD_DRY_RUN_AUDIT]: createDryRunAudit({- loadVersion: (widgetId, versionId) => dashboardService.getVersion(widgetId, versionId),- }),- pathScopeAudit: createPathScopeAudit({- areAllPathsSafe: async ({ paths, resolveAgainstScope }) => {- if (!isDesktop) return false;-- const result = await localFileService.auditSafePaths({ paths, resolveAgainstScope });- return result.allSafe;- },- }),-};-const getMediaAvailability = (messages: UIChatMessage[]) => ({hasAudios: messages.some((message) => message.role === 'user' && !!message.audioList?.length),hasImages: messages.some((message) => message.role === 'user' && !!message.imageList?.length),@@ -711,7 +694,7 @@ export class StreamingExecutorActionImpl {enabled: agentConfigData.chatConfig?.enableContextCompression ?? true, // Default to enabledmaxWindowToken: contextWindowTokens ?? undefined,},- dynamicInterventionAudits,+ dynamicInterventionAudits: clientInterventionAudits,operationId: `${messageKey}/${params.parentMessageId}`,modelRuntimeConfig,});diff --git a/src/store/dashboard/store.test.ts b/src/store/dashboard/store.test.tsindex 3849dd6f998..4737e105206 100644--- a/src/store/dashboard/store.test.ts+++ b/src/store/dashboard/store.test.ts@@ -11,16 +11,25 @@ vi.mock('@/libs/swr', () => ({mutate: vi.fn(),useClientDataSWR: vi.fn(),}));+const userStore = vi.hoisted(() => ({ refreshUserState: vi.fn() }));+vi.mock('@/store/user', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useUserStore: { getState: () => userStore },+}));+vi.mock('@/services/dashboard', () => ({dashboardService: {addItem: vi.fn(),create: vi.fn(),getPreviewRun: vi.fn(),+ grantDryRunAccess: vi.fn(),publish: vi.fn(),removeItems: vi.fn(),- rename: vi.fn(),runWidget: vi.fn(),+ setWidgetSchedule: vi.fn(),trash: vi.fn(),+ update: vi.fn(),+ updateWidget: vi.fn(),updateItemLayouts: vi.fn(),},}));@@ -91,9 +100,9 @@ describe('board entity propagation', () => {dashboardListByLevel: { personal: [board()] },projectDashboardsMap: { p1: [board({ projectId: 'p1' })] },});- vi.mocked(dashboardService.rename).mockResolvedValue(undefined as any);+ vi.mocked(dashboardService.update).mockResolvedValue(undefined as any);- await useDashboardStore.getState().renameDashboard('d1', 'Renamed', {});+ await useDashboardStore.getState().updateDashboard('d1', { title: 'Renamed' }, {});const state = useDashboardStore.getState();expect(state.dashboardDetailMap.d1.title).toBe('Renamed');@@ -103,6 +112,26 @@ describe('board entity propagation', () => {expect(state.projectDashboardsMap.p1[0].title).toBe('Renamed');});+ it('shows the visibility the server kept, not the one asked for', async () => {+ useDashboardStore.setState({+ dashboardDetailMap: { d1: detail },+ dashboardListByLevel: { personal: [board({ visibility: 'private' })] },+ });+ // A board of a private project stays private whatever the settings asked.+ vi.mocked(dashboardService.update).mockResolvedValue(+ board({ description: 'Ops health', visibility: 'private' }),+ );++ const saved = await useDashboardStore+ .getState()+ .updateDashboard('d1', { description: 'Ops health', visibility: 'public' }, {});++ expect(saved?.visibility).toBe('private');+ const state = useDashboardStore.getState();+ expect(state.dashboardListByLevel.personal[0].visibility).toBe('private');+ expect(state.dashboardListByLevel.personal[0].description).toBe('Ops health');+ });+it('drops the board from the loaded lists when trashed', async () => {useDashboardStore.setState({dashboardDetailMap: { d1: detail },@@ -252,3 +281,65 @@ describe('refreshWidgetPlacement', () => {expect(vi.mocked(mutate).mock.calls.length).toBeGreaterThanOrEqual(5);});});++describe('setWidgetsSchedule', () => {+ it('saves every widget and counts the ones the server refused', async () => {+ vi.mocked(dashboardService.setWidgetSchedule)+ .mockResolvedValueOnce({} as any)+ .mockRejectedValueOnce(new Error('Only the widget creator can change it'))+ .mockResolvedValueOnce({} as any);++ const result = await useDashboardStore+ .getState()+ .setWidgetsSchedule(['w1', 'w2', 'w3'], { pattern: '0 * * * *', timezone: 'Asia/Shanghai' });++ expect(result).toEqual({ failed: 1 });+ expect(dashboardService.setWidgetSchedule).toHaveBeenCalledTimes(3);+ expect(dashboardService.setWidgetSchedule).toHaveBeenCalledWith(+ 'w2',+ '0 * * * *',+ 'Asia/Shanghai',+ );+ });+});++describe('updateWidget', () => {+ it("saves the widget's title and metric definition", async () => {+ vi.mocked(dashboardService.updateWidget).mockResolvedValue({} as any);++ await useDashboardStore+ .getState()+ .updateWidget('w1', { description: 'Open PRs by me', title: 'My open PRs' });++ expect(dashboardService.updateWidget).toHaveBeenCalledWith('w1', {+ description: 'Open PRs by me',+ title: 'My open PRs',+ });+ });++ it('surfaces a refused save to the caller', async () => {+ vi.mocked(dashboardService.updateWidget).mockRejectedValue(new Error('NOT_FOUND'));++ await expect(useDashboardStore.getState().updateWidget('w1', { title: 'x' })).rejects.toThrow(+ 'NOT_FOUND',+ );+ });+});++describe('grantDryRunAccess', () => {+ it('reloads user settings after the grant so the next audit sees it', async () => {+ const order: string[] = [];+ vi.mocked(dashboardService.grantDryRunAccess).mockImplementation(async () => {+ order.push('grant');+ return undefined;+ });+ userStore.refreshUserState.mockImplementation(async () => {+ order.push('refresh');+ });++ await useDashboardStore.getState().grantDryRunAccess('w1', 'v2');++ expect(dashboardService.grantDryRunAccess).toHaveBeenCalledWith('w1', 'v2');+ expect(order).toEqual(['grant', 'refresh']);+ });+});diff --git a/src/store/dashboard/store.ts b/src/store/dashboard/store.tsindex d92efdfef64..700ebd31eb2 100644--- a/src/store/dashboard/store.ts+++ b/src/store/dashboard/store.ts@@ -16,9 +16,11 @@ import {type CreateDashboardParams,type DashboardLayoutPatch,dashboardService,+ type DashboardSettingsPatch,} from '@/services/dashboard';import { createDevtools } from '@/store/middleware/createDevtools';import { expose } from '@/store/middleware/expose';+import { useUserStore } from '@/store/user';import { dashboardLevelKey, type DashboardState, initialState } from './initialState';import {@@ -98,6 +100,12 @@ const toRequest = <TData>(export interface DashboardAction {addWidgetToDashboard: (dashboardId: string, widgetId: string) => Promise<unknown>;createDashboard: (params: CreateDashboardParams) => Promise<DashboardListItem>;+ /**+ * Record a standing dry-run grant for this version's access, then reload+ * the user's settings so the client-side audit of the very next dry run+ * already sees it.+ */+ grantDryRunAccess: (widgetId: string, versionId: string) => Promise<void>;publishWidgetVersion: (widgetId: string,versionId: string,@@ -109,14 +117,35 @@ export interface DashboardAction {/** The agent placed a widget server-side: revalidate everything that shows it. */refreshWidgetPlacement: (widgetId: string, dashboardId?: string) => Promise<unknown>;removeWidgetFromDashboard: (dashboardId: string, itemId: string) => Promise<void>;- renameDashboard: (dashboardId: string, title: string, level?: WidgetLevelFilter) => Promise<void>;runWidget: (widgetId: string) => Promise<DashboardWidgetRunItem | undefined>;saveDashboardLayout: (dashboardId: string,layouts: Record<string, DashboardItemLayout>,order: string[],) => Promise<void>;+ /**+ * Set the cadence of several widgets at once (a board's settings). Each+ * widget saves on its own; resolves with how many the server refused.+ */+ setWidgetsSchedule: (+ widgetIds: string[],+ schedule: { pattern: string | null; timezone?: string | null },+ ) => Promise<{ failed: number }>;trashDashboard: (dashboardId: string, level?: WidgetLevelFilter) => Promise<void>;+ /** Save a board's settings; resolves with the saved row (visibility may be kept private). */+ updateDashboard: (+ dashboardId: string,+ value: DashboardSettingsPatch,+ level?: WidgetLevelFilter,+ ) => Promise<DashboardListItem | undefined>;+ /**+ * Save a widget's own title / metric definition, then refresh every board,+ * list and drill-down that shows it.+ */+ updateWidget: (+ widgetId: string,+ patch: { description?: string | null; title?: string },+ ) => Promise<void>;/** Fetch orchestration only; read the board with `dashboardSelectors.dashboardDetail`. */useFetchDashboardDetail: (dashboardId?: string) => DashboardRequest<DashboardDetail>;useFetchDashboards: (@@ -362,12 +391,17 @@ export const useDashboardStore = createWithEqualityFn<DashboardStore>()(}},- renameDashboard: async (dashboardId, title, level) => {- await dashboardService.rename(dashboardId, title);+ updateDashboard: async (dashboardId, value, level) => {+ const saved = await dashboardService.update(dashboardId, value);// The linked board entity updates the level list, the project list and// the detail page in one commit; revalidating picks up server fields.- board.update(dashboardId, (current) => ({ ...current, title }));+ board.update(dashboardId, (current) => ({+ ...current,+ ...value,+ ...(saved ? { visibility: saved.visibility } : {}),+ }));await Promise.all([detail.revalidate(dashboardId), refreshDashboards(level)]);+ return saved as DashboardListItem | undefined;},trashDashboard: async (dashboardId, level) => {@@ -487,6 +521,34 @@ export const useDashboardStore = createWithEqualityFn<DashboardStore>()(}},+ grantDryRunAccess: async (widgetId, versionId) => {+ await dashboardService.grantDryRunAccess(widgetId, versionId);+ await useUserStore.getState().refreshUserState();+ },++ updateWidget: async (widgetId, patch) => {+ await dashboardService.updateWidget(widgetId, patch);+ await Promise.all([+ detail.revalidate(),+ projectWidgets.revalidate(),+ widgetDetail.revalidate(widgetId),+ ]);+ },++ setWidgetsSchedule: async (widgetIds, { pattern, timezone }) => {+ const results = await Promise.allSettled(+ widgetIds.map((widgetId) =>+ dashboardService.setWidgetSchedule(widgetId, pattern, timezone),+ ),+ );+ await Promise.all([+ detail.revalidate(),+ projectWidgets.revalidate(),+ ...widgetIds.map((widgetId) => widgetDetail.revalidate(widgetId)),+ ]);+ return { failed: results.filter((result) => result.status === 'rejected').length };+ },+addWidgetToDashboard: async (dashboardId, widgetId) => {set((s) => ({ widgetAddingIds: [...s.widgetAddingIds, widgetId] }),