@eum-agent/agent-management 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +735 -32
  2. package/package.json +2 -2
  3. package/ui/ui.js +1639 -1601
package/ui/ui.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Alert, AlertDialog, Avatar, Button, Checkbox, Dialog, DialogContent, DialogHeader, DialogTitle, EmptyState, Failure, Field, FilterChips, FormFailure, Input, InputNumber, PLUGIN_ICONS, Panel, ReadFailure, RenderingRegion, Segmented, Select, SlotOutlet, Switch, Tabs, TabsContent, TabsList, TabsTrigger, Textarea, Tooltip, TooltipContent, TooltipHint, TooltipTrigger, Warning, agentDeleted, agentOf, cn, codePoints, contributionsIn, failureText, goToSession, i18next, localeLeaves, pictureOf, pngDataUrl, resolveLabel, useAgents, useAvatarPicker, useGateway, useGatewayAction, useGatewayRead, useNavigation, usePlugins, useToast, useTranslation, uuid } from "@eum-agent/host/framework";
2
- import { createContext, createElement, forwardRef, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
1
+ import { Alert, AlertDialog, Avatar, Button, DataTable, Dialog, DialogContent, DialogHeader, DialogTitle, EmptyState, Failure, Field, FormFailure, Input, InputNumber, PLUGIN_ICONS, Panel, ReadFailure, RenderingRegion, Segmented, Select, SlotOutlet, Tabs, TabsContent, TabsList, TabsTrigger, Textarea, Tooltip, TooltipContent, TooltipHint, TooltipTrigger, Warning, agentDeleted, agentOf, cn, codePoints, contributionsIn, failureText, goToSession, i18next, localeLeaves, pictureOf, pngDataUrl, resolveLabel, useAgents, useAvatarPicker, useBrowserService, useGateway, useGatewayAction, useGatewayRead, useNavigation, usePlugins, useToast, useTranslation, uuid } from "@eum-agent/host/framework";
2
+ import { createContext, createElement, forwardRef, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
4
  //#region ui-src/styles.css?raw
5
5
  var styles_default = "@layer components {\n [data-slot=\"settings-panel\"] {\n container-type: inline-size;\n }\n}\n\n.ag-shell {\n display: grid;\n flex: 1;\n min-height: 0;\n grid-template-columns: 15rem minmax(0, 1fr);\n}\n.ag-list {\n display: flex;\n flex-direction: column;\n min-height: 0;\n padding: 0 0.75rem 0.75rem;\n border-inline-end: 1px solid var(--border);\n}\n.ag-list-title {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 0.5rem;\n flex: none;\n height: 4rem;\n padding-inline: 0.625rem 0;\n}\n.ag-list-title h2 {\n font-size: 1.125rem;\n font-weight: 600;\n}\n.ag-list-title [data-slot=\"button\"],\n.ag-list-title [data-slot=\"tooltip-trigger\"] {\n color: var(--muted-foreground);\n}\n.ag-rows {\n display: flex;\n flex: 1;\n flex-direction: column;\n min-height: 0;\n overflow-y: auto;\n}\n.ag-group {\n display: flex;\n flex-direction: column;\n gap: 2px;\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.ag-group-title {\n margin: 1rem 0 0.25rem;\n padding-inline: 0.625rem;\n font-size: 0.75rem;\n color: var(--muted-foreground);\n}\n.ag-row {\n --row-fill: var(--card);\n position: relative;\n min-width: 0;\n border-radius: var(--radius-control);\n background: var(--row-fill);\n transition: background-color 150ms ease;\n}\n.ag-row:hover {\n --row-fill: var(--muted);\n}\n.ag-row[data-active] {\n --row-fill: var(--accent);\n}\n.ag .ag-row-open {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n width: 100%;\n min-width: 0;\n padding: 0.625rem;\n border-radius: var(--radius-control);\n text-align: start;\n cursor: pointer;\n}\n.ag .ag-row-open:focus-visible {\n outline: none;\n}\n.ag-row:has(> .ag-row-open:focus-visible) {\n outline: var(--focus-ring-width) solid var(--focus-ring-color);\n}\n.ag-row-name {\n display: flex;\n flex: 1;\n flex-direction: column;\n min-width: 0;\n}\n.ag-row-name strong,\n.ag-row-name small {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.ag-row-name strong {\n font-size: 0.875rem;\n font-weight: 500;\n}\n.ag-row[data-active] .ag-row-name strong {\n color: var(--accent-foreground);\n}\n.ag-row-name small {\n margin-top: 0.125rem;\n font-size: 0.75rem;\n color: var(--muted-foreground);\n}\n.ag-chapter-icon {\n display: grid;\n flex: none;\n place-items: center;\n width: 2rem;\n height: 2rem;\n border-radius: var(--radius-pill);\n background: var(--muted);\n color: var(--muted-foreground);\n}\n.ag-row:is(:hover, [data-active]) .ag-chapter-icon {\n background: var(--card);\n}\n/* Hover actions fade into the row, as the model and MCP lists do. */\n.ag-row-actions {\n position: absolute;\n inset-block: 0;\n inset-inline-end: 0;\n display: flex;\n align-items: center;\n gap: 0.125rem;\n padding-inline: 1.25rem 0.375rem;\n border-radius: var(--radius-control);\n background: linear-gradient(to right, transparent, var(--row-fill) 1rem);\n opacity: 0;\n pointer-events: none;\n transition: opacity 150ms ease;\n}\n.ag-row:hover .ag-row-actions,\n.ag-row:focus-within .ag-row-actions {\n opacity: 1;\n pointer-events: auto;\n}\n@media (hover: none) {\n .ag-row-actions {\n opacity: 1;\n pointer-events: auto;\n }\n}\n.ag-list-foot {\n flex: none;\n padding-top: 0.75rem;\n}\n.ag-detail {\n display: flex;\n flex-direction: column;\n min-width: 0;\n min-height: 0;\n}\n.ag-detail-header {\n display: flex;\n align-items: center;\n gap: 0.875rem;\n flex: none;\n min-height: 4.5rem;\n padding: 1rem 3.5rem 0.75rem 1.5rem;\n}\n.ag-grow {\n flex: 1;\n min-width: 0;\n}\n.ag-detail-header h3 {\n overflow: hidden;\n font-size: 1.125rem;\n font-weight: 600;\n line-height: 1.4;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.ag-detail-header small {\n display: block;\n font-size: 0.75rem;\n color: var(--muted-foreground);\n}\n.ag-tabs {\n display: flex;\n flex: 1;\n flex-direction: column;\n min-height: 0;\n min-width: 0;\n gap: 0;\n}\n.ag-tabs > .ag-tabs-list {\n flex: none;\n margin-inline: 1.5rem;\n}\n.ag-tab {\n min-height: 0;\n overflow-y: auto;\n padding: 1rem 1.5rem 0.25rem;\n}\n.ag-tab.ag-tab-skills:not([hidden]) {\n display: flex;\n flex-direction: column;\n overflow: hidden;\n}\n.ag-tab.ag-tab-fill {\n display: flex;\n flex-direction: column;\n overflow: hidden;\n}\n.ag-chapter-body {\n flex: 1;\n min-height: 0;\n overflow-y: auto;\n padding: 0 1.5rem 1.5rem;\n}\n/* One label column with the model and MCP forms. */\n@container (min-width: 28rem) {\n .ag-detail .settings-field-row {\n grid-template-columns: 7rem minmax(0, 1fr);\n }\n}\n/* Discard and save, one equal share each, at the foot of the column. */\n/* The footer's buttons rest 0.75rem above the pane's floor, where the list\n * column's add button rests, so the two bottom rows line up. */\n.ag-footer {\n display: flex;\n flex: none;\n flex-direction: column;\n gap: 0.75rem;\n padding: 0.5rem 1.5rem 0.75rem;\n}\n.ag-footer-actions {\n display: flex;\n gap: 0.5rem;\n}\n.ag-footer-actions > * {\n flex: 1 1 0;\n min-width: 0;\n}\n@container ag (max-width: 38rem) {\n .ag-shell {\n grid-template-columns: minmax(0, 1fr);\n grid-template-rows: auto minmax(0, 1fr);\n }\n .ag-list {\n flex-direction: row;\n align-items: center;\n gap: 0.5rem;\n padding: 0.5rem 3rem 0.5rem 1rem;\n border-inline-end: 0;\n border-bottom: 1px solid var(--border);\n }\n .ag-list-title h2,\n .ag-row-name small,\n .ag-group-title {\n display: none;\n }\n .ag-list-title {\n order: 2;\n height: auto;\n padding: 0;\n }\n .ag-rows {\n flex-direction: row;\n gap: 2px;\n overflow-x: auto;\n overflow-y: hidden;\n }\n .ag-group {\n flex-direction: row;\n }\n .ag-row {\n flex: none;\n }\n .ag .ag-row-open {\n padding: 0.375rem 0.625rem 0.375rem 0.375rem;\n gap: 0.5rem;\n }\n /* The chosen chip keeps its actions inline: a strip has no hover room. */\n .ag-row[data-active] {\n display: flex;\n align-items: center;\n padding-inline-end: 0.25rem;\n }\n .ag-row .ag-row-actions {\n display: none;\n }\n .ag-row[data-active] .ag-row-actions {\n position: static;\n display: flex;\n padding: 0;\n background: none;\n opacity: 1;\n pointer-events: auto;\n }\n .ag-list-foot {\n order: 3;\n padding: 0;\n }\n .ag-list-foot [data-slot=\"button\"] {\n width: auto;\n }\n .ag-detail-header,\n .ag-tab,\n .ag-chapter-body,\n .ag-footer {\n padding-inline: 1rem;\n }\n .ag-tabs > .ag-tabs-list {\n margin-inline: 1rem;\n }\n}\n";
@@ -8,6 +8,8 @@ var styles_default = "@layer components {\n [data-slot=\"settings-panel\"] {\n
8
8
  /** Text owned by this browser capability. */
9
9
  var catalogue$1 = {
10
10
  runSettings: {
11
+ budgetOn: "On",
12
+ budgetOff: "Off",
11
13
  blocked: "Configuration recovery is incomplete. New rounds are blocked until reading succeeds.",
12
14
  current: "Current limits: {{steps}} steps per round; token budget {{budget}}.",
13
15
  unlimited: "unlimited",
@@ -147,6 +149,24 @@ var catalogue$1 = {
147
149
  readFailed: "The rules file cannot be read and cannot be edited: {{reason}}"
148
150
  },
149
151
  toolSettings: {
152
+ tool: "Tool",
153
+ permitted: "Allow calls",
154
+ forbidden: "Block calls",
155
+ preload: "Preload",
156
+ preloadOn: "Preloaded. Click to load on demand.",
157
+ preloadOff: "Loaded on demand. Click to preload.",
158
+ deferred: "On demand",
159
+ cancelPreload: "Stop preloading",
160
+ defaultSuggestion: "Suggested default",
161
+ followDefault: "Following default",
162
+ customized: "Customized",
163
+ restoreDefault: "Restore default",
164
+ resetDefaultsHint: "Reset access and preload settings for every tool, including tools hidden by search",
165
+ on: "On",
166
+ off: "Off",
167
+ preloadInactive: "Calls are blocked; this preference is inactive.",
168
+ preloadUnavailable: "Preload configuration is unavailable. Saved preferences are retained.",
169
+ systemTools: "The system provides tool discovery and dispatch automatically.",
150
170
  heading: "Available tools",
151
171
  hint: "Choose which tools this agent can call. Calls still follow the safety authorization settings.",
152
172
  mode: "Tool access",
@@ -170,11 +190,11 @@ var catalogue$1 = {
170
190
  selectWholeGroup_one: "Select or clear the {{count}} tool in this group",
171
191
  unknownSource: "Unknown source",
172
192
  unrestricted: "Allow all tools",
173
- none: "This agent will have no tools at all",
193
+ none: "This agent will have no callable ordinary tools",
174
194
  selectAll: "Select all of {{group}}",
175
195
  chosen: "{{chosen}} of {{total}} chosen",
176
196
  unavailable: "Unavailable",
177
- unavailableHint: "On the whitelist, but no plugin provides it now.",
197
+ unavailableHint: "Retained preferences for tools missing from the current catalogue. These tools cannot be called.",
178
198
  all: "Select all",
179
199
  clear: "Clear"
180
200
  }
@@ -186,6 +206,8 @@ var catalogue$1 = {
186
206
  /** Text owned by this browser capability. */
187
207
  var catalogue = {
188
208
  runSettings: {
209
+ budgetOn: "开启",
210
+ budgetOff: "关闭",
189
211
  blocked: "配置恢复尚未完成,新轮次暂时阻断;成功重新读取后恢复。",
190
212
  current: "当前限额:每轮 {{steps}} 步;token 预算 {{budget}}。",
191
213
  unlimited: "不设上限",
@@ -329,11 +351,29 @@ var catalogue = {
329
351
  readFailed: "无法读取规则文件,不能编辑:{{reason}}"
330
352
  },
331
353
  toolSettings: {
354
+ tool: "工具",
355
+ permitted: "允许调用",
356
+ forbidden: "禁止调用",
357
+ preload: "预加载",
358
+ preloadOn: "已预加载,点击改为按需加载",
359
+ preloadOff: "按需加载,点击开启预加载",
360
+ deferred: "按需加载",
361
+ cancelPreload: "取消预加载",
362
+ defaultSuggestion: "默认建议",
363
+ followDefault: "跟随默认",
364
+ customized: "已自定义",
365
+ restoreDefault: "恢复默认",
366
+ resetDefaultsHint: "恢复全部工具的默认调用权限和预加载设置",
367
+ on: "开启",
368
+ off: "关闭",
369
+ preloadInactive: "未允许调用,暂不生效",
370
+ preloadUnavailable: "预加载配置暂不可用,已保存的偏好会保留。",
371
+ systemTools: "系统自动提供工具检索与调用。",
332
372
  heading: "可用工具",
333
373
  hint: "决定智能体可以调用哪些工具,执行时仍遵循安全授权。",
334
374
  mode: "工具授权范围",
335
375
  custom: "自定义",
336
- allowAll: "允许全部",
376
+ allowAll: "全部允许",
337
377
  searchLabel: "搜索工具",
338
378
  searchPlaceholder: "搜索工具名称、说明或来源",
339
379
  filterLabel: "筛选工具",
@@ -350,11 +390,11 @@ var catalogue = {
350
390
  selectWholeGroup: "选择或取消本组全部 {{count}} 个工具",
351
391
  unknownSource: "未知来源",
352
392
  unrestricted: "授权所有工具调用",
353
- none: "该智能体将没有任何工具",
393
+ none: "该智能体将没有可调用的普通工具",
354
394
  selectAll: "全选 {{group}}",
355
395
  chosen: "已选 {{chosen}} 个,共 {{total}} 个",
356
396
  unavailable: "不可用",
357
- unavailableHint: "白名单里有、但当前没有插件提供的工具。",
397
+ unavailableHint: "已保留配置但当前目录中没有的工具,不能调用。",
358
398
  all: "全选",
359
399
  clear: "全不选"
360
400
  }
@@ -365,6 +405,7 @@ var catalogue = {
365
405
  //#region src/tool-names.ts
366
406
  /** Canonical names shared by tool registration and browser presentation. */
367
407
  var AGENT_TOOL_NAMES = [
408
+ "agent_list",
368
409
  "agent_read",
369
410
  "agent_update",
370
411
  "agent_create"
@@ -375,6 +416,7 @@ var CATALOGUES = {
375
416
  "en-US": {
376
417
  section: "Core capability",
377
418
  group: "Agent definition",
419
+ agent_list: "List agents",
378
420
  agent_read: "Read agent definition",
379
421
  agent_update: "Update agent definition",
380
422
  agent_create: "Create agent"
@@ -382,6 +424,7 @@ var CATALOGUES = {
382
424
  "zh-CN": {
383
425
  section: "核心能力",
384
426
  group: "智能体定义",
427
+ agent_list: "列出智能体",
385
428
  agent_read: "读取智能体设定",
386
429
  agent_update: "更新智能体设定",
387
430
  agent_create: "创建智能体"
@@ -660,1684 +703,1671 @@ var Puzzle = createLucideIcon("puzzle", [["path", {
660
703
  d: "M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z",
661
704
  key: "w46dr5"
662
705
  }]]);
706
+ //#endregion
707
+ //#region ui-src/components/settings/agent/editor.tsx
663
708
  /**
664
- * @license lucide-react v1.40.0 - ISC
709
+ * The agent detail page's one draft and its one save.
665
710
  *
666
- * This source code is licensed under the ISC license.
667
- * See the LICENSE file in the root directory of this source tree.
711
+ * Base fields, prompt slots, tool access, and opaque owner configuration stay
712
+ * in one draft until Save submits their complete changed values together.
713
+ * Owner fields are validated by their active contributions before that request.
714
+ *
715
+ * A draft remembers the saved value it was started from. When another client
716
+ * changes the agent (`config.agentChanged`, which re-reads the list and the
717
+ * prompt text), a field without a draft simply shows the new value; a field
718
+ * with one keeps it and reports `stale`, and `reload` takes the new value.
719
+ * A draft that the saved value has caught up with is no longer dirty.
668
720
  */
669
- var Search = createLucideIcon("search", [["path", {
670
- d: "m21 21-4.34-4.34",
671
- key: "14j7rj"
672
- }], ["circle", {
673
- cx: "11",
674
- cy: "11",
675
- r: "8",
676
- key: "4ej97u"
677
- }]]);
678
- //#endregion
679
- //#region ui-src/components/settings/execution-limits.tsx
680
- /** Global execution limits; each successful save applies to subsequent rounds. */
681
- function ExecutionLimits({ ctx, registerGuard }) {
682
- const host = useGateway();
683
- const gateway = ctx?.gateway ?? host;
684
- const { t } = useTranslation();
685
- const toast = useToast();
686
- const translation = useRef(t);
687
- translation.current = t;
688
- const [saved, setSaved] = useState(null);
689
- const [inputKey, setInputKey] = useState(0);
690
- const [draft, setDraft] = useState(null);
691
- const [readError, setReadError] = useState(null);
692
- const [saveError, setSaveError] = useState(null);
693
- const [reading, setReading] = useState(true);
694
- const [blocked, setBlocked] = useState(false);
695
- const [saving, setSaving] = useState(false);
696
- const [notice, setNotice] = useState(null);
697
- const [online, setOnline] = useState(gateway.connection.status === "online");
698
- const latest = useRef({
699
- draft,
700
- saved,
701
- saving
721
+ var SLOT_IDS = [
722
+ "identity",
723
+ "instructions",
724
+ "style",
725
+ "reminder"
726
+ ];
727
+ var TAB_IDS = [
728
+ "basic",
729
+ "prompts",
730
+ "tools"
731
+ ];
732
+ var TAB_OF = {
733
+ name: "basic",
734
+ description: "basic",
735
+ startsSessions: "basic",
736
+ avatar: "basic",
737
+ tools: "tools",
738
+ "prompt.identity": "prompts",
739
+ "prompt.instructions": "prompts",
740
+ "prompt.style": "prompts",
741
+ "prompt.reminder": "prompts"
742
+ };
743
+ function same(key, a, b) {
744
+ if (key === "avatar") return a === null && b === null || typeof a === "string" && a === b;
745
+ return JSON.stringify(a) === JSON.stringify(b);
746
+ }
747
+ /** Which field a gateway refusal is about, when its words say so. */
748
+ function fieldOfRefusal(reason) {
749
+ const owner = /^extensionData[.:]([^:]+):/.exec(reason)?.[1];
750
+ if (owner) return `extension:${owner}`;
751
+ if (/avatar/i.test(reason)) return "avatar";
752
+ const slot = /prompt slot (identity|instructions|style|reminder)/i.exec(reason)?.[1];
753
+ if (slot) return `prompt.${slot.toLowerCase()}`;
754
+ if (/AGENTS\.md|rules file|instructions/i.test(reason)) return "prompt.instructions";
755
+ if (/start(s)? sessions|startsSessions/i.test(reason)) return "startsSessions";
756
+ if (/description/i.test(reason)) return "description";
757
+ if (/\btool/i.test(reason)) return "tools";
758
+ if (/\bname\b/i.test(reason) && !/no such agent/i.test(reason)) return "name";
759
+ return null;
760
+ }
761
+ var EditorContext = createContext(null);
762
+ function useAgentEditor() {
763
+ const editor = useContext(EditorContext);
764
+ if (editor === null) throw new Error("useAgentEditor outside an agent editor");
765
+ return editor;
766
+ }
767
+ /** The prompt text of one agent, asked again whenever that agent changes;
768
+ * an answer to an older question is dropped. */
769
+ function usePromptSlots(agentId) {
770
+ const read = useGatewayRead("config.agent.promptSlots", {
771
+ agentIds: [agentId],
772
+ maxItemBytes: 262144,
773
+ maxTotalBytes: 8388608
702
774
  });
703
- latest.current = {
704
- draft,
705
- saved,
706
- saving
775
+ const member = read.data?.results.find((member) => member.target === agentId);
776
+ return {
777
+ slots: member?.ok ? member.value : null,
778
+ error: read.error ?? (member && !member.ok ? member.error.message : null),
779
+ pending: read.pending,
780
+ reload: read.reload
707
781
  };
708
- const invalidated = useRef(false);
709
- const uncertain = useRef(false);
710
- const lifetime = useRef(null);
711
- const controller = useRef(null);
712
- const reload = useCallback(async (notify = false) => {
713
- controller.current?.abort();
714
- const request = new AbortController();
715
- controller.current = request;
716
- setReading(true);
717
- setReadError(null);
718
- try {
719
- const result = await gateway.read("config.limits.get", {}, { signal: request.signal });
720
- if (!request.signal.aborted) {
721
- setSaved(result.limits);
722
- setBlocked(false);
723
- if (uncertain.current) setSaveError(translation.current("runSettings.unconfirmed"));
724
- if (!(latest.current.draft !== null && JSON.stringify(latest.current.draft) !== JSON.stringify(latest.current.saved))) {
725
- setDraft(null);
726
- if (JSON.stringify(result.limits) !== JSON.stringify(latest.current.saved)) setInputKey((key) => key + 1);
727
- } else if (notify) setNotice("changed");
728
- return result.limits;
729
- }
730
- } catch (error) {
731
- if (!request.signal.aborted) {
732
- setReadError(error instanceof Error ? error.message : String(error));
733
- if (error instanceof Error && "errorCode" in error && error.errorCode === "configuration_recovery_required") setBlocked(true);
734
- }
735
- } finally {
736
- if (!request.signal.aborted) setReading(false);
737
- }
738
- return null;
739
- }, [gateway]);
782
+ }
783
+ function AgentEditorProvider({ agent: listed, agents, children }) {
784
+ const { slots, error: slotsError, pending: slotsPending, reload: reloadSlots } = usePromptSlots(listed.agentId);
785
+ const contributions = usePlugins((state) => state.contributions);
786
+ const preload = useBrowserService("tool-preload:configuration");
787
+ const preloadOwner = useRef(preload?.owner);
788
+ if (preload) preloadOwner.current = preload.owner;
789
+ const definitions = useGatewayRead("config.prompt.slots");
790
+ const saving = useGatewayAction();
791
+ const remember = useAgents((state) => state.remember);
792
+ const [drafts, setDrafts] = useState(/* @__PURE__ */ new Map());
793
+ const [errors, setErrors] = useState({});
794
+ const [footerError, setFooterError] = useState(null);
795
+ const [reply, setReply] = useState(null);
796
+ const [savedSlots, setSavedSlots] = useState({});
740
797
  useEffect(() => {
741
- lifetime.current = new AbortController();
742
- reload();
743
- return () => {
744
- controller.current?.abort();
745
- lifetime.current?.abort();
746
- };
747
- }, [reload]);
798
+ setReply(null);
799
+ }, [listed]);
748
800
  useEffect(() => {
749
- let previous = gateway.connection.status;
750
- const off = gateway.watchConnection((state) => {
751
- setOnline(state.status === "online");
752
- if (state.status === "online" && previous !== "online") reload(true);
753
- previous = state.status;
801
+ setSavedSlots({});
802
+ }, [slots]);
803
+ const agent = reply ?? listed;
804
+ const revisionBase = useRef(agent);
805
+ if (drafts.size === 0) revisionBase.current = agent;
806
+ const saved = useCallback((key) => {
807
+ if (key.startsWith("extension:")) return agent.extensionData?.[key.slice(10)];
808
+ if (key.startsWith("prompt.")) {
809
+ const slot = key.slice(7);
810
+ return savedSlots[slot] ?? slots?.[slot] ?? "";
811
+ }
812
+ return agent[key];
813
+ }, [
814
+ agent,
815
+ slots,
816
+ savedSlots
817
+ ]);
818
+ const dirty = useCallback((key) => {
819
+ const draft = drafts.get(key);
820
+ return draft !== void 0 && !same(key, draft.value, saved(key));
821
+ }, [drafts, saved]);
822
+ const value = useCallback((key) => dirty(key) ? drafts.get(key)?.value : saved(key), [
823
+ drafts,
824
+ dirty,
825
+ saved
826
+ ]);
827
+ const set = useCallback((key, next) => {
828
+ setDrafts((current) => {
829
+ const copy = new Map(current);
830
+ const base = current.get(key)?.base ?? saved(key);
831
+ if (same(key, next, saved(key))) copy.delete(key);
832
+ else copy.set(key, {
833
+ value: next,
834
+ base
835
+ });
836
+ return copy;
754
837
  });
755
- const stop = gateway.subscribe((frame) => {
756
- if (frame.kind !== "config.limitsChanged") return;
757
- if (latest.current.saving) invalidated.current = true;
758
- else reload(true);
838
+ setErrors((current) => {
839
+ if (!(key in current)) return current;
840
+ const { [key]: _, ...rest } = current;
841
+ return rest;
759
842
  });
760
- return () => {
761
- off();
762
- stop();
843
+ }, [saved]);
844
+ const stale = useCallback((key) => {
845
+ const draft = drafts.get(key);
846
+ return draft !== void 0 && dirty(key) && !same(key, draft.base, saved(key));
847
+ }, [
848
+ drafts,
849
+ dirty,
850
+ saved
851
+ ]);
852
+ const reload = useCallback((key) => {
853
+ setDrafts((current) => {
854
+ const copy = new Map(current);
855
+ copy.delete(key);
856
+ return copy;
857
+ });
858
+ }, []);
859
+ const limitOf = useCallback((slot) => definitions.data?.find((one) => one.id === slot)?.maxLength, [definitions.data]);
860
+ const invalid = useCallback((key) => {
861
+ if (!dirty(key)) return false;
862
+ const current = value(key);
863
+ if (key.startsWith("extension:")) {
864
+ const owner = key.slice(10);
865
+ if (owner === preloadOwner.current) {
866
+ if (!preload) return true;
867
+ try {
868
+ preload.read(current);
869
+ } catch {
870
+ return true;
871
+ }
872
+ }
873
+ return contributions.some((entry) => entry.plugin === owner && (entry.slot === "shell.agentEditor.field" || entry.slot === "shell.agentEditor.tab") && entry.contribution.validate?.(current) != null);
874
+ }
875
+ if (key === "name") return String(current).trim() === "";
876
+ if (key === "description") return codePoints(String(current)) > 500;
877
+ if (key.startsWith("prompt.")) {
878
+ const slot = key.slice(7);
879
+ const limit = limitOf(slot);
880
+ if (slot === "instructions" && slots?.failure !== void 0) return true;
881
+ return limit !== void 0 && codePoints(String(current)) > limit;
882
+ }
883
+ return false;
884
+ }, [
885
+ dirty,
886
+ value,
887
+ limitOf,
888
+ slots,
889
+ contributions,
890
+ preload
891
+ ]);
892
+ const dirtyKeys = [.../* @__PURE__ */ new Set([...Object.keys(TAB_OF), ...drafts.keys()])].filter((key) => dirty(key));
893
+ const dirtyTabs = [...new Set(dirtyKeys.map((key) => key.startsWith("extension:") ? (() => {
894
+ const tab = contributions.find((entry) => entry.plugin === key.slice(10) && entry.slot === "shell.agentEditor.tab");
895
+ if (key.slice(10) === preloadOwner.current) return "tools";
896
+ return tab ? `plugin:${tab.key}` : "basic";
897
+ })() : TAB_OF[key]))];
898
+ const canSave = dirtyKeys.length > 0 && !dirtyKeys.some(invalid) && !saving.pending;
899
+ const save = useCallback(async () => {
900
+ if (!canSave) return false;
901
+ const params = {
902
+ agentId: agent.agentId,
903
+ expectedRevision: revisionBase.current.revision,
904
+ expectedContentHash: revisionBase.current.contentHash
763
905
  };
764
- }, [gateway, reload]);
765
- const guardState = useRef({
766
- dirty: false,
767
- pending: false
768
- });
769
- guardState.current = {
770
- dirty: draft !== null && JSON.stringify(draft) !== JSON.stringify(saved),
771
- pending: saving
772
- };
773
- useEffect(() => {
774
- registerGuard(() => guardState.current);
775
- return () => registerGuard(null);
776
- }, [registerGuard]);
777
- const values = draft ?? saved;
778
- const positive = (value) => value !== void 0 && Number.isSafeInteger(value) && value > 0;
779
- async function save() {
780
- if (values === null || saving || !online || reading || readError !== null || !positive(values.maxSteps) || values.tokenBudget !== void 0 && !positive(values.tokenBudget)) return;
781
- let committed = false;
782
- setSaving(true);
783
- uncertain.current = false;
784
- setSaveError(null);
785
- try {
786
- const result = await gateway.call("config.limits.set", { limits: values }, {
787
- timeoutMs: 5e3,
788
- signal: lifetime.current?.signal
789
- });
790
- if (lifetime.current?.signal.aborted) return;
791
- controller.current?.abort();
792
- setReading(false);
793
- committed = true;
794
- setSaved(result.limits);
795
- setDraft(null);
796
- setNotice(null);
797
- toast.add({
798
- tone: "success",
799
- title: t("runSettings.saved")
800
- });
801
- } catch (error) {
802
- if (lifetime.current?.signal.aborted) return;
803
- const code = error instanceof Error && "errorCode" in error ? error.errorCode : void 0;
804
- const refused = error instanceof Error && "failure" in error && error.failure === "refused";
805
- if (code === "configuration_write_rejected" || refused && code !== "configuration_recovery_required") setSaveError(error instanceof Error ? error.message : String(error));
806
- else {
807
- uncertain.current = true;
808
- if (code === "configuration_recovery_required") setBlocked(true);
809
- setSaveError(t("runSettings.unconfirmedFailed"));
810
- await reload();
811
- }
812
- } finally {
813
- if (!lifetime.current?.signal.aborted) {
814
- setSaving(false);
815
- if (invalidated.current) {
816
- invalidated.current = false;
817
- reload(!committed);
818
- }
819
- }
906
+ const prompts = {};
907
+ for (const key of dirtyKeys) {
908
+ const current = value(key);
909
+ if (key === "name") params.name = String(current).trim();
910
+ else if (key === "description") params.description = String(current).trim();
911
+ else if (key === "startsSessions") params.startsSessions = current;
912
+ else if (key === "tools") params.tools = current === null ? null : [...current];
913
+ else if (key === "avatar") params.avatar = current === null ? null : current.image;
914
+ else if (key.startsWith("extension:")) params.extensionData = {
915
+ ...params.extensionData,
916
+ [key.slice(10)]: current
917
+ };
918
+ else prompts[key.slice(7)] = String(current);
820
919
  }
821
- }
822
- return /* @__PURE__ */ jsxs(Fragment, { children: [
823
- /* @__PURE__ */ jsx(ReadFailure, {
824
- reason: readError,
825
- pending: reading && values === null,
826
- onRetry: () => void reload()
827
- }),
828
- blocked && !reading && /* @__PURE__ */ jsx("p", {
829
- role: "alert",
830
- className: "text-xs text-destructive",
831
- children: t("runSettings.blocked")
920
+ if (Object.keys(prompts).length > 0) params.prompts = prompts;
921
+ setErrors({});
922
+ setFooterError(null);
923
+ const sent = new Map(dirtyKeys.map((key) => [key, drafts.get(key)]));
924
+ const result = await saving.run((client) => client.call("config.agent.save", params));
925
+ if (!result.ok) return false;
926
+ const avatarDraft = sent.get("avatar")?.value;
927
+ if (avatarDraft && result.data.avatar !== null) remember(result.data.avatar, avatarDraft.preview);
928
+ setReply(result.data);
929
+ setSavedSlots((current) => {
930
+ const next = { ...current };
931
+ for (const [slot, text] of Object.entries(prompts)) next[slot] = text.trim();
932
+ return next;
933
+ });
934
+ setDrafts((current) => {
935
+ const copy = new Map(current);
936
+ for (const [key, draft] of sent) if (copy.get(key) === draft) copy.delete(key);
937
+ return copy;
938
+ });
939
+ return true;
940
+ }, [
941
+ canSave,
942
+ agent.agentId,
943
+ dirtyKeys,
944
+ value,
945
+ drafts,
946
+ saving,
947
+ remember
948
+ ]);
949
+ const lastError = useRef(null);
950
+ useEffect(() => {
951
+ if (saving.error === lastError.current) return;
952
+ lastError.current = saving.error;
953
+ if (saving.error === null) return;
954
+ const field = fieldOfRefusal(saving.error);
955
+ if (field !== null && dirty(field)) setErrors({ [field]: saving.error });
956
+ else setFooterError(saving.error);
957
+ }, [saving.error, dirty]);
958
+ const discard = useCallback(() => {
959
+ setDrafts(/* @__PURE__ */ new Map());
960
+ setErrors({});
961
+ setFooterError(null);
962
+ }, []);
963
+ const editor = {
964
+ agent,
965
+ agents,
966
+ slots,
967
+ slotsError,
968
+ slotsPending,
969
+ reloadSlots,
970
+ slotDefinitions: definitions.data,
971
+ value,
972
+ set,
973
+ dirty,
974
+ stale,
975
+ invalid,
976
+ reload,
977
+ dirtyTabs,
978
+ error: (key) => errors[key] ?? null,
979
+ footerError,
980
+ pending: saving.pending,
981
+ canSave,
982
+ save,
983
+ extension: (owner) => ({
984
+ read: (fallback) => value(`extension:${owner}`) ?? fallback,
985
+ update: (next) => set(`extension:${owner}`, next),
986
+ pending: saving.pending,
987
+ tools: value("tools"),
988
+ error: errors[`extension:${owner}`] ?? (dirty(`extension:${owner}`) ? contributions.flatMap((entry) => entry.plugin === owner && (entry.slot === "shell.agentEditor.field" || entry.slot === "shell.agentEditor.tab") ? [entry.contribution.validate?.(value(`extension:${owner}`))] : []).find((message) => message != null) ?? null : null)
832
989
  }),
833
- values && /* @__PURE__ */ jsxs("form", {
834
- className: "flex flex-col gap-6",
835
- onSubmit: (event) => {
836
- event.preventDefault();
837
- save();
838
- },
839
- children: [
840
- /* @__PURE__ */ jsx("p", {
841
- className: "text-xs text-muted-foreground",
842
- children: t("runSettings.timing")
843
- }),
844
- /* @__PURE__ */ jsx(Field, {
845
- label: t("runSettings.maxSteps"),
846
- required: true,
847
- inline: true,
848
- error: positive(values.maxSteps) ? void 0 : t("runSettings.positive"),
849
- children: (binding) => /* @__PURE__ */ jsx(InputNumber, {
850
- ...binding,
851
- label: t("runSettings.maxSteps"),
852
- incrementLabel: t("common.increase"),
853
- decrementLabel: t("common.decrease"),
854
- min: 1,
855
- step: 1,
856
- disabled: saving,
857
- value: values.maxSteps || null,
858
- onValueChange: (value) => setDraft({
859
- ...values,
860
- maxSteps: value ?? 0
861
- })
862
- }, inputKey)
863
- }),
864
- /* @__PURE__ */ jsx(Field, {
865
- label: t("runSettings.budgetEnabled"),
866
- inline: true,
867
- children: (binding) => /* @__PURE__ */ jsx(Switch, {
868
- ...binding,
869
- checked: values.tokenBudget !== void 0,
870
- disabled: saving,
871
- onCheckedChange: (checked) => setDraft(checked ? {
872
- ...values,
873
- tokenBudget: 0
874
- } : { maxSteps: values.maxSteps })
875
- })
876
- }),
877
- values.tokenBudget !== void 0 && /* @__PURE__ */ jsx(Field, {
878
- label: t("runSettings.tokenBudget"),
879
- required: true,
880
- inline: true,
881
- error: positive(values.tokenBudget) ? void 0 : t("runSettings.positive"),
882
- children: (binding) => /* @__PURE__ */ jsx(InputNumber, {
883
- ...binding,
884
- label: t("runSettings.tokenBudget"),
885
- incrementLabel: t("common.increase"),
886
- decrementLabel: t("common.decrease"),
887
- min: 1,
888
- step: 1,
889
- disabled: saving,
890
- value: values.tokenBudget || null,
891
- onValueChange: (value) => setDraft({
892
- ...values,
893
- tokenBudget: value ?? 0
894
- })
895
- }, inputKey)
896
- }),
897
- notice && /* @__PURE__ */ jsx("p", {
898
- role: "status",
899
- className: "text-xs text-muted-foreground",
900
- children: t("runSettings.changed")
901
- }),
902
- /* @__PURE__ */ jsx(FormFailure, { reason: saveError }),
903
- uncertain.current && saved && readError === null && !reading && /* @__PURE__ */ jsx("p", {
904
- className: "text-xs text-muted-foreground",
905
- children: t("runSettings.current", {
906
- steps: saved.maxSteps,
907
- budget: saved.tokenBudget ?? t("runSettings.unlimited")
908
- })
909
- }),
910
- /* @__PURE__ */ jsx("div", {
911
- className: "flex justify-end",
912
- children: /* @__PURE__ */ jsx(Button, {
913
- variant: "primary",
914
- type: "submit",
915
- loading: saving,
916
- disabled: !online || reading || readError !== null || !positive(values.maxSteps) || values.tokenBudget !== void 0 && !positive(values.tokenBudget),
917
- children: t("common.save")
918
- })
919
- })
920
- ]
921
- })
922
- ] });
990
+ discard
991
+ };
992
+ return /* @__PURE__ */ jsx(EditorContext.Provider, {
993
+ value: editor,
994
+ children
995
+ });
923
996
  }
924
997
  //#endregion
925
- //#region ui-src/components/settings/run-settings.tsx
926
- /** Fixed global running-settings entrance owned by Agent management. */
927
- function RunSettingsButton({ ctx }) {
998
+ //#region ui-src/components/settings/agent/parts.tsx
999
+ /** Pieces shared by the agent editor's tabs. */
1000
+ /** Says a field with a draft was changed elsewhere, and takes the new value
1001
+ * on request. Renders nothing while none of `fields` is stale. */
1002
+ function ChangedElsewhere({ fields }) {
928
1003
  const { t } = useTranslation();
929
- const [open, setOpen] = useState(false);
930
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(TooltipHint, {
931
- content: t("runSettings.title"),
932
- children: /* @__PURE__ */ jsx(Button, {
933
- variant: "plain",
934
- size: "sm",
935
- icon: "settings",
936
- "aria-label": t("runSettings.title"),
937
- onClick: () => setOpen(true)
938
- })
939
- }), open && /* @__PURE__ */ jsx(RunSettingsDialog, {
940
- ctx,
941
- onClose: () => setOpen(false)
942
- })] });
943
- }
944
- /** One retained page per live owner, with a shared close guard and independent saves. */
945
- function RunSettingsDialog({ ctx, onClose }) {
1004
+ const editor = useAgentEditor();
1005
+ const stale = fields.filter((key) => editor.stale(key));
1006
+ if (stale.length === 0) return null;
1007
+ return /* @__PURE__ */ jsx(Alert, {
1008
+ tone: "warning",
1009
+ variant: "soft",
1010
+ "data-slot": "agent-changed-elsewhere",
1011
+ className: "text-xs",
1012
+ children: /* @__PURE__ */ jsxs("div", {
1013
+ className: "flex flex-wrap items-start justify-between gap-3",
1014
+ children: [/* @__PURE__ */ jsx("span", { children: t("agents.changedElsewhere") }), /* @__PURE__ */ jsx(Button, {
1015
+ size: "sm",
1016
+ variant: "ghost",
1017
+ onClick: () => {
1018
+ for (const key of stale) editor.reload(key);
1019
+ },
1020
+ children: t("agents.loadRemote")
1021
+ })]
1022
+ })
1023
+ });
1024
+ }
1025
+ //#endregion
1026
+ //#region ui-src/components/settings/agent/basic.tsx
1027
+ /**
1028
+ * The basic-information tab: picture, name, description and the
1029
+ * model cell. Every field, the model cell's included, is part of the editor's
1030
+ * one draft. Whether a person can chat with the agent directly is a toggle on
1031
+ * the agent list, not here.
1032
+ *
1033
+ * The picture is its own upload control: pressing it picks an image, and the
1034
+ * crop shows in place until the save. While the agent has a picture — saved,
1035
+ * or a crop waiting for the save — 恢复默认 beside it drafts the return to the
1036
+ * derived letters face, which the same save applies.
1037
+ */
1038
+ /** The factory agent, whose session switch the gateway keeps on. */
1039
+ function AvatarField() {
946
1040
  const { t } = useTranslation();
947
- const state = usePlugins((state) => state);
948
- const pages = contributionsIn(state, "shell.agentRunSettings.section");
949
- const [selected, setSelected] = useState("execution");
950
- const shown = selected === "execution" || pages.some((page) => page.key === selected) ? selected : "execution";
951
- useEffect(() => {
952
- if (shown !== selected) setSelected(shown);
953
- }, [shown, selected]);
954
- const guards = useRef(/* @__PURE__ */ new Map());
955
- const register = useCallback((key, guard) => {
956
- if (guard) guards.current.set(key, guard);
957
- else guards.current.delete(key);
958
- }, []);
959
- const labels = new Map([["execution", t("runSettings.execution")], ...pages.map((page) => [page.key, resolveLabel(page.contribution.label, page.key)])]);
960
- const [asking, setAsking] = useState(null);
961
- const requestClose = () => {
962
- const valid = [...guards.current].filter(([key]) => labels.has(key));
963
- if (valid.some(([, guard]) => guard().pending)) return;
964
- const dirty = valid.filter(([, guard]) => guard().dirty).map(([key]) => key);
965
- if (dirty.length > 0) setAsking(dirty);
966
- else onClose();
967
- };
968
- const executionGuard = useCallback((guard) => register("execution", guard), [register]);
969
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Dialog, {
970
- open: true,
971
- onOpenChange: (next) => {
972
- if (!next) requestClose();
973
- },
974
- children: /* @__PURE__ */ jsxs(DialogContent, {
975
- closeLabel: t("settings.close"),
976
- overlayProps: {
977
- forceRender: true,
978
- className: "file-picker-backdrop"
979
- },
980
- className: "@container max-w-md gap-5 p-6 sm:max-w-md",
981
- children: [/* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("runSettings.title") }) }), /* @__PURE__ */ jsxs(Tabs, {
982
- value: shown,
983
- onValueChange: (next) => setSelected(String(next)),
984
- children: [
985
- /* @__PURE__ */ jsxs(TabsList, {
986
- "aria-label": t("runSettings.title"),
987
- className: "mb-5 w-full",
988
- children: [/* @__PURE__ */ jsx(TabsTrigger, {
989
- value: "execution",
990
- children: t("runSettings.execution")
991
- }), pages.map((page) => /* @__PURE__ */ jsx(TabsTrigger, {
992
- value: page.key,
993
- "data-plugin": page.owner,
994
- children: labels.get(page.key)
995
- }, page.key))]
996
- }),
997
- /* @__PURE__ */ jsx(TabsContent, {
998
- value: "execution",
999
- keepMounted: true,
1000
- children: /* @__PURE__ */ jsx(ExecutionLimits, {
1001
- ctx,
1002
- registerGuard: executionGuard,
1003
- requestClose
1004
- })
1041
+ const editor = useAgentEditor();
1042
+ const { agent } = editor;
1043
+ const picker = useAvatarPicker((base64) => {
1044
+ editor.set("avatar", {
1045
+ image: base64,
1046
+ preview: pngDataUrl(base64)
1047
+ });
1048
+ });
1049
+ const draft = editor.dirty("avatar") ? editor.value("avatar") : void 0;
1050
+ const pictured = draft === void 0 ? agent.avatar !== null : draft !== null;
1051
+ return /* @__PURE__ */ jsxs(Panel, {
1052
+ title: t("agents.avatar"),
1053
+ level: "field",
1054
+ inline: true,
1055
+ children: [
1056
+ /* @__PURE__ */ jsxs("div", {
1057
+ className: "flex min-w-0 items-center",
1058
+ children: [/* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsxs(TooltipTrigger, {
1059
+ render: /* @__PURE__ */ jsx(Button, {
1060
+ variant: "plain",
1061
+ "data-slot": "agent-avatar-trigger",
1062
+ className: "group relative size-11 shrink-0 cursor-pointer rounded-pill outline-none focus-visible:ring-3 focus-visible:ring-ring/50",
1063
+ onClick: () => void picker.pick()
1005
1064
  }),
1006
- pages.map((page) => /* @__PURE__ */ jsx(TabsContent, {
1007
- value: page.key,
1008
- keepMounted: true,
1009
- children: /* @__PURE__ */ jsx(OwnerSection, {
1010
- registrationKey: page.key,
1011
- register,
1012
- requestClose
1065
+ "aria-label": t("avatar.change"),
1066
+ children: [/* @__PURE__ */ jsx(AgentAvatar, {
1067
+ agentId: agent.agentId,
1068
+ name: editor.value("name") || agent.name,
1069
+ avatar: draft === null ? null : agent.avatar,
1070
+ ...draft ? { src: draft.preview } : {},
1071
+ size: "lg",
1072
+ decorative: true,
1073
+ className: "size-11 text-sm"
1074
+ }), /* @__PURE__ */ jsx("span", {
1075
+ "data-slot": "agent-avatar-overlay",
1076
+ "aria-hidden": "true",
1077
+ className: "absolute inset-0 grid place-items-center rounded-pill bg-foreground/60 text-background opacity-0 transition-opacity duration-150 group-hover:opacity-100 group-focus-visible:opacity-100",
1078
+ children: /* @__PURE__ */ jsx(Camera, {
1079
+ className: "size-4",
1080
+ strokeWidth: 1.75
1013
1081
  })
1014
- }, page.key))
1015
- ]
1016
- })]
1017
- })
1018
- }), /* @__PURE__ */ jsxs(AlertDialog, {
1019
- open: asking !== null,
1020
- onOpenChange: (next) => {
1021
- if (!next) setAsking(null);
1022
- },
1023
- title: t("agents.leaveTitle"),
1024
- actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
1025
- variant: "ghost",
1026
- onClick: () => setAsking(null),
1027
- children: t("agents.leaveStay")
1028
- }), /* @__PURE__ */ jsx(Button, {
1029
- variant: "destructive",
1030
- onClick: onClose,
1031
- children: t("agents.discard")
1032
- })] }),
1033
- children: [/* @__PURE__ */ jsx("p", { children: t("agents.leaveBody") }), /* @__PURE__ */ jsx("ul", {
1034
- className: "list-disc ps-5",
1035
- children: asking?.filter((key) => labels.has(key)).map((key) => /* @__PURE__ */ jsx("li", { children: labels.get(key) }, key))
1036
- })]
1037
- })] });
1082
+ })]
1083
+ }), /* @__PURE__ */ jsx(TooltipContent, {
1084
+ side: "top",
1085
+ children: t("avatar.change")
1086
+ })] }), pictured && /* @__PURE__ */ jsx(Button, {
1087
+ variant: "ghost",
1088
+ size: "sm",
1089
+ "data-slot": "agent-avatar-reset",
1090
+ className: "ml-3",
1091
+ onClick: () => {
1092
+ picker.clearRefusal();
1093
+ editor.set("avatar", null);
1094
+ },
1095
+ children: t("avatar.reset")
1096
+ })]
1097
+ }),
1098
+ /* @__PURE__ */ jsx(FormFailure, { reason: picker.refusal ?? editor.error("avatar") }),
1099
+ picker.dialog
1100
+ ]
1101
+ });
1038
1102
  }
1039
- function OwnerSection({ registrationKey, register, requestClose }) {
1040
- const registerGuard = useCallback((guard) => register(registrationKey, guard), [registrationKey, register]);
1041
- useEffect(() => () => registerGuard(null), [registerGuard]);
1042
- return /* @__PURE__ */ jsx(SlotOutlet, {
1043
- slot: "shell.agentRunSettings.section",
1044
- only: registrationKey,
1045
- props: {
1046
- registerGuard,
1047
- requestClose
1048
- }
1103
+ function BasicTab() {
1104
+ const { t } = useTranslation();
1105
+ const editor = useAgentEditor();
1106
+ const { agent } = editor;
1107
+ const name = editor.value("name");
1108
+ const description = editor.value("description");
1109
+ const pluginState = usePlugins((state) => state);
1110
+ const registrations = contributionsIn(pluginState, "shell.agentEditor.field");
1111
+ return /* @__PURE__ */ jsxs("div", {
1112
+ className: "flex min-w-0 flex-col gap-5",
1113
+ children: [
1114
+ /* @__PURE__ */ jsx(ChangedElsewhere, { fields: [
1115
+ "name",
1116
+ "description",
1117
+ "avatar",
1118
+ ...registrations.map((one) => `extension:${one.plugin}`)
1119
+ ] }),
1120
+ /* @__PURE__ */ jsx(AvatarField, {}),
1121
+ /* @__PURE__ */ jsx(Field, {
1122
+ label: t("agents.name"),
1123
+ required: true,
1124
+ inline: true,
1125
+ className: "settings-field-row",
1126
+ error: editor.error("name") ?? (editor.invalid("name") ? t("agents.nameRequired") : void 0),
1127
+ children: (binding) => /* @__PURE__ */ jsx(Input, {
1128
+ ...binding,
1129
+ value: name,
1130
+ placeholder: t("agents.namePlaceholder"),
1131
+ onChange: (event) => editor.set("name", event.target.value),
1132
+ onKeyDown: (event) => {
1133
+ if (event.key === "Escape" && !event.nativeEvent.isComposing) editor.reload("name");
1134
+ }
1135
+ })
1136
+ }),
1137
+ /* @__PURE__ */ jsx(Field, {
1138
+ label: t("agents.description"),
1139
+ inline: true,
1140
+ className: "settings-field-row",
1141
+ error: editor.error("description") ?? (editor.invalid("description") ? t("agents.descriptionTooLong", { limit: 500 }) : void 0),
1142
+ children: (binding) => /* @__PURE__ */ jsx(Textarea, {
1143
+ ...binding,
1144
+ limit: 500,
1145
+ rows: 5,
1146
+ className: "h-[calc(5lh+1rem)] resize-none [field-sizing:fixed]",
1147
+ value: description,
1148
+ placeholder: t("agents.descriptionPlaceholder"),
1149
+ onChange: (event) => editor.set("description", event.target.value)
1150
+ })
1151
+ }),
1152
+ registrations.map((one) => /* @__PURE__ */ jsx(SlotOutlet, {
1153
+ slot: "shell.agentEditor.field",
1154
+ only: one.key,
1155
+ props: {
1156
+ agentId: agent.agentId,
1157
+ editor: editor.extension(one.plugin),
1158
+ errors: { owner: editor.error(`extension:${one.plugin}`) }
1159
+ }
1160
+ }, one.key))
1161
+ ]
1049
1162
  });
1050
1163
  }
1051
1164
  //#endregion
1052
- //#region ui-src/components/settings/agent/editor.tsx
1053
- var SLOT_IDS = [
1054
- "identity",
1055
- "instructions",
1165
+ //#region ui-src/components/settings/agent/prompts.tsx
1166
+ /**
1167
+ * The prompt tab: the four slots, one edited at a time, listed as identity,
1168
+ * style, reminder, AGENTS.md — the slots `config.prompt.slots` declares, in
1169
+ * this tab's own order, with their limits from that listing. Each slot keeps
1170
+ * its own draft in the editor, so switching slots asks nothing; the text area
1171
+ * fills the tab and is its only scroller. Above the text area the chosen
1172
+ * slot says what to write there and where the text lands in the model's input.
1173
+ */
1174
+ /** A dot that says a slot or tab has an unsaved change, to eyes and ears. */
1175
+ /** The slot's identifier as the list's second line. Identifiers, not copy:
1176
+ * the same in every language. Only AGENTS.md is a file. */
1177
+ var SLOT_TAGS = {
1178
+ identity: "IDENTITY Slot",
1179
+ style: "SOUL Slot",
1180
+ reminder: "REMINDER Slot",
1181
+ instructions: "AGENTS.md"
1182
+ };
1183
+ function UnsavedDot() {
1184
+ const { t } = useTranslation();
1185
+ return /* @__PURE__ */ jsxs("span", {
1186
+ "data-slot": "unsaved-dot",
1187
+ className: "inline-flex shrink-0 items-center",
1188
+ children: [/* @__PURE__ */ jsx("span", {
1189
+ "aria-hidden": "true",
1190
+ className: "size-1.5 rounded-pill bg-primary"
1191
+ }), /* @__PURE__ */ jsx("span", {
1192
+ className: "sr-only",
1193
+ children: t("agents.unsaved")
1194
+ })]
1195
+ });
1196
+ }
1197
+ /** The order this tab lists the slots in. */
1198
+ var DISPLAY_ORDER = [
1199
+ "identity",
1056
1200
  "style",
1057
- "reminder"
1201
+ "reminder",
1202
+ "instructions"
1058
1203
  ];
1059
- var TAB_IDS = [
1060
- "basic",
1061
- "prompts",
1062
- "tools"
1204
+ var NOTES = [
1205
+ "where",
1206
+ "scope",
1207
+ "cache",
1208
+ "tip"
1063
1209
  ];
1064
- var TAB_OF = {
1065
- name: "basic",
1066
- description: "basic",
1067
- startsSessions: "basic",
1068
- avatar: "basic",
1069
- tools: "tools",
1070
- "prompt.identity": "prompts",
1071
- "prompt.instructions": "prompts",
1072
- "prompt.style": "prompts",
1073
- "prompt.reminder": "prompts"
1074
- };
1075
- function same(key, a, b) {
1076
- if (key === "avatar") return a === null && b === null || typeof a === "string" && a === b;
1077
- return JSON.stringify(a) === JSON.stringify(b);
1078
- }
1079
- /** Which field a gateway refusal is about, when its words say so. */
1080
- function fieldOfRefusal(reason) {
1081
- const owner = /^extensionData[.:]([^:]+):/.exec(reason)?.[1];
1082
- if (owner) return `extension:${owner}`;
1083
- if (/avatar/i.test(reason)) return "avatar";
1084
- const slot = /prompt slot (identity|instructions|style|reminder)/i.exec(reason)?.[1];
1085
- if (slot) return `prompt.${slot.toLowerCase()}`;
1086
- if (/AGENTS\.md|rules file|instructions/i.test(reason)) return "prompt.instructions";
1087
- if (/start(s)? sessions|startsSessions/i.test(reason)) return "startsSessions";
1088
- if (/description/i.test(reason)) return "description";
1089
- if (/\btool/i.test(reason)) return "tools";
1090
- if (/\bname\b/i.test(reason) && !/no such agent/i.test(reason)) return "name";
1091
- return null;
1092
- }
1093
- var EditorContext = createContext(null);
1094
- function useAgentEditor() {
1095
- const editor = useContext(EditorContext);
1096
- if (editor === null) throw new Error("useAgentEditor outside an agent editor");
1097
- return editor;
1210
+ /** What the chosen slot is for and where it goes, shown above its editor for
1211
+ * as long as it is chosen: the purpose with an example, then the placement. */
1212
+ function SlotAbout({ slot, limit, path }) {
1213
+ const { t } = useTranslation();
1214
+ return /* @__PURE__ */ jsxs("section", {
1215
+ "aria-label": t("agents.prompts.about", { slot: t(`agents.prompts.${slot}`) }),
1216
+ "data-slot": "prompt-slot-about",
1217
+ className: "flex shrink-0 flex-col gap-2 rounded-control bg-muted/60 px-3 py-2.5 text-xs leading-relaxed @xl:flex-row @xl:gap-6",
1218
+ children: [/* @__PURE__ */ jsxs("div", {
1219
+ className: "flex min-w-0 flex-col gap-1 @xl:flex-1",
1220
+ children: [
1221
+ /* @__PURE__ */ jsx("h4", {
1222
+ className: "font-medium text-foreground",
1223
+ children: t("agents.prompts.purpose")
1224
+ }),
1225
+ /* @__PURE__ */ jsx("p", {
1226
+ className: "text-muted-foreground",
1227
+ children: t(`agents.prompts.info.${slot}.purpose`)
1228
+ }),
1229
+ /* @__PURE__ */ jsx("p", {
1230
+ className: "text-muted-foreground",
1231
+ children: t("agents.prompts.example", { text: t(`agents.prompts.info.${slot}.example`) })
1232
+ })
1233
+ ]
1234
+ }), /* @__PURE__ */ jsxs("div", {
1235
+ className: "flex min-w-0 flex-col gap-1 @xl:flex-1",
1236
+ children: [/* @__PURE__ */ jsx("h4", {
1237
+ className: "font-medium text-foreground",
1238
+ children: t("agents.prompts.placement")
1239
+ }), /* @__PURE__ */ jsx("ul", {
1240
+ className: "flex list-disc flex-col gap-0.5 ps-4 text-muted-foreground",
1241
+ children: NOTES.map((note) => /* @__PURE__ */ jsx("li", {
1242
+ className: "break-words",
1243
+ children: t(`agents.prompts.info.${slot}.${note}`, {
1244
+ path,
1245
+ limit: limit ?? ""
1246
+ })
1247
+ }, note))
1248
+ })]
1249
+ })]
1250
+ });
1098
1251
  }
1099
- /** The prompt text of one agent, asked again whenever that agent changes;
1100
- * an answer to an older question is dropped. */
1101
- function usePromptSlots(agentId) {
1102
- const read = useGatewayRead("config.agent.promptSlots", { agentId });
1103
- return {
1104
- slots: read.data,
1105
- error: read.error,
1106
- pending: read.pending,
1107
- reload: read.reload
1108
- };
1252
+ function PromptsTab() {
1253
+ const { t } = useTranslation();
1254
+ const editor = useAgentEditor();
1255
+ const declared = editor.slotDefinitions?.map((one) => one.id);
1256
+ const order = DISPLAY_ORDER.filter((id) => declared?.includes(id) ?? true);
1257
+ const [picked, setPicked] = useState(order[0] ?? "identity");
1258
+ const slot = order.includes(picked) ? picked : order[0] ?? "identity";
1259
+ const key = `prompt.${slot}`;
1260
+ const limit = editor.slotDefinitions?.find((one) => one.id === slot)?.maxLength;
1261
+ const failure = slot === "instructions" ? editor.slots?.failure : void 0;
1262
+ const label = (id) => t(`agents.prompts.${id}`);
1263
+ const rulesPath = editor.slots?.path ?? `agents/${editor.agent.agentId}/AGENTS.md`;
1264
+ if (editor.slots === null) return /* @__PURE__ */ jsx(ReadFailure, {
1265
+ reason: editor.slotsError,
1266
+ pending: editor.slotsPending,
1267
+ onRetry: editor.reloadSlots
1268
+ });
1269
+ return /* @__PURE__ */ jsxs("div", {
1270
+ className: "@container flex min-h-0 min-w-0 flex-1 flex-col gap-3",
1271
+ children: [/* @__PURE__ */ jsx(ChangedElsewhere, { fields: SLOT_IDS.map((id) => `prompt.${id}`) }), /* @__PURE__ */ jsxs("div", {
1272
+ className: "flex min-h-0 min-w-0 flex-1 flex-col gap-4 @2xl:flex-row",
1273
+ children: [
1274
+ /* @__PURE__ */ jsx("nav", {
1275
+ "aria-label": t("agents.prompts.slots"),
1276
+ "data-slot": "prompt-slot-list",
1277
+ className: "hidden w-52 shrink-0 flex-col gap-1 @2xl:flex",
1278
+ children: order.map((id) => /* @__PURE__ */ jsx("div", {
1279
+ "data-slot": "prompt-slot",
1280
+ className: cn("flex min-w-0 items-center gap-1 rounded-control pe-1", id === slot ? "bg-accent text-accent-foreground" : "hover:bg-muted"),
1281
+ children: /* @__PURE__ */ jsxs(Button, {
1282
+ variant: "plain",
1283
+ "data-slot": "prompt-slot-select",
1284
+ "aria-current": id === slot,
1285
+ onClick: () => setPicked(id),
1286
+ className: "flex h-auto min-w-0 flex-1 items-center justify-start gap-2 px-3 py-1.5 text-left",
1287
+ children: [/* @__PURE__ */ jsxs("span", {
1288
+ className: "flex min-w-0 flex-col",
1289
+ children: [/* @__PURE__ */ jsx("span", {
1290
+ className: "truncate text-sm font-medium",
1291
+ children: label(id)
1292
+ }), /* @__PURE__ */ jsx("span", {
1293
+ className: "truncate font-mono text-2xs text-muted-foreground",
1294
+ children: SLOT_TAGS[id]
1295
+ })]
1296
+ }), editor.dirty(`prompt.${id}`) && /* @__PURE__ */ jsx(UnsavedDot, {})]
1297
+ })
1298
+ }, id))
1299
+ }),
1300
+ /* @__PURE__ */ jsx("div", {
1301
+ "data-slot": "prompt-slot-switch",
1302
+ className: "min-w-0 @2xl:hidden",
1303
+ children: /* @__PURE__ */ jsx(Segmented, {
1304
+ fullWidth: true,
1305
+ label: t("agents.prompts.slots"),
1306
+ value: slot,
1307
+ options: order.map((id) => ({
1308
+ value: id,
1309
+ label: editor.dirty(`prompt.${id}`) ? `${label(id)} •` : label(id)
1310
+ })),
1311
+ onSelect: setPicked
1312
+ })
1313
+ }),
1314
+ /* @__PURE__ */ jsxs("section", {
1315
+ "aria-label": label(slot),
1316
+ "data-slot": "prompt-editor",
1317
+ className: "flex min-h-0 min-w-0 flex-1 flex-col gap-2",
1318
+ children: [
1319
+ /* @__PURE__ */ jsx(SlotAbout, {
1320
+ slot,
1321
+ limit,
1322
+ path: rulesPath
1323
+ }),
1324
+ failure !== void 0 && /* @__PURE__ */ jsx(Failure, { reason: t("agents.prompts.readFailed", { reason: failure }) }),
1325
+ /* @__PURE__ */ jsx(Textarea, {
1326
+ "aria-label": label(slot),
1327
+ fill: true,
1328
+ ...limit === void 0 ? {} : { limit },
1329
+ readOnly: failure !== void 0,
1330
+ value: editor.value(key),
1331
+ onChange: (event) => editor.set(key, event.target.value),
1332
+ className: "font-mono"
1333
+ }, slot),
1334
+ /* @__PURE__ */ jsx(FormFailure, { reason: editor.error(key) })
1335
+ ]
1336
+ })
1337
+ ]
1338
+ })]
1339
+ });
1109
1340
  }
1110
- function AgentEditorProvider({ agent: listed, agents, children }) {
1111
- const { slots, error: slotsError, pending: slotsPending, reload: reloadSlots } = usePromptSlots(listed.agentId);
1112
- const contributions = usePlugins((state) => state.contributions);
1113
- const definitions = useGatewayRead("config.prompt.slots");
1114
- const saving = useGatewayAction();
1115
- const remember = useAgents((state) => state.remember);
1116
- const [drafts, setDrafts] = useState(/* @__PURE__ */ new Map());
1117
- const [errors, setErrors] = useState({});
1118
- const [footerError, setFooterError] = useState(null);
1119
- const [reply, setReply] = useState(null);
1120
- const [savedSlots, setSavedSlots] = useState({});
1121
- useEffect(() => {
1122
- setReply(null);
1123
- }, [listed]);
1124
- useEffect(() => {
1125
- setSavedSlots({});
1126
- }, [slots]);
1127
- const agent = reply ?? listed;
1128
- const revisionBase = useRef(agent);
1129
- if (drafts.size === 0) revisionBase.current = agent;
1130
- const saved = useCallback((key) => {
1131
- if (key.startsWith("extension:")) return agent.extensionData?.[key.slice(10)];
1132
- if (key.startsWith("prompt.")) {
1133
- const slot = key.slice(7);
1134
- return savedSlots[slot] ?? slots?.[slot] ?? "";
1135
- }
1136
- return agent[key];
1137
- }, [
1138
- agent,
1139
- slots,
1140
- savedSlots
1141
- ]);
1142
- const dirty = useCallback((key) => {
1143
- const draft = drafts.get(key);
1144
- return draft !== void 0 && !same(key, draft.value, saved(key));
1145
- }, [drafts, saved]);
1146
- const value = useCallback((key) => dirty(key) ? drafts.get(key)?.value : saved(key), [
1147
- drafts,
1148
- dirty,
1149
- saved
1150
- ]);
1151
- const set = useCallback((key, next) => {
1152
- setDrafts((current) => {
1153
- const copy = new Map(current);
1154
- const base = current.get(key)?.base ?? saved(key);
1155
- if (same(key, next, saved(key))) copy.delete(key);
1156
- else copy.set(key, {
1157
- value: next,
1158
- base
1341
+ //#endregion
1342
+ //#region ui-src/components/settings/agent/revisions.tsx
1343
+ /** Compact history with explicit comparison and a retryable restore confirmation. */
1344
+ function AgentRevisions({ agentId, onClose, beforeLeave }) {
1345
+ const { t, i18n } = useTranslation();
1346
+ const client = useGateway();
1347
+ const observedRevision = useAgents((state) => state.agents.find((agent) => agent.agentId === agentId)?.revision);
1348
+ const [items, setItems] = useState([]);
1349
+ const [current, setCurrent] = useState(0);
1350
+ const [cursor, setCursor] = useState();
1351
+ const [selected, setSelected] = useState();
1352
+ const [compareTo, setCompareTo] = useState();
1353
+ const [changes, setChanges] = useState([]);
1354
+ const [comparing, setComparing] = useState(false);
1355
+ const [comparisonError, setComparisonError] = useState("");
1356
+ const [preview, setPreview] = useState();
1357
+ const [request, setRequest] = useState();
1358
+ const [busy, setBusy] = useState(false);
1359
+ const [error, setError] = useState("");
1360
+ const [notice, setNotice] = useState("");
1361
+ const [persistent, setPersistent] = useState(true);
1362
+ const generation = useRef(0);
1363
+ const restoring = useRef(false);
1364
+ const comparison = useRef(0);
1365
+ const reason = (cause) => failureText(cause, () => "") ?? "";
1366
+ const read = useCallback(async (next) => {
1367
+ const token = ++generation.current;
1368
+ setBusy(true);
1369
+ setError("");
1370
+ try {
1371
+ const page = await client.call("config.agent.revisions", {
1372
+ agentId,
1373
+ ...next ? { cursor: next } : {}
1159
1374
  });
1160
- return copy;
1161
- });
1162
- setErrors((current) => {
1163
- if (!(key in current)) return current;
1164
- const { [key]: _, ...rest } = current;
1165
- return rest;
1166
- });
1167
- }, [saved]);
1168
- const stale = useCallback((key) => {
1169
- const draft = drafts.get(key);
1170
- return draft !== void 0 && dirty(key) && !same(key, draft.base, saved(key));
1171
- }, [
1172
- drafts,
1173
- dirty,
1174
- saved
1175
- ]);
1176
- const reload = useCallback((key) => {
1177
- setDrafts((current) => {
1178
- const copy = new Map(current);
1179
- copy.delete(key);
1180
- return copy;
1181
- });
1182
- }, []);
1183
- const limitOf = useCallback((slot) => definitions.data?.find((one) => one.id === slot)?.maxLength, [definitions.data]);
1184
- const invalid = useCallback((key) => {
1185
- if (!dirty(key)) return false;
1186
- const current = value(key);
1187
- if (key.startsWith("extension:")) {
1188
- const owner = key.slice(10);
1189
- return contributions.some((entry) => entry.plugin === owner && (entry.slot === "shell.agentEditor.field" || entry.slot === "shell.agentEditor.tab") && entry.contribution.validate?.(current) != null);
1190
- }
1191
- if (key === "name") return String(current).trim() === "";
1192
- if (key === "description") return codePoints(String(current)) > 500;
1193
- if (key.startsWith("prompt.")) {
1194
- const slot = key.slice(7);
1195
- const limit = limitOf(slot);
1196
- if (slot === "instructions" && slots?.failure !== void 0) return true;
1197
- return limit !== void 0 && codePoints(String(current)) > limit;
1375
+ if (generation.current !== token) return;
1376
+ setItems((old) => next ? [...old, ...page.items.filter((row) => !old.some((item) => item.revision === row.revision))] : page.items);
1377
+ setCurrent(page.currentRevision);
1378
+ setCursor(page.nextCursor);
1379
+ setPersistent(page.persistent);
1380
+ } catch (cause) {
1381
+ if (generation.current === token) setError(reason(cause));
1382
+ } finally {
1383
+ if (generation.current === token) setBusy(false);
1198
1384
  }
1199
- return false;
1200
- }, [
1201
- dirty,
1202
- value,
1203
- limitOf,
1204
- slots,
1205
- contributions
1206
- ]);
1207
- const dirtyKeys = [.../* @__PURE__ */ new Set([...Object.keys(TAB_OF), ...drafts.keys()])].filter((key) => dirty(key));
1208
- const dirtyTabs = [...new Set(dirtyKeys.map((key) => key.startsWith("extension:") ? (() => {
1209
- const tab = contributions.find((entry) => entry.plugin === key.slice(10) && entry.slot === "shell.agentEditor.tab");
1210
- return tab ? `plugin:${tab.key}` : "basic";
1211
- })() : TAB_OF[key]))];
1212
- const canSave = dirtyKeys.length > 0 && !dirtyKeys.some(invalid) && !saving.pending;
1213
- const save = useCallback(async () => {
1214
- if (!canSave) return false;
1215
- const params = {
1216
- agentId: agent.agentId,
1217
- expectedRevision: revisionBase.current.revision,
1218
- expectedContentHash: revisionBase.current.contentHash
1385
+ }, [client, agentId]);
1386
+ useEffect(() => {
1387
+ read();
1388
+ return () => {
1389
+ generation.current++;
1390
+ comparison.current++;
1219
1391
  };
1220
- const prompts = {};
1221
- for (const key of dirtyKeys) {
1222
- const current = value(key);
1223
- if (key === "name") params.name = String(current).trim();
1224
- else if (key === "description") params.description = String(current).trim();
1225
- else if (key === "startsSessions") params.startsSessions = current;
1226
- else if (key === "tools") params.tools = current === null ? null : [...current];
1227
- else if (key === "avatar") params.avatar = current === null ? null : current.image;
1228
- else if (key.startsWith("extension:")) params.extensionData = {
1229
- ...params.extensionData,
1230
- [key.slice(10)]: current
1231
- };
1232
- else prompts[key.slice(7)] = String(current);
1233
- }
1234
- if (Object.keys(prompts).length > 0) params.prompts = prompts;
1235
- setErrors({});
1236
- setFooterError(null);
1237
- const sent = new Map(dirtyKeys.map((key) => [key, drafts.get(key)]));
1238
- const result = await saving.run((client) => client.call("config.agent.save", params));
1239
- if (!result.ok) return false;
1240
- const avatarDraft = sent.get("avatar")?.value;
1241
- if (avatarDraft && result.data.avatar !== null) remember(result.data.avatar, avatarDraft.preview);
1242
- setReply(result.data);
1243
- setSavedSlots((current) => {
1244
- const next = { ...current };
1245
- for (const [slot, text] of Object.entries(prompts)) next[slot] = text.trim();
1246
- return next;
1392
+ }, [read, observedRevision]);
1393
+ useEffect(() => {
1394
+ let previous = client.connection.status;
1395
+ return client.watchConnection((connection) => {
1396
+ if (connection.status === "online" && previous !== "online") read();
1397
+ previous = connection.status;
1247
1398
  });
1248
- setDrafts((current) => {
1249
- const copy = new Map(current);
1250
- for (const [key, draft] of sent) if (copy.get(key) === draft) copy.delete(key);
1251
- return copy;
1399
+ }, [client, read]);
1400
+ useEffect(() => {
1401
+ const token = ++comparison.current;
1402
+ setChanges([]);
1403
+ setComparisonError("");
1404
+ setComparing(false);
1405
+ if (selected === void 0 || compareTo === void 0 || selected === compareTo) return;
1406
+ setComparing(true);
1407
+ client.call("config.agent.compareRevisions", {
1408
+ agentId,
1409
+ fromRevision: selected,
1410
+ toRevision: compareTo
1411
+ }).then((result) => {
1412
+ if (token === comparison.current) setChanges(result.changes);
1413
+ }).catch((cause) => {
1414
+ if (token === comparison.current) setComparisonError(reason(cause));
1415
+ }).finally(() => {
1416
+ if (token === comparison.current) setComparing(false);
1252
1417
  });
1253
- return true;
1254
1418
  }, [
1255
- canSave,
1256
- agent.agentId,
1257
- dirtyKeys,
1258
- value,
1259
- drafts,
1260
- saving,
1261
- remember
1419
+ client,
1420
+ agentId,
1421
+ selected,
1422
+ compareTo,
1423
+ current
1262
1424
  ]);
1263
- const lastError = useRef(null);
1264
- useEffect(() => {
1265
- if (saving.error === lastError.current) return;
1266
- lastError.current = saving.error;
1267
- if (saving.error === null) return;
1268
- const field = fieldOfRefusal(saving.error);
1269
- if (field !== null && dirty(field)) setErrors({ [field]: saving.error });
1270
- else setFooterError(saving.error);
1271
- }, [saving.error, dirty]);
1272
- const discard = useCallback(() => {
1273
- setDrafts(/* @__PURE__ */ new Map());
1274
- setErrors({});
1275
- setFooterError(null);
1276
- }, []);
1277
- const editor = {
1278
- agent,
1279
- agents,
1280
- slots,
1281
- slotsError,
1282
- slotsPending,
1283
- reloadSlots,
1284
- slotDefinitions: definitions.data,
1285
- value,
1286
- set,
1287
- dirty,
1288
- stale,
1289
- invalid,
1290
- reload,
1291
- dirtyTabs,
1292
- error: (key) => errors[key] ?? null,
1293
- footerError,
1294
- pending: saving.pending,
1295
- canSave,
1296
- save,
1297
- extension: (owner) => ({
1298
- read: (fallback) => value(`extension:${owner}`) ?? fallback,
1299
- update: (next) => set(`extension:${owner}`, next),
1300
- pending: saving.pending,
1301
- tools: value("tools"),
1302
- error: errors[`extension:${owner}`] ?? (dirty(`extension:${owner}`) ? contributions.flatMap((entry) => entry.plugin === owner && (entry.slot === "shell.agentEditor.field" || entry.slot === "shell.agentEditor.tab") ? [entry.contribution.validate?.(value(`extension:${owner}`))] : []).find((message) => message != null) ?? null : null)
1303
- }),
1304
- discard
1305
- };
1306
- return /* @__PURE__ */ jsx(EditorContext.Provider, {
1307
- value: editor,
1308
- children
1309
- });
1310
- }
1311
- //#endregion
1312
- //#region ui-src/components/settings/agent/parts.tsx
1313
- /** Pieces shared by the agent editor's tabs. */
1314
- /** Says a field with a draft was changed elsewhere, and takes the new value
1315
- * on request. Renders nothing while none of `fields` is stale. */
1316
- function ChangedElsewhere({ fields }) {
1317
- const { t } = useTranslation();
1318
- const editor = useAgentEditor();
1319
- const stale = fields.filter((key) => editor.stale(key));
1320
- if (stale.length === 0) return null;
1321
- return /* @__PURE__ */ jsx(Alert, {
1322
- tone: "warning",
1323
- variant: "soft",
1324
- "data-slot": "agent-changed-elsewhere",
1325
- className: "text-xs",
1326
- children: /* @__PURE__ */ jsxs("div", {
1327
- className: "flex flex-wrap items-start justify-between gap-3",
1328
- children: [/* @__PURE__ */ jsx("span", { children: t("agents.changedElsewhere") }), /* @__PURE__ */ jsx(Button, {
1329
- size: "sm",
1330
- variant: "ghost",
1331
- onClick: () => {
1332
- for (const key of stale) editor.reload(key);
1333
- },
1334
- children: t("agents.loadRemote")
1425
+ async function prepare(targetRevision) {
1426
+ if (beforeLeave && !await beforeLeave()) return;
1427
+ setBusy(true);
1428
+ setError("");
1429
+ setRequest(void 0);
1430
+ try {
1431
+ const value = await client.call("config.agent.previewRestore", {
1432
+ agentId,
1433
+ targetRevision
1434
+ });
1435
+ setPreview(value);
1436
+ setRequest({
1437
+ targetRevision,
1438
+ expectedRevision: value.expectedRevision,
1439
+ expectedContentHash: value.expectedContentHash,
1440
+ restoreRequestId: uuid()
1441
+ });
1442
+ } catch (cause) {
1443
+ setError(reason(cause));
1444
+ } finally {
1445
+ setBusy(false);
1446
+ }
1447
+ }
1448
+ async function restore() {
1449
+ if (!request || busy || restoring.current) return;
1450
+ restoring.current = true;
1451
+ setBusy(true);
1452
+ setError("");
1453
+ try {
1454
+ const result = await client.call("config.agent.restoreRevision", {
1455
+ agentId,
1456
+ ...request
1457
+ });
1458
+ useAgents.getState().consume({
1459
+ kind: "config.agentChanged",
1460
+ agent: result.agent
1461
+ });
1462
+ setNotice(t("revisions.saved", {
1463
+ revision: result.revision,
1464
+ current: result.currentRevision
1465
+ }));
1466
+ setPreview(void 0);
1467
+ setRequest(void 0);
1468
+ await read();
1469
+ } catch (cause) {
1470
+ setError(reason(cause));
1471
+ } finally {
1472
+ restoring.current = false;
1473
+ setBusy(false);
1474
+ }
1475
+ }
1476
+ const diff = (rows) => /* @__PURE__ */ jsx("div", {
1477
+ className: "space-y-4",
1478
+ children: rows.map((row) => /* @__PURE__ */ jsxs("div", {
1479
+ className: "space-y-2",
1480
+ children: [/* @__PURE__ */ jsx("p", {
1481
+ className: "text-xs font-medium",
1482
+ children: t(`revisions.fields.${row.path}`, { defaultValue: row.path })
1483
+ }), /* @__PURE__ */ jsx("div", {
1484
+ className: "grid gap-2 sm:grid-cols-2",
1485
+ children: [row.before, row.after].map((value, index) => /* @__PURE__ */ jsxs("div", {
1486
+ className: "min-w-0 rounded-control bg-muted/40 p-3",
1487
+ children: [/* @__PURE__ */ jsx("p", {
1488
+ className: "mb-2 text-xs text-muted-foreground",
1489
+ children: t(index === 0 ? "revisions.before" : "revisions.after")
1490
+ }), row.path === "avatar" && typeof value === "string" ? /* @__PURE__ */ jsx("img", {
1491
+ src: `data:image/png;base64,${value}`,
1492
+ alt: t(index === 0 ? "revisions.before" : "revisions.after"),
1493
+ className: "size-16 rounded-pill"
1494
+ }) : /* @__PURE__ */ jsx("pre", {
1495
+ className: "max-h-64 overflow-auto whitespace-pre-wrap break-words text-xs",
1496
+ children: typeof value === "string" ? value || "∅" : JSON.stringify(value, null, 2)
1497
+ })]
1498
+ }, index === 0 ? "before" : "after"))
1335
1499
  })]
1336
- })
1337
- });
1338
- }
1339
- //#endregion
1340
- //#region ui-src/components/settings/agent/basic.tsx
1341
- /**
1342
- * The basic-information tab: picture, name, description and the
1343
- * model cell. Every field, the model cell's included, is part of the editor's
1344
- * one draft. Whether a person can chat with the agent directly is a toggle on
1345
- * the agent list, not here.
1346
- *
1347
- * The picture is its own upload control: pressing it picks an image, and the
1348
- * crop shows in place until the save. While the agent has a picture — saved,
1349
- * or a crop waiting for the save — 恢复默认 beside it drafts the return to the
1350
- * derived letters face, which the same save applies.
1351
- */
1352
- /** The factory agent, whose session switch the gateway keeps on. */
1353
- function AvatarField() {
1354
- const { t } = useTranslation();
1355
- const editor = useAgentEditor();
1356
- const { agent } = editor;
1357
- const picker = useAvatarPicker((base64) => {
1358
- editor.set("avatar", {
1359
- image: base64,
1360
- preview: pngDataUrl(base64)
1361
- });
1500
+ }, row.path))
1362
1501
  });
1363
- const draft = editor.dirty("avatar") ? editor.value("avatar") : void 0;
1364
- const pictured = draft === void 0 ? agent.avatar !== null : draft !== null;
1365
- return /* @__PURE__ */ jsxs(Panel, {
1366
- title: t("agents.avatar"),
1367
- level: "field",
1368
- inline: true,
1502
+ return /* @__PURE__ */ jsxs("section", {
1503
+ className: "min-h-0 flex-1 space-y-4 overflow-auto px-6 pb-6",
1504
+ "aria-label": t("revisions.title"),
1369
1505
  children: [
1370
1506
  /* @__PURE__ */ jsxs("div", {
1371
- className: "flex min-w-0 items-center",
1372
- children: [/* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsxs(TooltipTrigger, {
1373
- render: /* @__PURE__ */ jsx(Button, {
1374
- variant: "plain",
1375
- "data-slot": "agent-avatar-trigger",
1376
- className: "group relative size-11 shrink-0 cursor-pointer rounded-pill outline-none focus-visible:ring-3 focus-visible:ring-ring/50",
1377
- onClick: () => void picker.pick()
1378
- }),
1379
- "aria-label": t("avatar.change"),
1380
- children: [/* @__PURE__ */ jsx(AgentAvatar, {
1381
- agentId: agent.agentId,
1382
- name: editor.value("name") || agent.name,
1383
- avatar: draft === null ? null : agent.avatar,
1384
- ...draft ? { src: draft.preview } : {},
1385
- size: "lg",
1386
- decorative: true,
1387
- className: "size-11 text-sm"
1388
- }), /* @__PURE__ */ jsx("span", {
1389
- "data-slot": "agent-avatar-overlay",
1390
- "aria-hidden": "true",
1391
- className: "absolute inset-0 grid place-items-center rounded-pill bg-foreground/60 text-background opacity-0 transition-opacity duration-150 group-hover:opacity-100 group-focus-visible:opacity-100",
1392
- children: /* @__PURE__ */ jsx(Camera, {
1393
- className: "size-4",
1394
- strokeWidth: 1.75
1395
- })
1396
- })]
1397
- }), /* @__PURE__ */ jsx(TooltipContent, {
1398
- side: "top",
1399
- children: t("avatar.change")
1400
- })] }), pictured && /* @__PURE__ */ jsx(Button, {
1507
+ className: "flex items-center justify-between",
1508
+ children: [/* @__PURE__ */ jsx(Button, {
1401
1509
  variant: "ghost",
1402
1510
  size: "sm",
1403
- "data-slot": "agent-avatar-reset",
1404
- className: "ml-3",
1405
- onClick: () => {
1406
- picker.clearRefusal();
1407
- editor.set("avatar", null);
1408
- },
1409
- children: t("avatar.reset")
1511
+ onClick: onClose,
1512
+ children: t("revisions.back")
1513
+ }), /* @__PURE__ */ jsx(Button, {
1514
+ variant: "ghost",
1515
+ size: "sm",
1516
+ disabled: busy,
1517
+ onClick: () => void read(),
1518
+ children: t("revisions.refresh")
1410
1519
  })]
1411
1520
  }),
1412
- /* @__PURE__ */ jsx(FormFailure, { reason: picker.refusal ?? editor.error("avatar") }),
1413
- picker.dialog
1414
- ]
1415
- });
1416
- }
1417
- function BasicTab() {
1418
- const { t } = useTranslation();
1419
- const editor = useAgentEditor();
1420
- const { agent } = editor;
1421
- const name = editor.value("name");
1422
- const description = editor.value("description");
1423
- const pluginState = usePlugins((state) => state);
1424
- const registrations = contributionsIn(pluginState, "shell.agentEditor.field");
1425
- return /* @__PURE__ */ jsxs("div", {
1426
- className: "flex min-w-0 flex-col gap-5",
1427
- children: [
1428
- /* @__PURE__ */ jsx(ChangedElsewhere, { fields: [
1429
- "name",
1430
- "description",
1431
- "avatar",
1432
- ...registrations.map((one) => `extension:${one.plugin}`)
1433
- ] }),
1434
- /* @__PURE__ */ jsx(AvatarField, {}),
1435
- /* @__PURE__ */ jsx(Field, {
1436
- label: t("agents.name"),
1437
- required: true,
1438
- inline: true,
1439
- className: "settings-field-row",
1440
- error: editor.error("name") ?? (editor.invalid("name") ? t("agents.nameRequired") : void 0),
1441
- children: (binding) => /* @__PURE__ */ jsx(Input, {
1442
- ...binding,
1443
- value: name,
1444
- placeholder: t("agents.namePlaceholder"),
1445
- onChange: (event) => editor.set("name", event.target.value),
1446
- onKeyDown: (event) => {
1447
- if (event.key === "Escape" && !event.nativeEvent.isComposing) editor.reload("name");
1448
- }
1449
- })
1521
+ !persistent && /* @__PURE__ */ jsx("p", {
1522
+ className: "text-xs text-muted-foreground",
1523
+ children: t("revisions.memory")
1450
1524
  }),
1451
- /* @__PURE__ */ jsx(Field, {
1452
- label: t("agents.description"),
1453
- inline: true,
1454
- className: "settings-field-row",
1455
- error: editor.error("description") ?? (editor.invalid("description") ? t("agents.descriptionTooLong", { limit: 500 }) : void 0),
1456
- children: (binding) => /* @__PURE__ */ jsx(Textarea, {
1457
- ...binding,
1458
- limit: 500,
1459
- rows: 5,
1460
- className: "h-[calc(5lh+1rem)] resize-none [field-sizing:fixed]",
1461
- value: description,
1462
- placeholder: t("agents.descriptionPlaceholder"),
1463
- onChange: (event) => editor.set("description", event.target.value)
1464
- })
1525
+ error && /* @__PURE__ */ jsx("p", {
1526
+ role: "alert",
1527
+ className: "text-sm text-destructive",
1528
+ children: error
1465
1529
  }),
1466
- registrations.map((one) => /* @__PURE__ */ jsx(SlotOutlet, {
1467
- slot: "shell.agentEditor.field",
1468
- only: one.key,
1469
- props: {
1470
- agentId: agent.agentId,
1471
- editor: editor.extension(one.plugin),
1472
- errors: { owner: editor.error(`extension:${one.plugin}`) }
1473
- }
1474
- }, one.key))
1475
- ]
1476
- });
1477
- }
1478
- //#endregion
1479
- //#region ui-src/components/settings/agent/prompts.tsx
1480
- /**
1481
- * The prompt tab: the four slots, one edited at a time, listed as identity,
1482
- * style, reminder, AGENTS.md — the slots `config.prompt.slots` declares, in
1483
- * this tab's own order, with their limits from that listing. Each slot keeps
1484
- * its own draft in the editor, so switching slots asks nothing; the text area
1485
- * fills the tab and is its only scroller. Above the text area the chosen
1486
- * slot says what to write there and where the text lands in the model's input.
1487
- */
1488
- /** A dot that says a slot or tab has an unsaved change, to eyes and ears. */
1489
- /** The slot's identifier as the list's second line. Identifiers, not copy:
1490
- * the same in every language. Only AGENTS.md is a file. */
1491
- var SLOT_TAGS = {
1492
- identity: "IDENTITY Slot",
1493
- style: "SOUL Slot",
1494
- reminder: "REMINDER Slot",
1495
- instructions: "AGENTS.md"
1496
- };
1497
- function UnsavedDot() {
1498
- const { t } = useTranslation();
1499
- return /* @__PURE__ */ jsxs("span", {
1500
- "data-slot": "unsaved-dot",
1501
- className: "inline-flex shrink-0 items-center",
1502
- children: [/* @__PURE__ */ jsx("span", {
1503
- "aria-hidden": "true",
1504
- className: "size-1.5 rounded-pill bg-primary"
1505
- }), /* @__PURE__ */ jsx("span", {
1506
- className: "sr-only",
1507
- children: t("agents.unsaved")
1508
- })]
1509
- });
1510
- }
1511
- /** The order this tab lists the slots in. */
1512
- var DISPLAY_ORDER = [
1513
- "identity",
1514
- "style",
1515
- "reminder",
1516
- "instructions"
1517
- ];
1518
- var NOTES = [
1519
- "where",
1520
- "scope",
1521
- "cache",
1522
- "tip"
1523
- ];
1524
- /** What the chosen slot is for and where it goes, shown above its editor for
1525
- * as long as it is chosen: the purpose with an example, then the placement. */
1526
- function SlotAbout({ slot, limit, path }) {
1527
- const { t } = useTranslation();
1528
- return /* @__PURE__ */ jsxs("section", {
1529
- "aria-label": t("agents.prompts.about", { slot: t(`agents.prompts.${slot}`) }),
1530
- "data-slot": "prompt-slot-about",
1531
- className: "flex shrink-0 flex-col gap-2 rounded-control bg-muted/60 px-3 py-2.5 text-xs leading-relaxed @xl:flex-row @xl:gap-6",
1532
- children: [/* @__PURE__ */ jsxs("div", {
1533
- className: "flex min-w-0 flex-col gap-1 @xl:flex-1",
1534
- children: [
1535
- /* @__PURE__ */ jsx("h4", {
1536
- className: "font-medium text-foreground",
1537
- children: t("agents.prompts.purpose")
1538
- }),
1539
- /* @__PURE__ */ jsx("p", {
1540
- className: "text-muted-foreground",
1541
- children: t(`agents.prompts.info.${slot}.purpose`)
1542
- }),
1543
- /* @__PURE__ */ jsx("p", {
1544
- className: "text-muted-foreground",
1545
- children: t("agents.prompts.example", { text: t(`agents.prompts.info.${slot}.example`) })
1546
- })
1547
- ]
1548
- }), /* @__PURE__ */ jsxs("div", {
1549
- className: "flex min-w-0 flex-col gap-1 @xl:flex-1",
1550
- children: [/* @__PURE__ */ jsx("h4", {
1551
- className: "font-medium text-foreground",
1552
- children: t("agents.prompts.placement")
1553
- }), /* @__PURE__ */ jsx("ul", {
1554
- className: "flex list-disc flex-col gap-0.5 ps-4 text-muted-foreground",
1555
- children: NOTES.map((note) => /* @__PURE__ */ jsx("li", {
1556
- className: "break-words",
1557
- children: t(`agents.prompts.info.${slot}.${note}`, {
1558
- path,
1559
- limit: limit ?? ""
1530
+ notice && /* @__PURE__ */ jsx("p", {
1531
+ role: "status",
1532
+ className: "text-sm",
1533
+ children: notice
1534
+ }),
1535
+ busy && /* @__PURE__ */ jsx("p", {
1536
+ role: "status",
1537
+ className: "text-sm text-muted-foreground",
1538
+ children: t("revisions.loading")
1539
+ }),
1540
+ preview && /* @__PURE__ */ jsxs("div", {
1541
+ className: "space-y-4 rounded-control border p-4",
1542
+ children: [
1543
+ /* @__PURE__ */ jsx("h4", { children: t("revisions.confirm", {
1544
+ from: preview.expectedRevision,
1545
+ to: preview.targetRevision
1546
+ }) }),
1547
+ /* @__PURE__ */ jsx("p", {
1548
+ className: "text-xs text-muted-foreground",
1549
+ children: t("revisions.timing")
1550
+ }),
1551
+ diff(preview.changes),
1552
+ preview.blockers.map((blocker) => /* @__PURE__ */ jsxs("p", {
1553
+ className: "text-sm text-destructive",
1554
+ children: [
1555
+ blocker.path,
1556
+ ": ",
1557
+ blocker.reason
1558
+ ]
1559
+ }, blocker.path + blocker.reason)),
1560
+ preview.unchanged && /* @__PURE__ */ jsx("p", { children: t("revisions.unchanged") }),
1561
+ /* @__PURE__ */ jsxs("div", {
1562
+ className: "flex gap-2",
1563
+ children: [
1564
+ /* @__PURE__ */ jsx(Button, {
1565
+ disabled: busy || preview.unchanged || preview.blockers.length > 0,
1566
+ onClick: () => void restore(),
1567
+ children: t("revisions.restore")
1568
+ }),
1569
+ /* @__PURE__ */ jsx(Button, {
1570
+ variant: "ghost",
1571
+ disabled: busy,
1572
+ onClick: () => void prepare(preview.targetRevision),
1573
+ children: t("revisions.refresh")
1574
+ }),
1575
+ /* @__PURE__ */ jsx(Button, {
1576
+ variant: "ghost",
1577
+ disabled: busy,
1578
+ onClick: () => {
1579
+ setPreview(void 0);
1580
+ setRequest(void 0);
1581
+ },
1582
+ children: t("revisions.cancel")
1583
+ })
1584
+ ]
1560
1585
  })
1561
- }, note))
1562
- })]
1563
- })]
1586
+ ]
1587
+ }),
1588
+ /* @__PURE__ */ jsx("ol", {
1589
+ className: "divide-y",
1590
+ children: items.map((item) => {
1591
+ const expanded = selected === item.revision;
1592
+ const canExpand = items.length > 1 || item.revision !== current || !!item.source.sessionId;
1593
+ const heading = /* @__PURE__ */ jsxs("span", {
1594
+ className: "min-w-0 flex-1 space-y-1",
1595
+ children: [/* @__PURE__ */ jsxs("span", {
1596
+ className: "block text-sm font-medium break-words",
1597
+ children: [
1598
+ "v",
1599
+ item.revision,
1600
+ " · ",
1601
+ item.summary
1602
+ ]
1603
+ }), /* @__PURE__ */ jsxs("span", {
1604
+ className: "block text-xs text-muted-foreground",
1605
+ children: [
1606
+ new Date(item.createdAt).toLocaleString(i18n.language),
1607
+ " ·",
1608
+ " ",
1609
+ t(`revisions.${item.source.kind}`)
1610
+ ]
1611
+ })]
1612
+ });
1613
+ const currentMark = item.revision === current && /* @__PURE__ */ jsx("span", {
1614
+ className: "shrink-0 rounded-control bg-muted px-2 py-1 text-xs text-muted-foreground",
1615
+ children: t("revisions.current")
1616
+ });
1617
+ return /* @__PURE__ */ jsxs("li", {
1618
+ className: "py-2",
1619
+ children: [canExpand ? /* @__PURE__ */ jsxs(Button, {
1620
+ variant: "plain",
1621
+ "aria-expanded": expanded,
1622
+ className: "flex w-full items-center gap-3 rounded-control p-3 text-start hover:bg-muted/50 focus-visible:ring-2 focus-visible:ring-ring",
1623
+ onClick: () => {
1624
+ setSelected(expanded ? void 0 : item.revision);
1625
+ setCompareTo(item.revision === current ? items.find((option) => option.revision !== item.revision)?.revision : current);
1626
+ },
1627
+ children: [
1628
+ heading,
1629
+ currentMark,
1630
+ /* @__PURE__ */ jsx(ChevronDown, {
1631
+ "aria-hidden": "true",
1632
+ className: `size-4 shrink-0 text-muted-foreground transition-transform ${expanded ? "rotate-180" : ""}`
1633
+ })
1634
+ ]
1635
+ }) : /* @__PURE__ */ jsxs("div", {
1636
+ className: "flex items-center gap-3 p-3",
1637
+ children: [heading, currentMark]
1638
+ }), expanded && /* @__PURE__ */ jsxs("div", {
1639
+ className: "space-y-4 px-3 pt-3 pb-2",
1640
+ children: [compareTo !== void 0 && compareTo !== item.revision && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("label", {
1641
+ className: "flex flex-wrap items-center gap-2 text-xs text-muted-foreground",
1642
+ children: [
1643
+ t("revisions.compare"),
1644
+ " · v",
1645
+ item.revision,
1646
+ " →",
1647
+ /* @__PURE__ */ jsx(Select, {
1648
+ size: "sm",
1649
+ "aria-label": t("revisions.compare"),
1650
+ value: String(compareTo),
1651
+ onValueChange: (value) => setCompareTo(Number(value)),
1652
+ children: items.filter((option) => option.revision !== item.revision).map((option) => /* @__PURE__ */ jsxs("option", {
1653
+ value: option.revision,
1654
+ children: ["v", option.revision]
1655
+ }, option.revision))
1656
+ })
1657
+ ]
1658
+ }), comparing ? /* @__PURE__ */ jsx("p", {
1659
+ role: "status",
1660
+ className: "text-xs text-muted-foreground",
1661
+ children: t("revisions.loading")
1662
+ }) : comparisonError ? /* @__PURE__ */ jsx("p", {
1663
+ role: "alert",
1664
+ className: "text-xs text-destructive",
1665
+ children: comparisonError
1666
+ }) : changes.length === 0 ? /* @__PURE__ */ jsx("p", {
1667
+ className: "text-xs text-muted-foreground",
1668
+ children: t("revisions.noDifference")
1669
+ }) : diff(changes)] }), /* @__PURE__ */ jsxs("div", {
1670
+ className: "flex flex-wrap gap-2",
1671
+ children: [item.revision !== current && /* @__PURE__ */ jsx(Button, {
1672
+ variant: "outline",
1673
+ size: "sm",
1674
+ disabled: busy,
1675
+ onClick: () => void prepare(item.revision),
1676
+ children: t("revisions.restore")
1677
+ }), item.source.sessionId && /* @__PURE__ */ jsx(Button, {
1678
+ variant: "ghost",
1679
+ size: "sm",
1680
+ onClick: async () => {
1681
+ if (beforeLeave && !await beforeLeave()) return;
1682
+ if (!await goToSession(client, item.source.sessionId)) setError(t("revisions.sourceMissing"));
1683
+ else useNavigation.getState().openSettings(false);
1684
+ },
1685
+ children: t("revisions.source")
1686
+ })]
1687
+ })]
1688
+ })]
1689
+ }, item.revision);
1690
+ })
1691
+ }),
1692
+ cursor && /* @__PURE__ */ jsx(Button, {
1693
+ variant: "ghost",
1694
+ disabled: busy,
1695
+ onClick: () => void read(cursor),
1696
+ children: t("revisions.more")
1697
+ })
1698
+ ]
1564
1699
  });
1565
1700
  }
1566
- function PromptsTab() {
1701
+ //#endregion
1702
+ //#region ui-src/components/settings/agent/tools.tsx
1703
+ /** Agent tool access and preload preferences grouped from the live tool list. */
1704
+ /** Uses extension metadata without interpreting package names or tool naming conventions. */
1705
+ function groupsOf(tools, describe, unknownSource) {
1706
+ const groups = /* @__PURE__ */ new Map();
1707
+ for (const tool of tools) {
1708
+ const existing = groups.get(tool.plugin);
1709
+ const presentation = describe(tool);
1710
+ const facts = (presentation?.source === tool.plugin ? presentation : existing) ?? {
1711
+ label: tool.plugin || unknownSource,
1712
+ sectionLabel: unknownSource,
1713
+ sectionOrder: 2,
1714
+ order: 0
1715
+ };
1716
+ groups.set(tool.plugin, {
1717
+ ...facts,
1718
+ key: `plugin:${tool.plugin}`,
1719
+ source: tool.plugin || unknownSource,
1720
+ tools: [...existing?.tools ?? [], tool]
1721
+ });
1722
+ }
1723
+ return [...groups.values()].map((group) => ({
1724
+ ...group,
1725
+ tools: [...group.tools].sort((a, b) => a.name.localeCompare(b.name))
1726
+ })).sort((a, b) => a.sectionOrder - b.sectionOrder || a.order - b.order || a.label.localeCompare(b.label));
1727
+ }
1728
+ /** Tool permissions and independent preload preferences share the Agent editor transaction. */
1729
+ function ToolsTab() {
1567
1730
  const { t } = useTranslation();
1568
1731
  const editor = useAgentEditor();
1569
- const declared = editor.slotDefinitions?.map((one) => one.id);
1570
- const order = DISPLAY_ORDER.filter((id) => declared?.includes(id) ?? true);
1571
- const [picked, setPicked] = useState(order[0] ?? "identity");
1572
- const slot = order.includes(picked) ? picked : order[0] ?? "identity";
1573
- const key = `prompt.${slot}`;
1574
- const limit = editor.slotDefinitions?.find((one) => one.id === slot)?.maxLength;
1575
- const failure = slot === "instructions" ? editor.slots?.failure : void 0;
1576
- const label = (id) => t(`agents.prompts.${id}`);
1577
- const rulesPath = editor.slots?.path ?? `agents/${editor.agent.agentId}/AGENTS.md`;
1578
- if (editor.slots === null) return /* @__PURE__ */ jsx(ReadFailure, {
1579
- reason: editor.slotsError,
1580
- pending: editor.slotsPending,
1581
- onRetry: editor.reloadSlots
1732
+ const { agent } = editor;
1733
+ const preload = useBrowserService("tool-preload:configuration");
1734
+ const rememberedOwner = useRef(preload?.owner);
1735
+ if (preload) rememberedOwner.current = preload.owner;
1736
+ const owner = preload?.owner ?? rememberedOwner.current;
1737
+ const ownerKey = owner ? `extension:${owner}` : void 0;
1738
+ const ownerValue = ownerKey ? editor.value(ownerKey) : void 0;
1739
+ const lastOverrides = useRef({});
1740
+ let overrides = lastOverrides.current;
1741
+ let preloadError = null;
1742
+ try {
1743
+ if (preload) {
1744
+ overrides = preload.read(ownerValue);
1745
+ lastOverrides.current = overrides;
1746
+ }
1747
+ } catch (error) {
1748
+ preloadError = error instanceof Error ? error.message : String(error);
1749
+ }
1750
+ const listing = useGatewayRead("config.tool.list", {
1751
+ agentIds: [agent.agentId],
1752
+ maxItemBytes: 262144,
1753
+ maxTotalBytes: 8388608
1582
1754
  });
1755
+ const member = listing.data?.results.find((one) => one.target === agent.agentId);
1756
+ const tools = member?.ok && member.value.agentId === agent.agentId ? member.value.tools : null;
1757
+ const whitelist = editor.value("tools");
1758
+ const unrestricted = whitelist === null;
1759
+ const permitted = (name) => unrestricted || whitelist.includes(name);
1760
+ const pluginState = usePlugins((state) => state);
1761
+ const presentations = contributionsIn(pluginState, "shell.tools.group");
1762
+ const labels = contributionsIn(pluginState, "chat.tool.presentation");
1763
+ const titleOf = (tool) => {
1764
+ for (const entry of labels) {
1765
+ if (entry.plugin !== tool.plugin) continue;
1766
+ try {
1767
+ const label = entry.contribution.describe({
1768
+ call: {
1769
+ id: tool.name,
1770
+ name: tool.name,
1771
+ input: {}
1772
+ },
1773
+ result: void 0
1774
+ })?.label;
1775
+ if (label) return label;
1776
+ } catch {}
1777
+ }
1778
+ return tool.name;
1779
+ };
1780
+ const groups = groupsOf(tools ?? [], (tool) => presentations.map((one) => one.contribution.describe(tool)).find((value) => value !== void 0), t("agents.toolSettings.unknownSource"));
1781
+ const groupFor = new Map(groups.flatMap((group) => group.tools.map((tool) => [tool.name, group])));
1782
+ const rows = groups.flatMap((group) => group.tools);
1783
+ const known = new Set(rows.map((tool) => tool.name));
1784
+ const unavailable = tools === null ? [] : [.../* @__PURE__ */ new Set([...Object.keys(overrides).filter((name) => !known.has(name)), ...unrestricted ? [] : whitelist.filter((name) => !known.has(name))])];
1785
+ const overridden = (name) => Object.hasOwn(overrides, name);
1786
+ const effective = (tool) => overridden(tool.name) ? overrides[tool.name] === true : tool.preloadDefault;
1787
+ const blocked = !preload || preloadError !== null || editor.pending;
1788
+ const loading = listing.pending && tools === null;
1789
+ function changePermission(names, on) {
1790
+ if (on && whitelist === null) return;
1791
+ const without = (whitelist ?? rows.map((tool) => tool.name)).filter((name) => !names.includes(name));
1792
+ editor.set("tools", on ? [...without, ...names] : without);
1793
+ }
1794
+ function changePreload(names, on) {
1795
+ if (!preload || blocked || !ownerKey) return;
1796
+ const next = { ...overrides };
1797
+ for (const name of names) if (on === void 0) delete next[name];
1798
+ else next[name] = on;
1799
+ editor.set(ownerKey, preload.replace(ownerValue, next));
1800
+ }
1801
+ function resetDefaults() {
1802
+ if (!preload || blocked || !ownerKey) return;
1803
+ const next = preload.replace(ownerValue, {});
1804
+ editor.set("tools", null);
1805
+ editor.set(ownerKey, next);
1806
+ }
1583
1807
  return /* @__PURE__ */ jsxs("div", {
1584
- className: "@container flex min-h-0 min-w-0 flex-1 flex-col gap-3",
1585
- children: [/* @__PURE__ */ jsx(ChangedElsewhere, { fields: SLOT_IDS.map((id) => `prompt.${id}`) }), /* @__PURE__ */ jsxs("div", {
1586
- className: "flex min-h-0 min-w-0 flex-1 flex-col gap-4 @2xl:flex-row",
1587
- children: [
1588
- /* @__PURE__ */ jsx("nav", {
1589
- "aria-label": t("agents.prompts.slots"),
1590
- "data-slot": "prompt-slot-list",
1591
- className: "hidden w-52 shrink-0 flex-col gap-1 @2xl:flex",
1592
- children: order.map((id) => /* @__PURE__ */ jsx("div", {
1593
- "data-slot": "prompt-slot",
1594
- className: cn("flex min-w-0 items-center gap-1 rounded-control pe-1", id === slot ? "bg-accent text-accent-foreground" : "hover:bg-muted"),
1595
- children: /* @__PURE__ */ jsxs(Button, {
1596
- variant: "plain",
1597
- "data-slot": "prompt-slot-select",
1598
- "aria-current": id === slot,
1599
- onClick: () => setPicked(id),
1600
- className: "flex h-auto min-w-0 flex-1 items-center justify-start gap-2 px-3 py-1.5 text-left",
1601
- children: [/* @__PURE__ */ jsxs("span", {
1602
- className: "flex min-w-0 flex-col",
1808
+ className: "@container flex min-w-0 flex-col gap-4",
1809
+ children: [
1810
+ /* @__PURE__ */ jsx(ChangedElsewhere, { fields: ownerKey ? ["tools", ownerKey] : ["tools"] }),
1811
+ /* @__PURE__ */ jsxs("div", {
1812
+ className: "min-w-0",
1813
+ children: [/* @__PURE__ */ jsxs("div", {
1814
+ className: "flex min-w-0 items-center justify-between gap-3",
1815
+ children: [/* @__PURE__ */ jsx("h3", {
1816
+ className: "text-sm font-semibold",
1817
+ children: t("agents.toolSettings.heading")
1818
+ }), /* @__PURE__ */ jsx(Segmented, {
1819
+ label: t("agents.toolSettings.mode"),
1820
+ value: unrestricted ? "all" : "custom",
1821
+ disabled: tools === null || editor.pending,
1822
+ options: [{
1823
+ value: "custom",
1824
+ label: t("agents.toolSettings.custom")
1825
+ }, {
1826
+ value: "all",
1827
+ label: t("agents.toolSettings.allowAll")
1828
+ }],
1829
+ onSelect: (mode) => editor.set("tools", mode === "all" ? null : rows.filter((tool) => permitted(tool.name)).map((tool) => tool.name))
1830
+ })]
1831
+ }), /* @__PURE__ */ jsx("p", {
1832
+ className: "mt-1 text-xs leading-relaxed text-muted-foreground",
1833
+ children: t("agents.toolSettings.hint")
1834
+ })]
1835
+ }),
1836
+ /* @__PURE__ */ jsx(ReadFailure, {
1837
+ reason: listing.error ?? (member && !member.ok ? member.error.message : null),
1838
+ pending: loading,
1839
+ onRetry: listing.reload
1840
+ }),
1841
+ !preload && /* @__PURE__ */ jsx(Warning, { children: t("agents.toolSettings.preloadUnavailable") }),
1842
+ /* @__PURE__ */ jsx(FormFailure, { reason: preloadError }),
1843
+ (tools !== null || loading) && /* @__PURE__ */ jsx(DataTable, {
1844
+ defaultExpandedGroups: [],
1845
+ ariaLabel: t("agents.toolSettings.heading"),
1846
+ items: rows,
1847
+ keyOf: (tool) => tool.name,
1848
+ labelOf: (tool) => tool.name,
1849
+ searchOf: (tool) => `${titleOf(tool)} ${tool.name} ${tool.description} ${tool.plugin}`,
1850
+ groupSelectionScope: "matching",
1851
+ toolbar: /* @__PURE__ */ jsx(TooltipHint, {
1852
+ content: t("agents.toolSettings.resetDefaultsHint"),
1853
+ children: /* @__PURE__ */ jsx(Button, {
1854
+ size: "sm",
1855
+ variant: "ghost",
1856
+ icon: "reset",
1857
+ className: "w-[var(--control-height)] p-0",
1858
+ "aria-label": t("agents.toolSettings.restoreDefault"),
1859
+ disabled: blocked || tools === null,
1860
+ onClick: resetDefaults
1861
+ })
1862
+ }),
1863
+ groupOf: (tool) => {
1864
+ const group = groupFor.get(tool.name);
1865
+ return {
1866
+ key: group.key,
1867
+ label: group.label,
1868
+ hint: group.source
1869
+ };
1870
+ },
1871
+ columns: [{
1872
+ id: "tool",
1873
+ label: t("agents.toolSettings.tool"),
1874
+ render: (tool) => {
1875
+ const title = titleOf(tool);
1876
+ return /* @__PURE__ */ jsxs("div", {
1877
+ className: "flex w-full min-w-0 max-w-full flex-col gap-1",
1878
+ children: [/* @__PURE__ */ jsxs("div", {
1879
+ className: "flex min-w-0 items-center gap-2 whitespace-nowrap",
1603
1880
  children: [/* @__PURE__ */ jsx("span", {
1604
- className: "truncate text-sm font-medium",
1605
- children: label(id)
1606
- }), /* @__PURE__ */ jsx("span", {
1607
- className: "truncate font-mono text-2xs text-muted-foreground",
1608
- children: SLOT_TAGS[id]
1881
+ title: tool.name,
1882
+ className: title === tool.name ? "min-w-0 truncate font-mono text-xs text-foreground" : "min-w-0 max-w-[65%] truncate font-mono text-xs text-foreground",
1883
+ children: tool.name
1884
+ }), title !== tool.name && /* @__PURE__ */ jsx("span", {
1885
+ title,
1886
+ className: "min-w-0 truncate text-xs font-medium text-muted-foreground",
1887
+ children: title
1609
1888
  })]
1610
- }), editor.dirty(`prompt.${id}`) && /* @__PURE__ */ jsx(UnsavedDot, {})]
1889
+ }), /* @__PURE__ */ jsx(TooltipHint, {
1890
+ content: /* @__PURE__ */ jsx("span", {
1891
+ className: "max-h-64 overflow-y-auto whitespace-pre-wrap",
1892
+ children: tool.description
1893
+ }),
1894
+ side: "bottom",
1895
+ closeOnClick: false,
1896
+ children: /* @__PURE__ */ jsx("button", {
1897
+ type: "button",
1898
+ "data-slot": "tool-description",
1899
+ className: "block w-full max-w-full truncate rounded-sm border-0 bg-transparent p-0 text-left text-xs text-muted-foreground focus-visible:outline-2 focus-visible:outline-ring",
1900
+ children: tool.description
1901
+ })
1902
+ })]
1903
+ });
1904
+ }
1905
+ }, {
1906
+ id: "preload",
1907
+ label: t("agents.toolSettings.preload"),
1908
+ width: "4rem",
1909
+ render: (tool) => /* @__PURE__ */ jsx("div", {
1910
+ className: "flex items-center gap-1",
1911
+ children: /* @__PURE__ */ jsx(TooltipHint, {
1912
+ content: t(effective(tool) ? "agents.toolSettings.preloadOn" : "agents.toolSettings.preloadOff"),
1913
+ children: /* @__PURE__ */ jsx(Button, {
1914
+ size: "sm",
1915
+ variant: "ghost",
1916
+ className: effective(tool) ? "w-8 p-0 text-yellow-500" : "w-8 p-0 text-muted-foreground",
1917
+ "aria-label": `${t("agents.toolSettings.preload")} ${tool.name}`,
1918
+ "aria-pressed": effective(tool),
1919
+ disabled: blocked,
1920
+ onClick: () => changePreload([tool.name], !effective(tool)),
1921
+ children: /* @__PURE__ */ jsx("svg", {
1922
+ viewBox: "0 0 24 24",
1923
+ width: "16",
1924
+ height: "16",
1925
+ fill: effective(tool) ? "currentColor" : "none",
1926
+ stroke: "currentColor",
1927
+ strokeWidth: "1.6",
1928
+ strokeLinejoin: "round",
1929
+ "aria-hidden": "true",
1930
+ children: /* @__PURE__ */ jsx("path", { d: "m13 2-9 12h7l-1 8 10-13h-7l1-7Z" })
1931
+ })
1932
+ })
1611
1933
  })
1612
- }, id))
1613
- }),
1614
- /* @__PURE__ */ jsx("div", {
1615
- "data-slot": "prompt-slot-switch",
1616
- className: "min-w-0 @2xl:hidden",
1617
- children: /* @__PURE__ */ jsx(Segmented, {
1618
- fullWidth: true,
1619
- label: t("agents.prompts.slots"),
1620
- value: slot,
1621
- options: order.map((id) => ({
1622
- value: id,
1623
- label: editor.dirty(`prompt.${id}`) ? `${label(id)} •` : label(id)
1624
- })),
1625
- onSelect: setPicked
1626
1934
  })
1935
+ }],
1936
+ selection: {
1937
+ keys: new Set(unrestricted ? rows.map((tool) => tool.name) : whitelist),
1938
+ mode: "enablement",
1939
+ onChange: (next) => {
1940
+ if (unrestricted && rows.every((tool) => next.has(tool.name))) return;
1941
+ editor.set("tools", [...next]);
1942
+ },
1943
+ disabled: editor.pending
1944
+ },
1945
+ loading,
1946
+ size: "sm",
1947
+ empty: /* @__PURE__ */ jsx("p", {
1948
+ className: "text-xs text-muted-foreground",
1949
+ children: t("agents.toolsEmpty")
1627
1950
  }),
1628
- /* @__PURE__ */ jsxs("section", {
1629
- "aria-label": label(slot),
1630
- "data-slot": "prompt-editor",
1631
- className: "flex min-h-0 min-w-0 flex-1 flex-col gap-2",
1632
- children: [
1633
- /* @__PURE__ */ jsx(SlotAbout, {
1634
- slot,
1635
- limit,
1636
- path: rulesPath
1637
- }),
1638
- failure !== void 0 && /* @__PURE__ */ jsx(Failure, { reason: t("agents.prompts.readFailed", { reason: failure }) }),
1639
- /* @__PURE__ */ jsx(Textarea, {
1640
- "aria-label": label(slot),
1641
- fill: true,
1642
- ...limit === void 0 ? {} : { limit },
1643
- readOnly: failure !== void 0,
1644
- value: editor.value(key),
1645
- onChange: (event) => editor.set(key, event.target.value),
1646
- className: "font-mono"
1647
- }, slot),
1648
- /* @__PURE__ */ jsx(FormFailure, { reason: editor.error(key) })
1649
- ]
1650
- })
1651
- ]
1652
- })]
1951
+ className: "w-full min-w-0 [&_table]:table-fixed"
1952
+ }, `${agent.agentId}:${tools === null ? "loading" : "ready"}`),
1953
+ unavailable.length > 0 && /* @__PURE__ */ jsxs("section", {
1954
+ "data-slot": "tool-unavailable",
1955
+ "aria-label": t("agents.toolSettings.unavailable"),
1956
+ className: "rounded-control border border-dashed border-border p-3",
1957
+ children: [
1958
+ /* @__PURE__ */ jsx("h4", {
1959
+ className: "text-xs font-medium",
1960
+ children: t("agents.toolSettings.unavailable")
1961
+ }),
1962
+ /* @__PURE__ */ jsx("p", {
1963
+ className: "mt-1 text-2xs text-muted-foreground",
1964
+ children: t("agents.toolSettings.unavailableHint")
1965
+ }),
1966
+ /* @__PURE__ */ jsx("ul", {
1967
+ className: "mt-2 flex flex-col gap-1",
1968
+ children: unavailable.map((name) => /* @__PURE__ */ jsxs("li", {
1969
+ className: "flex min-w-0 flex-wrap items-center gap-2",
1970
+ children: [/* @__PURE__ */ jsx("span", {
1971
+ className: "min-w-0 flex-1 break-all font-mono text-xs text-muted-foreground",
1972
+ children: name
1973
+ }), !unrestricted && whitelist.includes(name) && /* @__PURE__ */ jsx(Button, {
1974
+ size: "sm",
1975
+ variant: "ghost",
1976
+ "aria-label": `${t("common.remove")} ${name}`,
1977
+ disabled: editor.pending,
1978
+ onClick: () => changePermission([name], false),
1979
+ children: t("common.remove")
1980
+ })]
1981
+ }, name))
1982
+ })
1983
+ ]
1984
+ }),
1985
+ /* @__PURE__ */ jsx(FormFailure, { reason: editor.error("tools") }),
1986
+ ownerKey && /* @__PURE__ */ jsx(FormFailure, { reason: editor.error(ownerKey) })
1987
+ ]
1653
1988
  });
1654
1989
  }
1655
1990
  //#endregion
1656
- //#region ui-src/components/settings/agent/revisions.tsx
1657
- /** Compact history with explicit comparison and a retryable restore confirmation. */
1658
- function AgentRevisions({ agentId, onClose, beforeLeave }) {
1659
- const { t, i18n } = useTranslation();
1660
- const client = useGateway();
1661
- const observedRevision = useAgents((state) => state.agents.find((agent) => agent.agentId === agentId)?.revision);
1662
- const [items, setItems] = useState([]);
1663
- const [current, setCurrent] = useState(0);
1664
- const [cursor, setCursor] = useState();
1665
- const [selected, setSelected] = useState();
1666
- const [compareTo, setCompareTo] = useState();
1667
- const [changes, setChanges] = useState([]);
1668
- const [comparing, setComparing] = useState(false);
1669
- const [comparisonError, setComparisonError] = useState("");
1670
- const [preview, setPreview] = useState();
1671
- const [request, setRequest] = useState();
1672
- const [busy, setBusy] = useState(false);
1673
- const [error, setError] = useState("");
1674
- const [notice, setNotice] = useState("");
1675
- const [persistent, setPersistent] = useState(true);
1676
- const generation = useRef(0);
1677
- const restoring = useRef(false);
1678
- const comparison = useRef(0);
1679
- const reason = (cause) => failureText(cause, () => "") ?? "";
1680
- const read = useCallback(async (next) => {
1681
- const token = ++generation.current;
1682
- setBusy(true);
1683
- setError("");
1991
+ //#region ui-src/components/settings/execution-limits.tsx
1992
+ /** Global execution limits; each successful save applies to subsequent rounds. */
1993
+ function ExecutionLimits({ ctx, registerGuard }) {
1994
+ const host = useGateway();
1995
+ const gateway = ctx?.gateway ?? host;
1996
+ const { t } = useTranslation();
1997
+ const toast = useToast();
1998
+ const translation = useRef(t);
1999
+ translation.current = t;
2000
+ const [saved, setSaved] = useState(null);
2001
+ const [inputKey, setInputKey] = useState(0);
2002
+ const [draft, setDraft] = useState(null);
2003
+ const [readError, setReadError] = useState(null);
2004
+ const [saveError, setSaveError] = useState(null);
2005
+ const [reading, setReading] = useState(true);
2006
+ const [blocked, setBlocked] = useState(false);
2007
+ const [saving, setSaving] = useState(false);
2008
+ const [notice, setNotice] = useState(null);
2009
+ const [online, setOnline] = useState(gateway.connection.status === "online");
2010
+ const latest = useRef({
2011
+ draft,
2012
+ saved,
2013
+ saving
2014
+ });
2015
+ latest.current = {
2016
+ draft,
2017
+ saved,
2018
+ saving
2019
+ };
2020
+ const invalidated = useRef(false);
2021
+ const uncertain = useRef(false);
2022
+ const lifetime = useRef(null);
2023
+ const controller = useRef(null);
2024
+ const reload = useCallback(async (notify = false) => {
2025
+ controller.current?.abort();
2026
+ const request = new AbortController();
2027
+ controller.current = request;
2028
+ setReading(true);
2029
+ setReadError(null);
1684
2030
  try {
1685
- const page = await client.call("config.agent.revisions", {
1686
- agentId,
1687
- ...next ? { cursor: next } : {}
1688
- });
1689
- if (generation.current !== token) return;
1690
- setItems((old) => next ? [...old, ...page.items.filter((row) => !old.some((item) => item.revision === row.revision))] : page.items);
1691
- setCurrent(page.currentRevision);
1692
- setCursor(page.nextCursor);
1693
- setPersistent(page.persistent);
1694
- } catch (cause) {
1695
- if (generation.current === token) setError(reason(cause));
2031
+ const result = await gateway.read("config.limits.get", {}, { signal: request.signal });
2032
+ if (!request.signal.aborted) {
2033
+ setSaved(result.limits);
2034
+ setBlocked(false);
2035
+ if (uncertain.current) setSaveError(translation.current("runSettings.unconfirmed"));
2036
+ if (!(latest.current.draft !== null && JSON.stringify(latest.current.draft) !== JSON.stringify(latest.current.saved))) {
2037
+ setDraft(null);
2038
+ if (JSON.stringify(result.limits) !== JSON.stringify(latest.current.saved)) setInputKey((key) => key + 1);
2039
+ } else if (notify) setNotice("changed");
2040
+ return result.limits;
2041
+ }
2042
+ } catch (error) {
2043
+ if (!request.signal.aborted) {
2044
+ setReadError(error instanceof Error ? error.message : String(error));
2045
+ if (error instanceof Error && "errorCode" in error && error.errorCode === "configuration_recovery_required") setBlocked(true);
2046
+ }
1696
2047
  } finally {
1697
- if (generation.current === token) setBusy(false);
2048
+ if (!request.signal.aborted) setReading(false);
1698
2049
  }
1699
- }, [client, agentId]);
2050
+ return null;
2051
+ }, [gateway]);
1700
2052
  useEffect(() => {
1701
- read();
2053
+ lifetime.current = new AbortController();
2054
+ reload();
1702
2055
  return () => {
1703
- generation.current++;
1704
- comparison.current++;
2056
+ controller.current?.abort();
2057
+ lifetime.current?.abort();
1705
2058
  };
1706
- }, [read, observedRevision]);
2059
+ }, [reload]);
1707
2060
  useEffect(() => {
1708
- let previous = client.connection.status;
1709
- return client.watchConnection((connection) => {
1710
- if (connection.status === "online" && previous !== "online") read();
1711
- previous = connection.status;
2061
+ let previous = gateway.connection.status;
2062
+ const off = gateway.watchConnection((state) => {
2063
+ setOnline(state.status === "online");
2064
+ if (state.status === "online" && previous !== "online") reload(true);
2065
+ previous = state.status;
1712
2066
  });
1713
- }, [client, read]);
1714
- useEffect(() => {
1715
- const token = ++comparison.current;
1716
- setChanges([]);
1717
- setComparisonError("");
1718
- setComparing(false);
1719
- if (selected === void 0 || compareTo === void 0 || selected === compareTo) return;
1720
- setComparing(true);
1721
- client.call("config.agent.compareRevisions", {
1722
- agentId,
1723
- fromRevision: selected,
1724
- toRevision: compareTo
1725
- }).then((result) => {
1726
- if (token === comparison.current) setChanges(result.changes);
1727
- }).catch((cause) => {
1728
- if (token === comparison.current) setComparisonError(reason(cause));
1729
- }).finally(() => {
1730
- if (token === comparison.current) setComparing(false);
2067
+ const stop = gateway.subscribe((frame) => {
2068
+ if (frame.kind !== "config.limitsChanged") return;
2069
+ if (latest.current.saving) invalidated.current = true;
2070
+ else reload(true);
1731
2071
  });
1732
- }, [
1733
- client,
1734
- agentId,
1735
- selected,
1736
- compareTo,
1737
- current
1738
- ]);
1739
- async function prepare(targetRevision) {
1740
- if (beforeLeave && !await beforeLeave()) return;
1741
- setBusy(true);
1742
- setError("");
1743
- setRequest(void 0);
1744
- try {
1745
- const value = await client.call("config.agent.previewRestore", {
1746
- agentId,
1747
- targetRevision
1748
- });
1749
- setPreview(value);
1750
- setRequest({
1751
- targetRevision,
1752
- expectedRevision: value.expectedRevision,
1753
- expectedContentHash: value.expectedContentHash,
1754
- restoreRequestId: uuid()
1755
- });
1756
- } catch (cause) {
1757
- setError(reason(cause));
1758
- } finally {
1759
- setBusy(false);
1760
- }
1761
- }
1762
- async function restore() {
1763
- if (!request || busy || restoring.current) return;
1764
- restoring.current = true;
1765
- setBusy(true);
1766
- setError("");
2072
+ return () => {
2073
+ off();
2074
+ stop();
2075
+ };
2076
+ }, [gateway, reload]);
2077
+ const guardState = useRef({
2078
+ dirty: false,
2079
+ pending: false
2080
+ });
2081
+ guardState.current = {
2082
+ dirty: draft !== null && JSON.stringify(draft) !== JSON.stringify(saved),
2083
+ pending: saving
2084
+ };
2085
+ useEffect(() => {
2086
+ registerGuard(() => guardState.current);
2087
+ return () => registerGuard(null);
2088
+ }, [registerGuard]);
2089
+ const values = draft ?? saved;
2090
+ const positive = (value) => value !== void 0 && Number.isSafeInteger(value) && value > 0;
2091
+ async function save() {
2092
+ if (values === null || saving || !online || reading || readError !== null || !positive(values.maxSteps) || values.tokenBudget !== void 0 && !positive(values.tokenBudget)) return;
2093
+ let committed = false;
2094
+ setSaving(true);
2095
+ uncertain.current = false;
2096
+ setSaveError(null);
1767
2097
  try {
1768
- const result = await client.call("config.agent.restoreRevision", {
1769
- agentId,
1770
- ...request
2098
+ const result = await gateway.call("config.limits.set", { limits: values }, {
2099
+ timeoutMs: 5e3,
2100
+ signal: lifetime.current?.signal
1771
2101
  });
1772
- useAgents.getState().consume({
1773
- kind: "config.agentChanged",
1774
- agent: result.agent
2102
+ if (lifetime.current?.signal.aborted) return;
2103
+ controller.current?.abort();
2104
+ setReading(false);
2105
+ committed = true;
2106
+ setSaved(result.limits);
2107
+ setDraft(null);
2108
+ setNotice(null);
2109
+ toast.add({
2110
+ tone: "success",
2111
+ title: t("runSettings.saved")
1775
2112
  });
1776
- setNotice(t("revisions.saved", {
1777
- revision: result.revision,
1778
- current: result.currentRevision
1779
- }));
1780
- setPreview(void 0);
1781
- setRequest(void 0);
1782
- await read();
1783
- } catch (cause) {
1784
- setError(reason(cause));
2113
+ } catch (error) {
2114
+ if (lifetime.current?.signal.aborted) return;
2115
+ const code = error instanceof Error && "errorCode" in error ? error.errorCode : void 0;
2116
+ const refused = error instanceof Error && "failure" in error && error.failure === "refused";
2117
+ if (code === "configuration_write_rejected" || refused && code !== "configuration_recovery_required") setSaveError(error instanceof Error ? error.message : String(error));
2118
+ else {
2119
+ uncertain.current = true;
2120
+ if (code === "configuration_recovery_required") setBlocked(true);
2121
+ setSaveError(t("runSettings.unconfirmedFailed"));
2122
+ await reload();
2123
+ }
1785
2124
  } finally {
1786
- restoring.current = false;
1787
- setBusy(false);
2125
+ if (!lifetime.current?.signal.aborted) {
2126
+ setSaving(false);
2127
+ if (invalidated.current) {
2128
+ invalidated.current = false;
2129
+ reload(!committed);
2130
+ }
2131
+ }
1788
2132
  }
1789
2133
  }
1790
- const diff = (rows) => /* @__PURE__ */ jsx("div", {
1791
- className: "space-y-4",
1792
- children: rows.map((row) => /* @__PURE__ */ jsxs("div", {
1793
- className: "space-y-2",
1794
- children: [/* @__PURE__ */ jsx("p", {
1795
- className: "text-xs font-medium",
1796
- children: t(`revisions.fields.${row.path}`, { defaultValue: row.path })
1797
- }), /* @__PURE__ */ jsx("div", {
1798
- className: "grid gap-2 sm:grid-cols-2",
1799
- children: [row.before, row.after].map((value, index) => /* @__PURE__ */ jsxs("div", {
1800
- className: "min-w-0 rounded-control bg-muted/40 p-3",
1801
- children: [/* @__PURE__ */ jsx("p", {
1802
- className: "mb-2 text-xs text-muted-foreground",
1803
- children: t(index === 0 ? "revisions.before" : "revisions.after")
1804
- }), row.path === "avatar" && typeof value === "string" ? /* @__PURE__ */ jsx("img", {
1805
- src: `data:image/png;base64,${value}`,
1806
- alt: t(index === 0 ? "revisions.before" : "revisions.after"),
1807
- className: "size-16 rounded-pill"
1808
- }) : /* @__PURE__ */ jsx("pre", {
1809
- className: "max-h-64 overflow-auto whitespace-pre-wrap break-words text-xs",
1810
- children: typeof value === "string" ? value || "∅" : JSON.stringify(value, null, 2)
1811
- })]
1812
- }, index === 0 ? "before" : "after"))
1813
- })]
1814
- }, row.path))
1815
- });
1816
- return /* @__PURE__ */ jsxs("section", {
1817
- className: "min-h-0 flex-1 space-y-4 overflow-auto px-6 pb-6",
1818
- "aria-label": t("revisions.title"),
1819
- children: [
1820
- /* @__PURE__ */ jsxs("div", {
1821
- className: "flex items-center justify-between",
1822
- children: [/* @__PURE__ */ jsx(Button, {
1823
- variant: "ghost",
1824
- size: "sm",
1825
- onClick: onClose,
1826
- children: t("revisions.back")
1827
- }), /* @__PURE__ */ jsx(Button, {
1828
- variant: "ghost",
1829
- size: "sm",
1830
- disabled: busy,
1831
- onClick: () => void read(),
1832
- children: t("revisions.refresh")
1833
- })]
1834
- }),
1835
- !persistent && /* @__PURE__ */ jsx("p", {
1836
- className: "text-xs text-muted-foreground",
1837
- children: t("revisions.memory")
1838
- }),
1839
- error && /* @__PURE__ */ jsx("p", {
1840
- role: "alert",
1841
- className: "text-sm text-destructive",
1842
- children: error
1843
- }),
1844
- notice && /* @__PURE__ */ jsx("p", {
1845
- role: "status",
1846
- className: "text-sm",
1847
- children: notice
1848
- }),
1849
- busy && /* @__PURE__ */ jsx("p", {
1850
- role: "status",
1851
- className: "text-sm text-muted-foreground",
1852
- children: t("revisions.loading")
1853
- }),
1854
- preview && /* @__PURE__ */ jsxs("div", {
1855
- className: "space-y-4 rounded-control border p-4",
1856
- children: [
1857
- /* @__PURE__ */ jsx("h4", { children: t("revisions.confirm", {
1858
- from: preview.expectedRevision,
1859
- to: preview.targetRevision
1860
- }) }),
1861
- /* @__PURE__ */ jsx("p", {
1862
- className: "text-xs text-muted-foreground",
1863
- children: t("revisions.timing")
1864
- }),
1865
- diff(preview.changes),
1866
- preview.blockers.map((blocker) => /* @__PURE__ */ jsxs("p", {
1867
- className: "text-sm text-destructive",
1868
- children: [
1869
- blocker.path,
1870
- ": ",
1871
- blocker.reason
1872
- ]
1873
- }, blocker.path + blocker.reason)),
1874
- preview.unchanged && /* @__PURE__ */ jsx("p", { children: t("revisions.unchanged") }),
1875
- /* @__PURE__ */ jsxs("div", {
1876
- className: "flex gap-2",
1877
- children: [
1878
- /* @__PURE__ */ jsx(Button, {
1879
- disabled: busy || preview.unchanged || preview.blockers.length > 0,
1880
- onClick: () => void restore(),
1881
- children: t("revisions.restore")
1882
- }),
1883
- /* @__PURE__ */ jsx(Button, {
1884
- variant: "ghost",
1885
- disabled: busy,
1886
- onClick: () => void prepare(preview.targetRevision),
1887
- children: t("revisions.refresh")
1888
- }),
1889
- /* @__PURE__ */ jsx(Button, {
1890
- variant: "ghost",
1891
- disabled: busy,
1892
- onClick: () => {
1893
- setPreview(void 0);
1894
- setRequest(void 0);
1895
- },
1896
- children: t("revisions.cancel")
1897
- })
1898
- ]
2134
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2135
+ /* @__PURE__ */ jsx(ReadFailure, {
2136
+ reason: readError,
2137
+ pending: reading && values === null,
2138
+ onRetry: () => void reload()
2139
+ }),
2140
+ blocked && !reading && /* @__PURE__ */ jsx("p", {
2141
+ role: "alert",
2142
+ className: "text-xs text-destructive",
2143
+ children: t("runSettings.blocked")
2144
+ }),
2145
+ values && /* @__PURE__ */ jsxs("form", {
2146
+ className: "flex flex-col gap-6",
2147
+ onSubmit: (event) => {
2148
+ event.preventDefault();
2149
+ save();
2150
+ },
2151
+ children: [
2152
+ /* @__PURE__ */ jsx("p", {
2153
+ className: "text-xs text-muted-foreground",
2154
+ children: t("runSettings.timing")
2155
+ }),
2156
+ /* @__PURE__ */ jsx(Field, {
2157
+ label: t("runSettings.maxSteps"),
2158
+ required: true,
2159
+ inline: true,
2160
+ error: positive(values.maxSteps) ? void 0 : t("runSettings.positive"),
2161
+ children: (binding) => /* @__PURE__ */ jsx(InputNumber, {
2162
+ ...binding,
2163
+ label: t("runSettings.maxSteps"),
2164
+ incrementLabel: t("common.increase"),
2165
+ decrementLabel: t("common.decrease"),
2166
+ min: 1,
2167
+ step: 1,
2168
+ disabled: saving,
2169
+ value: values.maxSteps || null,
2170
+ onValueChange: (value) => setDraft({
2171
+ ...values,
2172
+ maxSteps: value ?? 0
2173
+ })
2174
+ }, inputKey)
2175
+ }),
2176
+ /* @__PURE__ */ jsx(Field, {
2177
+ label: t("runSettings.budgetEnabled"),
2178
+ inline: true,
2179
+ children: () => /* @__PURE__ */ jsx("div", {
2180
+ className: "flex min-w-0 justify-end",
2181
+ children: /* @__PURE__ */ jsx(Segmented, {
2182
+ label: t("runSettings.budgetEnabled"),
2183
+ value: values.tokenBudget !== void 0 ? "on" : "off",
2184
+ options: [{
2185
+ value: "off",
2186
+ label: t("runSettings.budgetOff")
2187
+ }, {
2188
+ value: "on",
2189
+ label: t("runSettings.budgetOn")
2190
+ }],
2191
+ disabled: saving,
2192
+ onSelect: (value) => setDraft(value === "on" ? {
2193
+ ...values,
2194
+ tokenBudget: 0
2195
+ } : { maxSteps: values.maxSteps })
2196
+ })
2197
+ })
2198
+ }),
2199
+ values.tokenBudget !== void 0 && /* @__PURE__ */ jsx(Field, {
2200
+ label: t("runSettings.tokenBudget"),
2201
+ required: true,
2202
+ inline: true,
2203
+ error: positive(values.tokenBudget) ? void 0 : t("runSettings.positive"),
2204
+ children: (binding) => /* @__PURE__ */ jsx(InputNumber, {
2205
+ ...binding,
2206
+ label: t("runSettings.tokenBudget"),
2207
+ incrementLabel: t("common.increase"),
2208
+ decrementLabel: t("common.decrease"),
2209
+ min: 1,
2210
+ step: 1,
2211
+ disabled: saving,
2212
+ value: values.tokenBudget || null,
2213
+ onValueChange: (value) => setDraft({
2214
+ ...values,
2215
+ tokenBudget: value ?? 0
2216
+ })
2217
+ }, inputKey)
2218
+ }),
2219
+ notice && /* @__PURE__ */ jsx("p", {
2220
+ role: "status",
2221
+ className: "text-xs text-muted-foreground",
2222
+ children: t("runSettings.changed")
2223
+ }),
2224
+ /* @__PURE__ */ jsx(FormFailure, { reason: saveError }),
2225
+ uncertain.current && saved && readError === null && !reading && /* @__PURE__ */ jsx("p", {
2226
+ className: "text-xs text-muted-foreground",
2227
+ children: t("runSettings.current", {
2228
+ steps: saved.maxSteps,
2229
+ budget: saved.tokenBudget ?? t("runSettings.unlimited")
2230
+ })
2231
+ }),
2232
+ /* @__PURE__ */ jsx("div", {
2233
+ className: "flex justify-end",
2234
+ children: /* @__PURE__ */ jsx(Button, {
2235
+ variant: "primary",
2236
+ type: "submit",
2237
+ loading: saving,
2238
+ disabled: !online || reading || readError !== null || !positive(values.maxSteps) || values.tokenBudget !== void 0 && !positive(values.tokenBudget),
2239
+ children: t("common.save")
1899
2240
  })
1900
- ]
1901
- }),
1902
- /* @__PURE__ */ jsx("ol", {
1903
- className: "divide-y",
1904
- children: items.map((item) => {
1905
- const expanded = selected === item.revision;
1906
- const canExpand = items.length > 1 || item.revision !== current || !!item.source.sessionId;
1907
- const heading = /* @__PURE__ */ jsxs("span", {
1908
- className: "min-w-0 flex-1 space-y-1",
1909
- children: [/* @__PURE__ */ jsxs("span", {
1910
- className: "block text-sm font-medium break-words",
1911
- children: [
1912
- "v",
1913
- item.revision,
1914
- " · ",
1915
- item.summary
1916
- ]
1917
- }), /* @__PURE__ */ jsxs("span", {
1918
- className: "block text-xs text-muted-foreground",
1919
- children: [
1920
- new Date(item.createdAt).toLocaleString(i18n.language),
1921
- " ·",
1922
- " ",
1923
- t(`revisions.${item.source.kind}`)
1924
- ]
1925
- })]
1926
- });
1927
- const currentMark = item.revision === current && /* @__PURE__ */ jsx("span", {
1928
- className: "shrink-0 rounded-control bg-muted px-2 py-1 text-xs text-muted-foreground",
1929
- children: t("revisions.current")
1930
- });
1931
- return /* @__PURE__ */ jsxs("li", {
1932
- className: "py-2",
1933
- children: [canExpand ? /* @__PURE__ */ jsxs(Button, {
1934
- variant: "plain",
1935
- "aria-expanded": expanded,
1936
- className: "flex w-full items-center gap-3 rounded-control p-3 text-start hover:bg-muted/50 focus-visible:ring-2 focus-visible:ring-ring",
1937
- onClick: () => {
1938
- setSelected(expanded ? void 0 : item.revision);
1939
- setCompareTo(item.revision === current ? items.find((option) => option.revision !== item.revision)?.revision : current);
1940
- },
1941
- children: [
1942
- heading,
1943
- currentMark,
1944
- /* @__PURE__ */ jsx(ChevronDown, {
1945
- "aria-hidden": "true",
1946
- className: `size-4 shrink-0 text-muted-foreground transition-transform ${expanded ? "rotate-180" : ""}`
1947
- })
1948
- ]
1949
- }) : /* @__PURE__ */ jsxs("div", {
1950
- className: "flex items-center gap-3 p-3",
1951
- children: [heading, currentMark]
1952
- }), expanded && /* @__PURE__ */ jsxs("div", {
1953
- className: "space-y-4 px-3 pt-3 pb-2",
1954
- children: [compareTo !== void 0 && compareTo !== item.revision && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("label", {
1955
- className: "flex flex-wrap items-center gap-2 text-xs text-muted-foreground",
1956
- children: [
1957
- t("revisions.compare"),
1958
- " · v",
1959
- item.revision,
1960
- " →",
1961
- /* @__PURE__ */ jsx(Select, {
1962
- size: "sm",
1963
- "aria-label": t("revisions.compare"),
1964
- value: String(compareTo),
1965
- onValueChange: (value) => setCompareTo(Number(value)),
1966
- children: items.filter((option) => option.revision !== item.revision).map((option) => /* @__PURE__ */ jsxs("option", {
1967
- value: option.revision,
1968
- children: ["v", option.revision]
1969
- }, option.revision))
1970
- })
1971
- ]
1972
- }), comparing ? /* @__PURE__ */ jsx("p", {
1973
- role: "status",
1974
- className: "text-xs text-muted-foreground",
1975
- children: t("revisions.loading")
1976
- }) : comparisonError ? /* @__PURE__ */ jsx("p", {
1977
- role: "alert",
1978
- className: "text-xs text-destructive",
1979
- children: comparisonError
1980
- }) : changes.length === 0 ? /* @__PURE__ */ jsx("p", {
1981
- className: "text-xs text-muted-foreground",
1982
- children: t("revisions.noDifference")
1983
- }) : diff(changes)] }), /* @__PURE__ */ jsxs("div", {
1984
- className: "flex flex-wrap gap-2",
1985
- children: [item.revision !== current && /* @__PURE__ */ jsx(Button, {
1986
- variant: "outline",
1987
- size: "sm",
1988
- disabled: busy,
1989
- onClick: () => void prepare(item.revision),
1990
- children: t("revisions.restore")
1991
- }), item.source.sessionId && /* @__PURE__ */ jsx(Button, {
1992
- variant: "ghost",
1993
- size: "sm",
1994
- onClick: async () => {
1995
- if (beforeLeave && !await beforeLeave()) return;
1996
- if (!await goToSession(client, item.source.sessionId)) setError(t("revisions.sourceMissing"));
1997
- else useNavigation.getState().openSettings(false);
1998
- },
1999
- children: t("revisions.source")
2000
- })]
2001
- })]
2002
- })]
2003
- }, item.revision);
2004
2241
  })
2005
- }),
2006
- cursor && /* @__PURE__ */ jsx(Button, {
2007
- variant: "ghost",
2008
- disabled: busy,
2009
- onClick: () => void read(cursor),
2010
- children: t("revisions.more")
2011
- })
2012
- ]
2013
- });
2242
+ ]
2243
+ })
2244
+ ] });
2014
2245
  }
2015
2246
  //#endregion
2016
- //#region ui-src/components/settings/agent/tools.tsx
2017
- /** Uses extension metadata without interpreting package names or tool naming conventions. */
2018
- function groupsOf(tools, describe, unknownSource) {
2019
- const groups = /* @__PURE__ */ new Map();
2020
- for (const tool of tools) {
2021
- const facts = describe(tool) ?? {
2022
- key: `plugin:${tool.plugin}`,
2023
- label: tool.plugin || unknownSource,
2024
- source: tool.plugin || unknownSource,
2025
- sectionLabel: unknownSource,
2026
- sectionOrder: 2,
2027
- order: 0
2028
- };
2029
- const group = groups.get(facts.key) ?? {
2030
- ...facts,
2031
- tools: []
2032
- };
2033
- groups.set(facts.key, {
2034
- ...group,
2035
- tools: [...group.tools, tool]
2036
- });
2037
- }
2038
- return [...groups.values()].map((group) => ({
2039
- ...group,
2040
- tools: [...group.tools].sort((a, b) => a.name.localeCompare(b.name))
2041
- })).sort((a, b) => a.sectionOrder - b.sectionOrder || a.order - b.order || a.label.localeCompare(b.label));
2247
+ //#region ui-src/components/settings/run-settings.tsx
2248
+ /** Fixed global running-settings entrance owned by Agent management. */
2249
+ function RunSettingsButton({ ctx }) {
2250
+ const { t } = useTranslation();
2251
+ const [open, setOpen] = useState(false);
2252
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(TooltipHint, {
2253
+ content: t("runSettings.title"),
2254
+ children: /* @__PURE__ */ jsx(Button, {
2255
+ variant: "plain",
2256
+ size: "sm",
2257
+ icon: "settings",
2258
+ "aria-label": t("runSettings.title"),
2259
+ onClick: () => setOpen(true)
2260
+ })
2261
+ }), open && /* @__PURE__ */ jsx(RunSettingsDialog, {
2262
+ ctx,
2263
+ onClose: () => setOpen(false)
2264
+ })] });
2042
2265
  }
2043
- function SelectAll({ group, chosen, onChange }) {
2266
+ /** One retained page per live owner, with a shared close guard and independent saves. */
2267
+ function RunSettingsDialog({ ctx, onClose }) {
2044
2268
  const { t } = useTranslation();
2045
- const count = group.tools.filter((tool) => chosen.has(tool.name)).length;
2046
- return /* @__PURE__ */ jsx(Checkbox, {
2047
- "aria-label": t("agents.toolSettings.selectAll", { group: group.label }),
2048
- title: t("agents.toolSettings.selectWholeGroup", { count: group.tools.length }),
2049
- checked: count === group.tools.length,
2050
- ref: (element) => {
2051
- if (element) element.indeterminate = count > 0 && count < group.tools.length;
2269
+ const state = usePlugins((state) => state);
2270
+ const pages = contributionsIn(state, "shell.agentRunSettings.section");
2271
+ const [selected, setSelected] = useState("execution");
2272
+ const shown = selected === "execution" || pages.some((page) => page.key === selected) ? selected : "execution";
2273
+ useEffect(() => {
2274
+ if (shown !== selected) setSelected(shown);
2275
+ }, [shown, selected]);
2276
+ const guards = useRef(/* @__PURE__ */ new Map());
2277
+ const register = useCallback((key, guard) => {
2278
+ if (guard) guards.current.set(key, guard);
2279
+ else guards.current.delete(key);
2280
+ }, []);
2281
+ const labels = new Map([["execution", t("runSettings.execution")], ...pages.map((page) => [page.key, resolveLabel(page.contribution.label, page.key)])]);
2282
+ const [asking, setAsking] = useState(null);
2283
+ const requestClose = () => {
2284
+ const valid = [...guards.current].filter(([key]) => labels.has(key));
2285
+ if (valid.some(([, guard]) => guard().pending)) return;
2286
+ const dirty = valid.filter(([, guard]) => guard().dirty).map(([key]) => key);
2287
+ if (dirty.length > 0) setAsking(dirty);
2288
+ else onClose();
2289
+ };
2290
+ const executionGuard = useCallback((guard) => register("execution", guard), [register]);
2291
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Dialog, {
2292
+ open: true,
2293
+ onOpenChange: (next) => {
2294
+ if (!next) requestClose();
2052
2295
  },
2053
- onChange: (event) => onChange(group.tools.map((tool) => tool.name), event.target.checked),
2054
- className: "shrink-0"
2055
- });
2056
- }
2057
- function ToolRow({ tool, checked, onChange }) {
2058
- const describedBy = useId();
2059
- return /* @__PURE__ */ jsx("li", {
2060
- className: "border-t border-border/60 first:border-t-0",
2061
- children: /* @__PURE__ */ jsxs("label", {
2062
- className: "flex min-w-0 cursor-pointer items-start gap-2.5 px-3 py-2 hover:bg-muted/50",
2063
- children: [/* @__PURE__ */ jsx(Checkbox, {
2064
- "aria-label": tool.name,
2065
- "aria-describedby": tool.description ? describedBy : void 0,
2066
- checked,
2067
- onChange: (event) => onChange(event.target.checked),
2068
- className: "mt-0.5 shrink-0"
2069
- }), /* @__PURE__ */ jsxs("span", {
2070
- className: "flex min-w-0 flex-1 flex-col gap-0.5 @lg:flex-row @lg:items-baseline @lg:gap-3",
2071
- children: [/* @__PURE__ */ jsx("span", {
2072
- className: "min-w-0 shrink-0 break-all font-mono text-xs text-foreground @lg:w-40",
2073
- children: tool.name
2074
- }), tool.description && /* @__PURE__ */ jsx("span", {
2075
- id: describedBy,
2076
- "data-slot": "tool-description",
2077
- title: tool.description,
2078
- className: "line-clamp-2 min-w-0 flex-1 text-xs text-muted-foreground @lg:line-clamp-1",
2079
- children: tool.description
2080
- })]
2296
+ children: /* @__PURE__ */ jsxs(DialogContent, {
2297
+ closeLabel: t("settings.close"),
2298
+ overlayProps: {
2299
+ forceRender: true,
2300
+ className: "file-picker-backdrop"
2301
+ },
2302
+ className: "@container max-w-md gap-5 p-6 sm:max-w-md",
2303
+ children: [/* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("runSettings.title") }) }), /* @__PURE__ */ jsxs(Tabs, {
2304
+ value: shown,
2305
+ onValueChange: (next) => setSelected(String(next)),
2306
+ children: [
2307
+ /* @__PURE__ */ jsxs(TabsList, {
2308
+ "aria-label": t("runSettings.title"),
2309
+ className: "mb-5 w-full",
2310
+ children: [/* @__PURE__ */ jsx(TabsTrigger, {
2311
+ value: "execution",
2312
+ children: t("runSettings.execution")
2313
+ }), pages.map((page) => /* @__PURE__ */ jsx(TabsTrigger, {
2314
+ value: page.key,
2315
+ "data-plugin": page.owner,
2316
+ children: labels.get(page.key)
2317
+ }, page.key))]
2318
+ }),
2319
+ /* @__PURE__ */ jsx(TabsContent, {
2320
+ value: "execution",
2321
+ keepMounted: true,
2322
+ children: /* @__PURE__ */ jsx(ExecutionLimits, {
2323
+ ctx,
2324
+ registerGuard: executionGuard,
2325
+ requestClose
2326
+ })
2327
+ }),
2328
+ pages.map((page) => /* @__PURE__ */ jsx(TabsContent, {
2329
+ value: page.key,
2330
+ keepMounted: true,
2331
+ children: /* @__PURE__ */ jsx(OwnerSection, {
2332
+ registrationKey: page.key,
2333
+ register,
2334
+ requestClose
2335
+ })
2336
+ }, page.key))
2337
+ ]
2081
2338
  })]
2082
2339
  })
2083
- });
2340
+ }), /* @__PURE__ */ jsxs(AlertDialog, {
2341
+ open: asking !== null,
2342
+ onOpenChange: (next) => {
2343
+ if (!next) setAsking(null);
2344
+ },
2345
+ title: t("agents.leaveTitle"),
2346
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
2347
+ variant: "ghost",
2348
+ onClick: () => setAsking(null),
2349
+ children: t("agents.leaveStay")
2350
+ }), /* @__PURE__ */ jsx(Button, {
2351
+ variant: "destructive",
2352
+ onClick: onClose,
2353
+ children: t("agents.discard")
2354
+ })] }),
2355
+ children: [/* @__PURE__ */ jsx("p", { children: t("agents.leaveBody") }), /* @__PURE__ */ jsx("ul", {
2356
+ className: "list-disc ps-5",
2357
+ children: asking?.filter((key) => labels.has(key)).map((key) => /* @__PURE__ */ jsx("li", { children: labels.get(key) }, key))
2358
+ })]
2359
+ })] });
2084
2360
  }
2085
- /** Tool access tab; selection changes stay in the shared agent editor draft. */
2086
- function ToolsTab() {
2087
- const { t } = useTranslation();
2088
- const editor = useAgentEditor();
2089
- const { agent } = editor;
2090
- const listing = useGatewayRead("config.tool.list", { agentId: agent.agentId });
2091
- const tools = listing.data?.agentId === agent.agentId ? listing.data.tools : null;
2092
- const whitelist = editor.value("tools");
2093
- const unrestricted = whitelist === null;
2094
- const chosen = new Set(unrestricted ? [] : whitelist);
2095
- const known = new Set((tools ?? []).map((tool) => tool.name));
2096
- const unavailable = unrestricted ? [] : whitelist.filter((name) => !known.has(name));
2097
- const [query, setQuery] = useState("");
2098
- const [filter, setFilter] = useState("all");
2099
- const [expanded, setExpanded] = useState(/* @__PURE__ */ new Set());
2100
- const [collapsed, setCollapsed] = useState(/* @__PURE__ */ new Set());
2101
- const pluginState = usePlugins((state) => state);
2102
- const presentations = contributionsIn(pluginState, "shell.tools.group");
2103
- const groups = groupsOf(tools ?? [], (tool) => presentations.map((one) => one.contribution.describe(tool)).find((value) => value !== void 0), t("agents.toolSettings.unknownSource"));
2104
- const search = query.trim().toLocaleLowerCase();
2105
- const visible = groups.map((group) => ({
2106
- group,
2107
- tools: group.tools.filter((tool) => (!search || [
2108
- tool.name,
2109
- tool.description,
2110
- group.label,
2111
- group.source
2112
- ].some((value) => value.toLocaleLowerCase().includes(search))) && (filter === "all" || filter === "selected" === chosen.has(tool.name)))
2113
- })).filter(({ tools: members }) => members.length > 0);
2114
- const matching = visible.reduce((total, one) => total + one.tools.length, 0);
2115
- const allExpanded = visible.every(({ group }) => expanded.has(group.key) || group.defaultExpanded === true && !collapsed.has(group.key));
2116
- function change(names, on) {
2117
- if (whitelist === null) return;
2118
- const without = whitelist.filter((name) => !names.includes(name));
2119
- editor.set("tools", on ? [...without, ...names] : without);
2120
- }
2121
- function toggle(key) {
2122
- const next = new Set(expanded);
2123
- const isOpen = next.has(key) || groups.find((one) => one.key === key)?.defaultExpanded === true && !collapsed.has(key);
2124
- const hidden = new Set(collapsed);
2125
- if (isOpen) {
2126
- next.delete(key);
2127
- hidden.add(key);
2128
- } else {
2129
- next.add(key);
2130
- hidden.delete(key);
2361
+ function OwnerSection({ registrationKey, register, requestClose }) {
2362
+ const registerGuard = useCallback((guard) => register(registrationKey, guard), [registrationKey, register]);
2363
+ useEffect(() => () => registerGuard(null), [registerGuard]);
2364
+ return /* @__PURE__ */ jsx(SlotOutlet, {
2365
+ slot: "shell.agentRunSettings.section",
2366
+ only: registrationKey,
2367
+ props: {
2368
+ registerGuard,
2369
+ requestClose
2131
2370
  }
2132
- setCollapsed(hidden);
2133
- setExpanded(next);
2134
- }
2135
- return /* @__PURE__ */ jsxs("div", {
2136
- className: "@container flex min-w-0 flex-col gap-4",
2137
- children: [
2138
- /* @__PURE__ */ jsx(ChangedElsewhere, { fields: ["tools"] }),
2139
- /* @__PURE__ */ jsxs("div", {
2140
- className: "flex min-w-0 flex-col gap-3 @lg:flex-row @lg:items-start @lg:justify-between",
2141
- children: [/* @__PURE__ */ jsxs("div", {
2142
- className: "min-w-0",
2143
- children: [/* @__PURE__ */ jsx("h3", {
2144
- className: "text-sm font-semibold",
2145
- children: t("agents.toolSettings.heading")
2146
- }), /* @__PURE__ */ jsx("p", {
2147
- className: "mt-1 text-xs leading-relaxed text-muted-foreground",
2148
- children: t("agents.toolSettings.hint")
2149
- })]
2150
- }), /* @__PURE__ */ jsx(Segmented, {
2151
- label: t("agents.toolSettings.mode"),
2152
- value: unrestricted ? "all" : "custom",
2153
- disabled: tools === null && unrestricted,
2154
- options: [{
2155
- value: "custom",
2156
- label: t("agents.toolSettings.custom")
2157
- }, {
2158
- value: "all",
2159
- label: t("agents.toolSettings.allowAll")
2160
- }],
2161
- onSelect: (mode) => editor.set("tools", mode === "all" ? null : (tools ?? []).filter((tool) => tool.permitted).map((tool) => tool.name))
2162
- })]
2163
- }),
2164
- /* @__PURE__ */ jsx(ReadFailure, {
2165
- reason: listing.error,
2166
- pending: listing.pending && listing.data === null,
2167
- onRetry: listing.reload
2168
- }),
2169
- !unrestricted && /* @__PURE__ */ jsxs(Fragment, { children: [
2170
- /* @__PURE__ */ jsx("div", {
2171
- "data-slot": "tool-search-divider",
2172
- className: "border-t border-border"
2173
- }),
2174
- /* @__PURE__ */ jsxs("div", {
2175
- className: "flex min-w-0 flex-col gap-2 @lg:flex-row @lg:items-center",
2176
- children: [/* @__PURE__ */ jsxs("label", {
2177
- className: "flex min-w-0 flex-1 items-center gap-2 rounded-control border border-border bg-input/30 px-2.5 focus-within:border-ring",
2178
- children: [/* @__PURE__ */ jsx(Search, {
2179
- className: "size-4 shrink-0 text-muted-foreground",
2180
- "aria-hidden": "true"
2181
- }), /* @__PURE__ */ jsx(Input, {
2182
- type: "search",
2183
- "aria-label": t("agents.toolSettings.searchLabel"),
2184
- placeholder: t("agents.toolSettings.searchPlaceholder"),
2185
- value: query,
2186
- onChange: (event) => setQuery(event.target.value),
2187
- className: "h-8 min-w-0 flex-1 border-0 bg-transparent text-xs outline-none focus-visible:border-0 placeholder:text-muted-foreground"
2188
- })]
2189
- }), /* @__PURE__ */ jsx(FilterChips, {
2190
- label: t("agents.toolSettings.filterLabel"),
2191
- value: filter,
2192
- options: [
2193
- {
2194
- value: "all",
2195
- label: t("agents.toolSettings.filterAll")
2196
- },
2197
- {
2198
- value: "selected",
2199
- label: t("agents.toolSettings.filterSelected")
2200
- },
2201
- {
2202
- value: "unselected",
2203
- label: t("agents.toolSettings.filterUnselected")
2204
- }
2205
- ],
2206
- onSelect: (value) => setFilter(value)
2207
- })]
2208
- }),
2209
- whitelist.length === 0 && /* @__PURE__ */ jsx(Warning, { children: t("agents.toolSettings.none") }),
2210
- tools !== null && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("div", {
2211
- className: "flex items-center gap-2 text-xs text-muted-foreground",
2212
- children: [
2213
- /* @__PURE__ */ jsx("span", { children: t("agents.toolSettings.chosen", {
2214
- chosen: tools.filter((tool) => chosen.has(tool.name)).length,
2215
- total: tools.length
2216
- }) }),
2217
- (search || filter !== "all") && /* @__PURE__ */ jsx("span", { children: t("agents.toolSettings.matching", { count: matching }) }),
2218
- visible.length > 0 && !search && filter === "all" && /* @__PURE__ */ jsx(Button, {
2219
- variant: "ghost",
2220
- size: "sm",
2221
- className: "ms-auto h-7 text-xs",
2222
- onClick: () => {
2223
- setExpanded(allExpanded ? /* @__PURE__ */ new Set() : new Set(groups.map((group) => group.key)));
2224
- setCollapsed(allExpanded ? new Set(groups.map((group) => group.key)) : /* @__PURE__ */ new Set());
2225
- },
2226
- children: t(allExpanded ? "agents.toolSettings.collapseAll" : "agents.toolSettings.expandAll")
2227
- })
2228
- ]
2229
- }), /* @__PURE__ */ jsxs("div", {
2230
- "data-slot": "tool-list",
2231
- className: "flex min-w-0 flex-col gap-3",
2232
- children: [
2233
- tools.length === 0 && unavailable.length === 0 && /* @__PURE__ */ jsx("p", {
2234
- className: "text-xs text-muted-foreground",
2235
- children: t("agents.toolsEmpty")
2236
- }),
2237
- matching === 0 && tools.length > 0 && /* @__PURE__ */ jsxs("div", {
2238
- className: "flex flex-col items-center gap-2 py-6 text-center text-xs text-muted-foreground",
2239
- children: [/* @__PURE__ */ jsx("p", { children: t("agents.toolSettings.noMatches") }), /* @__PURE__ */ jsx(Button, {
2240
- variant: "outline",
2241
- size: "sm",
2242
- onClick: () => {
2243
- setQuery("");
2244
- setFilter("all");
2245
- },
2246
- children: t("agents.toolSettings.clearFilters")
2247
- })]
2248
- }),
2249
- visible.map(({ group, tools: members }, index) => {
2250
- const forcedOpen = Boolean(search || filter !== "all");
2251
- const open = forcedOpen || expanded.has(group.key) || group.defaultExpanded === true && !collapsed.has(group.key);
2252
- const count = group.tools.filter((tool) => chosen.has(tool.name)).length;
2253
- const previous = visible[index - 1]?.group.sectionOrder;
2254
- return /* @__PURE__ */ jsxs("div", { children: [group.sectionOrder !== previous && /* @__PURE__ */ jsx("p", {
2255
- className: "mb-2 text-xs text-muted-foreground",
2256
- children: group.sectionLabel
2257
- }), /* @__PURE__ */ jsxs("section", {
2258
- "aria-label": group.label,
2259
- "data-slot": "tool-group",
2260
- className: "min-w-0 overflow-hidden rounded-control border border-border",
2261
- children: [/* @__PURE__ */ jsxs("header", {
2262
- className: "flex min-w-0 items-center gap-2 px-3 py-2",
2263
- children: [/* @__PURE__ */ jsx(SelectAll, {
2264
- group,
2265
- chosen,
2266
- onChange: change
2267
- }), /* @__PURE__ */ jsxs(Button, {
2268
- variant: "plain",
2269
- "aria-label": t(open ? "agents.toolSettings.collapse" : "agents.toolSettings.expand", { group: group.label }),
2270
- "aria-expanded": open,
2271
- disabled: forcedOpen,
2272
- onClick: () => toggle(group.key),
2273
- className: "flex min-w-0 flex-1 items-center gap-2 text-start disabled:opacity-100",
2274
- children: [
2275
- /* @__PURE__ */ jsx("span", {
2276
- className: "min-w-0 truncate text-xs font-medium",
2277
- children: group.label
2278
- }),
2279
- /* @__PURE__ */ jsx("span", {
2280
- className: "min-w-0 truncate font-mono text-2xs text-muted-foreground",
2281
- children: group.source
2282
- }),
2283
- /* @__PURE__ */ jsxs("span", {
2284
- "data-slot": "tool-group-count",
2285
- className: "ms-auto shrink-0 text-2xs tabular-nums text-muted-foreground",
2286
- children: [
2287
- count,
2288
- "/",
2289
- group.tools.length
2290
- ]
2291
- }),
2292
- /* @__PURE__ */ jsx(ChevronDown, { className: cn("size-4 shrink-0 text-muted-foreground transition-transform", open && "rotate-180") })
2293
- ]
2294
- })]
2295
- }), open && /* @__PURE__ */ jsx("ul", {
2296
- className: "border-t border-border",
2297
- children: members.map((tool) => /* @__PURE__ */ jsx(ToolRow, {
2298
- tool,
2299
- checked: chosen.has(tool.name),
2300
- onChange: (on) => change([tool.name], on)
2301
- }, tool.name))
2302
- })]
2303
- })] }, group.key);
2304
- }),
2305
- unavailable.length > 0 && !search && filter !== "unselected" && /* @__PURE__ */ jsxs("section", {
2306
- "aria-label": t("agents.toolSettings.unavailable"),
2307
- "data-slot": "tool-unavailable",
2308
- className: "rounded-control border border-dashed border-border px-3 py-2",
2309
- children: [
2310
- /* @__PURE__ */ jsx("h4", {
2311
- className: "text-xs font-medium",
2312
- children: t("agents.toolSettings.unavailable")
2313
- }),
2314
- /* @__PURE__ */ jsx("p", {
2315
- className: "mt-1 text-2xs text-muted-foreground",
2316
- children: t("agents.toolSettings.unavailableHint")
2317
- }),
2318
- /* @__PURE__ */ jsx("ul", {
2319
- className: "mt-2 flex flex-col gap-1",
2320
- children: unavailable.map((name) => /* @__PURE__ */ jsxs("li", {
2321
- className: "flex min-w-0 items-center gap-2",
2322
- children: [/* @__PURE__ */ jsx("span", {
2323
- className: "min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground line-through",
2324
- children: name
2325
- }), /* @__PURE__ */ jsx(Button, {
2326
- size: "sm",
2327
- variant: "ghost",
2328
- "aria-label": `${t("common.remove")} ${name}`,
2329
- onClick: () => change([name], false),
2330
- children: t("common.remove")
2331
- })]
2332
- }, name))
2333
- })
2334
- ]
2335
- })
2336
- ]
2337
- })] })
2338
- ] }),
2339
- /* @__PURE__ */ jsx(FormFailure, { reason: editor.error("tools") })
2340
- ]
2341
2371
  });
2342
2372
  }
2343
2373
  //#endregion
@@ -2853,6 +2883,7 @@ function DirectChatToggle({ agent, onChanged }) {
2853
2883
  function RemoveAgentButton({ agent, onRemoved }) {
2854
2884
  const { t } = useTranslation();
2855
2885
  const remove = useGatewayAction();
2886
+ const operationId = useRef(uuid());
2856
2887
  const [asking, setAsking] = useState(false);
2857
2888
  return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsx(TooltipTrigger, {
2858
2889
  "aria-label": `${t("agents.remove")} ${agent.name}`,
@@ -2886,7 +2917,14 @@ function RemoveAgentButton({ agent, onRemoved }) {
2886
2917
  variant: "destructive",
2887
2918
  disabled: remove.pending,
2888
2919
  onClick: () => {
2889
- remove.run((client) => client.call("config.agent.remove", { agentId: agent.agentId })).then((done) => {
2920
+ remove.run(async (client) => {
2921
+ const result = await client.call("config.agent.remove", {
2922
+ operationId: operationId.current,
2923
+ agentIds: [agent.agentId]
2924
+ });
2925
+ if (result.operationState === "admitted") throw new Error(t("common.working"));
2926
+ return result;
2927
+ }).then((done) => {
2890
2928
  if (!done.ok) return;
2891
2929
  setAsking(false);
2892
2930
  onRemoved();