From e916d4ebb071365187febac32f784f848281156e Mon Sep 17 00:00:00 2001 From: Thatgfsj <171755367+Thatgfsj@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:44:18 +0800 Subject: [PATCH] feat(settings): let the user pick the PTC disclosure tier Add the row page's PTC disclosure tier card (#989): one choice unifies both PTC rows in a single revision-checked save. An untouched old profile is never written, on-demand returns both rows to the absent key, disagreeing rows are named mixed and unified by the next choice, and a cancelled edit writes nothing. The tier rides the merged row page as a volatile string beside bashPath; the legacy per-mode form stays YAML-only. While the dynamic-tools bundle switch is off the card names the suspension and keeps the saved choice. The end-to-end suite saves through the real host writer, boots the shipped apply from the loader-merged profile, and asserts the full tier's loader-less first round carries exactly the permitted pool; switching the tier between saves applies to the next session. --- docs/CHANGELOG.md | 2 + src/client/locales.ts | 18 +++ src/client/row-form.tsx | 47 ++++++- src/client/row-schema.ts | 52 +++++++ src/settings/merged.ts | 6 + test/ptc-disclosure-policy.test.mjs | 6 +- test/settings-disclosure-e2e.test.mjs | 195 ++++++++++++++++++++++++++ test/settings-host.test.mjs | 31 +++- test/settings-rows.test.mjs | 40 +++++- test/settings-ui.test.mjs | 74 ++++++++++ 10 files changed, 459 insertions(+), 12 deletions(-) create mode 100644 test/settings-disclosure-e2e.test.mjs diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 4dca796f..e32bf5a3 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,6 +7,8 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [Unreleased] +- Add the settings-page entry for the PTC disclosure tier (#989): the row page carries one **PTC disclosure tier** card — *On-demand (default)* or *Full* — that unifies both PTC rows in one revision-checked save. An old profile shows the default rung and is never written unless the operator changes it; picking on-demand returns both rows to the absent key, so a profile saved through the card is letter-identical to one that never met it; disagreeing saved rows are named `mixed` and unified by the next choice; a cancelled edit writes nothing. The tier rides the merged row page as a volatile string beside `bashPath` (the legacy per-mode form stays YAML-only), survives unrelated saves, and applies to new sessions; while the dynamic-tools bundle switch is off the card names the suspension and keeps the saved choice. The full choice saved through the real writer boots a loader-less first round carrying exactly the permitted pool — the cap is never widened — and switching the tier between saves applies to the next session. +- 新增 PTC 披露档位的设置页入口(#989):行页面提供一张「PTC 披露档位」卡片——按需(默认)或全量——一次版本校验的保存同时统一两条 PTC 行。旧档案默认显示默认档且绝不被动写入;选回「按需」会把两行都还原为键缺失,经卡片保存过的档案与从未见过卡片的档案逐字一致;两行不一致时点名 `mixed`,由下一次选择统一;取消编辑不写入任何内容。档位以 volatile 字符串挂在合并行页面(与 `bashPath` 并列;旧的逐模式表单保持 YAML-only),无关保存不会丢,且只对新会话生效;动态工具总开关关闭期间卡片点名暂停并保留已存选择。经真实写入器保存的全量选择启动无 loader 的首轮,且恰好携带获准池——上限从不扩大——保存之间切换档位对下一个会话生效。 - Align custom PTC integrations with the publication plan (#988): the scoped diagnostic's expected first-round names now come from the same disclosure derivation (`src/ptc/disclosure.ts`) the publication uses, so a legal `profile: 'ptc'` row no longer reads degraded with a lone `PUBLICATION_UNAVAILABLE: ops_result` — `result` is selectable, not resident — while the explicit full tier's whole pool is expected when a row selects it and a genuinely missing first-round name still reports. Custom rows accept the same `disclosurePolicy` key the builtin rows parse (`'on-demand'` default, `'full'` explicit, Native-presentation rows reject it; nothing ever writes it for you). The custom path still rejects `alwaysLoaded` outside `allowedTools` where builtin rows accept it silently, with both sides now asserted; a native custom preset's visible tools are snapshotted, and the D1 truth-table pin that locked the misdiagnosis is flipped to `ready`. No publication behaviour changes on the on-demand tier. - 对齐自定义 PTC 接入与发布计划(#988):作用域诊断的首轮期望名改由发布使用的同一份披露推导(`src/ptc/disclosure.ts`)生成——合法 `profile: 'ptc'` 行不再被误诊为仅剩 `PUBLICATION_UNAVAILABLE: ops_result` 的 degraded(`result` 是可选加载而非常驻);选择显式全量档的行其整池都在期望之内;真正缺失的首轮名仍会报告。自定义行接受与内置行相同的 `disclosurePolicy` 键(缺省 `'on-demand'`,显式 `'full'`,Native 展示行拒绝该键;任何升级或保存都不替你写入)。自定义路径对落在 `allowedTools` 之外的 `alwaysLoaded` 仍抛错而内置行静默接受,两侧均已断言;原生自定义 preset 的可见工具集已做快照;D1 锁定误报的真值表检查翻转为 `ready`。on-demand 档的发布行为不变。 - Publish the explicit full PTC disclosure tier (#987): with `disclosurePolicy: 'full'` the `ptc` and `ops-ptc` rows' first round now carries the whole permitted `allowedTools` pool plus `ops_result` (the D1 sign-off item 1 decision, taken conservatively per #979 §3 so refs spilled this step stay consumable — and forced by the unified rule, since on-demand can always load `result`) with no `ops_load_sdk`. The first program can call the permitted pool directly; read-only sessions still exclude every write API, an empty cap stays at resident + `result`, `residentTools:false` drops the resident surface but not the tier, duplicated names register once, `global.dynamicTools:false` keeps its veto (the row publishes its legacy surface letter for letter) and a row that also turns its loader off keeps the tier. `PtcConfig.disclosurePolicy` stays optional because custom integrations keep the legacy on-demand default until #988; the builtin plan carries the parsed value. On-demand (default) behaviour is letter-identical; the settings-page entry is #989. diff --git a/src/client/locales.ts b/src/client/locales.ts index 145714c5..ae6bc9ab 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -90,6 +90,15 @@ export const en = { defaultPresetNoUpdate: 'Nothing to do: new sessions already start in OPS (PTC).', defaultPresetUnavailable: 'The OPS (PTC) preset is not registered right now, so the default preset was not changed.', defaultPresetFailed: 'The default preset was not changed:', + disclosureTitle: 'PTC disclosure tier', + disclosureHint: 'One choice for both PTC rows: when the full permitted tool declaration appears in a session. The distinction is the timing, never the permissions.', + disclosureOnDemand: 'On-demand (default)', + disclosureOnDemandHint: 'The first step publishes resident tools plus the loader; the full declaration appears after the loader call, two steps.', + disclosureFull: 'Full', + disclosureFullHint: 'The first step publishes the whole permitted tool pool with no loader. Choosing this never widens permissions.', + disclosureMixed: 'The saved PTC rows disagree about the tier. Choosing one below unifies them on save.', + disclosureSuspended: 'The dynamic-tools bundle switch is off, so the full tier is suspended and both rows run on-demand until it is back on; the saved choice is kept.', + disclosureAppliesOnSave: 'The choice applies to new sessions; running sessions keep their current surface.', } export const zh: Record = { ptcFilesRequired: '类型化 PTC 必须启用文件能力;用常驻开关控制启动 API。', @@ -182,6 +191,15 @@ export const zh: Record = { defaultPresetNoUpdate: '无需更改:新会话本来就默认使用 OPS (PTC)。', defaultPresetUnavailable: 'OPS (PTC) 预设当前未注册,默认预设没有改动。', defaultPresetFailed: '默认预设没有改动:', + disclosureTitle: 'PTC 披露档位', + disclosureHint: '两条 PTC 行统一选择:完整获准工具声明在会话中出现的时机。区别只在时机,从不改变权限。', + disclosureOnDemand: '按需(默认)', + disclosureOnDemandHint: '首步只发布常驻工具与加载入口;完整声明在加载调用之后出现,分两步。', + disclosureFull: '全量', + disclosureFullHint: '首步直接发布整个获准工具池,且无加载入口。选择全量不会扩大任何权限。', + disclosureMixed: '已保存的两条 PTC 行档位不一致。在下面选定一个,保存后会统一。', + disclosureSuspended: '动态工具总开关已关闭,全量档暂不生效,两行按需运行;已保存的选择原样保留,开关回开后重新生效。', + disclosureAppliesOnSave: '选择对新会话生效;正在运行的会话保持当前工具面。', } declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { dshOps: keyof typeof en } } export type Translator = TranslateNS<'dshOps'> diff --git a/src/client/row-form.tsx b/src/client/row-form.tsx index 32365cba..4995af27 100644 --- a/src/client/row-form.tsx +++ b/src/client/row-form.tsx @@ -11,8 +11,8 @@ import type { ReactElement } from 'react' import type { RuntimeRemote, RuntimeSnapshot } from '../settings/runtime-contract.js' import { FormActions, Unavailable, errorText, useEditor } from './forms.js' import type { SettingsProps } from './forms.js' -import { groupsFor, bundleGates, changedFields, executorDiffers, executorOps, flatKey, readExecutor, readRowValues, type FieldSpec } from './row-schema.js' -import type { ExecutorChoice } from './row-schema.js' +import { groupsFor, bundleGates, changedFields, disclosureDiffers, disclosureOps, executorDiffers, executorOps, flatKey, readDisclosure, readExecutor, readRowValues, type FieldSpec } from './row-schema.js' +import type { DisclosureSelection, ExecutorChoice } from './row-schema.js' import type { Translator } from './locales.js' /** The subset of the native Switch this page binds. */ @@ -36,19 +36,24 @@ export function RowForm(props: SettingsProps & { Switch: SwitchBinding; pwsh7Ins const editor = useEditor(form, read, t) const [opened, setOpened] = useState>({}) const [choice, setChoice] = useState(() => readExecutor(form?.state.value ?? {})) + const [tier, setTier] = useState(() => readDisclosure(form?.state.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. + // 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 const draft = editor.draft, gates = bundleGates(draft) const savedChoice = readExecutor(editor.baseline) const executorDirty = executorDiffers(choice, editor.baseline) + const savedTier = readDisclosure(editor.baseline) + // `mixed` only describes saved state, so it is never a choice to write. + const tierDirty = tier !== 'mixed' && disclosureDiffers(tier, editor.baseline) const candidates = executor.snapshot?.git ?? [] /** Ask the Host what a path resolves to; nothing is written by this call. */ @@ -83,6 +88,9 @@ export function RowForm(props: SettingsProps & { Switch: SwitchBinding; pwsh7Ins } catch (error) { setCheck({ ok: false, text: errorText(error) }); return } finally { setSaving(false) } } + // The disclosure card writes exactly the reviewed tier, nothing else: an + // untouched old profile (key absent) produces no operation at all. + if (tierDirty) operations.push(...disclosureOps(editor.baseline, tier)) await editor.save(operations) } // The companion linkage locks every host-PowerShell hide switch to off. @@ -178,8 +186,37 @@ export function RowForm(props: SettingsProps & { Switch: SwitchBinding; pwsh7Ins

{t('executorAppliesOnSave')}

- { editor.reset(); setChoice(savedChoice); setCheck(undefined) }} message={editor.message} t={t} /> +
+
+

