@yolk_vat-y/dsh-project-memory 0.6.8 → 0.6.9

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.
package/cordis.patch.yml CHANGED
@@ -11,6 +11,10 @@
11
11
  autoIndexOnFirstUse: false
12
12
  watch: true
13
13
  watchInterval: 30
14
+ # 其中三个也能在 web 的「插件 → 项目记忆」详情页里可视化修改(默认收起的「常用设置」):
15
+ # watchInterval / autoIndexOnFirstUse / llmQueryExpansion
16
+ # 保存即生效(autoIndexOnFirstUse 下次启动生效);页面上的改动落在 profile 的用户层,不改这个文件。
17
+ # watch / lazyIndexing / enableTypeScript 刻意不放进界面:关掉只会让记忆变旧。
14
18
  # 危险根护栏(家目录 / 文件系统根 / 系统与包管理器前缀整体扫描会吃满内存)。
15
19
  # 兼容开关:只放开内置名单;roots.deny / roots.exclude 仍然优先。
16
20
  allowUnsafeRoots: false
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolk_vat-y/dsh-project-memory",
3
- "version": "0.6.8",
3
+ "version": "0.6.9",
4
4
  "description": "Persistent project memory for dsh agents: index docs (PDF/Markdown/text) and code symbols into a searchable per-workspace store, recall them with cited sources, and keep experience entries (problems -> solutions) searchable on demand.",
5
5
  "author": "00080000 <3388065969@qq.com>",
6
6
  "type": "module",
@@ -20,7 +20,7 @@
20
20
  "url": "https://github.com/00080000/dsh-project-memory.git"
21
21
  },
22
22
  "scripts": {
23
- "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/signal-source.test.mjs && node test/skill.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/root-policy.test.mjs && node test/gitignore-index.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/store-concurrent.test.mjs && node test/store-lock.test.mjs && node test/windows-compat.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs && node test/multilingual-ru.test.mjs && node test/lazy-batch.test.mjs",
23
+ "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/signal-source.test.mjs && node test/skill.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/settings-card.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/root-policy.test.mjs && node test/gitignore-index.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/store-concurrent.test.mjs && node test/store-lock.test.mjs && node test/windows-compat.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs && node test/multilingual-ru.test.mjs && node test/lazy-batch.test.mjs && node test/pdfjs-host.test.mjs && node test/index-failures.test.mjs",
24
24
  "eval:injection": "node test/injection-scenarios.test.mjs",
25
25
  "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
26
26
  "selfcheck:triggers": "node test/injection-scenarios.test.mjs --selfcheck",
@@ -61,7 +61,7 @@
61
61
  "@deepseek-ai/dsh-client-ui-slots": "0.2.1-rc.2",
62
62
  "@deepseek-ai/dsh-llm": "0.2.1-rc.2",
63
63
  "@deepseek-ai/dsh-tools": "0.2.1-rc.2",
64
- "@deepseek-ai/schemastery": "^3.18.2",
64
+ "@deepseek-ai/schemastery": "^3.18.3",
65
65
  "@tsdown/css": "0.22.14",
66
66
  "@types/react": "^18.3.31",
67
67
  "@types/react-dom": "^18.3.7",
@@ -73,7 +73,7 @@
73
73
  "@deepseek-ai/cordis": "^4.0.1",
74
74
  "@deepseek-ai/dsh-llm": ">=0.0.1-rc.1 <0.1.0 || >=0.1.0-rc.1 <0.2.0-0 || >=0.1.1-rc.1 <0.2.0-0 || >=0.2.0-rc.1 <0.3.0-0",
75
75
  "@deepseek-ai/dsh-tools": ">=0.0.1-rc.1 <0.1.0 || >=0.1.0-rc.1 <0.2.0-0 || >=0.1.1-rc.1 <0.2.0-0 || >=0.2.0-rc.1 <0.3.0-0",
76
- "@deepseek-ai/schemastery": "^3.18.1",
76
+ "@deepseek-ai/schemastery": "^3.18.3",
77
77
  "typescript": "^5.0.0 || ^6.0.0"
78
78
  },
