@morlay/session-mode 0.0.0-stage → 0.2.0-alpha.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 (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +85 -2
  3. package/dist/endpoint.d.mts +2 -0
  4. package/dist/endpoint.mjs +3 -0
  5. package/dist/index.d.mts +691 -0
  6. package/dist/index.mjs +2350 -0
  7. package/dist/mode-config-BIYT66jI.mjs +22 -0
  8. package/dist/mode-config-rules-z4gdHLR1.mjs +52 -0
  9. package/dist/rolldown-runtime-3qf6kE1h.d.mts +1 -0
  10. package/dist/server.d.mts +2 -0
  11. package/dist/server.mjs +1 -0
  12. package/dist/session-mode-endpoint-CLpvSnzM.d.mts +120 -0
  13. package/dist/session-mode-endpoint-Dq-E_kHt.mjs +53 -0
  14. package/dist/session-mode-endpoint.service-Bn4EH6aB.d.mts +21 -0
  15. package/dist/session-mode-endpoint.service-MrqQipN6.mjs +79 -0
  16. package/dist/testing.d.mts +12 -0
  17. package/dist/testing.mjs +23 -0
  18. package/dist/ui.d.mts +125 -0
  19. package/dist/ui.mjs +1165 -0
  20. package/package.json +63 -3
  21. package/src/context-assembler.provide.ts +139 -0
  22. package/src/context-assembler.service.ts +67 -0
  23. package/src/contract/context-assembler.contract.ts +30 -0
  24. package/src/contract/index.ts +3 -0
  25. package/src/contract/session-mode.contract.ts +104 -0
  26. package/src/contract/session-scope.contract.ts +53 -0
  27. package/src/defaults.ts +39 -0
  28. package/src/endpoint/index.ts +6 -0
  29. package/src/endpoint/mode-config-rules.ts +59 -0
  30. package/src/endpoint/mode-config.ts +58 -0
  31. package/src/endpoint/session-mode-endpoint.ts +121 -0
  32. package/src/endpoint/session-mode-shapes.ts +71 -0
  33. package/src/endpoint/tool-group-ref.ts +11 -0
  34. package/src/events.ts +102 -0
  35. package/src/guidance/groups.ts +101 -0
  36. package/src/guidance/index.ts +4 -0
  37. package/src/guidance/packs/ask.ts +17 -0
  38. package/src/guidance/packs/code.ts +25 -0
  39. package/src/guidance/packs/fs.ts +60 -0
  40. package/src/guidance/packs/index.ts +52 -0
  41. package/src/guidance/packs/mcp.ts +25 -0
  42. package/src/guidance/packs/plan.ts +42 -0
  43. package/src/guidance/packs/shell.ts +45 -0
  44. package/src/guidance/packs/skill.ts +12 -0
  45. package/src/guidance/packs/swarm.ts +60 -0
  46. package/src/guidance/packs/web-access.ts +24 -0
  47. package/src/guidance/tool-groups.ts +72 -0
  48. package/src/guidance/types.ts +29 -0
  49. package/src/index.ts +63 -0
  50. package/src/mode-sources.ts +83 -0
  51. package/src/mode-store.ts +45 -0
  52. package/src/modes.ts +126 -0
  53. package/src/per-agent-rows.ts +62 -0
  54. package/src/per-agent.ts +36 -0
  55. package/src/persona.ts +30 -0
  56. package/src/ptc-describe.ts +136 -0
  57. package/src/ptc-sdk.ts +101 -0
  58. package/src/reminder.ts +89 -0
  59. package/src/rules.ts +8 -0
  60. package/src/server/index.ts +7 -0
  61. package/src/server/session-mode-endpoint.service.ts +117 -0
  62. package/src/session-mode-store.ts +218 -0
  63. package/src/session-mode.projection.ts +78 -0
  64. package/src/session-mode.provide.ts +38 -0
  65. package/src/session-mode.service.ts +670 -0
  66. package/src/session-scope.service.ts +515 -0
  67. package/src/subagent/delegation-context.ts +30 -0
  68. package/src/subagent/return-guidance.ts +56 -0
  69. package/src/subagent/subagent-guidance.service.ts +76 -0
  70. package/src/subagent.provide.ts +5 -0
  71. package/src/system-remainder.ts +43 -0
  72. package/src/testing/index.ts +34 -0
  73. package/src/tool-guidance.service.ts +265 -0
  74. package/src/ui/index.ts +12 -0
  75. package/src/ui/locales.ts +134 -0
  76. package/src/ui/session-mode-endpoint.client.ts +19 -0
  77. package/src/ui/session-mode-locales.contribution.ts +51 -0
  78. package/src/ui/session-mode-panel-tab.ts +39 -0
  79. package/src/ui/session-mode-panel.view.tsx +931 -0
  80. package/src/ui/session-mode-seat.view.tsx +174 -0
  81. package/src/ui/session-mode-slots.ts +13 -0
  82. package/src/ui/session-mode.provide.ts +24 -0
  83. package/src/ui/session-mode.store.ts +90 -0
  84. package/src/ui/use-roster.ts +24 -0
  85. package/src/ui/view-props.ts +19 -0
@@ -0,0 +1,931 @@
1
+ // 右栏面板:这个会话**选中的模式**与它当下生效的那一份。
2
+ //
3
+ // 折叠组对齐上游右栏内容(20/24/40 内边距、整列滚动),一次只开一组;工具 / 技能 / policy 用
4
+ // 「默认 / 允许 / 禁止」三态切换(工具按组折叠、组内逐条);每项标出来源(会话覆盖 / 模式默认),
5
+ // 被覆盖的项旁给「恢复默认」——它发的是 `setModePatch(id, null)`,只清这个字段的会话覆盖。
6
+ import { useEffect, useRef, useState, type ReactNode } from "react";
7
+ import { inject } from "@morlay/zephyr";
8
+ import { SlotView } from "@morlay/zephyr-app/client";
9
+ import {
10
+ Button,
11
+ IconChevronDownOutlineRegular,
12
+ Menu,
13
+ MenuItemButton,
14
+ Modal,
15
+ MultilineField,
16
+ Row,
17
+ SegmentedControl,
18
+ Stack,
19
+ Switch,
20
+ Text,
21
+ } from "@morlay/zephyr-ui";
22
+ import { applyDraft, type ModeDraft } from "../endpoint/mode-config-rules.ts";
23
+ import type { ModeConfig } from "../endpoint/mode-config.ts";
24
+ import type {
25
+ SessionModeActiveState,
26
+ SessionModeDirectoryEntry,
27
+ SessionModeTriState,
28
+ } from "../endpoint/session-mode-shapes.ts";
29
+ import { groupRef } from "../endpoint/tool-group-ref.ts";
30
+ import { zh, type SessionModeLocaleKey } from "./locales.ts";
31
+ import {
32
+ SessionModeLocales,
33
+ type SessionModeTranslate,
34
+ } from "./session-mode-locales.contribution.ts";
35
+ import { PANEL_ID, SidebarRightPaneTabSlot } from "./session-mode-slots.ts";
36
+ import { SessionModeStore } from "./session-mode.store.ts";
37
+ import { viewPropsOf, type SessionModeViewProps } from "./view-props.ts";
38
+
39
+ // 名单字段按「工具 / 技能 / policy」三对归拢:条目的「恢复默认」要清的是它所在的那一份名单。
40
+ const LIST_FIELDS = {
41
+ tools: { allow: "allowTools", deny: "denyTools" },
42
+ skills: { allow: "allowSkills", deny: "denySkills" },
43
+ policies: { allow: "allowPolicies", deny: "denyPolicies" },
44
+ } as const;
45
+
46
+ // 失败原因:`Error` 取 message,其它(wire 上常是字符串)直接转。
47
+ function messageOf(cause: unknown): string {
48
+ return cause instanceof Error ? cause.message : String(cause);
49
+ }
50
+
51
+ // 纯展示组件在测试里也是直接渲染的(不经容器),所以翻译座缺省取中文那份字典:
52
+ // 装配期由容器注入 `locales.t()`,单测里不装 Locale 服务也有文案。
53
+ const fallbackTranslate: SessionModeTranslate = (key: SessionModeLocaleKey) => zh[key];
54
+
55
+ // 右栏内容容器:整列滚动,20/24/40 的内边距。
56
+ const PANEL_STYLE = {
57
+ height: "100%",
58
+ overflowY: "auto",
59
+ boxSizing: "border-box",
60
+ padding: "20px 24px 40px",
61
+ } as const;
62
+
63
+ type SectionKey = "general" | "persona" | "tools" | "skills" | "policies";
64
+
65
+ // 三态之外还有「混合」:组里各条目的判定不一致时,组行没有单一档位可选。
66
+ type TriValue = "unset" | SessionModeTriState | "mixed";
67
+
68
+ // 草稿:本地改动先攒着,「应用到会话」时一次提交。
69
+ interface Draft {
70
+ readonly switches: Readonly<Record<string, boolean | null>>;
71
+ readonly items: Readonly<
72
+ Record<"tools" | "skills" | "policies", Readonly<Record<string, "unset" | "allow" | "deny">>>
73
+ >;
74
+ readonly persona?: { readonly prefix: string; readonly suffix: string } | undefined;
75
+ }
76
+
77
+ const EMPTY_DRAFT: Draft = { switches: {}, items: { tools: {}, skills: {}, policies: {} } };
78
+
79
+ /** 右栏的会话模式面板。 */
80
+ @SlotView()
81
+ export class SessionModePanelView extends SidebarRightPaneTabSlot {
82
+ private readonly store = inject(SessionModeStore);
83
+
84
+ private readonly locales = inject(SessionModeLocales);
85
+
86
+ render(): ReactNode {
87
+ const props = viewPropsOf(this.viewProps);
88
+ return (
89
+ <SessionModePanelBody
90
+ sessionId={props.sessionId}
91
+ store={this.store}
92
+ useSessions={props.useSessions}
93
+ panelId={PANEL_ID}
94
+ t={this.locales.t()}
95
+ />
96
+ );
97
+ }
98
+ }
99
+
100
+ interface PanelProps extends SessionModeViewProps {
101
+ readonly store: SessionModeStore;
102
+ readonly panelId: string;
103
+ // 翻译座:容器(`SessionModePanelView`)从装配里取,纯展示组件只按它出文案。
104
+ readonly t?: SessionModeTranslate | undefined;
105
+ }
106
+
107
+ // 没有会话状态读面时(测试、没装会话行的宿主):两路投影读不到,面板只按 `sessionId` 重拉。
108
+ const NO_SESSIONS: NonNullable<SessionModeViewProps["useSessions"]> = () => undefined;
109
+
110
+ // 从会话目录快照里读一条投影值(上游 `useSessions` 的 selector 入参)。
111
+ function projectionOf(
112
+ snapshot: { byId: Record<string, { projectionValues?: Record<string, unknown> }> },
113
+ sessionId: string | undefined,
114
+ key: string,
115
+ ): unknown {
116
+ return sessionId === undefined ? undefined : snapshot.byId[sessionId]?.projectionValues?.[key];
117
+ }
118
+
119
+ export function SessionModePanelBody({
120
+ sessionId,
121
+ store,
122
+ useSessions,
123
+ panelId,
124
+ t = fallbackTranslate,
125
+ }: PanelProps): ReactNode {
126
+ const [active, setActive] = useState<SessionModeActiveState | undefined>(undefined);
127
+ // 错误与它对应的会话绑在一起:换会话时旧错误自动失效(不用在 effect 里同步清)。
128
+ const [errorOf, setErrorOf] = useState<{ sessionId: string; message: string } | undefined>(
129
+ undefined,
130
+ );
131
+ const [draft, setDraft] = useState<Draft>(EMPTY_DRAFT);
132
+ const [notice, setNotice] = useState<string | null>(null);
133
+ const [openSection, setOpenSection] = useState<SectionKey | null>("general");
134
+ const [openGroups, setOpenGroups] = useState<ReadonlySet<string>>(new Set());
135
+ // 「只看可调用」:打开后工具列表只留没被 deny、且属于本会话可见集合的条目。
136
+ const [onlyCallable, setOnlyCallable] = useState(false);
137
+ // 「应用到会话」右侧那半段的菜单开关。
138
+ const [menuOpen, setMenuOpen] = useState(false);
139
+ // 删除当前模式的二次确认。
140
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
141
+
142
+ // 两路会话投影:别处切了模式(`sessionMode`)或换了 preset(`agentPreset`),面板显示旧态就是误导。
143
+ // 与 chip 读的是同一份事实,所以两边不会分叉。
144
+ const sessions = useSessions ?? NO_SESSIONS;
145
+ const sessionMode = sessions((snapshot) => projectionOf(snapshot, sessionId, "sessionMode")) as
146
+ | string
147
+ | null
148
+ | undefined;
149
+ const agentPreset = sessions((snapshot) => projectionOf(snapshot, sessionId, "agentPreset")) as
150
+ | string
151
+ | null
152
+ | undefined;
153
+ // 上一份生效态属于哪个会话:换了会话就先丢掉它(见下面 effect 里的第一段)。
154
+ const loadedFor = useRef<string | undefined>(undefined);
155
+
156
+ // `t` 与 `sessions` 不在依赖里:容器每次 render 都会 `bind` 出一个新函数,进依赖会把 effect 变成每次
157
+ // 渲染都重拉(`useSessions` 是快照 selector hook,不是数据本身)。
158
+ useEffect(() => {
159
+ if (sessionId === undefined) return;
160
+ let alive = true;
161
+ // 会话切换:上一份生效态与草稿都属于**那个**会话,留着会让面板显示别的会话的模式、甚至把上一个
162
+ // 会话的草稿提交到新会话上。同一个会话内的投影变化只重拉,不清屏。
163
+ if (loadedFor.current !== sessionId) {
164
+ loadedFor.current = sessionId;
165
+ setActive(undefined);
166
+ setDraft(EMPTY_DRAFT);
167
+ }
168
+ store.loadActive(sessionId).then(
169
+ (value) => {
170
+ if (!alive) return;
171
+ // 读到就是没失败:错误的重置是**加载的产物**,不在 effect 的同步阶段做。
172
+ setErrorOf(undefined);
173
+ setActive(value);
174
+ },
175
+ (cause: unknown) => {
176
+ if (alive) setErrorOf({ sessionId, message: messageOf(cause) });
177
+ },
178
+ );
179
+ return () => {
180
+ alive = false;
181
+ };
182
+ }, [sessionId, store, sessionMode, agentPreset]);
183
+
184
+ // 三种「还没读到」的态各占整块:没有会话 / 读失败 / 正在读。读失败不能伪装成空列表或一直转圈。
185
+ if (sessionId === undefined) {
186
+ return (
187
+ <div data-role="session-mode-panel" data-panel={panelId} style={PANEL_STYLE}>
188
+ <Text size="sm" tone="tertiary">
189
+ {t("panelNoSession")}
190
+ </Text>
191
+ </div>
192
+ );
193
+ }
194
+ // 只显示属于**当前会话**的错误。
195
+ const error = errorOf?.sessionId === sessionId ? errorOf.message : undefined;
196
+ if (error !== undefined) {
197
+ return (
198
+ <div data-role="session-mode-panel" data-panel={panelId} style={PANEL_STYLE}>
199
+ <div data-role="panel-error" role="alert">
200
+ <Text as="p" size="sm" tone="danger">
201
+ {`${t("loadFailed")}: ${error}`}
202
+ </Text>
203
+ </div>
204
+ </div>
205
+ );
206
+ }
207
+ if (active === undefined) {
208
+ return (
209
+ <div data-role="session-mode-panel" data-panel={panelId} style={PANEL_STYLE}>
210
+ <Text size="sm" tone="tertiary">
211
+ {t("loading")}
212
+ </Text>
213
+ </div>
214
+ );
215
+ }
216
+
217
+ const effective =
218
+ active.session === undefined ? active.config : { ...active.config, ...active.session };
219
+ const overridden = new Set(active.overriddenFields);
220
+ const source = (field: string): string =>
221
+ overridden.has(field) ? t("fromSession") : t("fromMode");
222
+
223
+ // 逐字段回退:`null` 在宿主的语义是「清掉这个字段的会话覆盖,回到模式默认」,其余字段不动。
224
+ //
225
+ // 粒度就是 `ModeConfig` 的字段(与 `overriddenFields` 同名):一个工具条目回退清的是它所在的那对
226
+ // 名单字段——这是宿主的补丁能表达的最小粒度,条目级的「只回到默认这一条」在写面没有对应语义。
227
+ const restore = (fields: readonly string[]): void => {
228
+ if (sessionId === undefined) return;
229
+ const patch: Record<string, null> = {};
230
+ for (const field of fields) patch[field] = null;
231
+ void store
232
+ .patch(sessionId, patch)
233
+ .then((value) => {
234
+ setActive(value);
235
+ // 这些字段上的本地草稿跟着作废:它们不再是「待提交的改动」,而是回到了模式默认。
236
+ setDraft((prev) => {
237
+ const switches = { ...prev.switches };
238
+ const items = {
239
+ tools: { ...prev.items.tools },
240
+ skills: { ...prev.items.skills },
241
+ policies: { ...prev.items.policies },
242
+ };
243
+ let persona = prev.persona;
244
+ for (const field of fields) {
245
+ delete switches[field];
246
+ if (field === "persona") persona = undefined;
247
+ for (const kind of ["tools", "skills", "policies"] as const) {
248
+ const pair = LIST_FIELDS[kind];
249
+ if (field === pair.allow || field === pair.deny) items[kind] = {};
250
+ }
251
+ }
252
+ // 不展开 `prev`:它的 `persona` 正是要清掉的那一项,展开会把旧值又盖回来。
253
+ return { switches, items, ...(persona === undefined ? {} : { persona }) };
254
+ });
255
+ })
256
+ .catch((cause: unknown) => {
257
+ setNotice(`${t("saveFailed")}: ${messageOf(cause)}`);
258
+ });
259
+ };
260
+
261
+ const draftOf = (): ModeDraft => ({
262
+ lists: {
263
+ tools: draft.items.tools,
264
+ skills: draft.items.skills,
265
+ policies: draft.items.policies,
266
+ },
267
+ ...(draft.persona === undefined ? {} : { persona: { ...draft.persona } }),
268
+ switches: draft.switches,
269
+ });
270
+
271
+ // 草稿叠到生效配置上,得到「应用后会变成」的那一份(与宿主用同一个纯函数)。
272
+ const viewConfig = (): ModeConfig => applyDraft(effective, draftOf(), active.config);
273
+
274
+ const commit = (target: "session" | "config"): void => {
275
+ if (sessionId === undefined) return;
276
+ const config = viewConfig();
277
+ const request =
278
+ target === "session"
279
+ ? store.applyConfig(sessionId, config)
280
+ : store.saveConfig(sessionId, config);
281
+ void request
282
+ .then((value) => {
283
+ setActive(value);
284
+ setDraft(EMPTY_DRAFT);
285
+ setNotice(t(target === "session" ? "applied" : "saved"));
286
+ })
287
+ .catch((cause: unknown) => {
288
+ // 写失败**不清草稿**:用户可以原样重试,改到一半的内容不该被一个网络错误吃掉。
289
+ setNotice(`${t("saveFailed")}: ${messageOf(cause)}`);
290
+ });
291
+ };
292
+
293
+ // 删掉会话上当前模式的自定义:服务端会把会话落回内置默认,所以删完再拉一次生效态。
294
+ const removeCurrent = (): void => {
295
+ if (sessionId === undefined) return;
296
+ setConfirmingDelete(false);
297
+ void store
298
+ .remove(sessionId)
299
+ .then(async (mode) => {
300
+ setNotice(`${t("deleted")} ${mode}`);
301
+ setActive(await store.loadActive(sessionId));
302
+ setDraft(EMPTY_DRAFT);
303
+ })
304
+ .catch((cause: unknown) => {
305
+ setNotice(`${t("deleteFailed")}: ${messageOf(cause)}`);
306
+ });
307
+ };
308
+
309
+ const section = (key: SectionKey, title: string, children: ReactNode): ReactNode => (
310
+ <Section
311
+ title={title}
312
+ open={openSection === key}
313
+ onToggle={() => {
314
+ setOpenSection((current) => (current === key ? null : key));
315
+ }}
316
+ >
317
+ {children}
318
+ </Section>
319
+ );
320
+
321
+ // 一条目录项当下是「允许 / 禁止 / 默认」:名单里点名的那档优先,其次是草稿,最后是目录给的继承档。
322
+ const configValue = (entry: SessionModeDirectoryEntry): "unset" | SessionModeTriState => {
323
+ if (entry.group !== undefined && effective.denyTools.includes(groupRef(entry.group)))
324
+ return "deny";
325
+ return entry.fallback === undefined || entry.fallback === "default" ? "unset" : entry.fallback;
326
+ };
327
+
328
+ // 这一条在会话上被改过没有:目录给的 `override` 就是「生效值 ≠ 模式默认」的那一档。
329
+ const entryOverridden = (entry: SessionModeDirectoryEntry): boolean =>
330
+ entry.override !== undefined && entry.override !== null;
331
+
332
+ // 「只看可调用」的判据只用目录里已有的信息推:模式默认档 + 本会话覆盖 + 本地草稿,都不含 deny。
333
+ // (`active.catalog.tools` 本身就是本会话可见的工具集;再滤掉被 deny 的那些。)
334
+ const callable = (entry: SessionModeDirectoryEntry): boolean => {
335
+ const groupDraft =
336
+ entry.group === undefined ? undefined : draft.items.tools[groupRef(entry.group)];
337
+ if (groupDraft !== undefined) return groupDraft !== "deny";
338
+ return (draft.items.tools[entry.id] ?? entry.override ?? configValue(entry)) !== "deny";
339
+ };
340
+
341
+ const otherGroupLabel = t("otherGroup");
342
+ const toolGroups = new Map<string, SessionModeDirectoryEntry[]>();
343
+ for (const entry of active.catalog.tools) {
344
+ if (onlyCallable && !callable(entry)) continue;
345
+ // 目录里没有组的条目(工具都有组,这里只是兜底)归到本包字典里的「其它」那一档。
346
+ const group = entry.group ?? otherGroupLabel;
347
+ const list = toolGroups.get(group);
348
+ if (list === undefined) toolGroups.set(group, [entry]);
349
+ else list.push(entry);
350
+ }
351
+
352
+ return (
353
+ <div data-role="session-mode-panel" data-panel={panelId} style={PANEL_STYLE}>
354
+ <Stack gap="wide">
355
+ <Stack gap={4}>
356
+ <Text size="lg">{active.mode.name}</Text>
357
+ <Text size="sm" tone="tertiary">
358
+ {active.mode.description.length === 0 ? t("noDescription") : active.mode.description}
359
+ </Text>
360
+ </Stack>
361
+
362
+ {section(
363
+ "general",
364
+ t("general"),
365
+ <Stack gap={6}>
366
+ {(
367
+ [
368
+ ["instructions", "instructions", effective.instructions],
369
+ ["skills", "skillsCatalog", effective.skills],
370
+ ["runtimeContext", "runtimeContext", effective.runtimeContext],
371
+ ] as const
372
+ ).map(([key, labelKey, value]) => (
373
+ <Row key={key} gap={6} align="center" justify="between">
374
+ <Stack gap={2}>
375
+ <Text size="md">{t(labelKey)}</Text>
376
+ <SourceLine
377
+ source={source(key)}
378
+ restoreLabel={t("restoreDefault")}
379
+ onRestore={
380
+ overridden.has(key)
381
+ ? () => {
382
+ restore([key]);
383
+ }
384
+ : undefined
385
+ }
386
+ />
387
+ </Stack>
388
+ <Switch
389
+ checked={draft.switches[key] ?? value}
390
+ label={t(labelKey)}
391
+ onChange={(next) => {
392
+ setDraft((prev) => ({ ...prev, switches: { ...prev.switches, [key]: next } }));
393
+ }}
394
+ />
395
+ </Row>
396
+ ))}
397
+ </Stack>,
398
+ )}
399
+
400
+ {section(
401
+ "persona",
402
+ t("persona"),
403
+ <Stack gap={6}>
404
+ {(
405
+ [
406
+ ["prefix", "personaPrefix", "personaPrefixHint"],
407
+ ["suffix", "personaSuffix", "personaSuffixHint"],
408
+ ] as const
409
+ ).map(([key, labelKey, hintKey]) => {
410
+ // 草稿没动过这一项时,输入框显示的就是当下生效的那份(模式默认或会话覆盖)。
411
+ const value = draft.persona?.[key] ?? effective.persona[key];
412
+ return (
413
+ <Stack key={key} gap={2}>
414
+ <Text size="md">{t(labelKey)}</Text>
415
+ <MultilineField
416
+ aria-label={t(labelKey)}
417
+ placeholder={t(hintKey)}
418
+ value={value}
419
+ onChange={(event) => {
420
+ const next = event.currentTarget.value;
421
+ setDraft((prev) => ({
422
+ ...prev,
423
+ persona: {
424
+ prefix: prev.persona?.prefix ?? effective.persona.prefix,
425
+ suffix: prev.persona?.suffix ?? effective.persona.suffix,
426
+ [key]: next,
427
+ },
428
+ }));
429
+ }}
430
+ />
431
+ <SourceLine
432
+ source={source("persona")}
433
+ restoreLabel={t("restoreDefault")}
434
+ onRestore={
435
+ overridden.has("persona")
436
+ ? () => {
437
+ restore(["persona"]);
438
+ }
439
+ : undefined
440
+ }
441
+ />
442
+ </Stack>
443
+ );
444
+ })}
445
+ </Stack>,
446
+ )}
447
+
448
+ {section(
449
+ "tools",
450
+ `${t("tools")} (${String(active.catalog.tools.length)})`,
451
+ <Stack gap={2}>
452
+ <Row gap={6} align="center" justify="between">
453
+ <Stack gap={2}>
454
+ <Text size="md">{t("onlyCallable")}</Text>
455
+ <Text size="sm" tone="tertiary">
456
+ {t("onlyCallableHint")}
457
+ </Text>
458
+ </Stack>
459
+ <Switch
460
+ checked={onlyCallable}
461
+ label={t("onlyCallable")}
462
+ onChange={(next) => {
463
+ setOnlyCallable(next);
464
+ }}
465
+ />
466
+ </Row>
467
+ {toolGroups.size === 0 && onlyCallable ? (
468
+ <Text size="sm" tone="tertiary">
469
+ {t("empty")}
470
+ </Text>
471
+ ) : null}
472
+ {[...toolGroups].map(([group, entries]) => {
473
+ const groupDraft = draft.items.tools[groupRef(group)];
474
+ const values =
475
+ groupDraft !== undefined
476
+ ? entries.map(() => groupDraft)
477
+ : entries.map(
478
+ (entry) =>
479
+ draft.items.tools[entry.id] ?? entry.override ?? configValue(entry),
480
+ );
481
+ const uniform = values.every((value) => value === values[0]);
482
+ const groupValue: TriValue = uniform ? (values[0] ?? "unset") : "mixed";
483
+ // 组这一层的来源:把每条的模式默认档(目录给的 `fallback`)与生效档比一遍,
484
+ // 有一处不同就是这个会话盖过——不另加字段,也不用猜名单。
485
+ const groupOverridden = entries.some((entry) => {
486
+ const fallback =
487
+ entry.fallback === undefined || entry.fallback === "default"
488
+ ? "unset"
489
+ : entry.fallback;
490
+ return (entry.override ?? configValue(entry)) !== fallback;
491
+ });
492
+ return (
493
+ <Stack key={group} gap={2}>
494
+ <TriStateRow
495
+ id={`${entries[0]?.groupLabel ?? group} (${String(entries.length)})`}
496
+ value={groupValue}
497
+ onChange={(next) => {
498
+ setDraft((prev) => ({
499
+ ...prev,
500
+ items: {
501
+ ...prev.items,
502
+ tools: { ...prev.items.tools, [groupRef(group)]: next },
503
+ },
504
+ }));
505
+ }}
506
+ onLabelClick={() => {
507
+ setOpenGroups((current) => {
508
+ const next = new Set(current);
509
+ if (next.has(group)) next.delete(group);
510
+ else next.add(group);
511
+ return next;
512
+ });
513
+ }}
514
+ t={t}
515
+ source={groupOverridden ? t("fromSession") : t("fromMode")}
516
+ restoreLabel={t("restoreDefault")}
517
+ onRestore={
518
+ groupOverridden
519
+ ? () => {
520
+ // 组引用只是名单里的一项:清覆盖 = 把这对名单回退给模式默认。
521
+ restore([LIST_FIELDS.tools.allow, LIST_FIELDS.tools.deny]);
522
+ }
523
+ : undefined
524
+ }
525
+ />
526
+ {openGroups.has(group)
527
+ ? entries.map((entry) => (
528
+ <TriStateRow
529
+ key={entry.id}
530
+ id={entry.id}
531
+ description={entry.description}
532
+ indent={16}
533
+ value={
534
+ draft.items.tools[entry.id] ?? entry.override ?? configValue(entry)
535
+ }
536
+ onChange={(next) => {
537
+ setDraft((prev) => ({
538
+ ...prev,
539
+ items: {
540
+ ...prev.items,
541
+ tools: { ...prev.items.tools, [entry.id]: next },
542
+ },
543
+ }));
544
+ }}
545
+ t={t}
546
+ source={entryOverridden(entry) ? t("fromSession") : t("fromMode")}
547
+ restoreLabel={t("restoreDefault")}
548
+ onRestore={
549
+ entryOverridden(entry)
550
+ ? () => {
551
+ restore([LIST_FIELDS.tools.allow, LIST_FIELDS.tools.deny]);
552
+ }
553
+ : undefined
554
+ }
555
+ />
556
+ ))
557
+ : null}
558
+ </Stack>
559
+ );
560
+ })}
561
+ </Stack>,
562
+ )}
563
+
564
+ {section(
565
+ "skills",
566
+ `${t("skills")} (${String(active.catalog.skills.length)})`,
567
+ <Stack gap={2}>
568
+ {active.catalog.skills.map((entry) => (
569
+ <TriStateRow
570
+ key={entry.id}
571
+ id={entry.id}
572
+ description={entry.description}
573
+ value={draft.items.skills[entry.id] ?? entry.override ?? configValue(entry)}
574
+ onChange={(next) => {
575
+ setDraft((prev) => ({
576
+ ...prev,
577
+ items: {
578
+ ...prev.items,
579
+ skills: { ...prev.items.skills, [entry.id]: next },
580
+ },
581
+ }));
582
+ }}
583
+ t={t}
584
+ source={entryOverridden(entry) ? t("fromSession") : t("fromMode")}
585
+ restoreLabel={t("restoreDefault")}
586
+ onRestore={
587
+ entryOverridden(entry)
588
+ ? () => {
589
+ restore([LIST_FIELDS.skills.allow, LIST_FIELDS.skills.deny]);
590
+ }
591
+ : undefined
592
+ }
593
+ />
594
+ ))}
595
+ </Stack>,
596
+ )}
597
+
598
+ {section(
599
+ "policies",
600
+ `${t("policies")} (${String(active.catalog.policies.length)})`,
601
+ <Stack gap={2}>
602
+ {active.catalog.policies.map((entry) => (
603
+ <TriStateRow
604
+ key={entry.id}
605
+ id={entry.id}
606
+ description={entry.description}
607
+ value={draft.items.policies[entry.id] ?? entry.override ?? configValue(entry)}
608
+ onChange={(next) => {
609
+ setDraft((prev) => ({
610
+ ...prev,
611
+ items: {
612
+ ...prev.items,
613
+ policies: { ...prev.items.policies, [entry.id]: next },
614
+ },
615
+ }));
616
+ }}
617
+ t={t}
618
+ source={entryOverridden(entry) ? t("fromSession") : t("fromMode")}
619
+ restoreLabel={t("restoreDefault")}
620
+ onRestore={
621
+ entryOverridden(entry)
622
+ ? () => {
623
+ restore([LIST_FIELDS.policies.allow, LIST_FIELDS.policies.deny]);
624
+ }
625
+ : undefined
626
+ }
627
+ />
628
+ ))}
629
+ </Stack>,
630
+ )}
631
+
632
+ <Row gap={8} justify="end" align="center">
633
+ <Button
634
+ variant="outline"
635
+ onClick={() => {
636
+ setDraft(EMPTY_DRAFT);
637
+ setNotice(null);
638
+ }}
639
+ >
640
+ {t("reset")}
641
+ </Button>
642
+ {/* 分体主按钮(与上游 header 的 `OpenTargetButton` 同一形状):左半是主动作,右半是窄的 chevron,
643
+ 点开才是「保存为默认 / 另存为 / 删除」。两个半段贴在一起——内侧圆角归零、外侧保留。 */}
644
+ <Row gap={0} align="center">
645
+ <Button
646
+ variant="primary"
647
+ style={{ borderTopRightRadius: 0, borderBottomRightRadius: 0 }}
648
+ onClick={() => {
649
+ commit("session");
650
+ }}
651
+ >
652
+ {t("apply")}
653
+ </Button>
654
+ <Menu
655
+ open={menuOpen}
656
+ align="end"
657
+ anchor={
658
+ <Button
659
+ variant="primary"
660
+ aria-label={t("moreSaveWays")}
661
+ style={{
662
+ borderTopLeftRadius: 0,
663
+ borderBottomLeftRadius: 0,
664
+ paddingInline: 6,
665
+ }}
666
+ onClick={() => {
667
+ setMenuOpen(true);
668
+ }}
669
+ >
670
+ <IconChevronDownOutlineRegular />
671
+ </Button>
672
+ }
673
+ onClose={() => {
674
+ setMenuOpen(false);
675
+ }}
676
+ >
677
+ <MenuItemButton
678
+ onSelect={() => {
679
+ setMenuOpen(false);
680
+ commit("config");
681
+ }}
682
+ >
683
+ {t("saveDefault")}
684
+ </MenuItemButton>
685
+ {/* 「另存为」要用户给新模式的 code / name(`store.saveAs` 的三个参数),那个输入面还没做。
686
+ 禁用行必须给出**理由**(`disabledReason` 会读成该行的 description 并弹 tooltip),
687
+ 否则用户只会当成 bug。 */}
688
+ <MenuItemButton disabled disabledReason={t("saveAsNeedsName")} onSelect={() => {}}>
689
+ {t("saveAs")}
690
+ </MenuItemButton>
691
+ <MenuItemButton
692
+ disabled={!active.deletable}
693
+ {...(active.deletable ? {} : { disabledReason: t("deleteBuiltinReason") })}
694
+ danger
695
+ onSelect={() => {
696
+ setMenuOpen(false);
697
+ setConfirmingDelete(true);
698
+ }}
699
+ >
700
+ {t("delete")}
701
+ </MenuItemButton>
702
+ </Menu>
703
+ </Row>
704
+ </Row>
705
+
706
+ {!confirmingDelete ? null : (
707
+ <Modal
708
+ open
709
+ onClose={() => {
710
+ setConfirmingDelete(false);
711
+ }}
712
+ title={t("deleteCurrentTitle")}
713
+ closeLabel={t("cancel")}
714
+ description={`「${active.mode.name}」${t("deleteConfirm")}`}
715
+ footer={
716
+ <Row gap={8} justify="end">
717
+ <Button
718
+ variant="outline"
719
+ onClick={() => {
720
+ setConfirmingDelete(false);
721
+ }}
722
+ >
723
+ {t("cancel")}
724
+ </Button>
725
+ <Button variant="primary" tone="danger" onClick={removeCurrent}>
726
+ {t("confirmDelete")}
727
+ </Button>
728
+ </Row>
729
+ }
730
+ />
731
+ )}
732
+
733
+ {notice === null ? null : (
734
+ <Text as="p" size="sm" tone="tertiary">
735
+ {notice}
736
+ </Text>
737
+ )}
738
+ </Stack>
739
+ </div>
740
+ );
741
+ }
742
+
743
+ function Section({
744
+ title,
745
+ open,
746
+ onToggle,
747
+ children,
748
+ }: {
749
+ readonly title: string;
750
+ readonly open: boolean;
751
+ readonly onToggle: () => void;
752
+ readonly children: ReactNode;
753
+ }): ReactNode {
754
+ return (
755
+ <div
756
+ data-role="section"
757
+ data-section={title}
758
+ style={{ borderTop: "1px solid var(--dsw-alias-border-l1)" }}
759
+ >
760
+ <button
761
+ type="button"
762
+ data-role="section-heading"
763
+ onClick={onToggle}
764
+ style={{
765
+ width: "100%",
766
+ display: "flex",
767
+ alignItems: "center",
768
+ justifyContent: "space-between",
769
+ background: "none",
770
+ border: 0,
771
+ paddingBlock: 12,
772
+ paddingInline: 0,
773
+ font: "inherit",
774
+ fontSize: 13,
775
+ fontWeight: 500,
776
+ color: "inherit",
777
+ cursor: "pointer",
778
+ }}
779
+ >
780
+ <span>{title}</span>
781
+ <span data-role="section-icon" style={{ color: "var(--dsw-alias-label-tertiary)" }}>
782
+ {open ? "−" : "+"}
783
+ </span>
784
+ </button>
785
+ {open ? (
786
+ <div style={{ padding: "0 0 8px" }}>
787
+ <Stack gap={6}>{children}</Stack>
788
+ </div>
789
+ ) : null}
790
+ </div>
791
+ );
792
+ }
793
+
794
+ // 一行「来源 + 恢复默认」:来源一直显示(每个可改字段都要能看出现在吃的是哪一份),
795
+ // 恢复默认只在**这个字段被会话覆盖过**时给——多点几次没有意义。
796
+ function SourceLine({
797
+ source,
798
+ restoreLabel,
799
+ onRestore,
800
+ }: {
801
+ readonly source: string;
802
+ readonly restoreLabel?: string | undefined;
803
+ readonly onRestore?: (() => void) | undefined;
804
+ }): ReactNode {
805
+ return (
806
+ <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
807
+ <Text size="sm" tone="tertiary">
808
+ {source}
809
+ </Text>
810
+ {onRestore === undefined ? null : (
811
+ <button
812
+ type="button"
813
+ onClick={() => {
814
+ onRestore();
815
+ }}
816
+ style={{
817
+ background: "none",
818
+ border: 0,
819
+ padding: 0,
820
+ font: "inherit",
821
+ fontSize: 12,
822
+ color: "var(--dsw-alias-label-secondary)",
823
+ textDecoration: "underline",
824
+ cursor: "pointer",
825
+ }}
826
+ >
827
+ {restoreLabel}
828
+ </button>
829
+ )}
830
+ </span>
831
+ );
832
+ }
833
+
834
+ function TriStateRow({
835
+ id,
836
+ description,
837
+ value,
838
+ indent = 0,
839
+ onChange,
840
+ onLabelClick,
841
+ source,
842
+ restoreLabel,
843
+ onRestore,
844
+ t,
845
+ }: {
846
+ readonly id: string;
847
+ readonly description?: string | undefined;
848
+ readonly value: TriValue;
849
+ readonly indent?: number | undefined;
850
+ readonly onChange: (next: "unset" | SessionModeTriState) => void;
851
+ readonly onLabelClick?: (() => void) | undefined;
852
+ // 这一行的来源(会话覆盖 / 模式默认);不给就不显示。
853
+ readonly source?: string | undefined;
854
+ readonly restoreLabel?: string | undefined;
855
+ readonly onRestore?: (() => void) | undefined;
856
+ // 三态那几档的文案(中英各一份在 `locales.ts`):纯展示组件不装 Locale 服务,由调用方把 `t` 递进来。
857
+ readonly t?: SessionModeTranslate | undefined;
858
+ }): ReactNode {
859
+ const translate = t ?? fallbackTranslate;
860
+ return (
861
+ <div
862
+ data-role="tri-state"
863
+ data-id={id}
864
+ style={{
865
+ display: "flex",
866
+ flexWrap: "wrap",
867
+ alignItems: "center",
868
+ justifyContent: "space-between",
869
+ gap: 8,
870
+ padding: "6px 0",
871
+ paddingLeft: indent,
872
+ }}
873
+ >
874
+ <span
875
+ style={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 0, flex: "1 1 140px" }}
876
+ >
877
+ {onLabelClick === undefined ? (
878
+ <Text size="sm">{id}</Text>
879
+ ) : (
880
+ <button
881
+ type="button"
882
+ onClick={onLabelClick}
883
+ style={{
884
+ background: "none",
885
+ border: 0,
886
+ padding: 0,
887
+ font: "inherit",
888
+ fontSize: 13,
889
+ color: "inherit",
890
+ textAlign: "left",
891
+ cursor: "pointer",
892
+ }}
893
+ >
894
+ {id}
895
+ </button>
896
+ )}
897
+ {description === undefined || description.length === 0 ? null : (
898
+ <Text size="sm" tone="tertiary">
899
+ {description}
900
+ </Text>
901
+ )}
902
+ {source === undefined ? null : (
903
+ <SourceLine source={source} restoreLabel={restoreLabel} onRestore={onRestore} />
904
+ )}
905
+ </span>
906
+ <SegmentedControl<"unset" | "allow" | "deny" | "mixed">
907
+ id={`tri-${id.replace(/[^a-zA-Z0-9_-]+/gu, "-")}`}
908
+ label={id}
909
+ value={value}
910
+ options={
911
+ value === "mixed"
912
+ ? [
913
+ { value: "mixed", label: translate("stateMixed") },
914
+ { value: "unset", label: translate("stateDefault") },
915
+ { value: "allow", label: translate("stateAllow") },
916
+ { value: "deny", label: translate("stateDeny") },
917
+ ]
918
+ : [
919
+ { value: "unset", label: translate("stateDefault") },
920
+ { value: "allow", label: translate("stateAllow") },
921
+ { value: "deny", label: translate("stateDeny") },
922
+ ]
923
+ }
924
+ onChange={(next) => {
925
+ if (next === "mixed") return;
926
+ onChange(next);
927
+ }}
928
+ />
929
+ </div>
930
+ );
931
+ }