{t('disclosureTitle')}

+

{t('disclosureHint')}

+
+
+ {savedTier === 'mixed' &&

{t('disclosureMixed')}

} + {/* The bundle switch keeps its veto (sign-off item 2): the hint names the + suspension instead of hiding the choice, which still applies on save. */} + {!gates.dynamicTools &&

{t('disclosureSuspended')}

} + + +

{t('disclosureAppliesOnSave')}

+
+
+ { editor.reset(); setChoice(savedChoice); setTier(savedTier); setCheck(undefined) }} message={editor.message} t={t} /> } diff --git a/src/client/row-schema.ts b/src/client/row-schema.ts index 1001228b..3943c5be 100644 --- a/src/client/row-schema.ts +++ b/src/client/row-schema.ts @@ -247,6 +247,58 @@ function savedBashPaths(raw: Record): SavedBashPath[] { return list } +/** The mode sections that own a PTC publication surface and its disclosure tier. */ +export const DISCLOSURE_SECTIONS = Object.freeze(['ptc', 'ops-ptc'] as const) + +/** One disclosure tier as the page holds it, or \`mixed\` when the saved rows disagree. */ +export type DisclosureSelection = 'on-demand' | 'full' | 'mixed' + +/** The two tiers an operator can actually pick; \`mixed\` only describes saved state. */ +export type DisclosureTier = Exclude + +/** + * Read the disclosure tier the saved rows stand for. + * @param raw - the saved row config. + * @returns the agreed tier, or \`mixed\` when the two PTC rows disagree. + */ +export function readDisclosure(raw: Record): DisclosureSelection { + const tiers = new Set(DISCLOSURE_SECTIONS.map(section => + objectAt(raw[section]).disclosurePolicy === 'full' ? 'full' : 'on-demand')) + return tiers.size === 1 ? [...tiers][0]! : 'mixed' +} + +/** + * Whether the page's tier still differs from what is saved. + * @param selection - the operator's current choice. + * @param raw - the saved row config. + * @returns true when saving must write the tier. + */ +export function disclosureDiffers(selection: DisclosureSelection, raw: Record): boolean { + return selection !== readDisclosure(raw) +} + +/** + * The write operations that turn the saved rows into the reviewed tier. + * + * \`full\` pins both PTC rows; \`on-demand\` returns every row that carries the key + * to the absent default, so an old profile saved through the card is + * letter-identical to one that never met it. + * @param raw - the saved row config. + * @param tier - the operator's choice. + * @returns \`set\` operations for \`full\`, \`unset\` for the default rung. + */ +export function disclosureOps(raw: Record, tier: DisclosureTier): SettingsPathOpView[] { + const operations: SettingsPathOpView[] = [] + for (const section of DISCLOSURE_SECTIONS) { + const saved = objectAt(raw[section]).disclosurePolicy + if (tier === 'full' ? saved === 'full' : saved === undefined) continue + operations.push(tier === 'full' + ? { op: 'set', path: [section, 'disclosurePolicy'], value: 'full' } + : { op: 'unset', path: [section, 'disclosurePolicy'] }) + } + return operations +} + /** Whether a path names the Niubash executable rather than an MSYS bash. */ const niubashPath = (value: string): boolean => /(^|[\/])niu\.exe$/i.test(value) diff --git a/src/settings/merged.ts b/src/settings/merged.ts index 8d0f5102..8553a8fa 100644 --- a/src/settings/merged.ts +++ b/src/settings/merged.ts @@ -258,6 +258,12 @@ const MODE_SWITCHES: Record = { function modeSection(mode: ModeKey): Field { return { type: 'object', dict: { enabled: boolean('Apply this mode to its sessions.'), ...(mode === 'minimal' ? {} : { residentTools: boolean('Publish baseline file tools independently of dynamic loading.') }), + // Only the PTC rows own a disclosure tier; the key is volatile because the + // row page's disclosure card writes it, exactly like the executor card + // writes bashPath. Absent stays the on-demand default (#989). + ...(mode === 'ptc' || mode === 'ops-ptc' + ? { disclosurePolicy: editable('string', 'Optional explicit first-round disclosure tier selected on the row page.') } + : {}), bashPath: editable('string', 'Optional explicit Bash executable selected on the runtime page.'), ...MODE_SWITCHES } } } diff --git a/test/ptc-disclosure-policy.test.mjs b/test/ptc-disclosure-policy.test.mjs index a1d86c05..b69f4934 100644 --- a/test/ptc-disclosure-policy.test.mjs +++ b/test/ptc-disclosure-policy.test.mjs @@ -31,9 +31,11 @@ await test('input class 2 (legal value): on-demand and full parse and ride the s assert.equal(resolveModeConfig({ disclosurePolicy: 'full' }, mode).disclosurePolicy, 'full', mode) assert.equal(resolveModeConfig({ disclosurePolicy: 'on-demand' }, mode).disclosurePolicy, 'on-demand', mode) } - // D2 adds no settings-page field: the key stays YAML-only (the entry is D5). + // D5 (#989) moved the key onto the merged row page as a volatile string the + // disclosure card owns; the legacy per-mode form keeps it YAML-only. assert.equal('disclosurePolicy' in modeFields('ops-ptc'), false) - assert.equal('disclosurePolicy' in Config.dict['ops-ptc'].dict, false) + assert.equal('disclosurePolicy' in Config.dict['ops-ptc'].dict, true) + assert.equal(Config.dict['ops-ptc'].dict.disclosurePolicy.meta.volatile, true) }) await test('input class 3 (misspelled value): the diagnostic names the key and the value', () => { diff --git a/test/settings-disclosure-e2e.test.mjs b/test/settings-disclosure-e2e.test.mjs new file mode 100644 index 00000000..e2c3d05f --- /dev/null +++ b/test/settings-disclosure-e2e.test.mjs @@ -0,0 +1,195 @@ +/** D5 (#989): the settings-page choice reaches the real first round, end to end. + * + * The chain is the production one, twice over: the disclosure card's write + * operations go through the real host settings writer (profileFixture) and + * persist to the profile's cordis.patch.yml; the saved value then boots a + * fresh OPS-PTC session through the shipped apply with the real native + * worker, where the assertions read the settled first-round surface and run + * one real binding call. The full leg proves the first program can call the + * permitted business APIs with no loader; the untouched old profile keeps + * the two-step on-demand path letter for letter; switching the tier between + * saves applies to the next session. + */ +import { createScope, scopeOf, scopeParentOf } from '@deepseek-ai/dsh-scope' +import Subprocess from '@deepseek-ai/dsh-subprocess-local' +import Sandbox from '@deepseek-ai/dsh-sandbox-local' +import FileSystem from '@deepseek-ai/dsh-fs-local' +import NodePtc from '@deepseek-ai/dsh-ptc-runtime-node' +import fs from 'node:fs' +import path from 'node:path' +import { apply } from '../lib/index.js' +import { disclosureOps } from '../lib/client/row-schema.js' +import { profileFixture } from './lib/settings-profile.mjs' +import { bootHost, shutdown } from './lib/host.mjs' +import { prepareStep, executeCall, selectExecutor } from './lib/executor.mjs' +import { assert, test, report, wait, waitFor, withTempDir } from './lib/harness.mjs' +import { WORKER, requireWorker } from './lib/boundary.mjs' + +requireWorker('settings-disclosure-e2e') + +let sequence = 0 +const names = (ctx, agent) => ctx.get('tools').definitions(agent, agent.prepared?.toolSet).map(tool => tool.name).sort() +const opsNames = (ctx, agent) => names(ctx, agent).filter(name => name.startsWith('ops_')) + +/** One turn boundary, the way the loop issues it. */ +async function step(ctx, agent) { + ctx.emit('session/event', agent.session, { type: 'step/end', turn: 1, step: ++sequence }) + agent.prepared?.dispose(); agent.prepared = await prepareStep(ctx, agent) +} + +async function scoped(parent, key, parentKey) { + let result + await parent.plugin({ inject: ['tools'], apply(inner) { + result = createScope(inner, key, parentKey ? { parent: parentKey } : undefined).ctx + } }) + return result +} + +/** A saved settings value for an ops-ptc-only deployment of the merged row. */ +const savedBase = () => ({ + global: {}, + discovery: { binaryPath: WORKER, required: true }, + minimal: { enabled: false }, standard: { enabled: false }, ptc: { enabled: false }, cordis: { enabled: false }, + 'ops-ptc': { enabled: true, binaryPath: WORKER, required: true, allowedTools: ['grep', 'stat'] }, +}) + +/** + * The real settings writer for one profile; the card's saves go through it. + * + * `value()` is the host settings view (the editable surface, volatile keys + * only); `applied()` is the config the loader hands the row after the save — + * the profile layers merged, YAML-only keys (the `allowedTools` cap, the + * worker path) included. Sessions boot from `applied()` because that is the + * production chain; the settings view alone would silently drop the pool cap. + */ +async function writer(label, base) { + let applied + const fixture = await profileFixture(label, { + Config: (await import('../lib/settings/merged.js')).Config, apply(_ctx, config) { applied = config }, + }, base) + return { + value: () => fixture.snapshot().value, + applied: () => applied, + save: async operations => { + const snapshot = fixture.snapshot() + await fixture.mutate(operations, snapshot.revision) + await fixture.ctx.loader.await() + return fixture.snapshot().value + }, + close: () => shutdown(fixture.ctx), + } +} + +/** Boot the shipped merged row from a saved settings value, then one session. */ +async function session(saved, cwd) { + const { ctx } = await bootHost({ withWorkingDirectory: true }) + await ctx.plugin(Subprocess); await ctx.plugin(Sandbox); await ctx.plugin(FileSystem); await ctx.plugin(NodePtc) + ctx.provide('sandboxPolicy', { resolve: ({ session } = {}) => ({ mode: session?.mode ?? 'danger-full-access', workspaceRoot: cwd, sessionId: session?.id }) }) + const presets = new Map(), agents = [] + ctx.provide('agents', { list: () => [...agents] }) + ctx.provide('agentPresets', { composedPreset: inner => presets.get(scopeParentOf(scopeOf(inner))) }) + await ctx.plugin({ name: 'disclosure-e2e-fixture', apply: inner => apply(inner, saved) }) + const id = 'disclosure-' + ++sequence, preset = await scoped(ctx, { preset: id }) + presets.set(scopeOf(preset), 'ops-ptc') + for (const name of ['read', 'glob', 'grep']) preset.tools.register({ name, description: name, + parameters: { type: 'object', properties: {} }, output: { schema: { type: 'object' }, render: () => [] }, execute: async () => ({}) }) + const agent = { id, session: { id, mode: 'danger-full-access', header: { cwd }, append() {}, read() { return [] } } } + agent.ctx = await scoped(preset, agent, scopeOf(preset)) + await agent.ctx.plugin({ inject: ['tools', 'systemPrompt'], apply: inner => { selectExecutor(inner, 'ptc') } }) + agents.push(agent) + await ctx.serial('agent/created', { agent }) + await step(ctx, agent) + return { ctx, agent } +} + +/** One real run_code program through the prepared step, as the loop issues it. */ +async function program(ctx, agent, code, label) { + const result = await executeCall(ctx, { agent, toolSet: agent.prepared.toolSet, name: 'run_code', + arguments: { description: label, code }, callId: 'disclosure-' + ++sequence, signal: new AbortController().signal }) + assert.equal(result.isError, false, JSON.stringify(result)) + return result.value.result +} + +/** Wait for the first round to settle, then return its ops_* names. */ +async function settled(ctx, agent, anchor) { + await waitFor(() => opsNames(ctx, agent).includes(anchor), { what: anchor + ' published' }) + await wait(100) + return opsNames(ctx, agent) +} + +/** The on-demand first round: resident inspect plus the loader, nothing else. */ +const ON_DEMAND_FIRST = ['ops_inspect_local_file', 'ops_load_sdk'] +/** The full first round for allowedTools=[grep,stat]: the pool plus result, no loader. */ +const FULL_FIRST = ['ops_grep', 'ops_inspect_local_file', 'ops_result', 'ops_stat'] + +await test('a full choice saved through the real writer boots a loader-less first round', () => withTempDir('disclosure-full', async cwd => { + fs.writeFileSync(path.join(cwd, 'fixture.txt'), 'needle in haystack\nplain second line\n') + const store = await writer('disclosure-e2e-full', savedBase()) + try { + assert.equal('disclosurePolicy' in store.value()['ops-ptc'], false, 'the profile starts old: no key') + // Exactly the operations the card's save submits, through the real host writer. + const stored = await store.save(disclosureOps(store.value(), 'full')) + assert.equal(stored.ptc.disclosurePolicy, 'full') + assert.equal(stored['ops-ptc'].disclosurePolicy, 'full') + // The save keeps the YAML-only pool cap the tier must never widen (#989). + assert.deepEqual(store.applied()['ops-ptc'].allowedTools, ['grep', 'stat']) + const { ctx, agent } = await session(store.applied(), cwd) + try { + assert.deepEqual(await settled(ctx, agent, 'ops_grep'), FULL_FIRST, 'the whole permitted pool in the first round') + assert.equal(opsNames(ctx, agent).includes('ops_load_sdk'), false, 'the full tier publishes no loader') + const value = await program(ctx, agent, "const stat = await tools.ops_stat({ path: 'fixture.txt' })\n" + + "const grep = await tools.ops_grep({ pattern: 'needle', path: '.' })\n" + + "return { statStatus: stat.status, grepStatus: grep.status, grepText: JSON.stringify(grep), loader: typeof tools.ops_load_sdk }", + 'First-program business calls') + assert.equal(value.statStatus, 'completed', JSON.stringify(value)) + assert.equal(value.grepStatus, 'completed', JSON.stringify(value)) + assert.match(value.grepText, /needle/, 'the real worker answered the first-program call') + assert.equal(value.loader, 'undefined') + } finally { await shutdown(ctx) } + } finally { await store.close() } +})) + +await test('the untouched old profile keeps the two-step on-demand path', () => withTempDir('disclosure-on-demand', async cwd => { + fs.writeFileSync(path.join(cwd, 'fixture.txt'), 'needle in haystack\n') + const store = await writer('disclosure-e2e-on-demand', savedBase()) + try { + const stored = store.value() + assert.equal('disclosurePolicy' in stored['ops-ptc'], false, 'an old profile is never migrated to full') + const { ctx, agent } = await session(stored, cwd) + try { + assert.deepEqual(await settled(ctx, agent, 'ops_load_sdk'), ON_DEMAND_FIRST, 'resident plus loader, two steps before the pool') + const value = await program(ctx, agent, "const picked = await tools.ops_load_sdk({ tools: ['grep', 'stat', 'result'] })\n" + + "return { picked: picked.status, earlyGrep: typeof tools.ops_grep }", 'Load the business set') + assert.equal(value.picked, 'completed', JSON.stringify(value)) + assert.equal(value.earlyGrep, 'undefined', 'a loaded API is callable only in the next program') + await step(ctx, agent) + await wait(100) + assert.deepEqual(opsNames(ctx, agent).filter(name => name !== 'ops_load_sdk'), FULL_FIRST, + 'after the loader step the set equals the full first round') + } finally { await shutdown(ctx) } + } finally { await store.close() } +})) + +await test('switching the tier between saves applies to the next session', () => withTempDir('disclosure-switch', async cwd => { + fs.writeFileSync(path.join(cwd, 'fixture.txt'), 'needle in haystack\n') + const store = await writer('disclosure-e2e-switch', savedBase()) + try { + await store.save(disclosureOps(store.value(), 'full')) + const first = await session(store.applied(), cwd) + try { + assert.deepEqual(await settled(first.ctx, first.agent, 'ops_grep'), FULL_FIRST, 'the full save reaches the session') + } finally { await shutdown(first.ctx) } + const back = await store.save(disclosureOps(store.value(), 'on-demand')) + assert.equal('disclosurePolicy' in back.ptc, false, 'switching back returns to the absent default') + assert.equal('disclosurePolicy' in back['ops-ptc'], false) + const second = await session(store.applied(), cwd) + try { + assert.deepEqual(await settled(second.ctx, second.agent, 'ops_load_sdk'), ON_DEMAND_FIRST, 'the next session runs the new tier') + const value = await program(second.ctx, second.agent, "return { loader: typeof tools.ops_load_sdk, grep: typeof tools.ops_grep }", 'Probe the switched surface') + assert.equal(value.loader, 'function') + assert.equal(value.grep, 'undefined', 'the pool is back behind the loader') + } finally { await shutdown(second.ctx) } + } finally { await store.close() } +})) + +report('settings-disclosure-e2e') diff --git a/test/settings-host.test.mjs b/test/settings-host.test.mjs index 97eecd8f..752e1440 100644 --- a/test/settings-host.test.mjs +++ b/test/settings-host.test.mjs @@ -2,7 +2,7 @@ import fs from 'node:fs' import path from 'node:path' import { Config as MergedConfig } from '../lib/settings/merged.js' -import { executorOps } from '../lib/client/row-schema.js' +import { disclosureOps, executorOps } from '../lib/client/row-schema.js' import { parse } from 'yaml' import { profileFixture } from './lib/settings-profile.mjs' // These suites exercise the pre-merge component modules directly. @@ -108,6 +108,35 @@ await test('real shell form persists executor selection without erasing ordinary } finally { await shutdown(ctx) } }) +await test('the merged row persists the disclosure tier, keeps it through other saves, and clears it back to the absent default', async () => { + let observed + const { ctx, snapshot, mutate, patchPath } = await profileFixture('ops-merged-disclosure', { + Config: MergedConfig, apply(_ctx, config) { observed = config }, + }, { 'ops-ptc': { enabled: true } }) + try { + const before = snapshot() + assert.equal('disclosurePolicy' in before.value['ops-ptc'], false, 'the old profile carries no key') + await mutate(disclosureOps(before.value, 'full'), before.revision) + await ctx.loader.await() + assert.equal(observed.ptc.disclosurePolicy, 'full') + assert.equal(observed['ops-ptc'].disclosurePolicy, 'full') + assert.match(fs.readFileSync(patchPath, 'utf8'), /disclosurePolicy: full/) + // An unrelated save keeps the tier (the page only writes what changed). + await mutate([{ op: 'set', path: ['panel', 'enabled'], value: true }], snapshot().revision) + await ctx.loader.await() + assert.equal(observed.panel.enabled, true) + assert.equal(observed.ptc.disclosurePolicy, 'full') + assert.equal(observed['ops-ptc'].disclosurePolicy, 'full') + // Switching back returns both rows to the absent default, other keys intact. + await mutate(disclosureOps(snapshot().value, 'on-demand'), snapshot().revision) + await ctx.loader.await() + assert.equal('disclosurePolicy' in snapshot().value.ptc, false) + assert.equal('disclosurePolicy' in snapshot().value['ops-ptc'], false) + assert.doesNotMatch(fs.readFileSync(patchPath, 'utf8'), /disclosurePolicy/) + assert.equal(observed.panel.enabled, true, 'other choices survive the tier switch') + } finally { await shutdown(ctx) } +}) + await test('the actual shell component starts and reloads through the profile adapter without normalizing twice', async () => { const { ctx, snapshot, mutate, patchPath } = await profileFixture('actual-shell', Shell, { promptPolicy: false, publishBashTool: false }) try { diff --git a/test/settings-rows.test.mjs b/test/settings-rows.test.mjs index 3c4138de..ee082ffb 100644 --- a/test/settings-rows.test.mjs +++ b/test/settings-rows.test.mjs @@ -4,10 +4,10 @@ import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { companionVersion } from '../lib/settings/companion.js' -import { GROUPS, ROW_ID, groupsFor, bundleGates, changedFields, executorDiffers, executorOps, flatKey, readExecutor, readRowValues } from '../lib/client/row-schema.js' +import { GROUPS, ROW_ID, groupsFor, bundleGates, changedFields, executorDiffers, executorOps, flatKey, readExecutor, readRowValues, readDisclosure, disclosureDiffers, disclosureOps } from '../lib/client/row-schema.js' import { hasStatus, statusView } from '../lib/client/detail.js' import { en } from '../lib/client/locales.js' -import { Config, effectiveMode, resolveMergedConfig } from '../lib/settings/merged.js' +import { Config, effectiveMode, hostConfig, resolveMergedConfig } from '../lib/settings/merged.js' import { readRowValues as draftFor } from '../lib/client/row-schema.js' const t = key => en[key] const SWITCHES = ['bash', 'hidePwsh', 'hideOfficialTools', 'dynamicTools'] @@ -25,9 +25,12 @@ await test('the page matches the host descriptor, and the opt-in switches share const group = GROUPS.find(entry => entry.id === section) const expected = section === 'minimal' ? SWITCHES : ['bash', 'hidePwsh', 'hideOfficialTools', 'residentTools', 'dynamicTools'] assert.deepEqual(group.fields.map(spec => spec.path[1]), expected, section) - // bashPath belongs to the executor card rather than the boolean switch grid. - assert.deepEqual([...group.fields.map(spec => spec.path[1]), 'enabled', 'bashPath'].sort(), Object.keys(Config.dict[section].dict).sort(), section) + // bashPath belongs to the executor card; the two PTC rows' disclosurePolicy + // belongs to the disclosure card — neither is a boolean switch above. + const cardKeys = ['bashPath', ...(section === 'ptc' || section === 'ops-ptc' ? ['disclosurePolicy'] : [])] + assert.deepEqual([...group.fields.map(spec => spec.path[1]), 'enabled', ...cardKeys].sort(), Object.keys(Config.dict[section].dict).sort(), section) assert.equal(Config.dict[section].dict.bashPath.meta.volatile, true) + if (section === 'ptc' || section === 'ops-ptc') assert.equal(Config.dict[section].dict.disclosurePolicy.meta.volatile, true) } // compat/panel/tui used to be three single-switch cards; they are one card now. const other = GROUPS.find(group => group.id === 'other') @@ -137,6 +140,35 @@ await test('the executor card reads the saved rows and writes exactly one choice assert.equal(executorDiffers({ engine: 'git', path: 'C:/a/bash.exe' }, { ptc: { bashPath: 'C:/a/bash.exe' } }), false) }) +await test('the disclosure card reads the saved rows and writes exactly one tier', () => { + // Old profiles (key absent) and an explicit on-demand both read as the default rung. + assert.deepEqual(readDisclosure({}), 'on-demand') + assert.equal(readDisclosure({ ptc: { disclosurePolicy: 'on-demand' } }), 'on-demand') + assert.equal(readDisclosure({ ptc: { disclosurePolicy: 'full' }, 'ops-ptc': { disclosurePolicy: 'full' } }), 'full') + assert.equal(readDisclosure({ 'ops-ptc': { disclosurePolicy: 'full' } }), 'mixed', 'a row that disagrees is named, never reduced to a favourite') + // Full writes both PTC rows; on-demand returns them to the absent default. + assert.deepEqual(disclosureOps({}, 'full'), [ + { op: 'set', path: ['ptc', 'disclosurePolicy'], value: 'full' }, + { op: 'set', path: ['ops-ptc', 'disclosurePolicy'], value: 'full' }, + ]) + assert.deepEqual(disclosureOps({ ptc: { disclosurePolicy: 'full' }, 'ops-ptc': { disclosurePolicy: 'full' } }, 'full'), []) + assert.deepEqual(disclosureOps({ 'ops-ptc': { disclosurePolicy: 'full' } }, 'on-demand'), [{ op: 'unset', path: ['ops-ptc', 'disclosurePolicy'] }]) + assert.deepEqual(disclosureOps({}, 'on-demand'), []) + assert.equal(disclosureDiffers('full', {}), true) + assert.equal(disclosureDiffers('on-demand', {}), false, 'an untouched old profile is not dirty') + assert.equal(disclosureDiffers('full', { ptc: { disclosurePolicy: 'full' }, 'ops-ptc': { disclosurePolicy: 'full' } }), false) + // Old configs are never migrated to full: the resolved tier and every save + // path keep the absent key (#989 acceptance B). + assert.equal(resolveMergedConfig({})['ops-ptc'].config.disclosurePolicy, 'on-demand') + assert.equal('disclosurePolicy' in hostConfig({})['ops-ptc'], false) + // A saved full choice survives reopening and saving another switch (D). + const saved = { ptc: { disclosurePolicy: 'full' }, 'ops-ptc': { disclosurePolicy: 'full' } } + assert.equal(readDisclosure(saved), 'full', 'reopening reads the saved tier back') + const draft = readRowValues(saved) + draft['panel.enabled'] = true + assert.deepEqual(changedFields(draft, saved), [{ op: 'set', path: ['panel', 'enabled'], value: true }], 'the tier is not rewritten by an unrelated save') +}) + await test('the status section belongs to the bundle and to the one row', () => { const pkg = { name: 'dsh-ops', installed: true, enabled: true, rows: [] } // Other plugins' pages mount the same slot; the section must stay off them. diff --git a/test/settings-ui.test.mjs b/test/settings-ui.test.mjs index 9114b838..e73a5e99 100644 --- a/test/settings-ui.test.mjs +++ b/test/settings-ui.test.mjs @@ -141,6 +141,80 @@ await test('an invalid typed path blocks the save and names the host reason', as } finally { await view.close() } }) +await test('the disclosure card picks the tier, cancels edits, and never writes an untouched old profile', async () => { + const writes = [] + const form = { state: ready({}), mutate: async ops => { writes.push(ops); return true } } + const view = await mount(RowForm, { form, Switch: TestSwitch }) + try { + const card = group(view.container, en.disclosureTitle) + assert.ok(card, 'the disclosure card renders') + const radios = card.querySelectorAll('input[type=radio]') + assert.equal(radios.length, 2) + assert.equal(radios[0].checked, true, 'an old profile shows the on-demand default') + assert.equal(radios[1].checked, false) + // The bundle switch keeps its veto: while dynamic tools are off the card + // names the suspension instead of hiding the choice. + await click(switchIn(group(view.container, en.groupGlobal), en.dynamicTools)) + assert.ok(card.textContent.includes(en.disclosureSuspended), 'the suspended full tier is named') + await click(button(view.container, en.reset)) + assert.equal(card.textContent.includes(en.disclosureSuspended), false, 'reset restores the running tier') + // Cancel before saving: reset restores the saved tier and writes nothing. + await click(radios[1]) + await click(button(view.container, en.reset)) + assert.equal(card.querySelectorAll('input[type=radio]')[0].checked, true, 'reset restores the saved tier') + assert.deepEqual(writes, [], 'a cancelled edit is never written') + // Saving the full tier writes both PTC rows once. + await click(card.querySelectorAll('input[type=radio]')[1]) + await click(button(view.container, en.save)) + assert.deepEqual(writes[0], [ + { op: 'set', path: ['ptc', 'disclosurePolicy'], value: 'full' }, + { op: 'set', path: ['ops-ptc', 'disclosurePolicy'], value: 'full' }, + ]) + // Disagreeing saved rows are named, never reduced to a favourite. + const mixed = { state: ready({ 'ops-ptc': { disclosurePolicy: 'full' } }, 'v2'), mutate: async ops => { writes.push(ops); return true } } + await view.render({ form: mixed, Switch: TestSwitch }) + const mixedCard = group(view.container, en.disclosureTitle) + assert.ok(mixedCard.textContent.includes(en.disclosureMixed), 'a disagreement is named') + assert.equal(mixedCard.querySelectorAll('input[type=radio]')[0].checked, false, 'mixed checks neither radio') + assert.equal(mixedCard.querySelectorAll('input[type=radio]')[1].checked, false) + } finally { await view.close() } +}) + +await test('a saved full tier reads back through the real host and other saves keep it', async () => { + let observed + const fixture = await profileFixture('disclosure-page', { + Config: (await import('../lib/settings/merged.js')).Config, apply(_ctx, config) { observed = config }, + }, {}) + let pending + const form = { + state: ready(fixture.snapshot().value, fixture.snapshot().revision), + mutate(ops, revision) { + return pending = (async () => { + await fixture.mutate(ops, revision); await fixture.ctx.loader.await() + form.state = ready(fixture.snapshot().value, fixture.snapshot().revision) + return true + })() + }, + } + const view = await mount(RowForm, { form, Switch: TestSwitch }) + try { + const card = group(view.container, en.disclosureTitle) + await click(card.querySelectorAll('input[type=radio]')[1]) + await click(button(view.container, en.save)); await act(async () => { await pending }) + assert.equal(observed.ptc.disclosurePolicy, 'full') + assert.equal(observed['ops-ptc'].disclosurePolicy, 'full') + // Reopening the page reads the saved choice back. + await view.render({ form, Switch: TestSwitch }) + assert.equal(group(view.container, en.disclosureTitle).querySelectorAll('input[type=radio]')[1].checked, true) + // Saving another card's switch never loses the tier. + await click(switchIn(group(view.container, en.groupOther), en.featurePanel)) + await click(button(view.container, en.save)); await act(async () => { await pending }) + assert.equal(observed.panel.enabled, true) + assert.equal(observed.ptc.disclosurePolicy, 'full', 'the saved tier survives an unrelated save') + assert.equal(observed['ops-ptc'].disclosurePolicy, 'full') + } finally { await view.close(); await shutdown(fixture.ctx) } +}) + await test('rendered preset hints describe default conditional PowerShell hiding', async () => { const form = { state: ready({}), mutate: async () => true } const view = await mount(RowForm, { form, Switch: TestSwitch })