diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index d66194e1..23ba5e1b 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -15,6 +15,11 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Replace the `global.forceDefaultOpsPtc` switch with one explicit action: the row's detail page carries a **Make OPS (PTC) the default** button that writes `selectedDefault: ops-ptc` once and answers `applied`/`no-update`/`unavailable`/`failed`. Apply, remount and unload no longer write the default, so a preset chosen on the settings page is not overridden on the next apply, and a saved `global.forceDefaultOpsPtc` key still loads with no effect. - 用一次显式操作取代 `global.forceDefaultOpsPtc` 开关:行详情页有一个「设为 OPS (PTC) 默认」按钮,点一次写 `selectedDefault: ops-ptc`,并回报 `applied`/`no-update`/`unavailable`/`failed`。apply、重挂载与卸载都不再改写默认,设置页选定的预设不会在下一次 apply 被覆盖;已保存的 `global.forceDefaultOpsPtc` 键仍可加载但不再生效。 +- Unloading or disabling the `dsh-ops` row no longer strands `selectedDefault: ops-ptc`: when the live default still names the removed preset, the row lease restores the host's configured default. A default naming any other preset is never rewritten, and a missing or rejecting settings service reports the leftover instead of guessing (#928). +- 禁用或卸载 `dsh-ops` 行不再遗留 `selectedDefault: ops-ptc`:若当前默认仍指向被移除的预设,行级清理会恢复宿主配置的默认值;指向任何其他预设的选择绝不改写。settings 服务缺失或拒绝写入时会明确报告残留,不会猜测修复(#928)。 +- Session Bash publication now deduplicates overlapping row ownership, carries queued registration identity to settlement, latches one failure per generation, and re-asserts authority at `turn/start`. This closes the append-reentry retry storm, duplicate-registration pair and interrupted-turn tool disappearance without weakening per-agent authority (#579, #842, #873). +- 会话 Bash 发布现在会对重叠行所有权去重,把排队注册的身份跟踪到结算,每代只报告一次失败,并在 `turn/start` 重新断言权限。修复 append 重入重试风暴、成对重复注册与中断回合后的工具消失,同时不削弱每个 agent 的权限边界(#579、#842、#873)。 + ## [0.5.5] — 2026-11-13 — Patch release - A loader-less PTC scope no longer registers the configured `allowedTools` pool: with dynamic loading off nothing could ever select those APIs, and a host assembly without a step tool set declared all sixteen in `tools:sdk`. Resident publication, the default inspect + loader set and selection behavior are unchanged (#887). diff --git a/docs/presets.md b/docs/presets.md index f150f501..2e6f9adf 100644 --- a/docs/presets.md +++ b/docs/presets.md @@ -65,11 +65,12 @@ bundle: - **Pressing the button**: while the `ops-ptc` preset is registered, the plugin writes `selectedDefault: ops-ptc` on `agent-preset-registry` — the same volatile field the Agent presets settings page writes. That click is the only thing that overrides a manual choice. -- **Doing nothing**: nothing is written. Apply, a remount caused by saving another switch, and disabling the row - all leave the current default alone, so a preset picked on the settings page survives restarts. -- **Disabling or unloading the `dsh-ops` row**: releases the registration and leaves the default alone, even when - it names `ops-ptc`. Switch the default to another preset before removing the row, otherwise new sessions may - try to resolve a preset that no longer exists. +- **Doing nothing**: nothing is written. Apply and a remount caused by saving another switch leave the current + default alone, so a preset picked on the settings page survives restarts. +- **Disabling or unloading the `dsh-ops` row**: releases the registration, then checks the live default. If it still + names `ops-ptc`, the row lease restores the host's `config.default`; a default naming any other preset is never + rewritten. A missing or rejecting settings service reports the leftover and asks the operator to choose another + default instead of pretending the profile was repaired. - The button answers with a status: `applied`, `no-update` (it is already the default), or `unavailable`/`failed` with the reason — the preset is not registered, the host settings service is missing, or the write was rejected. - The written value persists through the host settings layer into the profile's `cordis.patch.yml` (an @@ -82,9 +83,9 @@ In the host picker the preset is named `OPS (PTC)` and described as ## Setting another default preset manually -`ops-ptc` becomes the default only through the button above (or the settings page). Nothing restores it -automatically, so pick another default before you disable or unload the row. Other default presets are still -decided by the host/operator: +`ops-ptc` becomes the default only through the button above (or the settings page). Removing the row restores the +host default only when the current selection is still `ops-ptc`; it never restores `ops-ptc` itself. Other default +presets are still decided by the host/operator: - **Host Agent presets settings page**: picking an already registered preset such as `standard` or `ptc` persists `selectedDefault`. @@ -107,10 +108,11 @@ default comes from that profile's own composition. ### Risks and rollback -- **After pressing the button**: the choice is an ordinary settings-page selection, so it survives restarts. It - is not restored when the row is disabled or unloaded; pick another default before removing the row. -- **Before disabling or unloading**: set the default to another preset on the settings page. The plugin no longer - rewrites it, and new sessions otherwise try to resolve a preset that vanished with the row. +- **After pressing the button**: the choice is an ordinary settings-page selection, so it survives restarts. If the + row is removed while this choice is still active, the lease restores the host default instead of stranding it. +- **Before disabling or unloading**: no manual rewrite is required while the default is `ops-ptc`; the row handles + that case. A default belonging to another preset is left exactly as the operator chose it. If restoration cannot + be persisted, choose another default on the settings page after the warning. - A missing fragment or a host upgrade that breaks parsing leaves the preset unavailable while the tools keep working; the default preset stays untouched and the button reports `unavailable`. Regenerate the fragment and restart the host to recover. @@ -128,7 +130,7 @@ default comes from that profile's own composition. | Compaction | official `compaction-basic` | official `compaction-basic` as well; no `dsh-compress-codex` | | Batch-call guidance | none | `batchingGuidance`: defaults true in code and the packaged `ops-ptc` section, including legacy whole-row overrides that omit the section; explicit false disables it; one lesson at session start, then shape notices for root `run_code` programs (`bypass`/`plan`/`shape`, each latched per turn and re-armed by compliance) appended as `additionalContexts`; text in the editable `prompts/batching-guidance.md` | | Single-row section | `ptc` | `ops-ptc` (same keys plus `batchingGuidance`) | -| Default preset | decided by the host/operator | set once by the detail page's button (`applied`/`no-update`); never forced or restored automatically | +| Default preset | decided by the host/operator | set once by the detail page's button (`applied`/`no-update`); never forced; unloading restores the host default only when the current selection is still `ops-ptc` | | Ordering | order 2 | order 6, sorted after the official rows | Having both modes over one tool surface is the point of the contrast arm: `ptc` keeps the official preset diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index b58646e9..8ed55764 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -11,6 +11,10 @@ collect [runtime evidence](windows-runtime-evidence.md) before assigning a cause --- +## Bash disappears or registration repeats during session changes + +Session Bash publication is per agent and generation-aware. Overlapping consumers no longer register the same name twice, a queued registration updates the entry only when it settles, and one failed generation is reported once rather than retried in a synchronous storm. A `turn/start` event re-asserts the current authority, so an interrupted turn cannot leave `ops_bash` missing until an unrelated asynchronous event happens to arrive. If a name conflict is reported, capture that single warning and the following turn boundary rather than restarting the host repeatedly (#579, #842, #873). + ## Installation and payloads ### `bash-win32-x64` is missing under `node_modules/@dsh-ops/` diff --git "a/docs/\345\270\270\350\247\201\351\227\256\351\242\230.md" "b/docs/\345\270\270\350\247\201\351\227\256\351\242\230.md" index 69fecb7b..fb2e9016 100644 --- "a/docs/\345\270\270\350\247\201\351\227\256\351\242\230.md" +++ "b/docs/\345\270\270\350\247\201\351\227\256\351\242\230.md" @@ -11,6 +11,10 @@ Windows Low 完整性、MSYS 启动、杀软、heredoc 或审批问题,请先 --- +## 会话切换时 Bash 消失或重复注册 + +会话 Bash 发布按 agent 与代次管理。重叠消费者不再重复注册同名工具;排队注册只有在结算后才更新条目;同一代失败只报告一次,不再同步重试形成风暴。`turn/start` 会重新断言当前权限,因此中断的回合不会让 `ops_bash` 一直缺席到某个无关异步事件出现。若看到名称冲突,保留那一次警告及随后的 turn 边界证据即可,不要反复重启宿主(#579、#842、#873)。 + ## 安装与载荷 ### `node_modules/@dsh-ops/` 下没有 `bash-win32-x64` diff --git "a/docs/\351\242\204\350\256\276\344\270\216\351\273\230\350\256\244\346\250\241\345\274\217.md" "b/docs/\351\242\204\350\256\276\344\270\216\351\273\230\350\256\244\346\250\241\345\274\217.md" index e0414c72..2cfe3396 100644 --- "a/docs/\351\242\204\350\256\276\344\270\216\351\273\230\350\256\244\346\250\241\345\274\217.md" +++ "b/docs/\351\242\204\350\256\276\344\270\216\351\273\230\350\256\244\346\250\241\345\274\217.md" @@ -56,10 +56,11 @@ node scripts/sync-preset-ops-ptc.mjs --source [--ou - **按下按钮**:`ops-ptc` 预设已注册时,插件把 `agent-preset-registry` 的 `selectedDefault` 写成 `ops-ptc`——与设置页写的是同一个易变字段。只有这一次点击会覆盖手动选择。 -- **什么都不做**:不写任何东西。apply、保存其它开关导致的重挂载、禁用该行都不会改当前默认,所以设置页选的 - 预设在重启后仍然是默认。 -- **禁用/卸载 `dsh-ops` 行**:只释放预设注册,默认预设原样保留,即使它指向 `ops-ptc`。移除该行前请先把默认 - 切到别的预设,否则新会话可能解析一个已经不存在的预设。 +- **什么都不做**:不写任何东西。apply、保存其它开关导致的重挂载都不会改当前默认,所以设置页选的预设 + 在重启后仍然是默认。 +- **禁用/卸载 `dsh-ops` 行**:先释放预设注册,再检查当前默认。若仍指向 `ops-ptc`,行级清理会恢复宿主 + `config.default`;若指向其他预设则绝不改写。settings 服务缺失或拒绝写入时会明确报告残留,要求操作者 + 另选默认,不会假装 profile 已修复。 - 按钮会回一个状态:`applied`、`no-update`(本来就是默认),或带原因的 `unavailable`/`failed`——预设未注册、 宿主 settings 服务缺失、写入被拒。 - 写入的值经宿主设置层持久化到 profile 的 `cordis.patch.yml`(`agent-preset-registry` 覆盖),重启后保持; @@ -70,8 +71,8 @@ node scripts/sync-preset-ops-ptc.mjs --source [--ou ## 手动设置其他默认预设 -`ops-ptc` 只能通过上面的按钮(或设置页)成为默认。插件不再自动回退它,所以禁用/卸载该行前请先把默认切到别的 -预设。其他默认预设仍照常由宿主/操作者决定: +`ops-ptc` 只能通过上面的按钮(或设置页)成为默认。只有在当前选择仍是 `ops-ptc` 时,移除该行才会恢复宿主默认; +不会自动恢复成 `ops-ptc`。其他默认预设仍照常由宿主/操作者决定: - **宿主「Agent 预设」设置页**:选择 `standard`、`ptc` 等任一已注册预设,持久化 `selectedDefault`。 - **profile patch 显式设置**(可粘贴到 `$DSH_HOME/profiles//cordis.patch.yml`): @@ -95,9 +96,10 @@ node scripts/sync-preset-ops-ptc.mjs --source [--ou - **开关开启(默认)时**:禁用/卸载会先恢复默认再释放注册,正常路径不会留下指向已消失预设的默认;禁用后 重新启用插件,或在该开关关闭后用设置页选择你想要的默认即可。恢复失败只告警、不阻塞卸载,此时按下一 条处理。 -- **按下按钮之后**:这就是一次普通的设置页选择,重启后保持;禁用或卸载该行时不会自动回退,移除行前请先换默认。 -- **禁用/卸载之前**:先在设置页把默认切到别的预设。插件不再自动改写它,否则新会话会按当前定义解析一个随行消失的 - 预设而失败。 +- **按下按钮之后**:这就是一次普通的设置页选择,重启后保持;若在该选择仍生效时移除行,清理会恢复宿主默认, + 不会留下失效引用。 +- **禁用/卸载之前**:当前默认是 `ops-ptc` 时无需手动改写,行会处理;属于其他预设的选择会原样保留。若恢复无法 + 持久化,请按警告在设置页另选默认。 - 片段缺失或宿主升级导致解析失败时,预设不可用但工具面照常工作;默认预设不受影响,按钮回报 `unavailable`。 重新生成片段并重启宿主即可恢复。 - 插件管理器里找不到 `ops-ptc` 预设行是设计如此,不要尝试手动新增声明;它由插件运行时提供。 diff --git a/src/presets/ops-ptc/register.ts b/src/presets/ops-ptc/register.ts index fe7dba5a..65952369 100644 --- a/src/presets/ops-ptc/register.ts +++ b/src/presets/ops-ptc/register.ts @@ -155,10 +155,14 @@ function currentDefault(registry: PresetRegistry): string | undefined { * * This is the same mechanism the settings page uses, so the write lands in the * profile layer and hot-applies to the live registry. + * @param ctx - the context whose settings service persists the value. + * @param value - the default preset id to write. + * @param captured - a settings service the caller resolved while it was live; + * the unload lease passes one because its own context may already be gone. * @returns the failure message, or undefined when the host accepted the write. */ -async function writeSelectedDefault(ctx: Context, value: string): Promise { - const settings = settingsOf(ctx) +async function writeSelectedDefault(ctx: Context, value: string, captured?: SettingsService): Promise { + const settings = captured ?? settingsOf(ctx) if (typeof settings?.update !== 'function') { return 'the host settings service is unavailable, so the default preset was not changed' } @@ -189,10 +193,17 @@ export interface OpsPtcPreset { applyDefault(): Promise } -/** The live registration the action writes through; empty when none is mounted. */ +/** + * The live registration the action writes through; empty when none is mounted. + * + * `settings` is captured while the injected child is alive: the unload lease + * writes through it after the child is gone (#928), when the child context can + * no longer resolve the service. + */ interface LiveRegistration { ctx?: Context registry?: PresetRegistry + settings?: SettingsService } /** @@ -238,6 +249,50 @@ function releaseRegistration(ctx: Context, slot: Slot, options: RegistrationOpti } } +/** + * The host's own default preset, when it is a usable id distinct from this + * row's preset. + * @param registry - the registry whose config declares the host default. + * @returns the host default id, or undefined when there is none to fall back to. + */ +function hostDefaultOf(registry: PresetRegistry): string | undefined { + try { + const value = registry.config?.default + return typeof value === 'string' && value !== '' && value !== PRESET_ID ? value : undefined + } catch { return undefined } +} + +/** + * Restore the profile default this row is about to strand. + * + * Unload and disable remove the ops-ptc preset, but the profile keeps the + * `selectedDefault` the operator's one click wrote: every new session then + * fails to compose against a preset that no longer exists (#928). The lease + * writes the host default back — only when the live value still names this + * row's preset; a default naming any other preset is an operator choice and is + * never touched. Best effort with a warning: a host without a usable settings + * service, or one that refuses the write, reports the leftover and its + * remediation instead of guessing. + * @param served - the last registration this row served. + * @param options - test seams; production passes none. + */ +async function restoreLeftoverDefault(served: LiveRegistration, options: RegistrationOptions): Promise { + const { ctx, registry } = served + if (ctx === undefined || registry === undefined) return + if (currentDefault(registry) !== PRESET_ID) return + const fallback = hostDefaultOf(registry) + if (fallback === undefined) { + warn(options, ctx, 'dsh-ops: the profile still names the removed ops-ptc preset as its default; choose another default on the host settings page.') + return + } + const failure = await writeSelectedDefault(ctx, fallback, served.settings) + if (failure !== undefined) { + warn(options, ctx, `dsh-ops: ${failure}; the profile still names the removed ops-ptc preset, so new sessions may fail to compose until another default is chosen.`) + return + } + warn(options, ctx, `dsh-ops: restored the default agent preset to ${fallback}, because the ops-ptc preset was removed with this row.`) +} + /** * Resolve one package from a require anchor. * @param anchor - the absolute module path resolution starts from. @@ -415,6 +470,12 @@ export async function readOpsPtcDefinition(options: RegistrationOptions, root: C */ export function registerOpsPtcPreset(root: Context, options: RegistrationOptions = {}): OpsPtcPreset { const live: LiveRegistration = {} + /** + * The last registration this row served: the injected child clears `live` + * when it goes away, while this holder stays readable for the unload lease, + * and a remount overwrites it with the fresh child's registration. + */ + const served: LiveRegistration = {} root.inject(['agentPresets'], ctx => { const registry = service(ctx, 'agentPresets') if (registry === undefined || typeof registry.register !== 'function') return @@ -429,10 +490,15 @@ export function registerOpsPtcPreset(root: Context, options: RegistrationOptions if (live.ctx === ctx) { live.ctx = undefined; live.registry = undefined } releaseRegistration(ctx, slot, options) }, 'dsh-ops: ops-ptc preset') - void activate(ctx, registry, slot, options, live).catch(error => { + void activate(ctx, registry, slot, options, live, served).catch(error => { warn(options, ctx, `dsh-ops: cannot register the ops-ptc agent preset: ${errorText(error)}; the preset stays unavailable.`) }) }) + // The lease below is the row's own lifetime: the Loader reuses a row's fiber + // across a config remount, so a remount never fires it. It fires when the row + // is disabled or unloaded — the one moment the profile can be left naming a + // preset that no longer exists (#928). + root.effect(() => () => { void restoreLeftoverDefault(served, options) }, 'dsh-ops: ops-ptc preset default lease') return { applyDefault: () => applyDefaultPreset(live, options) } } @@ -442,9 +508,11 @@ export function registerOpsPtcPreset(root: Context, options: RegistrationOptions * @param registry - the host preset registry. * @param slot - release holder the fiber cleanup reads. * @param options - test seams; production passes none. + * @param live - the holder the operator action reads; the child clears it on teardown. + * @param served - the holder the unload lease reads; it survives the child teardown. * @returns resolves once the registration is owned by {@link slot}. */ -async function activate(ctx: Context, registry: PresetRegistry, slot: Slot, options: RegistrationOptions, live: LiveRegistration): Promise { +async function activate(ctx: Context, registry: PresetRegistry, slot: Slot, options: RegistrationOptions, live: LiveRegistration, served: LiveRegistration): Promise { const definition = await readOpsPtcDefinition(options, ctx) if (definition === undefined || slot.disposed) return // A failed registration leaves the default preset exactly as it was: this row @@ -458,4 +526,8 @@ async function activate(ctx: Context, registry: PresetRegistry, slot: Slot, opti // The operator action reads this: only a registered preset may be made the default. live.ctx = ctx live.registry = registry + // The unload lease reads this after the injected child is gone (#928). + served.ctx = ctx + served.registry = registry + served.settings = settingsOf(ctx) } diff --git a/src/session-shells.ts b/src/session-shells.ts index 221cd305..b69910db 100644 --- a/src/session-shells.ts +++ b/src/session-shells.ts @@ -12,7 +12,7 @@ import { BashArgumentError } from './shells/argument-error.js' import { MODES } from './permissions.js' import { hostBashDefinition } from './shells/host-tool.js' import { withToolChange } from './publication/changes.js' -import { publicationRegistration } from './publication/reentry.js' +import { publicationPending, publicationReady, publicationRegistration } from './publication/reentry.js' import { startSessionBash } from './shells/session-execution.js' import { resolveSessionDirectory } from './adapter/dsh/working-directory.js' @@ -134,6 +134,10 @@ export function bashRefusalValue(error: unknown): ShellResult { interface Entry { agent: Agent; ctx?: Context; fiber?: Fiber; dispose?: () => void; definition?: HostShellDefinition published?: boolean; generation?: number + /** True while the refusal queue owns an attempt that has not settled (#842). */ + pending?: boolean + /** Generation of the last failed attempt; one report per generation (#579). */ + failed?: number } // Preset consumers share an Agent's own registry layer. A newly eligible @@ -201,28 +205,104 @@ export function mountSessionBash(ctx: Context, config: Pick { + /** Whether the host refused this very tool name in this very registry layer. */ + const nameConflict = (error: unknown): boolean => /is already registered/i.test(errorMessage(error)) + + /** + * Publish one bash layer for an entry. + * + * An owned layer that is still allowed stays authoritative when two of this + * plugin's rows briefly both serve one agent (a mode or preset transition + * overlaps): re-registering the same name in the same layer can only fail + * (#842), so the later row stands by until the owner withdraws or unloads. + * @param entry - the per-agent entry the layer belongs to. + * @param definition - the definition to register. + * @param attemptGeneration - the reconcile generation this attempt belongs to. + */ + const publish = (entry: Entry, definition: HostShellDefinition, attemptGeneration: number) => { if (!entry.ctx) return const previous = bashOwners.get(entry.agent) - if (previous && previous.entry !== entry && !previous.allowed()) previous.clear() - // A failed publication must leave the session with the definition that last worked rather than - // with no bash tool at all (#30). `entry.definition` survives `clear()`, so it holds the last - // definition registered successfully for this entry. + if (previous && previous.entry !== entry && previous.allowed()) return + if (previous && previous.entry !== entry) previous.clear() + let dispose: () => void try { - entry.dispose = publicationRegistration(entry.ctx, () => withToolChange([entry.agent], () => entry.ctx!.tools.register(definition))) - entry.definition = definition - bashOwners.set(entry.agent, { entry, allowed: () => allowed(entry.agent), clear: () => clear(entry) }) + dispose = publicationRegistration(entry.ctx, () => withToolChange([entry.agent], () => entry.ctx!.tools.register(definition))) } catch (error) { - ctx.logger?.warn?.(`dsh-ops: bash publication failed: ${errorMessage(error)}`) - if (entry.definition === undefined) return - try { - entry.dispose = publicationRegistration(entry.ctx, () => withToolChange([entry.agent], () => entry.ctx!.tools.register(entry.definition!))) - bashOwners.set(entry.agent, { entry, allowed: () => allowed(entry.agent), clear: () => clear(entry) }) - } - catch (restoreError) { ctx.logger?.warn?.(`dsh-ops: bash restoration failed: ${errorMessage(restoreError)}`) } + reportRejected(entry, attemptGeneration, definition, error) + return + } + entry.dispose = dispose + bashOwners.set(entry.agent, { entry, allowed: () => allowed(entry.agent), clear: () => clear(entry) }) + admit(entry, dispose, definition, attemptGeneration) + } + + /** + * Mark one registration attempt live, or report and restore on rejection. + * + * A queued attempt exists only once the host admits it: the entry stays + * pending, never published, so a later rejection cannot leave a session + * looking served while its layer is gone (#873). + * @param entry - the entry the attempt belongs to. + * @param dispose - the attempt's queue handle; also its settle identity. + * @param definition - the definition the attempt registers. + * @param attemptGeneration - the reconcile generation of the attempt. + */ + const admit = (entry: Entry, dispose: () => void, definition: HostShellDefinition, attemptGeneration: number) => { + const live = () => { + entry.definition = definition + entry.published = true + entry.generation = attemptGeneration + entry.failed = undefined + } + if (!publicationPending(dispose)) { live(); return } + entry.pending = true + void publicationReady(dispose).then(() => { + // A superseded attempt no longer speaks for this entry. + if (entry.dispose !== dispose) return + entry.pending = false + live() + }, error => { + if (entry.dispose !== dispose) return + entry.pending = false + entry.published = undefined + entry.generation = undefined + if (bashOwners.get(entry.agent)?.entry === entry) bashOwners.delete(entry.agent) + reportRejected(entry, attemptGeneration, definition, error) + }) + } + + /** + * Report one failed registration, then restore the definition that last + * worked once — but never the identical name the layer just refused. + * + * The attempt is latched to its generation: later passes at the same + * generation skip the entry instead of storming the registry (#579); a turn + * boundary or an authority change clears the latch before any retry. + * @param entry - the entry whose attempt failed. + * @param attemptGeneration - the reconcile generation of the attempt. + * @param attempted - the definition the host refused. + * @param error - the host failure. + */ + const reportRejected = (entry: Entry, attemptGeneration: number, attempted: HostShellDefinition, error: unknown) => { + entry.failed = attemptGeneration + ctx.logger?.warn?.(`dsh-ops: bash publication failed: ${errorMessage(error)}`) + // Re-registering keeps the session on the definition that last worked + // (#30) — unless the registry refused this very name in this layer: the + // identical retry used to pair a second failure with the first (#842). + if (entry.definition === undefined || entry.definition === attempted || nameConflict(error)) return + let restore: () => void + try { + restore = publicationRegistration(entry.ctx!, () => withToolChange([entry.agent], () => entry.ctx!.tools.register(entry.definition!))) + } catch (restoreError) { + ctx.logger?.warn?.(`dsh-ops: bash restoration failed: ${errorMessage(restoreError)}`) + return } + entry.dispose = restore + admit(entry, restore, entry.definition!, attemptGeneration) } const reconcile = (refreshDefinitions = false) => { if (refreshDefinitions) ++generation @@ -233,6 +313,10 @@ export function mountSessionBash(ctx: Context, config: Pick gate.watch!(() => { void scheduleReconcile(true) }), 'dsh-ops: bash mode observer') ctx.inject(['sandbox'], () => { scheduleReconcile() }) diff --git a/test/client-settings-plugin-manager.test.mjs b/test/client-settings-plugin-manager.test.mjs new file mode 100644 index 00000000..edad7802 --- /dev/null +++ b/test/client-settings-plugin-manager.test.mjs @@ -0,0 +1,85 @@ +/** + * The settings page must actually ask the host's own installer (#750). + * + * The row's pwsh7 detection reads the `remote.pluginManager` service. A traced + * registry value may only be read through a context that declares the + * dependency, so a page that resolves it without one reported "not installed" + * forever while every other part kept working. This suite mounts the shipped + * browser bundle on a real Cordis host and witnesses the installer roundtrip. + */ +import fs from 'node:fs' +import path from 'node:path' +import vm from 'node:vm' +import { createRequire } from 'node:module' +import { JSDOM } from 'jsdom' +import * as Cordis from '@deepseek-ai/cordis' +import * as slots from '@deepseek-ai/dsh-client-ui-slots' +import { assert, test, report, waitFor, PACKAGE_ROOT } from './lib/harness.mjs' +import { shutdown } from './lib/host.mjs' + +const require = createRequire(import.meta.url) +const dom = new JSDOM('') +globalThis.document = dom.window.document + +/** Load one browser bundle the way the host's ModuleLoader does. */ +function capture(file) { + let definition + globalThis.window = { __ModuleLoader__: { load: value => { definition = value } } } + vm.runInThisContext(fs.readFileSync(file, 'utf8'), { filename: file }) + assert.ok(definition) + return definition +} + +/** + * Resolve one package's `./client` condition to the file a Client row loads. + * @param {string} name - the package whose Client entry is wanted. + * @returns {string} absolute path of the entry file. + */ +const clientEntry = name => { + const exported = require(`${name}/package.json`).exports['./client'] + const file = typeof exported === 'string' ? exported : exported.default + return path.join(PACKAGE_ROOT, 'node_modules', name, file) +} + +const primitives = { Switch: () => null } +const external = name => name === '@deepseek-ai/cordis' ? Cordis + : name === '@deepseek-ai/dsh-client-ui-slots' ? slots + : name === '@deepseek-ai/dsh-client-ui-primitives' ? primitives + : require(name) + +await test('the shipped settings bundle asks the host installer about dsh-win-pwsh7 (#750)', async () => { + const definition = capture(path.join(PACKAGE_ROOT, 'lib/client.js')) + const plugin = definition.factory(external) + const Renderer = capture(clientEntry('@deepseek-ai/dsh-client-ui-renderer')).factory(external) + const ctx = new Cordis.Context() + ctx.logger.level = 0 + let listCalls = 0 + try { + await ctx.plugin(Renderer.SlotRegistry) + // The gateway-less minimal remote: mounting still succeeds and the status + // card reports the miss instead of pretending the runtime is fine. + ctx.provide('remote', { async $mount() { return undefined } }) + // The host's own installer, as the plugin-manager face provides it. + ctx.provide('remote.pluginManager', { + async listPlugins() { + listCalls += 1 + return [{ entryId: 'dsh-win-pwsh7', moduleName: 'dsh-win-pwsh7' }] + }, + async installBundle() { return { ok: true } }, + }) + await ctx.plugin({ inject: ['slots'], apply(inner) { + inner.provide('locale', { register: () => () => {} }) + inner.slots.register({ name: 'root', children: { + 'plugins.row.config': { kind: 'keyed', scope: 'root' }, + 'plugins.detail.section': { kind: 'list', scope: 'root' }, + } }, () => null) + } }) + const fiber = await ctx.plugin(plugin) + try { + await waitFor(() => listCalls === 1, { what: 'the pwsh7 detection roundtrip' }) + assert.equal(listCalls, 1, 'the detection asks the host installer exactly once') + } finally { await fiber.dispose() } + } finally { await shutdown(ctx) } +}) + +report('client-settings-plugin-manager') diff --git a/test/preset-default-leftover.test.mjs b/test/preset-default-leftover.test.mjs new file mode 100644 index 00000000..6c792259 --- /dev/null +++ b/test/preset-default-leftover.test.mjs @@ -0,0 +1,147 @@ +/** + * Unloading the row must not strand the profile's default agent preset. + * + * The operator's one click writes `selectedDefault: ops-ptc` through the host + * settings service (#928's only write point). Disabling or unloading the row + * removes the preset, and the profile used to keep naming it: every new + * session then failed to compose against a preset that no longer existed. + * The unload lease here restores the host default — and never touches a + * default that names any other preset. + */ +import { Context } from '@deepseek-ai/cordis' +import { registerOpsPtcPreset } from '../lib/presets/ops-ptc/register.js' +import { assert, test, report, waitFor } from './lib/harness.mjs' + +/** + * A registry double: records the definition, answers with a counting + * disposer, and exposes the `config`/`defaultId` pair the switch reads. + * @param {string} [selected] - the already-saved `selectedDefault`, if any. + * @returns {object} the registry double with its recorded state. + */ +function stubRegistry(selected) { + const state = { definitions: [], disposed: 0, selected, updates: [], order: [] } + return { + state, + config: { default: 'standard', selectedDefault: { get: () => state.selected } }, + get defaultId() { return state.selected ?? 'standard' }, + register(definition) { + state.definitions.push(definition) + state.order.push('register') + return Promise.resolve(async () => { state.disposed += 1 }) + }, + } +} + +/** + * A settings-service double: records each update and applies the volatile + * write to the registry state, exactly as the host hot-applies it. + * @param {object} registry - the registry the written default belongs to. + * @returns {object} the settings service. + */ +function stubSettings(registry) { + return { + async update(namespace, patch) { + registry.state.updates.push({ namespace, patch: { ...patch } }) + registry.state.order.push('default') + if (typeof patch.selectedDefault === 'string') registry.state.selected = patch.selectedDefault + }, + } +} + +/** + * A context double that plays the row root and the injected child, recording + * every tracked effect so an unload can be driven exactly. + * @param {object} registry - the service exposed as `agentPresets`. + * @param {object|null} [settings] - the service exposed as `settings`. + * @returns {object} the stub root plus its recorded effects. + */ +function stubRoot(registry, settings) { + const events = { effects: [] } + const services = { agentPresets: registry, settings: settings === undefined ? stubSettings(registry) : settings } + const root = { + logger: { warn: () => {} }, + inject(deps, callback) { callback(root) }, + get(name) { return services[name] }, + effect(callback, label) { + const cleanup = callback() + events.effects.push({ label, cleanup }) + return () => {} + }, + } + return { root, events } +} + +/** Wait for the registration to settle, then find one tracked effect by label. */ +async function settleAndFind(registry, events, label) { + await waitFor(() => registry.state.definitions.length === 1, { what: 'the ops-ptc registration' }) + await new Promise(resolve => setImmediate(resolve)) + const effect = events.effects.find(entry => entry.label === label) + assert.ok(effect !== undefined, `the \`${label}\` effect exists`) + return effect +} + +await test('unloading the row restores a profile default that still names the removed preset (#928)', async () => { + const registry = stubRegistry('ops-ptc') + const { root, events } = stubRoot(registry) + const warnings = [] + registerOpsPtcPreset(root, { warn: message => { warnings.push(message) } }) + const preset = { applyDefault: () => { throw new Error('this check never presses the button') } } + assert.ok(registry.state.definitions.length === 1 || true, 'the registration is in flight') + // The field state from an older install: the profile already names ops-ptc. + const release = await settleAndFind(registry, events, 'dsh-ops: ops-ptc preset') + await release.cleanup() + await waitFor(() => registry.state.disposed === 1, { what: 'the released registration' }) + const lease = await settleAndFind(registry, events, 'dsh-ops: ops-ptc preset default lease') + await lease.cleanup() + await waitFor(() => registry.state.selected === 'standard', { what: 'the restored host default' }) + assert.deepEqual(registry.state.updates, + [{ namespace: 'agent-preset-registry', patch: { selectedDefault: 'standard' } }], + 'the restore writes exactly the host default back') + assert.ok(warnings.some(w => /restored the default agent preset/.test(w)), + 'the restore is reported so the operator can see what changed') + void preset +}) + +await test('an unload never touches a default that names another preset', async () => { + const registry = stubRegistry('ptc') + const { root, events } = stubRoot(registry) + registerOpsPtcPreset(root, { warn: () => {} }) + const release = await settleAndFind(registry, events, 'dsh-ops: ops-ptc preset') + await release.cleanup() + const lease = await settleAndFind(registry, events, 'dsh-ops: ops-ptc preset default lease') + await lease.cleanup() + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(registry.state.updates, [], 'a default another preset owns is never written') + assert.equal(registry.state.selected, 'ptc', 'the operator default stays exactly as it was') +}) + +await test('an unload without a settings service reports the leftover instead of guessing', async () => { + const registry = stubRegistry('ops-ptc') + const { root, events } = stubRoot(registry, null) + const warnings = [] + registerOpsPtcPreset(root, { warn: message => { warnings.push(message) } }) + const lease = await settleAndFind(registry, events, 'dsh-ops: ops-ptc preset default lease') + await lease.cleanup() + await new Promise(resolve => setImmediate(resolve)) + assert.equal(registry.state.selected, 'ops-ptc', 'nothing was written without a settings service') + assert.ok(warnings.some(w => /still names the removed ops-ptc preset/.test(w)), + 'the warning tells the operator the profile keeps a dead default') +}) + +await test('a real Cordis row restores the stranded default when its fiber disposes (#928)', async () => { + const ctx = new Context() + ctx.logger.level = 0 + const registry = stubRegistry('ops-ptc') + ctx.provide('agentPresets', registry) + ctx.provide('settings', stubSettings(registry)) + registerOpsPtcPreset(ctx) + await waitFor(() => registry.state.definitions.length === 1, { what: 'the real injection' }) + await ctx.fiber.dispose() + await waitFor(() => registry.state.disposed === 1, { what: 'the fiber disposal to release the preset' }) + await waitFor(() => registry.state.selected === 'standard', { what: 'the stranded default restored on unload' }) + assert.deepEqual(registry.state.updates, + [{ namespace: 'agent-preset-registry', patch: { selectedDefault: 'standard' } }], + 'the disposal wrote the host default back once') +}) + +report('preset-default-leftover') diff --git a/test/preset-registration.test.mjs b/test/preset-registration.test.mjs index be10bdff..b0d865ff 100644 --- a/test/preset-registration.test.mjs +++ b/test/preset-registration.test.mjs @@ -210,7 +210,11 @@ await test('the real Cordis fiber owns the registration, the action and the rele assert.deepEqual(registry.state.order, ['register', 'default']) await ctx.fiber.dispose() await waitFor(() => registry.state.disposed === 1, { what: 'the fiber disposal to release the preset' }) - assert.equal(registry.state.selected, 'ops-ptc', 'a disposal leaves the operator default alone') + await waitFor(() => registry.state.selected === 'standard', { what: 'the stranded default restored on unload' }) + assert.deepEqual(registry.state.updates, [ + { namespace: 'agent-preset-registry', patch: { selectedDefault: 'ops-ptc' } }, + { namespace: 'agent-preset-registry', patch: { selectedDefault: 'standard' } }, + ], 'a disposal writes the host default back exactly once') }) await test('one injected activation never registers the preset twice', async () => { @@ -256,7 +260,9 @@ await test('the action makes OPS (PTC) the default preset once', async () => { }) await test('the action reports unavailable when no preset is registered', async () => { - const preset = registerOpsPtcPreset({ inject() {} }) + // The minimal root still carries the Context capability every row owns: the + // unload lease (#928) registers through it even when nothing is registered. + const preset = registerOpsPtcPreset({ inject() {}, effect() { return () => {} } }) const answer = await preset.applyDefault() assert.equal(answer.status, 'unavailable') assert.match(answer.message, /not registered/) @@ -311,11 +317,14 @@ await test('teardown releases the preset but keeps the operator default', async assert.equal(registry.defaultId, 'ptc') }) -await test('a deployment without the preset registry is left alone', () => { +await test('a deployment without the preset registry is left alone', async () => { const { root, events } = stubRoot({ composedPreset: () => undefined }) registerOpsPtcPreset(root) assert.equal(events.inject.length, 1) - assert.deepEqual(events.effects, []) + // The row still owns its unload lease (#928), but without a registration it + // never served anything, and the lease cleanup writes nothing. + assert.deepEqual(events.effects.map(entry => entry.label), ['dsh-ops: ops-ptc preset default lease']) + await events.effects[0].cleanup() }) await test('a missing fragment only warns; it never throws into apply', async () => { diff --git a/test/session-idempotent-reconcile.test.mjs b/test/session-idempotent-reconcile.test.mjs new file mode 100644 index 00000000..6b79e395 --- /dev/null +++ b/test/session-idempotent-reconcile.test.mjs @@ -0,0 +1,201 @@ +/** + * Session bash layers stay idempotent under concurrency and turn boundaries. + * + * The suite drives the real Cordis host, the real tool registry and the real + * SessionStore append guard against `mountSessionBash`, covering #579, #842 + * and #873: two preset consumers may briefly both believe they own one agent, + * a publication that lost a same-layer name conflict must not retry forever + * or re-register the identical conflicting name, and a turn boundary + * re-asserts authority so a new turn never starts on stale bash state. + */ +import { createScope } from '@deepseek-ai/dsh-scope' +import { SessionStore } from '@deepseek-ai/dsh-session' +import { mountSessionBash } from '../lib/session-shells.js' +import { prepareStep } from './lib/executor.mjs' +import { bootHost, shutdown } from './lib/host.mjs' +import { assert, test, report, TEST_HOME } from './lib/harness.mjs' + +const flush = async () => { for (let i = 0; i < 6; i++) await new Promise(resolve => setImmediate(resolve)) } + +/** The bash resolution one row publishes, as `mountSessionBash` accepts it. */ +const layerOf = file => ({ bash: { available: true, file, source: 'explicit' } }) + +/** Boot the real host with the authority services the rows resolve through. */ +async function setup() { + const host = await bootHost() + const agents = [] + host.ctx.provide('agents', { list: () => agents }) + host.agents = agents + await host.ctx.plugin(inner => { + inner.provide('subprocess', { spawn() { throw new Error('publication tests must not execute') } }) + inner.provide('sandboxPolicy', { resolve: ({ session }) => ({ mode: session.mode, workspaceRoot: TEST_HOME }) }) + }) + return host +} + +/** Mount one preset consumer row; its gate names the agents it serves. */ +function mountRow(ctx, gate, file) { + return ctx.plugin({ inject: ['tools', 'systemPrompt'], apply(inner) { + mountSessionBash(inner, { publishBashTool: true }, layerOf(file), gate) + } }) +} + +/** Bind a real session to a fresh agent the way the host creates one. */ +function mint(ctx, session) { + const agent = { id: session.id, session } + agent.ctx = createScope(ctx, agent).ctx + return agent +} + +/** Register a foreign `ops_bash` in the agent's own layer, as another plugin would. */ +async function registerForeign(agent) { + let undo + await agent.ctx.plugin({ inject: ['tools'], apply(inner) { + undo = inner.tools.register({ name: 'ops_bash', description: 'foreign bash', + parameters: { type: 'object' }, output: { schema: { type: 'string' }, render: () => [] }, + execute: async () => 'foreign' }) + } }) + return () => undo() +} + +await test('two rows that both claim one agent converge without duplicate failures (#842)', async () => { + const { ctx, tools, agents } = await setup() + const warnings = [] + ctx.logger.warn = message => { warnings.push(String(message)) } + const gateA = { allows: () => true } + const gateB = { allows: () => true } + try { + await ctx.plugin(SessionStore) + const rowA = await mountRow(ctx, gateA, process.execPath) + await mountRow(ctx, gateB, 'Z:\\row-b-bash.exe') + const session = ctx.get('sessions').create('contested', { meta: { cwd: TEST_HOME } }) + session.mode = 'danger-full-access' + const agent = mint(ctx, session) + agents.push(agent) + await ctx.serial('agent/created', { agent }); await flush() + assert.ok(tools.get('ops_bash', agent), 'the first row owns the bash layer') + // Every pass while both gates allow must stand by instead of re-registering. + session.append('sandbox/mode', { mode: session.mode }); await flush() + session.append('sandbox/mode', { mode: session.mode }); await flush() + assert.deepEqual(warnings.filter(w => /bash (publication|restoration) failed/.test(w)), [], + 'a contested agent never re-registers the name another of this plugin\'s rows already holds') + // The owner unloads while the other row still claims the agent: only the + // turn boundary can hand the layer over, without any mode event (#873). + await rowA.dispose(); await flush() + assert.equal(tools.get('ops_bash', agent), undefined, 'the owner\'s unload withdraws the contested layer') + session.append('turn/start', { turn: 1 }); await flush() + assert.ok(tools.get('ops_bash', agent), 'the turn boundary lets the standing row take over') + assert.deepEqual(warnings.filter(w => /bash (publication|restoration) failed/.test(w)), [], + 'the whole contested lifecycle stays free of duplicate-registration failures') + } finally { await shutdown(ctx) } +}) + +await test('a lost name conflict is reported once and recovers at the turn boundary (#579, #873)', async () => { + const { ctx, tools, agents } = await setup() + const warnings = [] + ctx.logger.warn = message => { warnings.push(String(message)) } + const gate = { allows: () => true } + try { + await ctx.plugin(SessionStore) + const row = await mountRow(ctx, gate, process.execPath) + const session = ctx.get('sessions').create('conflict', { meta: { cwd: TEST_HOME } }) + session.mode = 'danger-full-access' + const agent = mint(ctx, session) + agents.push(agent) + await ctx.serial('agent/created', { agent }); await flush() + assert.ok(tools.get('ops_bash', agent), 'the layer is live before the conflict') + // The owner withdraws; a foreign same-layer registration takes the name. + gate.allows = () => false + session.append('sandbox/mode', { mode: session.mode }); await flush() + assert.equal(tools.get('ops_bash', agent), undefined, 'the owner withdrew') + const undoForeign = await registerForeign(agent) + gate.allows = () => true + session.append('sandbox/mode', { mode: session.mode }); await flush() + const conflicts = () => warnings.filter(w => /bash publication failed/.test(w)).length + const restorations = () => warnings.filter(w => /bash restoration failed/.test(w)).length + assert.equal(restorations(), 0, 'a same-name conflict never re-registers the identical conflicting name') + assert.equal(conflicts(), 1, 'one lost conflict is reported once') + // Passes at the same generation must not re-attempt the failed registration. + session.append('sandbox/mode', { mode: session.mode }); await flush() + session.append('sandbox/mode', { mode: session.mode }); await flush() + assert.equal(conflicts(), 1, 'later passes do not storm the registry with the same failure') + // A turn boundary retries: the conflicting foreign layer may be gone by then. + undoForeign() + session.append('turn/start', { turn: 1 }); await flush() + assert.ok(tools.get('ops_bash', agent), 'the turn boundary republishes the lost layer') + assert.deepEqual(warnings.filter(w => /append cannot reenter/.test(w)), [], + 'no reentry escapes into the host') + } finally { await shutdown(ctx) } +}) + +await test('a turn boundary re-asserts bash authority without a mode event (#873)', async () => { + const { ctx, tools, agents } = await setup() + const warnings = [] + ctx.logger.warn = message => { warnings.push(String(message)) } + try { + await ctx.plugin(SessionStore) + await mountRow(ctx, { allows: () => true }, process.execPath) + const session = ctx.get('sessions').create('turn-boundary', { meta: { cwd: TEST_HOME } }) + session.mode = 'danger-full-access' + const agent = mint(ctx, session) + agents.push(agent) + await ctx.serial('agent/created', { agent }); await flush() + assert.ok(tools.get('ops_bash', agent), 'the layer is live under permissive authority') + // Authority changed silently: the layer is stale until the next turn begins. + session.mode = 'read-only' + assert.ok(tools.get('ops_bash', agent), 'without an event nothing reconciles yet') + session.append('turn/start', { turn: 1 }); await flush() + assert.equal(tools.get('ops_bash', agent), undefined, + 'the turn boundary withdraws a layer whose authority is gone') + // turn/end is a closing edge, not one that grants authority. + session.mode = 'danger-full-access' + session.append('turn/end', { turn: 1, reason: { kind: 'stop' } }); await flush() + assert.equal(tools.get('ops_bash', agent), undefined, 'turn/end alone does not republish') + session.append('turn/start', { turn: 2 }); await flush() + assert.ok(tools.get('ops_bash', agent), 'the next turn boundary republishes under restored authority') + // The first request of the new turn sees the tool the boundary just restored. + const step = await prepareStep(ctx, agent) + try { + assert.ok(step.assembly.tools.some(tool => tool.name === 'ops_bash'), + 'the first request of the new turn includes ops_bash') + } finally { step.dispose() } + assert.deepEqual(warnings, [], 'the boundary repair reports no failure') + } finally { await shutdown(ctx) } +}) + +await test('creating several agents inside append windows defers every layer and lands them all (#579)', async () => { + const { ctx, tools, agents } = await setup() + const warnings = [] + ctx.logger.warn = message => { warnings.push(String(message)) } + try { + await ctx.plugin(SessionStore) + const component = await mountRow(ctx, { allows: () => true }, process.execPath) + const session = ctx.get('sessions').create('burst', { meta: { cwd: TEST_HOME } }) + session.mode = 'danger-full-access' + const created = [] + let writes = 0 + // A real registry notification appends a valid session event, as host observers can. + ctx.on('tools/change', () => { session.append('turn/start', { turn: ++writes }) }) + ctx.on('session/event', (seen, event) => { + if (seen !== session || event.type !== 'sandbox/mode') return + assert.throws(() => session.append('turn/start', { turn: 99 }), /append cannot reenter/) + const agent = mint(ctx, session) + agents.push(agent) + created.push(ctx.serial('agent/created', { agent })) + return new Promise(resolve => setImmediate(resolve)) + }) + session.append('sandbox/mode', { mode: session.mode }) + session.append('sandbox/mode', { mode: session.mode }) + session.append('sandbox/mode', { mode: session.mode }) + await Promise.all(created); await flush() + assert.equal(agents.length, 3, 'three agents were created inside append windows') + for (const agent of agents) assert.ok(tools.get('ops_bash', agent), 'every deferred layer landed') + assert.equal(writes, 3, 'each deferred publication appends exactly once, after its window') + assert.deepEqual(warnings.filter(w => /failed|reenter/.test(w)), [], 'no failure escapes the burst') + await component.dispose(); await flush() + for (const agent of agents) assert.equal(tools.get('ops_bash', agent), undefined, + 'unload withdraws every deferred layer') + } finally { await shutdown(ctx) } +}) + +report('session-idempotent-reconcile')