From ccae6f99ab00ffe85b6e6c491d0d406ca73b3074 Mon Sep 17 00:00:00 2001 From: Chirag Singhal <76880977+chirag127@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:19:51 +0530 Subject: [PATCH] fix(settings): preserve executor drafts and translate save notices --- docs/CHANGELOG.md | 3 + src/client/forms.tsx | 14 +-- src/client/row-form.tsx | 14 +-- test/settings-editor.test.mjs | 180 ++++++++++++++++++++++++++++++++++ 4 files changed, 199 insertions(+), 12 deletions(-) create mode 100644 test/settings-editor.test.mjs diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index d66194e1..82e2aca5 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,6 +7,9 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [Unreleased] +- Keep executor selections and switches in one row-editor draft, preserving the original baseline and revision across host refreshes until reset or an accepted save. Saved/refused notices now follow the active page language, including saves completed after a language change; raw host errors remain unchanged (#1028). +- 执行器选择与开关现在共用行编辑器草稿,在宿主刷新时保留原始基线与修订号,直到重置或保存被接受。保存成功及拒绝提示随页面当前语言更新,包括切换语言后完成的保存;宿主原始错误文本保持不变(#1028)。 + - Native tool construction and the publication refusal queue no longer attach listeners or lifetime effects to the composition root. The evidence observer and result admission subscribe on the caller's context with global dispatch, and the refusal queue falls back to the caller lifetime when the root refuses an effect. dsh-tui 0.20 refuses `root.events.on` and `root.effect` from a plugin activation, and the native-tools row is one, so every `dsh-tui --resume` aborted with "cannot resume session" before the agent mounted. - 原生工具构造与发布拒绝队列不再向组合根挂监听或生命周期 effect:证据观察者与 result admission 改为在调用方上下文订阅并声明 global 分发,拒绝队列在 root 拒绝 effect 时回落到调用方生命周期。dsh-tui 0.20 会拒绝插件激活期内的 `root.events.on` 与 `root.effect`,而原生工具行正是插件激活,导致每次 `dsh-tui --resume` 都在 agent 挂载前报 "cannot resume session"。 - The Bash tool description now states the parse contract of `stdout`/`stderr` where the model reads it: `text` may be a partial fragment, `truncated` marks one that must not be parsed as complete structured output, and `spillPath` is optional and not a completeness guarantee. The typed output schema is unchanged: repeating the contract there would cost every PTC request without saying anything the tool text does not. Command semantics, exit codes, result values, limits, spill files, permissions and rendering are unchanged. diff --git a/src/client/forms.tsx b/src/client/forms.tsx index 2adccfd5..13a8a0da 100644 --- a/src/client/forms.tsx +++ b/src/client/forms.tsx @@ -16,7 +16,9 @@ export function useEditor(form: ConfigPageForm | undefined, read: (value: Rec const [draft, setDraft] = useState(() => read(form?.state.value ?? {})) const [baseline, setBaseline] = useState>(() => form?.state.value ?? {}) const [revision, setRevision] = useState(form?.state.revision) - const [dirty, setDirty] = useState(false), [busy, setBusy] = useState(false), [message, setMessage] = useState('') + const [dirty, setDirty] = useState(false), [busy, setBusy] = useState(false) + const [notice, setNotice] = useState<{ key: 'saved' | 'rejected' } | { text: string }>() + const message = notice === undefined ? '' : 'key' in notice ? t(notice.key) : notice.text // A ready Host document that accepts writes is editable. The Host used to // distinguish its own page from another editor's with a `mode` field; that // field is gone, so writability is the only gate left. @@ -24,19 +26,19 @@ export function useEditor(form: ConfigPageForm | undefined, read: (value: Rec useEffect(() => { if (!dirty) { setDraft(read(form?.state.value ?? {})); setBaseline(form?.state.value ?? {}); setRevision(form?.state.revision) } }, [form?.state.revision, form?.state.status, read, dirty]) - const edit = (value: T) => { setDraft(value); setDirty(true); setMessage('') } + const edit = (value: T) => { setDraft(value); setDirty(true); setNotice(undefined) } const reset = () => { setDraft(read(form?.state.value ?? {})); setBaseline(form?.state.value ?? {}) - setRevision(form?.state.revision); setDirty(false); setMessage('') + setRevision(form?.state.revision); setDirty(false); setNotice(undefined) } const save = async (operations: readonly SettingsPathOpView[]) => { if (!form || !ready || busy || revision === undefined) return - setBusy(true); setMessage('') + setBusy(true); setNotice(undefined) try { const accepted = await form.mutate(operations, revision) - setMessage(t(accepted ? 'saved' : 'rejected')) + setNotice({ key: accepted ? 'saved' : 'rejected' }) if (accepted) setDirty(false) - } catch (error) { setMessage(errorText(error)) } + } catch (error) { setNotice({ text: errorText(error) }) } finally { setBusy(false) } } return { draft, baseline, edit, dirty, busy, ready, message, reset, save } diff --git a/src/client/row-form.tsx b/src/client/row-form.tsx index 32365cba..a8cfe2e3 100644 --- a/src/client/row-form.tsx +++ b/src/client/row-form.tsx @@ -32,21 +32,23 @@ export interface ExecutorSurface { export function RowForm(props: SettingsProps & { Switch: SwitchBinding; pwsh7Installed?: boolean; executor: ExecutorSurface }) { const { form, t, Switch, pwsh7Installed, executor } = props // A stable reader: a fresh closure would re-run the editor's effect every render. - const read = useMemo(() => (value: Record) => readRowValues(value, { pwsh7Installed }), [pwsh7Installed]) + const read = useMemo(() => (value: Record) => ({ + switches: readRowValues(value, { pwsh7Installed }), choice: readExecutor(value), + }), [pwsh7Installed]) const editor = useEditor(form, read, t) const [opened, setOpened] = useState>({}) - const [choice, setChoice] = useState(() => readExecutor(form?.state.value ?? {})) + const choice = editor.draft.choice + const setChoice = (value: ExecutorChoice) => editor.edit({ ...editor.draft, choice: value }) const [check, setCheck] = useState<{ ok: boolean; text: string }>() const [saving, setSaving] = useState(false) // The saved row is the baseline: a Host reload while the page is dirty must not // silently adopt somebody else's executor. useEffect(() => { if (editor.dirty) return - setChoice(readExecutor(editor.baseline)) setCheck(undefined) }, [editor.baseline, editor.dirty]) if (!editor.ready) return - const draft = editor.draft, gates = bundleGates(draft) + const draft = editor.draft.switches, gates = bundleGates(draft) const savedChoice = readExecutor(editor.baseline) const executorDirty = executorDiffers(choice, editor.baseline) const candidates = executor.snapshot?.git ?? [] @@ -89,7 +91,7 @@ export function RowForm(props: SettingsProps & { Switch: SwitchBinding; pwsh7Ins const pwsh7Link = draft['other.pwsh7Link'] === true // Detection would turn this on; an explicit off is worth naming so it is not read as a bug. const explicitOff = pwsh7Installed === true && draft['other.pwsh7Link'] === false - const set = (flat: string, value: boolean) => editor.edit({ ...draft, [flat]: value }) + const set = (flat: string, value: boolean) => editor.edit({ ...editor.draft, switches: { ...draft, [flat]: value } }) return
{ void submit(event) }}> {groupsFor(editor.baseline).map(group => { const enabled = group.toggle ? draft[`${group.id}.enabled`] !== false : true @@ -179,7 +181,7 @@ export function RowForm(props: SettingsProps & { Switch: SwitchBinding; pwsh7Ins { editor.reset(); setChoice(savedChoice); setCheck(undefined) }} message={editor.message} t={t} /> + reset={() => { editor.reset(); setCheck(undefined) }} message={editor.message} t={t} /> } diff --git a/test/settings-editor.test.mjs b/test/settings-editor.test.mjs new file mode 100644 index 00000000..e0b85b6e --- /dev/null +++ b/test/settings-editor.test.mjs @@ -0,0 +1,180 @@ +/** Row draft and status lifetimes under host revision and language changes. */ +import { JSDOM } from 'jsdom' +import { assert, test, report } from './lib/harness.mjs' +import { RowForm } from '../lib/client/row-form.js' +import { en, zh } from '../lib/client/locales.js' + +const dom = new JSDOM('', { url: 'http://localhost/' }) +for (const name of ['window', 'document', 'HTMLElement', 'HTMLInputElement', 'Node', 'Event', 'MouseEvent']) globalThis[name] = dom.window[name] +Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.window.navigator }) +globalThis.IS_REACT_ACT_ENVIRONMENT = true +const { createElement: h, act } = await import('react') +const { createRoot } = await import('react-dom/client') +const translate = dictionary => (key, params) => String(dictionary[key]).replace(/\{(\w+)\}/g, (_, name) => String(params?.[name] ?? `{${name}}`)) +const Switch = ({ checked, label, disabled, onChange }) => h('button', { + type: 'button', role: 'switch', 'aria-label': label, 'aria-checked': String(checked), disabled, + onClick: () => onChange(!checked), +}) +const ready = (value, revision = 'v1') => ({ status: 'ready', writable: true, value, base: {}, user: {}, revision }) +const selectedPath = 'C:/draft/bash.exe' +const modes = ['minimal', 'standard', 'ptc', 'ops-ptc', 'cordis'] +const pathOps = file => modes.map(mode => ({ op: 'set', path: [mode, 'bashPath'], value: file })) +const pathRow = file => Object.fromEntries(modes.map(mode => [mode, { bashPath: file }])) +const switchOp = { op: 'set', path: ['global', 'hideOfficialTools'], value: false } +async function mount(form, select = async request => ({ ok: true, value: { + clear: request.source === 'niubash', file: request.path, detail: 'Validated.', restriction: '', +} })) { + const container = document.createElement('div'); document.body.append(container) + const root = createRoot(container) + const executor = { api: { select }, snapshot: { git: ['C:/candidate/bash.exe'] }, busy: false, refresh() {} } + const render = (dictionary = en) => act(async () => root.render(h(RowForm, { form, t: translate(dictionary), Switch, executor }))) + await render() + return { container, render, save: () => container.querySelector('button[type=submit]'), + reset: () => container.querySelector('.ops-reset'), input: () => container.querySelector('input[type=text]'), + radio: engine => container.querySelectorAll('input[type=radio]')[engine === 'niubash' ? 0 : 1], + switch: () => container.querySelector(`[role=switch][aria-label="${en.hideOfficialTools}"]`), + status: () => container.querySelector('.ops-note')?.textContent, + async close() { await act(async () => root.unmount()); container.remove() } } +} +async function click(node) { assert.ok(node, 'DOM target exists'); await act(async () => node.click()) } +async function type(view, value) { + await act(async () => { + Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, 'value').set.call(view.input(), value) + view.input().dispatchEvent(new Event('input', { bubbles: true })) + }) +} + +await test('executor-only drafts retain the original revision and write set through a conflict, then reset to the host', async () => { + const calls = [], selections = [] + const form = { state: ready({}), mutate: async (...args) => { calls.push(args); return false } } + const view = await mount(form, async request => { + selections.push(request) + return { ok: true, value: { clear: false, file: request.path, detail: 'Validated.', restriction: '' } } + }) + try { + await click(view.radio('git')); await type(view, selectedPath) + assert.equal(view.input().value, selectedPath) + assert.equal(view.save().disabled, false) + form.state = ready({ ptc: { bashPath: 'C:/other/bash.exe' }, presets: { later: { bashPath: 'C:/later/bash.exe' } } }, 'v2') + await view.render() + assert.equal(view.input().value, selectedPath, 'host refresh must not discard an executor-only draft') + assert.equal(view.save().disabled, false) + assert.deepEqual(calls, [], 'refresh does not write') + await click(view.save()) + assert.deepEqual(selections, [{ source: 'git', path: selectedPath }]) + assert.deepEqual(calls, [[pathOps(selectedPath), 'v1']], 'new host paths are not silently adopted into the draft write set') + assert.equal(view.status(), en.rejected) + assert.equal(view.input().value, selectedPath) + assert.equal(view.save().disabled, false) + await click(view.reset()) + assert.equal(view.input(), null, 'reset adopts the mixed executor from the latest host row') + assert.equal(view.status(), undefined) + assert.equal(view.save().disabled, true) + await click(view.switch()); await click(view.save()) + assert.deepEqual(calls[1], [[switchOp], 'v2'], 'reset adopts the latest revision without rewriting executor paths') + } finally { await view.close() } +}) + +await test('combined drafts keep both fields and clear only executor paths from their original baseline', async () => { + const calls = [] + const form = { state: ready({ ptc: { bashPath: 'C:/saved/bash.exe' } }), mutate: async (...args) => { calls.push(args); return false } } + const view = await mount(form) + try { + await click(view.switch()); await click(view.radio('niubash')) + form.state = ready({ ptc: { bashPath: 'C:/other/bash.exe' }, standard: { bashPath: 'C:/new/bash.exe' } }, 'v2') + await view.render() + assert.equal(view.radio('niubash').checked, true) + assert.equal(view.switch().getAttribute('aria-checked'), 'false') + await click(view.save()) + assert.deepEqual(calls, [[[switchOp, { op: 'unset', path: ['ptc', 'bashPath'] }], 'v1']]) + assert.equal(view.status(), en.rejected) + } finally { await view.close() } +}) + +await test('switch-only drafts never adopt or write an executor changed by another editor', async () => { + const calls = [], selections = [] + const form = { state: ready({ ptc: { bashPath: 'C:/saved/bash.exe' } }), mutate: async (...args) => { calls.push(args); return false } } + const view = await mount(form, async request => { selections.push(request); throw new Error('Unexpected executor validation') }) + try { + await click(view.switch()) + form.state = ready({ ptc: { bashPath: 'C:/other/bash.exe' } }, 'v2') + await view.render(); await click(view.save()) + assert.equal(view.input().value, 'C:/saved/bash.exe') + assert.deepEqual(calls, [[[switchOp], 'v1']]) + assert.deepEqual(selections, []) + } finally { await view.close() } +}) + +await test('successful executor-only saves adopt the host-normalized path and next revision', async () => { + const calls = [], canonicalPath = 'C:/canonical/bash.exe' + const form = { state: ready({}), mutate: async (...args) => { + calls.push(args); form.state = ready(pathRow(canonicalPath), 'v2'); return true + } } + const view = await mount(form, async () => ({ ok: true, value: { clear: false, file: canonicalPath, detail: 'Validated.', restriction: '' } })) + try { + await click(view.radio('git')); await type(view, selectedPath); await click(view.save()) + assert.deepEqual(calls, [[pathOps(canonicalPath), 'v1']]) + assert.equal(view.input().value, canonicalPath) + assert.equal(view.save().disabled, true) + assert.equal(view.status(), en.saved) + await click(view.switch()); await click(view.save()) + assert.deepEqual(calls[1], [[switchOp], 'v2']) + } finally { await view.close() } +}) + +await test('clean forms follow host revisions and candidate edits keep their revision after refresh', async () => { + const calls = [] + const form = { state: ready({}), mutate: async (...args) => { calls.push(args); return false } } + const view = await mount(form) + try { + form.state = ready({ ptc: { bashPath: 'C:/host/bash.exe' } }, 'v2') + await view.render() + assert.equal(view.input().value, 'C:/host/bash.exe') + assert.equal(view.save().disabled, true) + await click(view.container.querySelector('.ops-candidate')) + form.state = ready({}, 'v3'); await view.render() + assert.equal(view.input().value, 'C:/candidate/bash.exe') + await click(view.save()) + assert.deepEqual(calls, [[pathOps('C:/candidate/bash.exe'), 'v2']]) + } finally { await view.close() } +}) + +for (const accepted of [true, false]) await test(`${accepted ? 'saved' : 'refused'} status retranslates on the mounted form without another write`, async () => { + let writes = 0 + const form = { state: ready({}), mutate: async () => { writes++; return accepted } } + const view = await mount(form) + try { + await click(view.switch()); await click(view.save()) + const key = accepted ? 'saved' : 'rejected' + assert.equal(view.status(), en[key]) + await view.render(zh) + assert.equal(view.save().textContent, zh.save) + assert.equal(view.status(), zh[key]) + await view.render(en) + assert.equal(view.status(), en[key]) + assert.equal(writes, 1) + } finally { await view.close() } +}) + +await test('in-flight save completion uses the current language while raw host errors stay literal', async () => { + let finish, writes = 0 + const form = { state: ready({}), mutate: () => { writes++; return new Promise(resolve => { finish = resolve }) } } + const view = await mount(form) + try { + await click(view.switch()); await click(view.save()); await view.render(zh) + assert.equal(view.save().textContent, zh.saving) + await act(async () => finish(false)) + assert.equal(view.status(), zh.rejected) + form.mutate = async () => { writes++; throw new Error('saved') } + await click(view.save()) + assert.equal(view.status(), 'saved', 'raw errors are not interpreted as translation keys') + await view.render(en) + assert.equal(view.status(), 'saved') + assert.equal(writes, 2) + await click(view.reset()) + assert.equal(view.status(), undefined) + } finally { await view.close() } +}) + +dom.window.close() +report('settings-editor')