fix(web): address settings document review

This commit is contained in:
Yichen Jiang
2026-08-04 17:31:36 +08:00
parent e31b7221e7
commit 4f717f2da7
42 changed files with 219 additions and 115 deletions

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/settings/settings-local/README.md
README.md: 16d66e3dd876ff58ba1745655b325212acc04ca1
README.zh.md: 75c3316bad3005a9e4e895699187a4b16ae8efef
README.md: d1f3d755f9073acdf6fcfc5d1de883d74cc023c4
README.zh.md: 3a290c2795e6d1944c5bce6edb99aab53f2728ee

View File

@@ -24,9 +24,9 @@ Defaulting is one explicit `resolveSpec(config)` step; an unsupported extension
- **YAML edits are leaf-level diffs.** A write sets only the values that changed and deletes only the keys that were removed, so comments, anchors, and formatting survive on every untouched node and on the key of every changed pair; a changed array (or other non-map value) replaces wholesale, taking comments inside it along. JSON re-serializes without comments.
- **Reloads and writes share one operation chain.** Watcher refreshes and persists from every namespace queue run one at a time in queue order; each render sees the text the previous operation committed.
- **The watcher's ready signal reconciles once.** The initial load races the watcher's own setup, so a change written in between never fires an event; the reconcile at ready closes that startup gap.
- **Dispose quiesces.** Teardown stops accepting watcher events, closes the watcher, then waits out any queued or in-flight operation, so nothing publishes after disposal.
- **Dispose quiesces in every watch mode.** Teardown marks the provider closed, closes the watcher when present, then waits out every queued or in-flight document operation, so nothing publishes after disposal.
- **Self-write suppression by content.** The provider caches the last good text; a watcher event whose content equals the cache (its own write included) is a no-op.
- **Local configuration surfaces receive the resolved path.** `ctx.settings.documentPath` is the absolute `resolveSpec()` filename, including a custom YAML/JSON path; `prepareDocument()` preserves an existing file or exclusively creates an absent empty file with owner-only permissions before the Host opens it. The browser never reconstructs `$DSH_HOME` or submits a filesystem target.
- **Host configuration adapters receive the resolved path.** `ctx.settings.documentPath` is the absolute `resolveSpec()` filename, including a custom YAML/JSON path; `prepareDocument()` preserves an existing file or exclusively creates an absent empty file with owner-only permissions before the Host opens it. The browser receives only an availability flag, never reconstructs `$DSH_HOME`, and never submits a filesystem target.
## Model Experience

View File

@@ -24,9 +24,9 @@
- **YAML 编辑是叶子级 diff。** 写入只设置发生变化的值、只删除被移除的键,因此注释、锚点与排版在每个未触碰的节点上以及每个被改键值对的键上都得以保留;被改的数组(或其他非 map 值整体替换其中的注释随之一同被换掉。JSON 重新序列化,无注释。
- **重载与写入共享一条操作链。** watcher 刷新与来自各 namespace 队列的 persist 按队列顺序逐个执行;每次渲染都基于上一次操作提交后的文本。
- **watcher 的 ready 信号做一次对账。** 初始加载与 watcher 自身的建立存在竞态因此其间写入的变更绝不会触发事件ready 时的对账补上这个启动缺口。
- **Dispose 保证静止。** 卸载先停止接收 watcher 事件、关闭 watcher再等完排队进行中的操作,之后不再有任何发布。
- **Dispose 在每种 watch 模式下都保证静止。** 卸载先把提供方标记为已关闭,在 watcher 存在时将其关闭,再等待所有已排队进行中的文档操作完成,之后不再有任何发布。
- **按内容抑制自写。** provider 缓存最后可用文本watcher 事件内容与缓存相同(含自己的写入)即为 no-op。
- **本地配置界面会收到解析后的路径。** `ctx.settings.documentPath``resolveSpec()` 得出的绝对文件名,包括自定义 YAML/JSON 路径;`prepareDocument()` 会保留现有文件,或在 Host 打开文档前,以仅属主可访问的权限独占创建缺失的空文件。浏览器绝不重建 `$DSH_HOME`,也不提交文件系统目标。
- **Host 配置适配器会收到解析后的路径。** `ctx.settings.documentPath``resolveSpec()` 得出的绝对文件名,包括自定义 YAML/JSON 路径;`prepareDocument()` 会保留现有文件,或在 Host 打开文档前,以仅属主可访问的权限独占创建缺失的空文件。浏览器只收到可用性标志,绝不重建 `$DSH_HOME`,也不提交文件系统目标。
## Model Experience

View File

@@ -234,34 +234,36 @@ export class SettingsLocal extends Settings {
// failure: an existing-but-invalid document must fail loud, never be
// silently ignored or overwritten.
yield* super[Service.init]()
if (!this.spec.watch) return
const watcher = chokidarWatch(this.spec.filename, {
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: this.spec.debounceMs,
pollInterval: Math.max(1, Math.min(this.spec.debounceMs, 10)),
},
})
watcher.on('all', () => {
if (this.closed) return
this.queueRefresh()
})
watcher.on('ready', () => {
// The base init's load raced the watcher's own setup: a change written
// between that read and the watcher becoming active never fires an
// event. One reconcile at ready closes the gap.
if (this.closed) return
this.queueRefresh()
})
watcher.on('error', (error) => {
this.ctx.logger.warn('settings-local: watcher error on %s', this.spec.filename)
this.ctx.logger.warn(error)
})
const watcher = this.spec.watch
? chokidarWatch(this.spec.filename, {
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: this.spec.debounceMs,
pollInterval: Math.max(1, Math.min(this.spec.debounceMs, 10)),
},
})
: undefined
if (watcher !== undefined) {
watcher.on('all', () => {
if (this.closed) return
this.queueRefresh()
})
watcher.on('ready', () => {
// The base init's load raced the watcher's own setup: a change written
// between that read and the watcher becoming active never fires an
// event. One reconcile at ready closes the gap.
if (this.closed) return
this.queueRefresh()
})
watcher.on('error', (error) => {
this.ctx.logger.warn('settings-local: watcher error on %s', this.spec.filename)
this.ctx.logger.warn(error)
})
}
yield async () => {
// Quiesce: stop accepting events, close the watcher, then wait out any
// queued or in-flight operation so nothing publishes after disposal.
// Quiesce every operation chain, even when no watcher is configured.
this.closed = true
await watcher.close()
await watcher?.close()
await this.operations
}
}