79
79
  "peerDependenciesMeta": {
@@ -445,7 +445,9 @@ export function buildInjection(opts) {
445
445
  const quotaChars = typeof opts.maxChars === 'number' ? opts.maxChars : Infinity
446
446
  const maxItems = typeof opts.maxItems === 'number' ? opts.maxItems : Infinity
447
447
  const skipItems = opts.skipItems === true
448
- const stepBudget = Math.max(0, (cfg.maxTokens || 400) * 3)
448
+ // 0 是合法值(= 不给注入预算):不能用 `|| 400` 把显式的 0 顶回默认值。
449
+ const maxTokens = typeof cfg.maxTokens === 'number' && Number.isFinite(cfg.maxTokens) ? cfg.maxTokens : 400
450
+ const stepBudget = Math.max(0, maxTokens * 3)
449
451
  const itemBudget = Math.max(0, Math.min(stepBudget, quotaChars))
450
452
 
451
453
  const skipItem = typeof opts.skipItem === 'function' ? opts.skipItem : null
@@ -474,7 +476,7 @@ export function buildInjection(opts) {
474
476
 
475
477
  // 常驻块文本。去重指纹包含“编辑中”行:否则这条常驻状态只会在别的条目变化时顺带更新,
476
478
  // 模型会一直看到旧文件列表;只有热点文件集合/顺序变化时才重发整块。
477
- const echo = cfg.entryOn !== false && shouldEchoTaskCard(task, cfg)
479
+ const echo = stepBudget > 0 && cfg.entryOn !== false && shouldEchoTaskCard(task, cfg)
478
480
  const entry = echo ? buildEntryContent(task, cfg) : ''
479
481
  const entryStable = entry
480
482
  let used = entry.length
@@ -0,0 +1,185 @@
1
+ /* 插件详情页的「常用设置」:外形照宿主自己的插件卡片(边框 + 16px 圆角 + 折叠头)。 */
2
+ .card {
3
+ box-sizing: border-box;
4
+ border: 0.5px solid var(--dsw-alias-settings-card-stroke, var(--dsw-alias-border-l4, #00000029));
5
+ border-radius: var(--dsw-radius-lg, 16px);
6
+ background: var(--dsw-alias-bg-layer-3, #fff);
7
+ transition: border-color 0.16s, background 0.16s;
8
+ }
9
+
10
+ .card:hover {
11
+ border-color: var(--dsw-alias-label-dimmed, #c8ccd4);
12
+ }
13
+
14
+ .cardOpen {
15
+ background: var(--dsw-alias-bg-layer-2, #f7f8fa);
16
+ border-color: var(--dsw-alias-label-dimmed, #c8ccd4);
17
+ }
18
+
19
+ .header {
20
+ appearance: none;
21
+ display: flex;
22
+ align-items: center;
23
+ gap: 12px;
24
+ width: 100%;
25
+ padding: 14px 16px;
26
+ border: 0;
27
+ border-radius: inherit;
28
+ background: none;
29
+ font: inherit;
30
+ color: inherit;
31
+ text-align: left;
32
+ cursor: pointer;
33
+ }
34
+
35
+ .header:focus-visible {
36
+ outline: 2px solid var(--dsw-alias-brand-primary, #4f6ef7);
37
+ outline-offset: -2px;
38
+ }
39
+
40
+ .headText {
41
+ display: flex;
42
+ flex: 1;
43
+ flex-direction: column;
44
+ gap: 4px;
45
+ min-width: 0;
46
+ }
47
+
48
+ .name {
49
+ font-size: 15px;
50
+ font-weight: 600;
51
+ line-height: 1.4;
52
+ color: var(--dsw-alias-label-primary, #1f2328);
53
+ }
54
+
55
+ .desc {
56
+ font-size: 13px;
57
+ line-height: 1.5;
58
+ color: var(--dsw-alias-label-tertiary, #8b93a1);
59
+ }
60
+
61
+ .unsaved {
62
+ flex: none;
63
+ padding: 0 6px;
64
+ border-radius: 9px;
65
+ font-size: 11px;
66
+ font-weight: 600;
67
+ line-height: 17px;
68
+ color: var(--dsw-alias-label-secondary, #6b7280);
69
+ background: var(--dsw-alias-bg-module-platform, #eef0f4);
70
+ }
71
+
72
+ .chevron {
73
+ flex: none;
74
+ display: inline-flex;
75
+ color: var(--dsw-alias-label-tertiary, #8b93a1);
76
+ transition: transform 0.16s;
77
+ }
78
+
79
+ .chevronOpen {
80
+ transform: rotate(180deg);
81
+ }
82
+
83
+ .body {
84
+ margin: 0 16px;
85
+ padding-bottom: 8px;
86
+ border-top: 1px solid var(--dsw-alias-border-l2, #e5e7eb);
87
+ }
88
+
89
+ .row {
90
+ display: flex;
91
+ align-items: center;
92
+ gap: 12px;
93
+ padding: 12px 0;
94
+ }
95
+
96
+ .row + .row {
97
+ border-top: 1px solid var(--dsw-alias-border-l2, #e5e7eb);
98
+ }
99
+
100
+ .labelBox {
101
+ display: flex;
102
+ flex: 1;
103
+ flex-direction: column;
104
+ gap: 3px;
105
+ min-width: 0;
106
+ }
107
+
108
+ .label {
109
+ font-size: 13px;
110
+ line-height: 20px;
111
+ color: var(--dsw-alias-label-primary, #1f2328);
112
+ }
113
+
114
+ .hint {
115
+ font-size: 12px;
116
+ line-height: 18px;
117
+ color: var(--dsw-alias-label-tertiary, #8b93a1);
118
+ }
119
+
120
+ .control {
121
+ flex: none;
122
+ display: flex;
123
+ align-items: center;
124
+ gap: 6px;
125
+ }
126
+
127
+ .number {
128
+ box-sizing: border-box;
129
+ width: 84px;
130
+ padding: 6px 8px;
131
+ border: 1px solid var(--dsw-alias-border-l2, #d1d5db);
132
+ border-radius: 7px;
133
+ background: var(--dsw-alias-bg-layer-3, #fff);
134
+ font: inherit;
135
+ font-size: 12px;
136
+ line-height: 18px;
137
+ color: var(--dsw-alias-label-primary, #1f2328);
138
+ text-align: right;
139
+ }
140
+
141
+ .number:disabled {
142
+ opacity: 0.5;
143
+ cursor: default;
144
+ }
145
+
146
+ .number:focus {
147
+ border-color: var(--dsw-alias-brand-primary, #4f6ef7);
148
+ outline: 2px solid color-mix(in srgb, var(--dsw-alias-brand-primary, #4f6ef7) 18%, transparent);
149
+ }
150
+
151
+ .number[aria-invalid='true'] {
152
+ border-color: var(--dsw-alias-state-error-primary, #dc2626);
153
+ }
154
+
155
+ .unit {
156
+ font-size: 12px;
157
+ line-height: 18px;
158
+ color: var(--dsw-alias-label-tertiary, #8b93a1);
159
+ }
160
+
161
+ .actions {
162
+ display: flex;
163
+ align-items: center;
164
+ justify-content: flex-end;
165
+ gap: 8px;
166
+ padding: 12px 0 4px;
167
+ border-top: 1px solid var(--dsw-alias-border-l2, #e5e7eb);
168
+ }
169
+
170
+ .failed {
171
+ flex: 1;
172
+ min-width: 0;
173
+ margin: 0;
174
+ font-size: 12px;
175
+ line-height: 18px;
176
+ color: var(--dsw-alias-label-error, #dc2626);
177
+ }
178
+
179
+ .notice {
180
+ margin: 0;
181
+ padding: 12px 0;
182
+ font-size: 12px;
183
+ line-height: 18px;
184
+ color: var(--dsw-alias-label-tertiary, #8b93a1);
185
+ }
@@ -26,6 +26,7 @@ import { registerShowTaskPanelView } from './ShowTaskPanelNode.tsx'
26
26
  import { taskUIStore } from './task-ui-store.ts'
27
27
  import { createSlashSource } from './slash.ts'
28
28
  import { DEGRADED_GRACE_MS, later, missingServices, service } from './services.ts'
29
+ import { registerSettingsCard } from './settings-card.tsx'
29
30
 
30
31
  const NS = 'dsh-project-memory'
31
32
 
@@ -174,8 +175,10 @@ function reportDegradedLater(ctx: any): void {
174
175
  }
175
176
 
176
177
  export function apply(ctx: any): void {
177
- // 顶层不再有任何硬依赖:这里的三步都在缺服务时降级,绝不早退(早退就是静默消失)。
178
+ // 顶层不再有任何硬依赖:这里的几步都在缺服务时降级,绝不早退(早退就是静默消失)。
178
179
  registerTaskPanel(ctx)
179
180
  registerSlashSource(ctx)
181
+ // 插件详情页上的可视化设置:宿主没有 settings / configForms 时整段不跑(见 settings-card.tsx)。
182
+ registerSettingsCard(ctx)
180
183
  reportDegradedLater(ctx)
181
184
  }
@@ -88,6 +88,22 @@ export const zh = {
88
88
  'slash.tasks-desc': '任务清单:步骤进度、涉及文件、当前会话绑定',
89
89
  'slash.project-desc': '项目记忆:本项目的教训 / 决策 / 流程',
90
90
  'slash.global-desc': '全局记忆:跨项目的经验条目',
91
+ // 插件页上的可视化设置卡片(src/client/settings-card.tsx)。
92
+ 'settings.title': '常用设置',
93
+ 'settings.subtitle': '保存后立即生效(启动时全量索引除外);其余配置在 profile 的 cordis.patch.yml 里。',
94
+ 'settings.unsaved': '未保存',
95
+ 'settings.autoIndexOnFirstUse.title': '启动时全量索引',
96
+ 'settings.autoIndexOnFirstUse.hint': '插件加载后扫描当前工作目录;打开后从下次启动开始生效。',
97
+ 'settings.watchInterval.title': '刷新间隔',
98
+ 'settings.watchInterval.hint': '后台自动刷新索引的频率(秒)。回合进行中降频,空闲时最多退避到 2 分钟。',
99
+ 'settings.llmQueryExpansion.title': '检索时扩展查询',
100
+ 'settings.llmQueryExpansion.hint': '让模型先改写几条变体查询再检索,命中更准,但会消耗 token。',
101
+ 'settings.unit.seconds': '秒',
102
+ 'settings.form.unavailable': '设置不可用:宿主没有提供本插件的配置命名空间。',
103
+ 'settings.form.readOnly': '当前部署只读,改动无法保存。',
104
+ 'settings.form.saveFailed': '宿主没有接受这次保存,请检查取值。',
105
+ 'settings.form.save': '保存',
106
+ 'settings.form.saving': '保存中…',
91
107
  }
92
108
 
93
109
  export const en = {
@@ -174,6 +190,21 @@ export const en = {
174
190
  'slash.tasks-desc': 'Task list: progress, involved files, current session binding',
175
191
  'slash.project-desc': 'Project memory: this project’s lessons / decisions / procedures',
176
192
  'slash.global-desc': 'Global memory: experience entries shared across projects',
193
+ 'settings.title': 'Common settings',
194
+ 'settings.subtitle': 'Saved changes apply immediately, except the startup full index; the rest stays in the profile’s cordis.patch.yml.',
195
+ 'settings.unsaved': 'Unsaved',
196
+ 'settings.autoIndexOnFirstUse.title': 'Full index on startup',
197
+ 'settings.autoIndexOnFirstUse.hint': 'Scan the current working directory after the plugin loads; takes effect from the next start.',
198
+ 'settings.watchInterval.title': 'Refresh interval',
199
+ 'settings.watchInterval.hint': 'How often the index refreshes in the background, in seconds. Slower during a turn, up to two minutes when idle.',
200
+ 'settings.llmQueryExpansion.title': 'Expand queries',
201
+ 'settings.llmQueryExpansion.hint': 'Ask the model for a few query variants before search: better recall, spends tokens.',
202
+ 'settings.unit.seconds': 's',
203
+ 'settings.form.unavailable': 'Settings unavailable: the host serves no configuration namespace for this plugin.',
204
+ 'settings.form.readOnly': 'This deployment is read-only; changes cannot be saved.',
205
+ 'settings.form.saveFailed': 'The host rejected this save; check the values.',
206
+ 'settings.form.save': 'Save',
207
+ 'settings.form.saving': 'Saving…',
177
208
  }
178
209
 
179
210
  export type LocaleDict = typeof zh
@@ -0,0 +1,346 @@
1
+ /**
2
+ * 插件详情页上的「常用设置」卡片。
3
+ *
4
+ * 座位是 `plugins.bundle.config`(key = 包名),外形照宿主自己的插件卡片长:
5
+ * 一行标题 + 说明 + 折叠箭头,**默认收起**;展开后是一列开关,底部右对齐一个保存。
6
+ *
7
+ * 数据面**完全走宿主设置**,不自建第二份配置:
8
+ * Config 里标了 `.volatile()` 的字段 → 宿主 settings 文档的一个命名空间(ns = 条目 id
9
+ * `project-memory`)→ 客户端 `ctx.configForms.get('project-memory')` 读写 → 宿主校验 +
10
+ * revision fence + volatile 原地更新(不重启插件)。这里既不写 profile 的 yml,也不缓存
11
+ * 值:卡片永远是宿主那份配置的投影,命令行改配置和这里改配置是同一条链路。
12
+ *
13
+ * 只放**用户真的会想调、且调了不会让记忆失真**的旋钮(见 SETTINGS_FIELDS 的注释)。
14
+ * memoryDir / roots / insight.* 这类一改就换数据位置或需要理解上下文的,仍留在 profile。
15
+ */
16
+ import {
17
+ Button, SettingsFormModel, Switch, settingsNumberField,
18
+ } from '@deepseek-ai/dsh-client-ui-primitives'
19
+ import type {
20
+ SettingsFieldSpec, SettingsFieldState, SettingsFormActions, SettingsFormScope, SettingsFormShell,
21
+ } from '@deepseek-ai/dsh-client-ui-primitives'
22
+ import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
23
+ import { useEffect, type ReactNode } from 'react'
24
+ import { IconChevronDownOutline14 } from './icons.ts'
25
+ import { createTranslate, en, zh, type LocaleDict } from './locales.ts'
26
+ import css from './SettingsCard.module.css'
27
+
28
+ /** bundle 包名:`plugins.bundle.config` 的 key 必须与 profile 里安装的包名一致。 */
29
+ export const SETTINGS_PACKAGE_NAME = '@yolk_vat-y/dsh-project-memory'
30
+ /** 本插件在 profile 的 loader 条目 id(bundle 的 cordis.patch.yml 定死的那个),也是 settings 命名空间。 */
31
+ export const SETTINGS_ENTRY_ID = 'project-memory'
32
+ /** 卡片文案的 locale 命名空间。与面板共用一份词典,但独立注册,互不影响。 */
33
+ export const SETTINGS_NS = 'dsh-project-memory.settings'
34
+
35
+ /**
36
+ * 卡片编辑的字段;顺序即渲染顺序。
37
+ *
38
+ * 入选标准只有两条:**用户会主动想调**,且**调坏了不会让记忆失真**。
39
+ * - `autoIndexOnFirstUse`:换项目时最常见的诉求("启动就把这里索引好"),默认关。
40
+ * - `watchInterval`:后台刷新唯一值得调的成本旋钮(频率)。监视本身**不提供关闭**——
41
+ * 关掉之后记忆只会越来越旧,那不是一个选项,是一个坑。
42
+ * - `llmQueryExpansion`:唯一直接花 token 的开关,该由用户自己决定。
43
+ * 刻意**没有**的:lazyIndexing(默认开,关掉只会让断言变旧)、enableTypeScript(内部实现
44
+ * 细节,用户无从判断)、watch(见上)、memoryDir / roots / 扫描上限(改的是数据落在哪)。
45
+ */
46
+ export const SETTINGS_FIELDS = [
47
+ 'autoIndexOnFirstUse',
48
+ 'watchInterval',
49
+ 'llmQueryExpansion',
50
+ ] as const
51
+ export type SettingsFieldName = typeof SETTINGS_FIELDS[number]
52
+
53
+ /** 卡片渲染的一份状态:表单级状态 + 展开状态 + 每个字段的草稿。 */
54
+ export interface SettingsCardState extends SettingsFormShell {
55
+ /** 卡片是否展开;默认收起,与宿主的插件卡片一致。 */
56
+ readonly expanded: boolean
57
+ readonly fields: Readonly<Record<SettingsFieldName, SettingsFieldState>>
58
+ }
59
+
60
+ /** 槽位注册侧注入给组件的动作与快照钩子。 */
61
+ export interface SettingsCardFace extends SettingsFormActions {
62
+ /** 收起 / 展开卡片。 */
63
+ toggleExpanded: () => void
64
+ hooks: {
65
+ /** 渲染器绑成 `useSettingsCard`。 */
66
+ settingsCard: SnapshotStore<SettingsCardState>
67
+ }
68
+ }
69
+
70
+ /** 渲染器交给组件的 props。`t` 由槽位的 `locale` 选项解析。 */
71
+ export interface SettingsCardProps {
72
+ /** 宿主只对 bundle 页要 `page`;`summary` 在本卡片没有对应物。 */
73
+ readonly view?: 'summary' | 'page'
74
+ readonly t?: (key: keyof LocaleDict, params?: Record<string, string | number>) => string
75
+ readonly useSettingsCard?: <S>(selector: (state: SettingsCardState) => S) => S
76
+ readonly toggleExpanded?: () => void
77
+ readonly edit?: (field: string, text: string) => void
78
+ readonly save?: () => void
79
+ readonly discard?: () => void
80
+ }
81
+
82
+ /** 布尔字段:草稿是 `'true'` / `'false'`,其它文本判为非法(挡住保存,而不是吞掉)。 */
83
+ function settingsBooleanField(field: string): SettingsFieldSpec {
84
+ return {
85
+ field,
86
+ format: value => typeof value === 'boolean' ? String(value) : '',
87
+ parse: text => text === 'true'
88
+ ? { kind: 'set', value: true }
89
+ : text === 'false'
90
+ ? { kind: 'set', value: false }
91
+ : undefined,
92
+ }
93
+ }
94
+
95
+ /** 把 `project-memory` 命名空间桥到卡片的状态上。 */
96
+ export class SettingsCardController {
97
+ private readonly form: SettingsFormModel<Record<string, unknown>>
98
+ private readonly store: SnapshotStore<SettingsCardState>
99
+ private expanded = false
100
+
101
+ /**
102
+ * @param scope - 宿主共享配置表单(`ctx.configForms.get('project-memory')`)
103
+ */
104
+ constructor(scope: SettingsFormScope<Record<string, unknown>>) {
105
+ this.form = new SettingsFormModel(scope, [
106
+ settingsBooleanField('autoIndexOnFirstUse'),
107
+ settingsNumberField('watchInterval'),
108
+ settingsBooleanField('llmQueryExpansion'),
109
+ ])
110
+ this.store = this.form.bind(() => this.projection())
111
+ }
112
+
113
+ /**
114
+ * 构造槽位注入面。
115
+ * @returns 快照钩子、展开动作与表单动作
116
+ */
117
+ inject(): SettingsCardFace {
118
+ return {
119
+ hooks: { settingsCard: this.store },
120
+ toggleExpanded: () => {
121
+ this.expanded = !this.expanded
122
+ // 展开状态不进表单模型;投影自己推一次,别等 scope 变化。
123
+ this.store.set(this.projection())
124
+ },
125
+ ...this.form.actions(),
126
+ }
127
+ }
128
+
129
+ /** 释放对宿主命名空间的订阅。 */
130
+ dispose(): void {
131
+ this.form.dispose()
132
+ }
133
+
134
+ private projection(): SettingsCardState {
135
+ const fields = {} as Record<SettingsFieldName, SettingsFieldState>
136
+ for (const field of SETTINGS_FIELDS) fields[field] = this.form.field(field)
137
+ return { ...this.form.shell(), expanded: this.expanded, fields }
138
+ }
139
+ }
140
+
141
+ /** 一行:左侧标题 + 说明,右侧控件(与宿主插件卡片的行同构)。 */
142
+ function SettingRow(props: {
143
+ readonly title: string
144
+ readonly hint: string
145
+ readonly children: ReactNode
146
+ }) {
147
+ return (
148
+ <div className={css.row}>
149
+ <div className={css.labelBox}>
150
+ <span className={css.label}>{props.title}</span>
151
+ <span className={css.hint}>{props.hint}</span>
152
+ </div>
153
+ <div className={css.control}>{props.children}</div>
154
+ </div>
155
+ )
156
+ }
157
+
158
+ /** 宿主导出的"可渲染组件":普通函数组件,或 `forwardRef` / `memo` 返回的对象。 */
159
+ function isComponent(value: unknown): boolean {
160
+ return typeof value === 'function' || (typeof value === 'object' && value !== null)
161
+ }
162
+
163
+ /** 渲染器缺钩子时的占位状态:卡片只显示标题,不读任何宿主值。 */
164
+ const UNAVAILABLE_STATE: SettingsCardState = {
165
+ available: false,
166
+ writable: false,
167
+ dirty: false,
168
+ invalid: false,
169
+ saving: false,
170
+ failed: false,
171
+ expanded: false,
172
+ fields: Object.fromEntries(
173
+ SETTINGS_FIELDS.map(field => [field, { text: '', overridden: false, invalid: false }]),
174
+ ) as Record<SettingsFieldName, SettingsFieldState>,
175
+ }
176
+
177
+ /** 非 Hook 的稳定回退:hook 数量在两次渲染之间不变,避免条件调用 Hooks。 */
178
+ const fallbackHook = <S,>(selector: (state: SettingsCardState) => S): S => selector(UNAVAILABLE_STATE)
179
+
180
+ /**
181
+ * 渲染本插件的常用设置。
182
+ * @param props - 表单快照与动作(由槽位注入)
183
+ * @returns 折叠卡片;`summary` 视图不渲染
184
+ */
185
+ export function SettingsCard(props: SettingsCardProps) {
186
+ const t = props.t ?? createTranslate(zh)
187
+ const useSettingsCard = props.useSettingsCard ?? fallbackHook
188
+ // Hook 必须无条件调用:`summary` 只影响后面的返回,不影响 hook 顺序。
189
+ const state = useSettingsCard(snapshot => snapshot)
190
+ const discard = props.discard
191
+ // 离开页面时丢掉未保存的草稿(与宿主设置表单的约定一致;收起卡片不算离开)。
192
+ useEffect(() => () => { discard?.() }, [discard])
193
+ if (props.view === 'summary') return null
194
+ const edit = props.edit
195
+ const save = props.save
196
+ if (edit === undefined || save === undefined) return null
197
+ const disabled = !state.writable || state.saving
198
+ const on = (field: SettingsFieldName): boolean => state.fields[field]?.text === 'true'
199
+ const toggle = (field: SettingsFieldName, next: boolean): void => { edit(field, next ? 'true' : 'false') }
200
+ const expanded = state.expanded === true
201
+ const saveBlocked = !state.dirty || state.invalid || state.saving || !state.writable
202
+
203
+ return (
204
+ <div className={expanded ? `${css.card} ${css.cardOpen}` : css.card} data-project-memory-settings>
205
+ <button
206
+ type="button"
207
+ className={css.header}
208
+ aria-expanded={expanded}
209
+ onClick={props.toggleExpanded}
210
+ >
211
+ <span className={css.headText}>
212
+ <span className={css.name}>{t('settings.title')}</span>
213
+ <span className={css.desc}>{t('settings.subtitle')}</span>
214
+ </span>
215
+ {state.dirty ? <span className={css.unsaved}>{t('settings.unsaved')}</span> : null}
216
+ <span className={expanded ? `${css.chevron} ${css.chevronOpen}` : css.chevron}>
217
+ <IconChevronDownOutline14 />
218
+ </span>
219
+ </button>
220
+ {expanded
221
+ ? (
222
+ <div className={css.body}>
223
+ {state.available
224
+ ? (
225
+ <>
226
+ {!state.writable ? <p className={css.notice}>{t('settings.form.readOnly')}</p> : null}
227
+ <SettingRow title={t('settings.autoIndexOnFirstUse.title')} hint={t('settings.autoIndexOnFirstUse.hint')}>
228
+ <Switch
229
+ checked={on('autoIndexOnFirstUse')} disabled={disabled}
230
+ label={t('settings.autoIndexOnFirstUse.title')}
231
+ onChange={(next) => { toggle('autoIndexOnFirstUse', next) }}
232
+ />
233
+ </SettingRow>
234
+ <SettingRow title={t('settings.watchInterval.title')} hint={t('settings.watchInterval.hint')}>
235
+ <input
236
+ className={css.number}
237
+ type="number"
238
+ min={5}
239
+ max={600}
240
+ step={1}
241
+ inputMode="numeric"
242
+ aria-label={t('settings.watchInterval.title')}
243
+ value={state.fields.watchInterval.text}
244
+ disabled={disabled}
245
+ aria-invalid={state.fields.watchInterval.invalid || undefined}
246
+ onChange={(event) => { edit('watchInterval', event.target.value) }}
247
+ />
248
+ <span className={css.unit}>{t('settings.unit.seconds')}</span>
249
+ </SettingRow>
250
+ <SettingRow title={t('settings.llmQueryExpansion.title')} hint={t('settings.llmQueryExpansion.hint')}>
251
+ <Switch
252
+ checked={on('llmQueryExpansion')} disabled={disabled}
253
+ label={t('settings.llmQueryExpansion.title')}
254
+ onChange={(next) => { toggle('llmQueryExpansion', next) }}
255
+ />
256
+ </SettingRow>
257
+ <div className={css.actions}>
258
+ {state.failed ? <p className={css.failed} role="status">{t('settings.form.saveFailed')}</p> : null}
259
+ <Button
260
+ variant="primary"
261
+ size="sm"
262
+ disabled={saveBlocked}
263
+ onClick={save}
264
+ >
265
+ {state.saving ? t('settings.form.saving') : t('settings.form.save')}
266
+ </Button>
267
+ </div>
268
+ </>
269
+ )
270
+ : <p className={css.notice}>{t('settings.form.unavailable')}</p>}
271
+ </div>
272
+ )
273
+ : null}
274
+ </div>
275
+ )
276
+ }
277
+
278
+ /**
279
+ * 注册卡片(软依赖,永不抛出)。
280
+ *
281
+ * 两层门控:
282
+ * 1. 嵌套 `inject(['slots','configForms','locale'])` —— 宿主没有设置服务时这里根本不跑;
283
+ * 2. `configForms.whileServed(['project-memory'])` + `slots.inject('plugins.bundle.config')`
284
+ * —— 命名空间没被宿主提供、或该版本没有这个槽时,不留下任何注册痕迹。
285
+ * @param ctx - client 根上下文
286
+ */
287
+ export function registerSettingsCard(ctx: any): void {
288
+ if (typeof ctx?.inject !== 'function') return
289
+ try {
290
+ ctx.inject(['slots', 'configForms', 'locale'], (scope: any) => {
291
+ try {
292
+ mountSettingsCard(scope)
293
+ } catch (err) {
294
+ console.warn(`[${SETTINGS_NS}] settings card registration failed:`, err)
295
+ }
296
+ })
297
+ } catch (err) {
298
+ console.warn(`[${SETTINGS_NS}] settings card injection failed:`, err)
299
+ }
300
+ }
301
+
302
+ /**
303
+ * 在已就绪的 scope 上挂载卡片。
304
+ * @param scope - 三个服务齐备的嵌套上下文
305
+ */
306
+ function mountSettingsCard(scope: any): void {
307
+ const slots = scope?.slots
308
+ const configForms = scope?.configForms
309
+ const locale = scope?.locale
310
+ if (typeof slots?.inject !== 'function' || typeof configForms?.get !== 'function'
311
+ || typeof configForms?.whileServed !== 'function' || typeof locale?.register !== 'function') return
312
+ // 卡片的保存按钮 / 开关来自宿主 ui-primitives:缺任何一个都别注册,避免渲染时才炸。
313
+ //
314
+ // ⚠ 组件不等于函数:宿主用 `forwardRef` 包了 Button(导出是对象 `{ $$typeof, render }`),
315
+ // 用 `typeof x === 'function'` 判定会把它当成"不存在",卡片在真实宿主上整块消失。
316
+ // 这就是当初"测试全绿、界面没东西"的原因 —— 判定必须接受函数与对象两种导出形状。
317
+ if (typeof SettingsFormModel !== 'function' || !isComponent(Switch) || !isComponent(Button)) {
318
+ console.warn(`[${SETTINGS_NS}] host ui-primitives has no settings controls — visual settings disabled`)
319
+ return
320
+ }
321
+ const effect = typeof scope.effect === 'function' ? scope.effect.bind(scope) : null
322
+ const keep = (dispose: unknown): void => {
323
+ if (typeof dispose !== 'function' || effect === null) return
324
+ effect(() => () => {
325
+ try {
326
+ dispose()
327
+ } catch {
328
+ // 宿主已经拆掉这层:忽略
329
+ }
330
+ })
331
+ }
332
+ try {
333
+ keep(locale.register(SETTINGS_NS, { zh, en }))
334
+ } catch (err) {
335
+ // 同 namespace 已注册(HMR 没等到 disposer):沿用既有词典,卡片照常挂。
336
+ console.warn(`[${SETTINGS_NS}] locale dictionary already registered:`, err)
337
+ }
338
+ const controller = new SettingsCardController(configForms.get(SETTINGS_ENTRY_ID))
339
+ keep(() => controller.dispose())
340
+ keep(configForms.whileServed([SETTINGS_ENTRY_ID], () => slots.inject('plugins.bundle.config', () => slots.register({
341
+ name: 'plugins.bundle.config',
342
+ key: SETTINGS_PACKAGE_NAME,
343
+ locale: SETTINGS_NS,
344
+ inject: () => controller.inject(),
345
+ }, SettingsCard))))
346
+ }