Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

## [Unreleased]

- Keep executor selections, disclosure tier 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)。

## [0.5.6] — 2026-11-21 — Patch release

- ops-ptc's batching teacher trajectory now teaches sandbox authority: the lesson states the
Expand Down
14 changes: 8 additions & 6 deletions src/client/forms.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,29 @@ export function useEditor<T>(form: ConfigPageForm | undefined, read: (value: Rec
const [draft, setDraft] = useState(() => read(form?.state.value ?? {}))
const [baseline, setBaseline] = useState<Record<string, unknown>>(() => 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.
const ready = form?.state.status === 'ready' && form.state.writable !== false
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 }
Expand Down
20 changes: 11 additions & 9 deletions src/client/row-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,25 @@ 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<string, unknown>) => readRowValues(value, { pwsh7Installed }), [pwsh7Installed])
const read = useMemo(() => (value: Record<string, unknown>) => ({
switches: readRowValues(value, { pwsh7Installed }), choice: readExecutor(value), tier: readDisclosure(value),
}), [pwsh7Installed])
const editor = useEditor(form, read, t)
const [opened, setOpened] = useState<Record<string, boolean>>({})
const [choice, setChoice] = useState<ExecutorChoice>(() => readExecutor(form?.state.value ?? {}))
const [tier, setTier] = useState<DisclosureSelection>(() => readDisclosure(form?.state.value ?? {}))
const choice = editor.draft.choice
const setChoice = (value: ExecutorChoice) => editor.edit({ ...editor.draft, choice: value })
const tier = editor.draft.tier
const setTier = (value: DisclosureSelection) => editor.edit({ ...editor.draft, tier: 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 or disclosure tier.
useEffect(() => {
if (editor.dirty) return
setChoice(readExecutor(editor.baseline))
setTier(readDisclosure(editor.baseline))
setCheck(undefined)
}, [editor.baseline, editor.dirty])
if (!editor.ready) return <Unavailable {...props} />
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 savedTier = readDisclosure(editor.baseline)
Expand All @@ -68,7 +70,7 @@ export function RowForm(props: SettingsProps & { Switch: SwitchBinding; pwsh7Ins
} catch (error) { setCheck({ ok: false, text: errorText(error) }) }
}

/** Save switches and the executor in one revision-checked write. */
/** Save switches, executor and disclosure tier in one revision-checked write. */
async function submit(event: { preventDefault(): void }): Promise<void> {
event.preventDefault()
if (editor.busy || saving) return
Expand Down Expand Up @@ -97,7 +99,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 <form className="ops-settings" onSubmit={event => { void submit(event) }}>
{groupsFor(editor.baseline).map(group => {
const enabled = group.toggle ? draft[`${group.id}.enabled`] !== false : true
Expand Down Expand Up @@ -216,7 +218,7 @@ export function RowForm(props: SettingsProps & { Switch: SwitchBinding; pwsh7Ins
</div>
</section>
<FormActions busy={editor.busy || saving} dirty={editor.dirty || executorDirty || tierDirty} valid
reset={() => { editor.reset(); setChoice(savedChoice); setTier(savedTier); setCheck(undefined) }} message={editor.message} t={t} />
reset={() => { editor.reset(); setCheck(undefined) }} message={editor.message} t={t} />
</form>
}

Expand Down
222 changes: 222 additions & 0 deletions test/settings-editor.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
/** 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('<!doctype html><html><body></body></html>', { 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() }
})

await test('disclosure-only drafts keep their revision across host refresh and reset to the latest tier', async () => {
const calls = []
const form = { state: ready({}), mutate: async (...args) => { calls.push(args); return false } }
const view = await mount(form)
const full = () => view.container.querySelectorAll('input[name=ops-disclosure]')[1]
try {
await click(full())
form.state = ready({ ptc: { disclosurePolicy: 'full' } }, 'v2')
await view.render(zh)
assert.equal(full().checked, true, 'host refresh retains the chosen tier')
await click(view.save())
assert.deepEqual(calls, [[[
{ op: 'set', path: ['ptc', 'disclosurePolicy'], value: 'full' },
{ op: 'set', path: ['ops-ptc', 'disclosurePolicy'], value: 'full' },
], 'v1']])
assert.equal(view.status(), zh.rejected)
await click(view.reset())
assert.equal(full().checked, false, 'reset adopts the latest mixed tier')
assert.equal(view.save().disabled, true)
await view.render(en)
await click(view.switch()); await click(view.save())
assert.deepEqual(calls[1], [[switchOp], 'v2'])
} finally { await view.close() }
})

await test('executor drafts do not adopt or overwrite a concurrently changed disclosure tier', async () => {
const calls = []
const form = { state: ready({}), mutate: async (...args) => { calls.push(args); return false } }
const view = await mount(form)
try {
await click(view.radio('git')); await type(view, selectedPath)
form.state = ready({ ptc: { disclosurePolicy: 'full' }, 'ops-ptc': { disclosurePolicy: 'full' } }, 'v2')
await view.render()
assert.equal(view.container.querySelector('input[name=ops-disclosure]').checked, true)
await click(view.save())
assert.deepEqual(calls, [[pathOps(selectedPath), 'v1']], 'executor-only save must not write disclosure')
await click(view.reset())
assert.equal(view.container.querySelectorAll('input[name=ops-disclosure]')[1].checked, true)
assert.equal(view.save().disabled, true)
} finally { await view.close() }
})

dom.window.close()
report('settings-editor')