View File

@@ -72,10 +72,13 @@ describe('writer-lock failure cleanup', () => {
const dir = await tempDir()
const path = join(dir, 'settings.yaml')
const ctx = new Context()
const fiber = ctx.plugin(SettingsLocal, { path, watch: true, debounceMs: 0 })
const fiber = ctx.plugin(SettingsLocal, { path, watch: false })
cleanups.push(async () => { await fiber.dispose() })
await fiber
const settings = ctx.settings
settings.register(settingsNamespace('alpha'), AlphaSchema)
const published: number[] = []
ctx.on('settings/document-updated', (_ns, revision) => { published.push(revision) })
let markStarted!: () => void
const started = new Promise<void>((resolve) => { markStarted = resolve })
let releaseCreate!: () => void
@@ -85,14 +88,18 @@ describe('writer-lock failure cleanup', () => {
const preparing = settings.prepareDocument()
await started
let disposed = false
const disposing = fiber.dispose()
void disposing.then(() => { disposed = true })
await vi.waitFor(() => {
expect((settings as unknown as { closed: boolean }).closed).toBe(true)
})
expect(disposed).toBe(false)
releaseCreate()
await expect(preparing).resolves.toBe(path)
await disposing
expect(await readFile(path, 'utf8')).toBe('')
expect(published).toEqual([])
})
it('surfaces an exclusive document-create failure and releases the lock', async () => {

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/settings/settings/README.md
README.md: afb4ed5c2b560de1639e773da3447dd79f15c8dc
README.zh.md: 8a7cc0c555a8d02c36d60f5a0b321cea7b89e382
README.md: 0841624e553364fa03f7a1f1209aa72ab13d97e4
README.zh.md: fa84ca198ba7383f8fbd7b29a53d74f2c375bd5e

View File

@@ -6,7 +6,7 @@ Abstract user-settings seam (`ctx.settings`). One provider holds a raw document
## Service API
- `documentPath` — absolute path of the provider's user-editable file when it has one; non-file providers leave it `undefined`. Local configuration surfaces use it as availability metadata, never as a browser-selected open target.
- `documentPath` — absolute path of the provider's user-editable file when it has one; non-file providers leave it `undefined`. Host configuration adapters derive availability from it, while browser protocols expose only a boolean capability and never a filesystem target.
- `prepareDocument()` — return that path after making the document ready for a native editor. The base implementation returns `documentPath`; a file provider may materialize an absent document first.
- `register(ns, schema, { base?, applies? })` — returns the owner `SettingsScope` (`get`/`watch`/`update`). The registration is an effect on the calling plugin's fiber: disposing that fiber removes the namespace and its observers. A stored section the schema rejects fails the registration itself; a duplicate namespace fails loud.
- `describe(options?)` — one descriptor per namespace (`schema.toJSON()` envelope, resolved value, detached `base`/`user` layers, `applies`) for configuration surfaces; a field's presence in `user` is what marks it user-overridden. `describe({ redactSecrets: true })` strips `role('secret')` fields from every layer and adds the `secrets` slot list (`{ path, set }`); every wire surface MUST pass it, and the pure `redactSecrets(schema, value)` walker is exported for other wires.

View File

@@ -6,7 +6,7 @@
## 服务 API
- `documentPath` — 提供方拥有用户可编辑文件时,该字段是文件的绝对路径;非文件提供方保留 `undefined`本地配置界面仅将其用作可用性元数据,绝不把它当作由浏览器选定的打开目标。
- `documentPath` — 提供方拥有用户可编辑文件时,该字段是文件的绝对路径;非文件提供方保留 `undefined`Host 配置适配器据此派生可用性,而浏览器协议只暴露一个布尔能力,绝不暴露文件系统目标。
- `prepareDocument()` — 让文档做好供原生编辑器打开的准备后返回该路径。基类实现返回 `documentPath`;文件提供方可先创建缺失的文档。
- `register(ns, schema, { base?, applies? })` — 返回 owner 的 `SettingsScope``get`/`watch`/`update`)。注册是调用方插件 fiber 上的 effectdispose 该 fiber 即移除 namespace 及其观察者。schema 拒绝的存量分节会使注册本身失败;重复 namespace 立即报错。
- `describe(options?)` — 每个 namespace 一条描述(`schema.toJSON()` 信封、解析值、分离出的 `base`/`user` 层、`applies`),供配置界面使用;字段出现在 `user` 中即标记其被用户覆盖。`describe({ redactSecrets: true })` 从每一层剥离 `role('secret')` 字段,并附加 `secrets` 槽位列表(`{ path, set }`);每个 wire 面都必须传入它,纯遍历器 `redactSecrets(schema, value)` 已导出,供其他 wire 使用。