DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor(plugins): 删除 dsh-tauri-kernel 并列入废弃名单 (#1155)
Hairyed83457d5b93
diff --git a/README.en.md b/README.en.mdindex f10f6143..c3ff8571 100644--- a/README.en.md+++ b/README.en.md@@ -48,8 +48,7 @@- 🪶 **Native desktop** — Tauri 2 + React 19 + HeroUI 3, embedding the local Harness UI.- 📱 **Remote connection** — Scan a QR code in the Android / iOS app to connect to your computer's DSH over LAN or a Cloudflare public tunnel.- 🔄 **Runtime management** — Install dependencies, select core versions, and access desktop/core updates.-- 🔀 **Multi-backend support** — Use DSH / Codex / Claude in one interface, powered by their native tools.-- 🧩 **Plugin management** — 13 built-in plugins, plus local-directory installs, built-in disabling, community plugin installation, upgrades, removal, and error details.+- 🧩 **Plugin management** — 12 built-in plugins, plus local-directory installs, built-in disabling, community plugin installation, upgrades, removal, and error details.- 🗂️ **Profile configuration** — Separate plugin/settings configurations, with one-click profile data migration, backup, and cloning.- 💽 **Data directory** — Pick where data lives during installation (Windows); migrate or roll it back later in Settings on Windows, macOS, and Linux.- ⌨️ **CLI integration** — Managed `dsh` / `pnpm` commands via shims, not a global npm core installation.@@ -63,7 +62,6 @@ First-party plugins distributed with desktop resources:- [DSH Tauri](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri) — Core plugin: desktop-to-Harness communication, version adapters, and plugin dependency management- [DSH Tauri UI](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri-ui) — Desktop settings UI, native core components, themes, and palettes- [DSH Tauri Mobile UI](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-mobile-ui) — Touch layouts and mobile preferences-- [DSH Tauri Kernel](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-kernel) — Local Codex / Claude integration and model selection- [DSH Tauri Worktree](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri-worktree) — Session-level Git worktrees and checkout- [DSH Tauri Extension](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri-extension) — Official plugin manager, plugin market, Skills, and MCP- [DSH Tauri Scheduler](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri-scheduler) — Scheduled tasks and run historydiff --git a/README.es.md b/README.es.mdindex c9794ab5..305eded2 100644--- a/README.es.md+++ b/README.es.md@@ -48,8 +48,7 @@- 🪶 **Escritorio nativo** — Tauri 2 + React 19 + HeroUI 3, con la interfaz local de Harness integrada.- 📱 **Conexión remota** — Escaneá un QR desde Android / iOS para conectarte al DSH de tu computadora por LAN o un túnel público de Cloudflare.- 🔄 **Gestión del runtime** — Instalá dependencias, elegí versiones del núcleo y accedé a actualizaciones del escritorio y del núcleo.-- 🔀 **Soporte para distintos motores** — Usá DSH / Codex / Claude en una misma interfaz, con sus herramientas nativas.-- 🧩 **Gestión de plugins** — 13 plugins integrados; instalación desde directorios locales, desactivación de integrados y gestión de plugins comunitarios.+- 🧩 **Gestión de plugins** — 12 plugins integrados; instalación desde directorios locales, desactivación de integrados y gestión de plugins comunitarios.- 🗂️ **Configuración por perfiles** — Separá plugins y ajustes, con migración de los datos del perfil en un clic, backup y clonado.- 💽 **Directorio de datos** — Elegí la ubicación al instalar en Windows; migrá o revertí los datos desde Ajustes en Windows, macOS y Linux.- ⌨️ **Integración con la terminal** — Comandos `dsh` / `pnpm` mediante shims administrados, no una instalación global del núcleo por npm.@@ -63,7 +62,6 @@ Plugins propios distribuidos con los recursos del escritorio:- [DSH Tauri](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri) — Plugin central: comunicación del escritorio con Harness, adaptadores de versión y gestión de dependencias de plugins- [DSH Tauri UI](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-ui) — Interfaz de ajustes del escritorio, componentes nativos del núcleo, temas y paletas- [DSH Tauri Mobile UI](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-mobile-ui) — Diseños táctiles y preferencias móviles-- [DSH Tauri Kernel](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-kernel) — Integración local de Codex / Claude y selección de modelos- [DSH Tauri Worktree](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-worktree) — Worktrees Git por sesión y checkout- [DSH Tauri Extension](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-extension) — Gestor oficial de plugins, mercado de plugins, Skills y MCP- [DSH Tauri Scheduler](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-scheduler) — Tareas programadas e historialdiff --git a/README.md b/README.mdindex 24e95d28..e0ebbd77 100644--- a/README.md+++ b/README.md@@ -47,8 +47,7 @@- 🪶 **原生桌面** — Tauri 2 + React 19 + Hero 3,内嵌本地 Harness 界面。- 📱 **远程连接** — Android / iOS 移动端扫码连接电脑上的 DSH,支持局域网与 Cloudflare 公网隧道。- 🔄 **运行时管理** — 安装依赖、选择内核版本,并提供桌面端与内核更新入口。-- 🔀 **多内核支持** — 在同一界面畅用 DSH / Codex / Claude,发挥各自原生工具能力。-- 🧩 **插件管理** — 13 个内置插件;支持本地路径安装、内置插件停用、社区插件安装、升级、卸载与错误查看。+- 🧩 **插件管理** — 12 个内置插件;支持本地路径安装、内置插件停用、社区插件安装、升级、卸载与错误查看。- 🗂️ **档案配置** — 分别管理插件与设置,支持一键迁移档案数据、备份、克隆;- 💽 **数据目录** — 安装时(Windows)可选择数据存放位置;能在设置里整体迁移与回滚。- ⌨️ **命令行集成** — 通过托管 shim 提供 `dsh` / `pnpm` 命令行工具,不是全局 npm 内核安装。@@ -62,7 +61,6 @@- [DSH Tauri](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri) — 核心插件,桌面端与 Harness 通信、版本适配器、插件依赖管理- [DSH Tauri UI](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-ui) — 桌面设置界面、原生核心组件、主题与配色- [DSH Tauri Mobile UI](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-mobile-ui) — 触屏布局与移动端偏好设置-- [DSH Tauri Kernel](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-kernel) — 本机 Codex / Claude 接入与模型选择- [DSH Tauri Worktree](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-worktree) — 会话级 Git 工作树与检出- [DSH Tauri Extension](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-extension) — 官方插件管理、插件市场、Skills 与 MCP- [DSH Tauri Scheduler](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-scheduler) — 定时任务与执行记录diff --git a/genapi.config.ts b/genapi.config.tsindex ac053b06..3cb8330c 100644--- a/genapi.config.ts+++ b/genapi.config.ts@@ -14,7 +14,6 @@ const plugins = ['dsh-tauri-notification','dsh-tauri-worktree','dsh-tauri-remote',- 'dsh-tauri-kernel',]export default defineConfig({diff --git a/packages/dsh-tauri-bundle/package.json b/packages/dsh-tauri-bundle/package.jsonindex 8c43c814..881f8189 100644--- a/packages/dsh-tauri-bundle/package.json+++ b/packages/dsh-tauri-bundle/package.json@@ -6,7 +6,6 @@"dsh-tauri": "workspace:*","dsh-tauri-archive": "workspace:*","dsh-tauri-extension": "workspace:*",- "dsh-tauri-kernel": "workspace:*","dsh-tauri-mobile-ui": "workspace:*","dsh-tauri-model": "workspace:*","dsh-tauri-notification": "workspace:*",diff --git a/packages/dsh-tauri-kernel/cordis.patch.yml b/packages/dsh-tauri-kernel/cordis.patch.ymldeleted file mode 100644index a8193ed8..00000000--- a/packages/dsh-tauri-kernel/cordis.patch.yml+++ /dev/null@@ -1,3 +0,0 @@-- insert:- - id: dsh-tauri-kernel- name: dsh-tauri-kerneldiff --git a/packages/dsh-tauri-kernel/package.json b/packages/dsh-tauri-kernel/package.jsondeleted file mode 100644index 48e6c5f8..00000000--- a/packages/dsh-tauri-kernel/package.json+++ /dev/null@@ -1,58 +0,0 @@-{- "name": "dsh-tauri-kernel",- "type": "module",- "version": "1.0.0",- "description": "在官方会话界面中连接用户本机安装的 Codex 和 Claude 内核。",- "author": "Hairyf <[email protected]>",- "license": "MIT",- "sideEffects": false,- "exports": {- ".": "./dist/index.js",- "./client": {- "types": "./dist/client.d.cts",- "default": "./dist/client.cjs"- },- "./package.json": "./package.json"- },- "main": "./dist/index.js",- "module": "./dist/index.js",- "types": "./dist/index.d.ts",- "files": ["cordis.patch.yml", "dist"],- "engines": {- "dsh": ">=0.1.7-rc.1"- },- "dsh": {- "client": {- "inject": [- "@deepseek-ai/dsh-client-connection",- "@deepseek-ai/dsh-client-locale",- "@deepseek-ai/dsh-client-store",- "@deepseek-ai/dsh-client-ui-layout",- "@deepseek-ai/dsh-client-ui-slots",- "@deepseek-ai/dsh-client-ui-session",- "@deepseek-ai/dsh-api-session-controller",- "@deepseek-ai/dsh-client-ui-workspace",- "dsh-tauri",- "dsh-tauri-ui"- ],- "external": ["dsh-tauri/client", "dsh-tauri-ui/client"],- "platform": "web"- },- "bundle": { "patch": "./cordis.patch.yml" }- },- "scripts": {- "build": "tsdown",- "dev": "tsdown --watch",- "typecheck": "tsc"- },- "dependencies": {- "dsh-h3": "catalog:",- "dsh-tauri": "workspace:*",- "h3": "catalog:"- },- "devDependencies": {- "dsh-tauri-tsdown": "workspace:*",- "dsh-tauri-ui": "workspace:*",- "tsdown": "catalog:cli"- }-}diff --git a/packages/dsh-tauri-kernel/src/client/apis/index.ts b/packages/dsh-tauri-kernel/src/client/apis/index.tsdeleted file mode 100644index 99038e59..00000000--- a/packages/dsh-tauri-kernel/src/client/apis/index.ts+++ /dev/null@@ -1,29 +0,0 @@-/*- * @title index- * @swagger 2.0- * @version 0.0.0- */--import type * as Types from "./index.type";-import { ofetch } from "dsh-tauri/client";-import type { FetchOptions } from "dsh-tauri/client";--/** @method get */-export function getBackends(options?: FetchOptions) {- return ofetch<Types.GetApiTauriBridgeBackendsResponse>("/api/tauri/bridge/backends", { method: "get", ...options });-}--/** @method get */-export function getModels(params: Types.GetApiTauriBridgeModelsQuery, options?: FetchOptions) {- return ofetch<Types.GetApiTauriBridgeModelsResponse>("/api/tauri/bridge/models", { method: "get", params, ...options });-}--/** @method post */-export function postModels(body: Types.PostApiTauriBridgeModelsBody, options?: FetchOptions) {- return ofetch<Types.PostApiTauriBridgeModelsResponse>("/api/tauri/bridge/models", { method: "post", body, ...options });-}--/** @method post */-export function postSessions(body: Types.PostApiTauriBridgeSessionsBody, options?: FetchOptions) {- return ofetch<Types.PostApiTauriBridgeSessionsResponse>("/api/tauri/bridge/sessions", { method: "post", body, ...options });-}diff --git a/packages/dsh-tauri-kernel/src/client/apis/index.type.ts b/packages/dsh-tauri-kernel/src/client/apis/index.type.tsdeleted file mode 100644index b5edbc99..00000000--- a/packages/dsh-tauri-kernel/src/client/apis/index.type.ts+++ /dev/null@@ -1,20 +0,0 @@-export type GetApiTauriBridgeBackendsResponse = { id: "codex" | "claude" | "dsh"; installed: false | true; bridgeReady?: undefined | false | true; auth: "ok" | "missing" | "unknown"; version: null | string; drift: false | true; hint: null | string }[];-export type GetApiTauriBridgeModelsResponse = { backend: "codex" | "claude"; current: { model: null | string; reasoningEffort: null | string }; models: { id: string; name: string; description?: undefined | string; reasoning?: undefined | { efforts: { id: string; name: string; description?: undefined | string }[]; defaultEffort?: undefined | string } }[]; defaultModel?: undefined | string; defaultReasoningEffort?: undefined | string };-export type GetApiTauriBridgeModelsQuerySessionId = string;-export type PostApiTauriBridgeModelsResponse = { model: null | string; reasoningEffort: null | string };-export type PostApiTauriBridgeSessionsResponse = { sessionId: string };--export interface PostApiTauriBridgeModelsBody {- sessionId: string;- model: null | string;- reasoningEffort: null | string;-}-export interface PostApiTauriBridgeSessionsBody {- backend: "codex" | "claude";- workspaceId?: undefined | string;- cwd?: undefined | string;- agentPreset?: undefined | string;-}-export interface GetApiTauriBridgeModelsQuery {- sessionId: GetApiTauriBridgeModelsQuerySessionId;-}diff --git a/packages/dsh-tauri-kernel/src/client/components/hero-kernel.tsx b/packages/dsh-tauri-kernel/src/client/components/hero-kernel.tsxdeleted file mode 100644index cf298d17..00000000--- a/packages/dsh-tauri-kernel/src/client/components/hero-kernel.tsx+++ /dev/null@@ -1,178 +0,0 @@-import type { ReactElement } from 'react'-import type { BackendDetection, BackendId } from '../../shared/types'-import type { HeroKernelProps } from './slot-contract'-import { ChevronDown, Chip, Menu, Xmark } from 'dsh-tauri-ui/client'-import { If, useAsyncState, useStore, useWatchImmediate } from 'dsh-tauri/client'-import { useRef, useState } from 'react'-import { locale } from '../locales'-import { backendFromIdentity, isBackendAvailable, isForkedIdentity } from '../service/kernel-identity'-import { kernelContentAvailable } from '../service/kernel-version'-import { kernelStore } from '../store/modules/kernel-store'-import { KernelIcon } from './kernel-icon'--const LABELS: Record<BackendId, string> = { dsh: 'DeepSeek Harness', codex: 'Codex', claude: 'Claude' }-const CHOICES = ['codex', 'claude'] as const--function backendHint(backend: BackendDetection | undefined): string | undefined {- if (backend === undefined || !backend.installed)- return locale.text('kernel.unavailable')- if (backend.bridgeReady === false)- return locale.text('kernel.coreUnavailable')- if (backend.drift)- return locale.text('kernel.drift')- if (backend.auth === 'missing')- return locale.text('kernel.authMissing')- return undefined-}--function pillClass(disabled: boolean, expanded: boolean): string {- const base = 'group inline-flex h-[28px] items-center rounded-sm whitespace-nowrap leading-none [&>span]:inline-flex [&>span]:h-full [&>span]:items-center'- if (disabled)- return `${base} text-[var(--dsw-alias-label-quaternary)]`- return `${base} text-primary ${expanded ? 'bg-hover' : 'hover:bg-hover'}`-}--export function HeroKernel(props: HeroKernelProps): ReactElement | null {- locale.useLocale()- const store = useStore(kernelStore)- const identity = props.useProjection('bridgeKernel')- const summary = props.useSessions(state => props.sessionId === undefined ? undefined : state.byId[props.sessionId])- const workspaces = props.useWorkspaces(state => state.items)- const [expanded, setExpanded] = useState(false)- const chipRef = useRef<HTMLButtonElement>(null)- const { isLoading, error, executeImmediate } = useAsyncState(props.createSession, undefined, {- immediate: false,- onSuccess: () => setExpanded(false),- })- useWatchImmediate([props.sessionId, identity] as const, ([sessionId, value]) => {- if (sessionId !== undefined && value === undefined)- void props.ensureProjection(sessionId)- })-- if (store.phase === 'ready' && !kernelContentAvailable(store.backends))- return null-- const awaiting = props.sessionId !== undefined && identity === undefined- const bound = backendFromIdentity(identity)- const backend = bound === 'codex' || bound === 'claude' ? bound : undefined- const roster = new Map(store.backends.map(item => [item.id, item]))- const workspaceBySession = new Map(workspaces.flatMap(workspace => workspace.sessionIds.map(id => [id, workspace.workspaceId] as const)))- const workspaceId = props.sessionId === undefined ? undefined : workspaceBySession.get(props.sessionId)- const busy = isLoading || store.phase === 'loading'- const capable = props.canCreate()- const clearable = backend !== undefined && !busy && capable- const disabled = busy || !capable || awaiting- const items = CHOICES.map((id) => {- const hint = backendHint(roster.get(id))- return {- id,- label: (- <>- {LABELS[id]}- <If- cond={hint !== undefined}- then={(- <span className="text-tertiary">{` · ${hint}`}</span>- )}- />- </>- ),- icon: <KernelIcon backend={id} />,- disabled: isLoading || !capable || store.phase !== 'ready' || !isBackendAvailable(roster.get(id)),- }- })- const forked = isForkedIdentity(identity, props.sessionId)- const title = forked- ? locale.text('kernel.fork')- : [- locale.text('kernel.selectorScope'),- backend === 'codex' || backend === 'claude' ? locale.text('kernel.immutable') : undefined,- ].filter(Boolean).join(' · ')- const failure = error == null ? store.error : error instanceof Error ? error.message : String(error)-- function select(id: string): void {- if (isLoading || store.phase !== 'ready' || !capable || (id !== 'codex' && id !== 'claude') || !isBackendAvailable(roster.get(id)))- return- const preset = summary?.projectionValues?.agentPreset- void executeImmediate(id, workspaceId === undefined- ? summary?.cwd === undefined ? {} : { cwd: summary.cwd }- : { workspaceId }, typeof preset === 'string' ? preset : undefined)- }-- function clear(): void {- setExpanded(false)- if (isLoading || store.phase !== 'ready' || !capable)- return- const preset = summary?.projectionValues?.agentPreset- void executeImmediate('dsh', workspaceId === undefined- ? summary?.cwd === undefined ? {} : { cwd: summary.cwd }- : { workspaceId }, typeof preset === 'string' ? preset : undefined)- }-- return (- <div className="relative inline-flex items-center" data-bridge-kernel-picker="" aria-busy={isLoading}>- <span className={pillClass(disabled, expanded)} data-bridge-kernel-pill="">- <Menu- open={expanded}- anchor={(- <Chip- ref={chipRef}- variant="seat"- className={`h-full rounded-none bg-transparent hover:not-disabled:bg-transparent aria-expanded:bg-transparent${clearable ? ' pr-0' : ''}`}- icon={<KernelIcon backend={backend} />}- chevron={clearable ? undefined : <ChevronDown />}- open={expanded}- disabled={disabled}- aria-label={locale.text('kernel.label')}- aria-haspopup="menu"- aria-expanded={expanded}- title={title}- onClick={() => setExpanded(current => !current)}- >- {backend === undefined ? awaiting ? locale.text('kernel.pending') : locale.text('kernel.select') : LABELS[backend]}- </Chip>- )}- items={items}- selectedId={backend}- onSelect={select}- onClose={() => setExpanded(false)}- portal- side="bottom"- getAnchorRect={() => chipRef.current?.getBoundingClientRect() ?? null}- />- <If- cond={clearable}- then={(- <button- type="button"- disabled={busy}- aria-label={locale.text('kernel.clear')}- title={locale.text('kernel.clear')}- data-bridge-kernel-clear=""- className="inline-flex shrink-0 cursor-pointer items-center self-stretch border-none bg-transparent pl-[4px] pr-[8px] text-[var(--dsw-alias-label-caption)] disabled:cursor-default [&_svg]:w-[11px] [&_svg]:h-[11px]"- onClick={clear}- >- <span className="inline-flex group-hover:hidden group-focus-visible:hidden" data-bridge-kernel-chevron="">- <ChevronDown />- </span>- <span className="hidden group-hover:inline-flex group-focus-visible:inline-flex" data-bridge-kernel-clear-icon="">- <Xmark />- </span>- </button>- )}- />- </span>- <If- cond={failure != null}- then={(- <span role="alert" className="text-secondary text-[13px]">- {failure}- <button type="button" disabled={busy} onClick={() => { void props.refreshBackends() }}>- {locale.text('kernel.retry')}- </button>- </span>- )}- />- </div>- )-}diff --git a/packages/dsh-tauri-kernel/src/client/components/kernel-icon.tsx b/packages/dsh-tauri-kernel/src/client/components/kernel-icon.tsxdeleted file mode 100644index 4c63f610..00000000--- a/packages/dsh-tauri-kernel/src/client/components/kernel-icon.tsx+++ /dev/null@@ -1,14 +0,0 @@-import type { ReactElement } from 'react'-import type { BackendId } from '../../shared/types'-import { ClaudeIcon, FishLogo, GptIcon } from 'dsh-tauri-ui/client'-import { If } from 'dsh-tauri/client'--export function KernelIcon({ backend }: { backend: BackendId | undefined }): ReactElement {- return (- <>- <If cond={backend === 'codex'} then={<GptIcon />} />- <If cond={backend === 'claude'} then={<ClaudeIcon />} />- <If cond={backend === 'dsh'} then={<FishLogo size={16} />} />- </>- )-}diff --git a/packages/dsh-tauri-kernel/src/client/components/kernel.test.tsx b/packages/dsh-tauri-kernel/src/client/components/kernel.test.tsxdeleted file mode 100644index b5e52a5d..00000000--- a/packages/dsh-tauri-kernel/src/client/components/kernel.test.tsx+++ /dev/null@@ -1,366 +0,0 @@-// @vitest-environment jsdom-import type { SessionId, SessionListState } from 'dsh-tauri/client'-import type { KernelBinding } from '../../shared/types'-import type { HeroKernelProps, SessionKernelHoverProps, SessionKernelProps } from './slot-contract'-import { act, cleanup, fireEvent, render } from '@testing-library/react'-import { useRef, useSyncExternalStore } from 'react'-import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { kernelStore } from '../store/modules/kernel-store'-import { HeroKernel } from './hero-kernel'-import { SessionKernel } from './session-kernel'-import { SessionKernelHover } from './session-kernel-hover'--vi.hoisted(() => vi.stubGlobal('localStorage', undefined))--vi.mock('dsh-tauri-ui/client', async () => ({- ...await import('../../../../dsh-tauri-ui/src/client/components/brand-icons'),- ...await import('../../../../dsh-tauri-ui/src/client/components/chip'),- ...await import('../../../../dsh-tauri-ui/src/client/components/icons'),- ...await import('../../../../dsh-tauri-ui/src/client/components/official'),-}))--const IDENTITY: KernelBinding = { backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }--function heroProps(options: { identity?: KernelBinding | null, sessionId?: string, workspaceId?: string, cwd?: string, canCreate?: boolean } = {}): HeroKernelProps {- const sessionId = options.sessionId- const summary = { id: sessionId, blank: true, cwd: options.cwd, projectionValues: { agentPreset: 'coding' } }- const workspace = { workspaceId: options.workspaceId, sessionIds: [sessionId], path: '/project' }- return {- sessionId,- useProjection: () => useRef(options.identity).current,- useSessions: (selector: (state: unknown) => unknown) => selector(useRef({ byId: sessionId === undefined ? {} : { [sessionId]: summary }, projectionsBySession: {} }).current),- useWorkspaces: (selector: (state: unknown) => unknown) => selector(useRef({ items: options.workspaceId === undefined ? [] : [workspace] }).current),- ensureProjection: vi.fn(async () => {}),- canCreate: () => options.canCreate ?? true,- createSession: vi.fn(async () => {}),- refreshBackends: vi.fn(async () => {}),- } as unknown as HeroKernelProps-}--function sidebarProps(identity: KernelBinding | null | undefined): SessionKernelProps & SessionKernelHoverProps {- return {- sessionId: 'session-a',- ensureProjection: vi.fn(async () => {}),- useSessions: (selector: (state: unknown) => unknown) => selector(useRef({ byId: {}, projectionsBySession: { 'session-a': { values: { bridgeKernel: identity } } } }).current),- } as unknown as SessionKernelProps & SessionKernelHoverProps-}--beforeEach(() => {- kernelStore.$patch({- phase: 'ready',- error: null,- backends: [- { id: 'dsh', installed: true, auth: 'ok', version: '0.2.1-alpha.2', drift: false, hint: null },- { id: 'codex', installed: true, auth: 'ok', version: '1.0', drift: false, hint: null },- { id: 'claude', installed: false, auth: 'unknown', version: null, drift: false, hint: null },- ],- })-})--afterEach(() => {- cleanup()- kernelStore.$patch({ backends: [], phase: 'idle', error: null })- vi.restoreAllMocks()-})--afterAll(() => vi.unstubAllGlobals())--describe('hero kernel picker', () => {- it('starts unselected with the two native kernels and no persisted default', () => {- const props = heroProps()- const view = render(<HeroKernel {...props} />)- const chip = view.getByRole('button', { name: 'Kernel' })- expect(chip.textContent).toContain('Select kernel')- expect((chip as HTMLButtonElement).disabled).toBe(false)- fireEvent.click(chip)- expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual(['Codex', 'Claude · Not installed'])- expect(view.getByRole('menu').querySelectorAll('[aria-checked="true"]')).toHaveLength(0)- })-- it('a session without a native binding stays unselected instead of showing the official kernel', () => {- const view = render(<HeroKernel {...heroProps({ sessionId: 'session-a', identity: null })} />)- const chip = view.getByRole('button', { name: 'Kernel' })- expect(chip.textContent).toContain('Select kernel')- expect((chip as HTMLButtonElement).disabled).toBe(false)- expect(view.queryByRole('button', { name: 'Clear kernel selection' })).toBeNull()- })-- it('shows the arrow by default and swaps it for the clear icon on hover', () => {- const view = render(<HeroKernel {...heroProps({ sessionId: 'session-a', identity: IDENTITY })} />)- const pill = view.container.querySelector('[data-bridge-kernel-pill]')- const clear = view.getByRole('button', { name: 'Clear kernel selection' })- expect(pill?.className).toContain('group')- expect(pill?.querySelector('[data-bridge-kernel-chevron]')?.className).toContain('group-hover:hidden')- const clearIcon = pill?.querySelector('[data-bridge-kernel-clear-icon]')- expect(clearIcon?.className).toContain('hidden')- expect(clearIcon?.className).toContain('group-hover:inline-flex')- expect(clearIcon?.className).toContain('group-focus-visible:inline-flex')- expect(clear.querySelectorAll('svg')).toHaveLength(2)- })-- it('a bound native session returns to dsh through the clear affordance', async () => {- const props = heroProps({ sessionId: 'session-a', identity: IDENTITY, workspaceId: 'workspace-a' })- const view = render(<HeroKernel {...props} />)- expect(view.getByRole('button', { name: 'Kernel' }).textContent).toContain('Codex')- const clear = view.getByRole('button', { name: 'Clear kernel selection' })- const pill = view.container.querySelector('[data-bridge-kernel-pill]')!- expect(pill.contains(view.getByRole('button', { name: 'Kernel' }))).toBe(true)- expect(pill.contains(clear)).toBe(true)- fireEvent.click(clear)- await vi.waitFor(() => expect(props.createSession).toHaveBeenCalledWith('dsh', { workspaceId: 'workspace-a' }, 'coding'))- expect(view.queryByRole('menu')).toBeNull()- })-- it('mounts no content when the detected runtime predates the bridge baseline', () => {- kernelStore.$patch({ backends: kernelStore.$state.backends.map(item => item.id === 'dsh' ? { ...item, version: '0.2.1-alpha.1' } : item) })- const view = render(<HeroKernel {...heroProps()} />)- expect(view.container.childElementCount).toBe(0)- })-- it('mounts no content when an unreadable runtime version has no capable kernel either', () => {- kernelStore.$patch({- backends: [- { id: 'dsh', installed: true, auth: 'ok', version: null, drift: false, hint: null },- { id: 'codex', installed: true, auth: 'ok', version: '1.0', drift: false, hint: null, bridgeReady: false },- ],- })- const view = render(<HeroKernel {...heroProps()} />)- expect(view.container.childElementCount).toBe(0)- })-- it('an unread session identity stays pending and disabled until its projection arrives', async () => {- const props = heroProps({ sessionId: 'session-a' })- const view = render(<HeroKernel {...props} />)- const chip = view.getByRole('button', { name: 'Kernel' }) as HTMLButtonElement- expect(chip.textContent).toContain('Reading session kernel')- expect(chip.disabled).toBe(true)- await vi.waitFor(() => expect(props.ensureProjection).toHaveBeenCalledWith('session-a'))- expect(props.createSession).not.toHaveBeenCalled()- })-- it('a bound identity is shown in the Chip inside the official Menu anchor', () => {- const view = render(<HeroKernel {...heroProps({ sessionId: 'session-a', identity: IDENTITY })} />)- const chip = view.getByRole('button', { name: 'Kernel' })- expect(chip.textContent).toContain('Codex')- expect(chip.parentElement?.tagName).toBe('SPAN')- expect(chip.getAttribute('title')).toContain('official new-session shortcuts')- expect(chip.getAttribute('title')).toContain('its kernel cannot be changed')- expect(chip.getAttribute('title')).not.toContain('model and kernel cannot be changed')- fireEvent.click(chip)- expect(view.getByRole('menu').querySelectorAll('button')).toHaveLength(2)- expect((view.getByRole('menuitem', { name: 'Claude · Not installed' }) as HTMLButtonElement).disabled).toBe(true)- })-- it('workspace creation passes only workspaceId and preserves the current agent preset', async () => {- const props = heroProps({ sessionId: 'session-a', identity: null, workspaceId: 'workspace-a', cwd: '/project' })- const view = render(<HeroKernel {...props} />)- fireEvent.click(view.getByRole('button', { name: 'Kernel' }))- fireEvent.click(view.getByRole('menuitem', { name: 'Codex' }))- await vi.waitFor(() => expect(props.createSession).toHaveBeenCalledWith('codex', { workspaceId: 'workspace-a' }, 'coding'))- await vi.waitFor(() => expect(view.queryByRole('menu')).toBeNull())- })-- it('ungrouped creation passes only cwd and uninstalled choices cannot create', async () => {- const props = heroProps({ sessionId: 'session-a', identity: null, cwd: '/ungrouped' })- const view = render(<HeroKernel {...props} />)- fireEvent.click(view.getByRole('button', { name: 'Kernel' }))- fireEvent.click(view.getByRole('menuitem', { name: 'Claude · Not installed' }))- expect(props.createSession).not.toHaveBeenCalled()- fireEvent.click(view.getByRole('menuitem', { name: 'Codex' }))- await vi.waitFor(() => expect(props.createSession).toHaveBeenCalledWith('codex', { cwd: '/ungrouped' }, 'coding'))- })-- it.each([- { patch: { auth: 'missing' as const }, hint: 'Not signed in' },- { patch: { drift: true }, hint: 'Incompatible protocol' },- ])('an unavailable native choice shows $hint and cannot invoke creation', ({ patch, hint }) => {- kernelStore.$patch({ backends: kernelStore.$state.backends.map(item => item.id === 'codex' ? { ...item, ...patch } : item) })- const props = heroProps({ sessionId: 'session-a', identity: null })- const view = render(<HeroKernel {...props} />)- fireEvent.click(view.getByRole('button', { name: 'Kernel' }))- const choice = view.getByRole('menuitem', { name: `Codex · ${hint}` }) as HTMLButtonElement- expect(choice.disabled).toBe(true)- fireEvent.click(choice)- expect(props.createSession).not.toHaveBeenCalled()- })-- it.each([- { patch: { installed: false, bridgeReady: true }, hint: 'BRIDGE_EXECUTABLE_MISSING: Install Codex and check PATH', label: 'Codex · Not installed', disabled: true },- { patch: { installed: false, bridgeReady: false }, hint: 'BRIDGE_CORE_UNAVAILABLE: Official plugin records are unavailable', label: 'Codex · Not installed', disabled: true },- { patch: { installed: true, bridgeReady: false, version: '0.162.0' }, hint: 'BRIDGE_CORE_UNAVAILABLE: Official plugin records are unavailable', label: 'Codex · Bridge unavailable', disabled: true },- { patch: { auth: 'unknown' as const, bridgeReady: true }, hint: 'BRIDGE_AUTH_UNKNOWN: Run codex login status', label: 'Codex', disabled: false },- { patch: { auth: 'missing' as const, bridgeReady: true }, hint: 'BRIDGE_AUTH_MISSING: Run codex login', label: 'Codex · Not signed in', disabled: true },- { patch: { drift: true, bridgeReady: true }, hint: 'BRIDGE_PROTOCOL: The native protocol does not match', label: 'Codex · Incompatible protocol', disabled: true },- { patch: { bridgeReady: true }, hint: 'BRIDGE_PROBE_DETAIL: Verbose backend diagnostic', label: 'Codex', disabled: false },- ])('the real Menu uses only the short backend status: $label', ({ patch, hint, label, disabled }) => {- kernelStore.$patch({ backends: kernelStore.$state.backends.map(item => item.id === 'codex' ? { ...item, ...patch, hint } : item) })- const props = heroProps({ sessionId: 'session-a', identity: null })- const view = render(<HeroKernel {...props} />)- fireEvent.click(view.getByRole('button', { name: 'Kernel' }))- const choice = view.getByRole('menuitem', { name: label }) as HTMLButtonElement- expect(choice.disabled).toBe(disabled)- expect(view.queryByText(hint, { exact: false })).toBeNull()- if (disabled) {- fireEvent.click(choice)- expect(props.createSession).not.toHaveBeenCalled()- }- })-- it('the sessionless picker starts unselected and reads no session projection', () => {- const props = heroProps()- const view = render(<HeroKernel {...props} />)- const chip = view.getByRole('button', { name: 'Kernel' }) as HTMLButtonElement- expect(chip.textContent).toContain('Select kernel')- expect(chip.disabled).toBe(false)- expect(props.ensureProjection).not.toHaveBeenCalled()- })-- it('creation failure stays on the current identity and presents an inline error', async () => {- const props = heroProps({ sessionId: 'session-a', identity: null })- vi.mocked(props.createSession).mockRejectedValue(new Error('native create refused'))- const view = render(<HeroKernel {...props} />)- fireEvent.click(view.getByRole('button', { name: 'Kernel' }))- fireEvent.click(view.getByRole('menuitem', { name: 'Codex' }))- await vi.waitFor(() => expect(view.getByRole('alert').textContent).toContain('native create refused'))- expect(view.getByRole('button', { name: 'Kernel' }).textContent).toContain('Select kernel')- })-- it('busy creation disables further selection until it settles', async () => {- const props = heroProps({ sessionId: 'session-a', identity: null })- let finish: (() => void) | undefined- vi.mocked(props.createSession).mockImplementation(() => new Promise<void>((resolve) => {- finish = resolve- }))- const view = render(<HeroKernel {...props} />)- fireEvent.click(view.getByRole('button', { name: 'Kernel' }))- fireEvent.click(view.getByRole('menuitem', { name: 'Codex' }))- expect((view.getByRole('button', { name: 'Kernel' }) as HTMLButtonElement).disabled).toBe(true)- expect((view.getByRole('menuitem', { name: 'Codex' }) as HTMLButtonElement).disabled).toBe(true)- fireEvent.click(view.getByRole('menuitem', { name: 'Codex' }))- expect(props.createSession).toHaveBeenCalledOnce()- if (finish === undefined)- throw new Error('creation promise was not started')- await act(async () => finish?.())- expect(view.queryByRole('menu')).toBeNull()- })-- it('official Menu keyboard entry and Escape return focus to the Chip anchor', async () => {- kernelStore.$patch({ backends: kernelStore.$state.backends.map(item => item.id === 'claude' ? { ...item, installed: true, auth: 'ok' } : item) })- const view = render(<HeroKernel {...heroProps({ sessionId: 'session-a', identity: null })} />)- const chip = view.getByRole('button', { name: 'Kernel' })- chip.focus()- fireEvent.click(chip)- fireEvent.keyDown(chip, { key: 'Tab' })- expect(document.activeElement).toBe(view.getByRole('menuitem', { name: 'Codex' }))- fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' })- expect(document.activeElement).toBe(view.getByRole('menuitem', { name: 'Claude' }))- fireEvent.keyDown(document.activeElement!, { key: 'End' })- expect(document.activeElement).toBe(view.getByRole('menuitem', { name: 'Claude' }))- fireEvent.keyDown(document.activeElement!, { key: 'Escape' })- await vi.waitFor(() => expect(view.queryByRole('menu')).toBeNull())- expect(document.activeElement).toBe(chip)- })-})--describe('sidebar kernel identity', () => {- it('mounts no sidebar decoration when the detected runtime predates the bridge baseline', () => {- kernelStore.$patch({ backends: kernelStore.$state.backends.map(item => item.id === 'dsh' ? { ...item, version: '0.2.0' } : item) })- const kernel = render(<SessionKernel {...sidebarProps(IDENTITY)} />)- expect(kernel.container.childElementCount).toBe(0)- const hover = render(<SessionKernelHover {...sidebarProps(IDENTITY)} />)- expect(hover.container.childElementCount).toBe(0)- })-- it('codex uses a gray currentColor GPT icon with an accessible identity label', () => {- const props = sidebarProps(IDENTITY)- const view = render(<SessionKernel {...props} />)- const identity = view.getByRole('img', { name: 'Codex Kernel' })- expect(identity.className).toContain('text-tertiary')- expect(identity.querySelector('svg')?.getAttribute('fill')).toBe('currentColor')- expect(identity.querySelector('svg')?.getAttribute('width')).toBe('16')- expect(identity.getAttribute('data-bridge-kernel')).toBe('codex')- expect(props.ensureProjection).not.toHaveBeenCalled()- })-- it('claude renders its own brand icon rather than the GPT path', () => {- const view = render(<SessionKernel {...sidebarProps({ ...IDENTITY, backend: 'claude' })} />)- expect(view.getByRole('img', { name: 'Claude Kernel' }).getAttribute('data-bridge-kernel')).toBe('claude')- expect(view.container.querySelector('path')?.getAttribute('d')).toContain('M4.709 15.955')- })-- it('deepseek identity has no extra leading brand decoration', () => {- const view = render(<SessionKernel {...sidebarProps(null)} />)- expect(view.queryByRole('img')).toBeNull()- })-- it('unknown identity stays undecorated and requests only a nonactivating projection read', async () => {- const props = sidebarProps(undefined)- const view = render(<SessionKernel {...props} />)- expect(view.queryByRole('img')).toBeNull()- await vi.waitFor(() => expect(props.ensureProjection).toHaveBeenCalledWith('session-a'))- })-- it('a cold cached identity follows a later live projection without retaining a session', async () => {- const id = 'session-a' as SessionId- let snapshot: SessionListState = {- ids: [id],- byId: {- [id]: {- id,- displayTitle: 'Session A',- running: false,- retainedBy: {},- blank: false,- updatedAt: 0,- projectionValues: { bridgeKernel: { backend: 'codex', nativeSessionId: 'native-a', sessionId: id } },- },- },- projectionsBySession: {},- phase: 'ready',- }- const listeners = new Set<() => void>()- function subscribe(listener: () => void): () => void {- listeners.add(listener)- return () => listeners.delete(listener)- }- const props = {- sessionId: id,- ensureProjection: vi.fn(async () => {}),- useSessions: (selector: (state: SessionListState) => unknown) => selector(useSyncExternalStore(subscribe, () => snapshot)),- } as unknown as SessionKernelProps- const view = render(<SessionKernel {...props} />)- expect(view.getByRole('img', { name: 'Codex Kernel' })).toBeTruthy()- await act(async () => {- snapshot = {- ...snapshot,- projectionsBySession: { [id]: { values: { bridgeKernel: { backend: 'claude', nativeSessionId: 'native-b', sessionId: id } }, state: 'ready', error: null } },- }- for (const listener of listeners)- listener()- })- expect(view.getByRole('img', { name: 'Claude Kernel' })).toBeTruthy()- expect(view.queryByRole('img', { name: 'Codex Kernel' })).toBeNull()- await act(async () => {- snapshot = { ...snapshot, projectionsBySession: { [id]: { values: { bridgeKernel: null }, state: 'ready', error: null } } }- for (const listener of listeners)- listener()- })- expect(view.queryByRole('img')).toBeNull()- expect(props.ensureProjection).not.toHaveBeenCalled()- view.unmount()- expect(listeners.size).toBe(0)- })-- it('the public hover fallback shows identity even when a leading seat is unavailable', () => {- const view = render(<SessionKernelHover {...sidebarProps(IDENTITY)} />)- expect(view.getByText('Kernel: Codex')).toBeTruthy()- expect(view.container.querySelector('[data-bridge-kernel-hover]')?.getAttribute('data-bridge-kernel-hover')).toBe('codex')- expect(view.container.querySelector('svg')?.getAttribute('fill')).toBe('currentColor')- })-- it('an inherited native owner is named in hover but explicitly cannot resume that kernel', () => {- const view = render(<SessionKernelHover {...sidebarProps({ ...IDENTITY, sessionId: 'parent-session' })} />)- expect(view.getByText('Kernel: Codex')).toBeTruthy()- expect(view.getByText('Forked sessions cannot resume the native kernel')).toBeTruthy()- })-})diff --git a/packages/dsh-tauri-kernel/src/client/components/model-kernel.test.tsx b/packages/dsh-tauri-kernel/src/client/components/model-kernel.test.tsxdeleted file mode 100644index 1ebe5ea9..00000000--- a/packages/dsh-tauri-kernel/src/client/components/model-kernel.test.tsx+++ /dev/null@@ -1,591 +0,0 @@-// @vitest-environment jsdom-import type { ModelSelection } from '@deepseek-ai/dsh-api-session-controller/types'-import type { SessionId, SessionListState } from 'dsh-tauri/client'-import type { NativeModelDirectory, NativeTurnOptions } from '../../shared/native-model'-import type { KernelBinding } from '../../shared/types'-import type { NativeModelActions, NativeModelDirectoryState } from '../types/kernel-model'-import type { ModelKernelProps } from './slot-contract'-import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'-import { defineRegister } from 'dsh-tauri/client'-import { createElement, StrictMode, useSyncExternalStore } from 'react'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { getModels, postModels } from '../apis'-import { registerNativeModels } from '../register/kernel-model'-import { nativeModel } from '../store/modules/native-model'-import { ModelKernel } from './model-kernel'--vi.mock('../apis', () => ({ getModels: vi.fn(), postModels: vi.fn() }))--const CATALOG: NativeModelDirectory = {- backend: 'codex',- defaultModel: 'gpt-5.4',- current: { model: null, reasoningEffort: null },- models: [- { id: 'gpt-5.4', name: 'GPT-5.4', reasoning: { efforts: [{ id: 'medium', name: 'Medium' }, { id: 'high', name: 'High' }], defaultEffort: 'medium' } },- { id: 'gpt-5.4-mini', name: 'GPT-5.4 Mini' },- ],-}-const OFFICIAL_DIRECTORY: NativeModelDirectoryState = {- current: { provider: 'openai', model: 'official-model' },- routable: true,- groups: [{ id: 'openai', name: 'OpenAI', models: [{ id: 'official-model', name: 'Official model' }] }],- failures: [],- status: 'ready',- pending: null,- error: null,-}-const disposers: (() => void)[] = []--interface ContractFace {- locked: boolean- available: boolean- directory: { subscribe: (listener: () => void) => () => void, getSnapshot: () => NativeModelDirectoryState }- load: () => void- select: (selection: ModelSelection) => Promise<unknown>- marker: string-}--function deferred<T>() {- let resolve: (value: T) => void = () => {- throw new Error('uninitialized promise')- }- const promise = new Promise<T>((accept) => {- resolve = accept- })- return { promise, resolve }-}--function fixture(identity: KernelBinding | null | undefined, options: { current?: NativeTurnOptions, locked?: boolean, available?: boolean, refresh?: boolean } = {}) {- const officialSelect = vi.fn(async () => ({ ok: true, value: undefined }))- const officialLoad = vi.fn()- const ensureProjection = vi.fn(async () => {})- const faces: ContractFace[] = []- const listeners = new Set<() => void>()- let state: SessionListState = { ids: [], byId: {}, phase: 'ready', projectionsBySession: {- ['session-a' as SessionId]: { values: { bridgeKernel: identity, bridgeModel: options.current ?? { model: null, reasoningEffort: null } }, state: 'ready', error: null },- } }- const list = {- getSnapshot: () => state,- subscribe(listener: () => void) {- listeners.add(listener)- return () => {- listeners.delete(listener)- }- },- }- let serverSelection: NativeTurnOptions = options.current ?? { model: null, reasoningEffort: null }- const refreshProjections = vi.fn(async (sessionId: string) => {- state = { ...state, projectionsBySession: { ...state.projectionsBySession, [sessionId]: {- values: { ...state.projectionsBySession?.[sessionId as SessionId]?.values, bridgeModel: serverSelection },- state: 'ready',- error: null,- } } }- for (const listener of listeners)- listener()- })- const sessions = { list, ...(options.refresh === false ? {} : { refreshProjections }), selectModel: vi.fn(), binding: vi.fn(), retain: vi.fn(), create: vi.fn() }- const navigation = { openSession: vi.fn(), startSession: vi.fn() }- const ctx = { get: (name: string) => ({ sessions, uiWorkspace: navigation } as Record<string, unknown>)[name] }- let actions: NativeModelActions | undefined- const dispose = defineRegister(ctx, (controller, _ctx, adapter) => {- actions = registerNativeModels(controller, adapter)- })()- disposers.push(dispose)- if (actions === undefined)- throw new Error('native model actions unavailable')- const directory = { getSnapshot: () => OFFICIAL_DIRECTORY, subscribe: () => () => {} }- function ModelSelect(props: ContractFace) {- faces.push(props)- const source = props.directory ?? directory- const snapshot = useSyncExternalStore(listener => source.subscribe(listener), () => source.getSnapshot())- if (!props.available)- return null- const group = snapshot.groups.find(group => group.id === snapshot.current?.provider)- const current = group?.models.find(model => model.id === snapshot.current?.model)- const label = current?.name ?? `${snapshot.current?.provider}/${snapshot.current?.model}`- const reasoning = current?.reasoning- const effectiveEffort = snapshot.current?.reasoningEffort ?? reasoning?.defaultEffort- const effortLabel = reasoning === undefined ? snapshot.retainedEffort : effectiveEffort === undefined ? undefined : reasoning.efforts.find(effort => effort.id === effectiveEffort)?.name ?? effectiveEffort- const chooseModel = (model: NonNullable<typeof group>['models'][number]) => {- if (snapshot.current?.provider === group!.id && snapshot.current.model === model.id)- return- void props.select({ provider: group!.id, model: model.id, ...(model.reasoning?.defaultEffort === undefined ? {} : { reasoningEffort: model.reasoning.defaultEffort }) })- }- const chooseEffort = (effort?: string) => {- if (snapshot.current === null || effectiveEffort === effort)- return- void props.select({ provider: snapshot.current.provider, model: snapshot.current.model, ...(effort === undefined ? {} : { reasoningEffort: effort }) })- }- return createElement('section', { 'data-original-marker': props.marker }, createElement('button', { disabled: props.locked, onClick: props.load }, `${label}${effortLabel === undefined ? '' : ` · ${effortLabel}`}`), ...(snapshot.status === 'ready' ? group?.models.map(model => createElement('button', { key: model.id, disabled: props.locked, onClick: () => chooseModel(model) }, `Model: ${model.name}`)) ?? [] : []), ...(snapshot.status === 'ready' && snapshot.current && reasoning- ? [- ...(reasoning.defaultEffort === undefined ? [createElement('button', { key: 'default-effort', disabled: props.locked, onClick: () => chooseEffort() }, 'Depth: default')] : []),- ...reasoning.efforts.map(effort => createElement('button', { key: effort.id, disabled: props.locked, onClick: () => chooseEffort(effort.id) }, `Depth: ${effort.name}`)),- ]- : []), ...(snapshot.error ? [createElement('div', { key: 'error', role: 'alert' }, snapshot.error), createElement('button', { key: 'retry', onClick: props.load }, 'Retry')] : []))- }- const base = { Original: ModelSelect, locked: options.locked ?? false, available: options.available ?? true, directory, load: officialLoad, select: officialSelect, ensureProjection, marker: 'original-owner', ...actions }- function propsFor(sessionId = 'session-a'): ModelKernelProps {- return { ...base, sessionId, useProjection(key: 'bridgeKernel' | 'bridgeModel') {- const snapshot = useSyncExternalStore(list.subscribe, list.getSnapshot)- return snapshot.projectionsBySession?.[sessionId as SessionId]?.values[key]- } } as unknown as ModelKernelProps- }- return {- props: propsFor(),- propsFor,- officialSelect,- officialLoad,- ensureProjection,- actions,- sessions,- refreshProjections,- navigation,- faces,- directory,- setServerSelection(value: NativeTurnOptions) { serverSelection = value },- setProjection(sessionId: string, binding: KernelBinding | null | undefined, current: NativeTurnOptions | undefined) {- state = { ...state, projectionsBySession: { ...state.projectionsBySession, [sessionId]: { values: { bridgeKernel: binding, bridgeModel: current }, state: 'ready', error: null } } }- for (const listener of listeners)- listener()- },- }-}--beforeEach(() => {- nativeModel.$patch({ generation: 0, entries: {} })- vi.mocked(getModels).mockReset().mockResolvedValue(CATALOG)- vi.mocked(postModels).mockReset().mockResolvedValue({ model: 'gpt-5.4', reasoningEffort: 'high' })-})--afterEach(() => {- cleanup()- for (const dispose of disposers.splice(0))- dispose()- nativeModel.$patch({ generation: 0, entries: {} })- vi.restoreAllMocks()-})--describe('native model renderer public contract', () => {- it('the initial native default shows its actual model and effective effort without a click or durable write', async () => {- vi.mocked(getModels).mockResolvedValue({- backend: 'codex',- defaultModel: 'deepseek',- defaultReasoningEffort: 'high',- current: { model: 'catalog-hint-is-not-durable', reasoningEffort: 'low' },- models: [{ id: 'deepseek', name: 'DeepSeek V4.1 Flash', reasoning: { efforts: [{ id: 'medium', name: 'Medium' }, { id: 'high', name: 'High' }], defaultEffort: 'medium' } }],- })- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'DeepSeek V4.1 Flash · High' })- expect(view.getAllByRole('button', { name: /^Model:/ }).map(button => button.textContent)).toEqual(['Model: DeepSeek V4.1 Flash'])- expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' })- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: null, reasoningEffort: null })- expect(nativeModel.$state.entries['session-a']?.directory.current).toEqual({ provider: 'bridge/codex', model: 'deepseek', reasoningEffort: 'high' })- expect(view.queryByRole('button', { name: /bridge\/codex/ })).toBeNull()- expect(postModels).not.toHaveBeenCalled()- for (const action of [feature.officialSelect, feature.officialLoad, feature.sessions.selectModel, feature.sessions.create, feature.sessions.binding, feature.sessions.retain, feature.navigation.openSession, feature.navigation.startSession])- expect(action).not.toHaveBeenCalled()- })-- it('the native custom default effort is a read-only caption when no native depth metadata exists', async () => {- vi.mocked(getModels).mockResolvedValue({ backend: 'codex', defaultModel: 'deepseek', defaultReasoningEffort: 'high', current: { model: null, reasoningEffort: null }, models: [{ id: 'deepseek', name: 'DeepSeek' }] })- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'DeepSeek · high' })- expect(view.getAllByRole('button', { name: /^Model:/ }).map(button => button.textContent)).toEqual(['Model: DeepSeek'])- expect(view.queryByRole('button', { name: /^Depth:/ })).toBeNull()- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: null, reasoningEffort: null })- expect(postModels).not.toHaveBeenCalled()- })-- it('a missing native default uses one honest placeholder and no guessed model or depth', async () => {- vi.mocked(getModels).mockResolvedValue({ backend: 'codex', current: { model: null, reasoningEffort: null }, models: [] })- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'Model: Native default' })- expect(view.getAllByRole('button', { name: /^Model:/ }).map(button => button.textContent)).toEqual(['Model: Native default'])- expect(view.queryByRole('button', { name: /GPT|Depth:|bridge\/codex/ })).toBeNull()- expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' })- expect(postModels).not.toHaveBeenCalled()- })-- it('default model and provider-default depth actions reset nullable options without persisting the displayed high hint', async () => {- vi.mocked(getModels).mockResolvedValue({ ...CATALOG, defaultReasoningEffort: 'high' })- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'GPT-5.4 · High' })- fireEvent.click(view.getByRole('button', { name: 'Model: GPT-5.4' }))- fireEvent.click(view.getByRole('button', { name: 'Depth: High' }))- expect(postModels).not.toHaveBeenCalled()- fireEvent.click(view.getByRole('button', { name: 'Depth: default' }))- await waitFor(() => expect(postModels).toHaveBeenNthCalledWith(1, { sessionId: 'session-a', model: null, reasoningEffort: null }))- await waitFor(() => expect(nativeModel.$state.entries['session-a']?.directory.status).toBe('ready'))- feature.setServerSelection({ model: 'gpt-5.4-mini', reasoningEffort: null })- fireEvent.click(view.getByRole('button', { name: 'Model: GPT-5.4 Mini' }))- await view.findByRole('button', { name: 'GPT-5.4 Mini' })- feature.setServerSelection({ model: null, reasoningEffort: null })- fireEvent.click(view.getByRole('button', { name: 'Model: GPT-5.4' }))- await view.findByRole('button', { name: 'GPT-5.4 · High' })- expect(vi.mocked(postModels).mock.calls).toEqual([- [{ sessionId: 'session-a', model: null, reasoningEffort: null }],- [{ sessionId: 'session-a', model: 'gpt-5.4-mini', reasoningEffort: null }],- [{ sessionId: 'session-a', model: null, reasoningEffort: null }],- ])- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: null, reasoningEffort: null })- })-- it('a medium-to-High user action submits the actual advertised effort rather than the native display baseline', async () => {- vi.mocked(getModels).mockResolvedValue({ ...CATALOG, defaultReasoningEffort: 'high' })- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }, { current: { model: null, reasoningEffort: 'medium' } })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'GPT-5.4 · Medium' })- feature.setServerSelection({ model: null, reasoningEffort: 'high' })- fireEvent.click(view.getByRole('button', { name: 'Depth: High' }))- await view.findByRole('button', { name: 'GPT-5.4 · High' })- expect(postModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a', model: null, reasoningEffort: 'high' })- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: null, reasoningEffort: 'high' })- })-- it('a Claude alias catalog shows exact native names with no second native-default row', async () => {- vi.mocked(getModels).mockResolvedValue({- backend: 'claude',- defaultModel: 'default',- current: { model: null, reasoningEffort: null },- models: [- { id: 'default', name: 'Default (recommended)' },- { id: 'opus', name: 'Opus' },- { id: 'fable', name: 'Fable' },- { id: 'sonnet', name: 'Sonnet' },- { id: 'haiku', name: 'Haiku' },- ],- })- const feature = fixture({ backend: 'claude', nativeSessionId: 'native-a', sessionId: 'session-a' })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'Default (recommended)' })- fireEvent.click(view.getByRole('button', { name: 'Default (recommended)' }))- await waitFor(() => expect(view.getAllByRole('button', { name: /^Model:/ }).map(button => button.textContent)).toEqual([- 'Model: Default (recommended)',- 'Model: Opus',- 'Model: Fable',- 'Model: Sonnet',- 'Model: Haiku',- ]))- expect(view.queryByRole('button', { name: /原生默认|Native default|bridge\/claude/ })).toBeNull()- expect(nativeModel.$state.entries['session-a']!.current).toEqual({ model: null, reasoningEffort: null })- expect(postModels).not.toHaveBeenCalled()- })-- it('reading an existing fixed default preference never silently converts it to nullable delegation', async () => {- vi.mocked(getModels).mockResolvedValue({ ...CATALOG, defaultReasoningEffort: 'high' })- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }, { current: { model: 'gpt-5.4', reasoningEffort: null } })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'GPT-5.4 · High' })- fireEvent.click(view.getByRole('button', { name: 'Model: GPT-5.4' }))- fireEvent.click(view.getByRole('button', { name: 'Depth: High' }))- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: 'gpt-5.4', reasoningEffort: null })- expect(postModels).not.toHaveBeenCalled()- expect(feature.refreshProjections).not.toHaveBeenCalled()- })-- it('strict mode and shared renderers perform one initial request for a nullable native default', async () => {- const pending = deferred<NativeModelDirectory>()- vi.mocked(getModels).mockReturnValueOnce(pending.promise)- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- const first = render(<StrictMode><ModelKernel {...feature.props} /></StrictMode>)- const second = render(<StrictMode><ModelKernel {...feature.props} /></StrictMode>)- await waitFor(() => expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' }))- const scope = nativeModel.$state.entries['session-a']!.scope- first.unmount()- await act(async () => {- pending.resolve({ backend: 'codex', defaultModel: 'deepseek', defaultReasoningEffort: 'high', current: { model: null, reasoningEffort: null }, models: [{ id: 'deepseek', name: 'DeepSeek' }] })- await pending.promise- })- await second.findByRole('button', { name: 'DeepSeek · high' })- expect(second.getAllByRole('button', { name: /^Model:/ }).map(button => button.textContent)).toEqual(['Model: DeepSeek'])- expect(nativeModel.$state.entries['session-a']!.scope).toBe(scope)- expect(nativeModel.$state.entries['session-a']!.current).toEqual({ model: null, reasoningEffort: null })- expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' })- expect(postModels).not.toHaveBeenCalled()- second.unmount()- await act(async () => {})- expect(nativeModel.$state.entries).toEqual({})- })-- it('an inherited native binding uses a native-default placeholder rather than presenting its bridge route as a model', () => {- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-parent', sessionId: 'parent-session' })- const view = render(<ModelKernel {...feature.props} />)- const trigger = view.getByRole('button', { name: 'Native default' }) as HTMLButtonElement- expect(trigger.disabled).toBe(true)- expect(trigger.title).toBe('Forked sessions cannot resume the native kernel')- expect(view.queryByRole('button', { name: /bridge\/codex/ })).toBeNull()- expect(nativeModel.$state.entries).toEqual({})- expect(getModels).not.toHaveBeenCalled()- expect(postModels).not.toHaveBeenCalled()- })-- it.each(['codex', 'claude'] as const)('the %s identity reuses the original renderer with real native model and depth metadata', async (backend) => {- const modelId = backend === 'codex' ? 'gpt-5.4' : 'claude-sonnet-4-6'- const modelName = backend === 'codex' ? 'GPT-5.4' : 'Sonnet 4.6'- vi.mocked(getModels).mockResolvedValue({ ...CATALOG, backend, defaultModel: modelId, models: [{ id: modelId, name: modelName, reasoning: { efforts: [{ id: 'high', name: 'High' }] } }] })- const feature = fixture({ backend, nativeSessionId: 'native-a', sessionId: 'session-a' }, { current: { model: modelId, reasoningEffort: 'high' } })- const view = render(<ModelKernel {...feature.props} />)- const initial = await view.findByRole('button', { name: `${modelName} · High` }) as HTMLButtonElement- expect(initial.disabled).toBe(false)- expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' })- expect(view.queryByRole('button', { name: 'Official model' })).toBeNull()- expect(view.container.querySelector('[data-bridge-kernel-model="native"]')?.getAttribute('title')).toBe('Model and reasoning changes apply to the next complete turn; this session kernel cannot be changed')- expect(view.container.querySelector('[data-original-marker="original-owner"]')).not.toBeNull()- expect(feature.officialLoad).not.toHaveBeenCalled()- expect(feature.officialSelect).not.toHaveBeenCalled()- })-- it('the official Codex catalog exposes GPT display names and distinct advertised Extra High and Max choices', async () => {- vi.mocked(getModels).mockResolvedValue({- backend: 'codex',- defaultModel: 'gpt-6.1-sol',- current: { model: null, reasoningEffort: null },- models: [- { id: 'gpt-6.1-sol', name: 'GPT-6.1-Sol', reasoning: { efforts: [- { id: 'low', name: 'Low' },- { id: 'medium', name: 'Medium' },- { id: 'high', name: 'High' },- { id: 'xhigh', name: 'Extra High' },- { id: 'max', name: 'Max' },- { id: 'ultra', name: 'Ultra' },- ], defaultEffort: 'low' } },- { id: 'gpt-6-astra', name: 'GPT-6-Astra' },- { id: 'gpt-6-luna', name: 'GPT-6-Luna' },- ],- })- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }, { current: { model: 'gpt-6.1-sol', reasoningEffort: 'low' } })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'GPT-6.1-Sol · Low' })- expect(view.getAllByRole('button', { name: /^Model: GPT/ }).map(button => button.textContent)).toEqual(['Model: GPT-6.1-Sol', 'Model: GPT-6-Astra', 'Model: GPT-6-Luna'])- expect(view.getAllByRole('button', { name: /^Depth:/ }).map(button => button.textContent)).toEqual(['Depth: default', 'Depth: Low', 'Depth: Medium', 'Depth: High', 'Depth: Extra High', 'Depth: Max', 'Depth: Ultra'])- expect(view.queryByRole('button', { name: 'Official model' })).toBeNull()- expect(view.queryByRole('button', { name: 'Depth: Off' })).toBeNull()- feature.setServerSelection({ model: 'gpt-6.1-sol', reasoningEffort: 'xhigh' })- fireEvent.click(view.getByRole('button', { name: 'Depth: Extra High' }))- await view.findByRole('button', { name: 'GPT-6.1-Sol · Extra High' })- feature.setServerSelection({ model: 'gpt-6.1-sol', reasoningEffort: 'max' })- fireEvent.click(view.getByRole('button', { name: 'Depth: Max' }))- await view.findByRole('button', { name: 'GPT-6.1-Sol · Max' })- expect(postModels).toHaveBeenNthCalledWith(1, { sessionId: 'session-a', model: null, reasoningEffort: 'xhigh' })- expect(postModels).toHaveBeenNthCalledWith(2, { sessionId: 'session-a', model: null, reasoningEffort: 'max' })- expect(feature.officialLoad).not.toHaveBeenCalled()- expect(feature.officialSelect).not.toHaveBeenCalled()- })-- it('advertised native Off sends none while the separate default choice sends null', async () => {- vi.mocked(getModels).mockResolvedValue({- backend: 'codex',- defaultModel: 'vendor-model',- current: { model: null, reasoningEffort: null },- models: [{ id: 'vendor-model', name: 'Native vendor model', reasoning: { efforts: [{ id: 'none', name: 'Off' }, { id: 'max', name: 'Max' }], defaultEffort: 'max' } }],- })- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }, { current: { model: 'vendor-model', reasoningEffort: 'max' } })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'Depth: Off' })- feature.setServerSelection({ model: 'vendor-model', reasoningEffort: 'none' })- fireEvent.click(view.getByRole('button', { name: 'Depth: Off' }))- await view.findByRole('button', { name: 'Native vendor model · Off' })- expect(postModels).toHaveBeenNthCalledWith(1, { sessionId: 'session-a', model: null, reasoningEffort: 'none' })- feature.setServerSelection({ model: 'vendor-model', reasoningEffort: null })- fireEvent.click(view.getByRole('button', { name: 'Depth: default' }))- await view.findByRole('button', { name: 'Native vendor model' })- expect(postModels).toHaveBeenNthCalledWith(2, { sessionId: 'session-a', model: null, reasoningEffort: null })- expect(feature.officialSelect).not.toHaveBeenCalled()- })-- it('model and depth choices use generated native APIs and durable projection without global model RPC or activation', async () => {- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }, { current: { model: 'gpt-5.4-mini', reasoningEffort: null } })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'Model: GPT-5.4' })- feature.setServerSelection({ model: null, reasoningEffort: null })- fireEvent.click(view.getByRole('button', { name: 'Model: GPT-5.4' }))- await view.findByRole('button', { name: 'GPT-5.4' })- expect(postModels).toHaveBeenNthCalledWith(1, { sessionId: 'session-a', model: null, reasoningEffort: null })- feature.setServerSelection({ model: null, reasoningEffort: 'high' })- fireEvent.click(view.getByRole('button', { name: 'Depth: High' }))- await view.findByRole('button', { name: 'GPT-5.4 · High' })- expect(postModels).toHaveBeenNthCalledWith(2, { sessionId: 'session-a', model: null, reasoningEffort: 'high' })- expect(feature.refreshProjections.mock.calls).toEqual([['session-a'], ['session-a']])- for (const action of [feature.officialSelect, feature.sessions.selectModel, feature.sessions.create, feature.sessions.binding, feature.sessions.retain, feature.navigation.openSession, feature.navigation.startSession])- expect(action).not.toHaveBeenCalled()- })-- it('the nullable default model retains actual depth choices and sends a nullable effort reset', async () => {- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'Depth: High' })- feature.setServerSelection({ model: null, reasoningEffort: 'high' })- fireEvent.click(view.getByRole('button', { name: 'Depth: High' }))- await view.findByRole('button', { name: 'GPT-5.4 · High' })- expect(postModels).toHaveBeenNthCalledWith(1, { sessionId: 'session-a', model: null, reasoningEffort: 'high' })- feature.setServerSelection({ model: null, reasoningEffort: null })- fireEvent.click(view.getByRole('button', { name: 'Depth: default' }))- await view.findByRole('button', { name: 'GPT-5.4' })- expect(postModels).toHaveBeenNthCalledWith(2, { sessionId: 'session-a', model: null, reasoningEffort: null })- })-- it('models without native reasoning metadata expose no invented depth controls', async () => {- vi.mocked(getModels).mockResolvedValue({ backend: 'claude', defaultModel: 'claude-sonnet-4-6', current: { model: null, reasoningEffort: null }, models: [{ id: 'claude-sonnet-4-6', name: 'Sonnet 4.6' }] })- const feature = fixture({ backend: 'claude', nativeSessionId: 'native-a', sessionId: 'session-a' }, { current: { model: 'claude-sonnet-4-6', reasoningEffort: null } })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'Sonnet 4.6' })- expect(view.queryByRole('button', { name: /Depth:/ })).toBeNull()- })-- it.each([{ locked: true, available: true }, { locked: false, available: false }])('preserves locked=$locked and available=$available even for direct public callback invocation', async (options) => {- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }, options)- const view = render(<ModelKernel {...feature.props} />)- if (options.available)- expect((await view.findByRole('button', { name: 'GPT-5.4' }) as HTMLButtonElement).disabled).toBe(true)- else- expect(view.queryByRole('button')).toBeNull()- await act(async () => {- await feature.faces.at(-1)?.select({ provider: 'bridge/codex', model: 'gpt-5.4' })- })- expect(postModels).not.toHaveBeenCalled()- expect(feature.officialSelect).not.toHaveBeenCalled()- })-- it('catalog failures stay visible and retry reloads the same native scope', async () => {- vi.mocked(getModels).mockRejectedValueOnce(new Error('CLI catalog failed'))- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- const view = render(<ModelKernel {...feature.props} />)- expect((await view.findByRole('alert')).textContent).toBe('CLI catalog failed')- fireEvent.click(view.getByRole('button', { name: 'Retry' }))- await view.findByRole('button', { name: 'Model: GPT-5.4' })- expect(view.queryByRole('alert')).toBeNull()- expect(getModels).toHaveBeenCalledTimes(2)- expect(feature.officialLoad).not.toHaveBeenCalled()- })-- it('a selection pending during session switch cannot update the new session or refresh the old projection', async () => {- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- const view = render(<ModelKernel {...feature.props} />)- await view.findByRole('button', { name: 'Model: GPT-5.4 Mini' })- const pending = deferred<NativeTurnOptions>()- vi.mocked(postModels).mockReturnValueOnce(pending.promise)- fireEvent.click(view.getByRole('button', { name: 'Model: GPT-5.4 Mini' }))- vi.mocked(getModels).mockResolvedValueOnce({ backend: 'claude', defaultModel: 'claude-native', current: { model: null, reasoningEffort: null }, models: [{ id: 'claude-native', name: 'Claude native' }] })- act(() => feature.setProjection('session-b', { backend: 'claude', nativeSessionId: 'native-b', sessionId: 'session-b' }, { model: null, reasoningEffort: null }))- view.rerender(<ModelKernel {...feature.propsFor('session-b')} />)- await act(async () => {- pending.resolve({ model: 'gpt-5.4', reasoningEffort: null })- await pending.promise- })- await view.findByRole('button', { name: 'Claude native' })- expect(nativeModel.$state.entries['session-a']).toBeUndefined()- expect(nativeModel.$state.entries['session-b']?.current).toEqual({ model: null, reasoningEffort: null })- expect(feature.refreshProjections).not.toHaveBeenCalled()- })-- it('unmount releases the register-owned native scope before a catalog can complete', async () => {- const pending = deferred<NativeModelDirectory>()- vi.mocked(getModels).mockReturnValueOnce(pending.promise)- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- const view = render(<ModelKernel {...feature.props} />)- await waitFor(() => expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' }))- view.unmount()- await act(async () => {- pending.resolve(CATALOG)- await pending.promise- })- expect(nativeModel.$state.entries).toEqual({})- })-- it('strict mode reconnects one stable directory without dropping shared renderers or durable selection', async () => {- const binding: KernelBinding = { backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }- const feature = fixture(binding, { current: { model: 'gpt-5.4', reasoningEffort: 'high' } })- const first = render(<StrictMode><ModelKernel {...feature.props} /></StrictMode>)- await first.findByRole('button', { name: 'GPT-5.4 · High' })- expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' })- expect(first.getAllByRole('button', { name: /^Model:/ }).map(button => button.textContent)).toEqual(['Model: GPT-5.4', 'Model: GPT-5.4 Mini'])- const directory = feature.faces.at(-1)?.directory- const scope = nativeModel.$state.entries['session-a']?.scope- act(() => feature.setProjection('session-a', { ...binding }, { model: 'gpt-5.4', reasoningEffort: 'medium' }))- await first.findByRole('button', { name: 'GPT-5.4 · Medium' })- expect(feature.faces.at(-1)?.directory).toBe(directory)- expect(nativeModel.$state.entries['session-a']?.scope).toBe(scope)- const second = render(<StrictMode><ModelKernel {...feature.props} /></StrictMode>)- await act(async () => {})- expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' })- first.unmount()- expect(nativeModel.$state.entries['session-a']?.scope).toBe(scope)- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: 'gpt-5.4', reasoningEffort: 'medium' })- second.unmount()- await act(async () => {})- expect(nativeModel.$state.entries).toEqual({})- })-- it('deepseek retains the original renderer directory and business actions', async () => {- const feature = fixture(null)- const view = render(<ModelKernel {...feature.props} />)- fireEvent.click(view.getByRole('button', { name: 'Official model' }))- await act(async () => {- await feature.faces.at(-1)!.select({ provider: 'openai', model: 'official-model' })- })- expect(feature.officialLoad).toHaveBeenCalledOnce()- expect(feature.officialSelect).toHaveBeenCalledExactlyOnceWith({ provider: 'openai', model: 'official-model' })- expect(feature.faces.at(-1)?.directory).toBe(feature.directory)- expect(feature.faces.at(-1)?.select).toBe(feature.officialSelect)- expect(view.container.querySelector('[data-bridge-kernel-model]')).toBeNull()- expect(getModels).not.toHaveBeenCalled()- expect(postModels).not.toHaveBeenCalled()- })-- it('an owner-locked DeepSeek composer never becomes unlocked', () => {- const feature = fixture(null, { locked: true })- const view = render(<ModelKernel {...feature.props} />)- expect((view.getByRole('button', { name: 'Official model' }) as HTMLButtonElement).disabled).toBe(true)- })-- it('unknown kernel identity stays locked and requests only nonactivating projection', async () => {- const feature = fixture(undefined)- const view = render(<ModelKernel {...feature.props} />)- const trigger = view.getByRole('button', { name: 'Kernel' }) as HTMLButtonElement- expect(trigger.disabled).toBe(true)- expect(trigger.title).toBe('Reading session kernel')- await waitFor(() => expect(feature.ensureProjection).toHaveBeenCalledExactlyOnceWith('session-a'))- expect(nativeModel.$state.entries).toEqual({})- expect(getModels).not.toHaveBeenCalled()- })-- it('missing durable native options remain locked instead of reading global model state', async () => {- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- feature.setProjection('session-a', { backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }, undefined)- const view = render(<ModelKernel {...feature.props} />)- expect((view.getByRole('button', { name: 'Native default' }) as HTMLButtonElement).disabled).toBe(true)- await waitFor(() => expect(feature.ensureProjection).toHaveBeenCalledExactlyOnceWith('session-a'))- expect(nativeModel.$state.entries).toEqual({})- })-- it('an inherited parent binding stays locked until the child owns a separate native identity', () => {- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-parent', sessionId: 'parent-session' })- const view = render(<ModelKernel {...feature.props} />)- expect((view.getByRole('button', { name: 'Native default' }) as HTMLButtonElement).disabled).toBe(true)- expect(nativeModel.$state.entries).toEqual({})- expect(getModels).not.toHaveBeenCalled()- })-- it('a missing official projection reader cannot silently unlock the native seat', () => {- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }, { refresh: false })- const view = render(<ModelKernel {...feature.props} />)- expect((view.getByRole('button', { name: 'Native default' }) as HTMLButtonElement).disabled).toBe(true)- expect(nativeModel.$state.entries).toEqual({})- })-- it('an unsupported renderer runtime face receives every original value untouched', () => {- const feature = fixture({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- const props = { ...feature.props, directory: undefined }- const view = render(<ModelKernel {...props} />)- expect((view.getByRole('button', { name: 'Official model' }) as HTMLButtonElement).disabled).toBe(false)- expect(feature.faces.at(-1)?.directory).toBeUndefined()- expect(feature.faces.at(-1)?.select).toBe(feature.officialSelect)- expect(view.container.querySelector('[data-bridge-kernel-model]')).toBeNull()- expect(feature.ensureProjection).not.toHaveBeenCalled()- expect(getModels).not.toHaveBeenCalled()- })-})diff --git a/packages/dsh-tauri-kernel/src/client/components/model-kernel.tsx b/packages/dsh-tauri-kernel/src/client/components/model-kernel.tsxdeleted file mode 100644index 1d003b26..00000000--- a/packages/dsh-tauri-kernel/src/client/components/model-kernel.tsx+++ /dev/null@@ -1,73 +0,0 @@-import type { ReactElement } from 'react'-import type { NativeTurnOptions } from '../../shared/native-model'-import type { KernelBinding } from '../../shared/types'-import type { OfficialModelSelectFace } from '../types/kernel-model'-import type { ModelKernelProps } from './slot-contract'-import { Select } from 'dsh-tauri-ui/client'-import { useStore, useWatchImmediate } from 'dsh-tauri/client'-import { createElement, useState } from 'react'-import { locale } from '../locales'-import { backendFromIdentity, isForkedIdentity } from '../service/kernel-identity'-import { hasModelLockFace } from '../service/kernel-model'-import { isNativeTurnOptions } from '../service/kernel-model.utils'-import { kernelContentAvailable } from '../service/kernel-version'-import { kernelStore } from '../store/modules/kernel-store'--export function ModelKernel(props: ModelKernelProps): ReactElement {- const store = useStore(kernelStore)- if (store.phase === 'ready' && !kernelContentAvailable(store.backends))- return createElement(props.Original, { ...props })- if (!hasModelLockFace(props))- return createElement(props.Original, { ...props })- return <VerifiedModelKernel {...props} />-}--function VerifiedModelKernel(props: ModelKernelProps & OfficialModelSelectFace): ReactElement {- locale.useLocale()- const identity = props.useProjection('bridgeKernel')- const current = props.useProjection('bridgeModel')- useWatchImmediate([props.sessionId, identity, current] as const, ([sessionId, value, selection]) => {- if (value === undefined || (backendFromIdentity(value) !== 'dsh' && !isNativeTurnOptions(selection)))- void props.ensureProjection(sessionId)- })- const backend = backendFromIdentity(identity)- if (backend === 'dsh')- return createElement(props.Original, { ...props })- if (backend === undefined || !isNativeTurnOptions(current) || isForkedIdentity(identity, props.sessionId)- || !props.canSelectNativeModel()) {- const label = backend === undefined ? locale.text('kernel.label') : locale.text('kernel.modelDefault')- return (- <Select- variant="composerTrigger"- options={[{ value: label, label }]}- value={label}- onChange={() => {}}- disabled- title={isForkedIdentity(identity, props.sessionId) ? locale.text('kernel.fork') : locale.text('kernel.pending')}- data-bridge-kernel-model="locked"- />- )- }- const binding = identity as KernelBinding- return <NativeModelKernel key={`${props.sessionId}:${binding.nativeSessionId}`} {...props} binding={binding} current={current} />-}--function NativeModelKernel(props: ModelKernelProps & OfficialModelSelectFace & { binding: KernelBinding, current: NativeTurnOptions }): ReactElement {- const { sessionId, binding, current, createNativeModelDirectory, syncNativeModel } = props- const [directory] = useState(() => createNativeModelDirectory(sessionId, binding, current))- useWatchImmediate([sessionId, binding.backend, binding.nativeSessionId, current.model, current.reasoningEffort] as const, () => {- syncNativeModel(sessionId, binding, current)- })- return (- <span title={locale.text('kernel.modelNextTurn')} data-bridge-kernel-model="native">- {createElement(props.Original, {- ...props,- directory,- load: () => { void props.loadNativeModels(sessionId, binding) },- select: (selection: Parameters<OfficialModelSelectFace['select']>[0]) => props.locked || !props.available- ? Promise.resolve(undefined)- : props.selectNativeModel(sessionId, binding, selection),- })}- </span>- )-}diff --git a/packages/dsh-tauri-kernel/src/client/components/session-kernel-hover.tsx b/packages/dsh-tauri-kernel/src/client/components/session-kernel-hover.tsxdeleted file mode 100644index 82f29314..00000000--- a/packages/dsh-tauri-kernel/src/client/components/session-kernel-hover.tsx+++ /dev/null@@ -1,31 +0,0 @@-import type { ReactElement } from 'react'-import type { SessionKernelHoverProps } from './slot-contract'-import { If, useStore, useWatchImmediate } from 'dsh-tauri/client'-import { locale } from '../locales'-import { backendFromIdentity, isForkedIdentity, kernelFromList } from '../service/kernel-identity'-import { kernelContentAvailable } from '../service/kernel-version'-import { kernelStore } from '../store/modules/kernel-store'-import { KernelIcon } from './kernel-icon'--const LABELS = { dsh: 'DeepSeek Harness', codex: 'Codex', claude: 'Claude' }--export function SessionKernelHover(props: SessionKernelHoverProps): ReactElement | null {- locale.useLocale()- const store = useStore(kernelStore)- const identity = props.useSessions(state => kernelFromList(state, props.sessionId))- useWatchImmediate([props.sessionId, identity] as const, ([sessionId, value]) => {- if (value === undefined)- void props.ensureProjection(sessionId)- })- if (store.phase === 'ready' && !kernelContentAvailable(store.backends))- return null- const backend = backendFromIdentity(identity)- const forked = isForkedIdentity(identity, props.sessionId)- return (- <div className="flex items-center gap-[8px] text-tertiary" data-bridge-kernel-hover={backend ?? 'unknown'}>- <KernelIcon backend={backend} />- <span>{backend === undefined ? locale.text('kernel.pending') : `${locale.text('kernel.label')}: ${LABELS[backend]}`}</span>- <If cond={forked} then={<span>{locale.text('kernel.fork')}</span>} />- </div>- )-}diff --git a/packages/dsh-tauri-kernel/src/client/components/session-kernel.tsx b/packages/dsh-tauri-kernel/src/client/components/session-kernel.tsxdeleted file mode 100644index 506d41e0..00000000--- a/packages/dsh-tauri-kernel/src/client/components/session-kernel.tsx+++ /dev/null@@ -1,32 +0,0 @@-import type { ReactElement } from 'react'-import type { SessionKernelProps } from './slot-contract'-import { If, useStore, useWatchImmediate } from 'dsh-tauri/client'-import { locale } from '../locales'-import { backendFromIdentity, kernelFromList } from '../service/kernel-identity'-import { kernelContentAvailable } from '../service/kernel-version'-import { kernelStore } from '../store/modules/kernel-store'-import { KernelIcon } from './kernel-icon'--export function SessionKernel(props: SessionKernelProps): ReactElement | null {- locale.useLocale()- const store = useStore(kernelStore)- const identity = props.useSessions(state => kernelFromList(state, props.sessionId))- useWatchImmediate([props.sessionId, identity] as const, ([sessionId, value]) => {- if (value === undefined)- void props.ensureProjection(sessionId)- })- if (store.phase === 'ready' && !kernelContentAvailable(store.backends))- return null- const backend = backendFromIdentity(identity)- const label = backend === 'codex' ? 'Codex' : 'Claude'- return (- <If- cond={backend === 'codex' || backend === 'claude'}- then={(- <span className="inline-flex shrink-0 text-tertiary" role="img" aria-label={`${label} ${locale.text('kernel.label')}`} title={label} data-bridge-kernel={backend}>- <KernelIcon backend={backend} />- </span>- )}- />- )-}diff --git a/packages/dsh-tauri-kernel/src/client/components/slot-contract.ts b/packages/dsh-tauri-kernel/src/client/components/slot-contract.tsdeleted file mode 100644index 25bb862c..00000000--- a/packages/dsh-tauri-kernel/src/client/components/slot-contract.ts+++ /dev/null@@ -1,21 +0,0 @@-import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'-import type {} from '@deepseek-ai/dsh-client-ui-session/client'-import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'-import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'-import type { SlotDecorationOriginalProps } from 'dsh-tauri-ui/client'-import type { AdapterSessionCreateOptions } from 'dsh-tauri/client'-import type { BackendId } from '../../shared/types'-import type { HERO_AGENT_PRESET_SLOT, MODEL_KERNEL_SLOT, SIDEBAR_KERNEL_HOVER_SLOT, SIDEBAR_KERNEL_SLOT } from '../constants'-import type { NativeModelActions } from '../types/kernel-model'--export interface KernelActions {- canCreate: () => boolean- createSession: (backend: BackendId, options: AdapterSessionCreateOptions, agentPreset?: string) => Promise<void>- refreshBackends: () => Promise<void>- ensureProjection: (sessionId: string) => Promise<void>-}--export type HeroKernelProps = PropsRuntime<typeof HERO_AGENT_PRESET_SLOT> & KernelActions-export type ModelKernelProps = PropsRuntime<typeof MODEL_KERNEL_SLOT> & Pick<KernelActions, 'ensureProjection'> & NativeModelActions & SlotDecorationOriginalProps-export type SessionKernelProps = PropsRuntime<typeof SIDEBAR_KERNEL_SLOT> & Pick<KernelActions, 'ensureProjection'>-export type SessionKernelHoverProps = PropsRuntime<typeof SIDEBAR_KERNEL_HOVER_SLOT> & Pick<KernelActions, 'ensureProjection'>diff --git a/packages/dsh-tauri-kernel/src/client/constants/index.ts b/packages/dsh-tauri-kernel/src/client/constants/index.tsdeleted file mode 100644index 9c6b3e0c..00000000--- a/packages/dsh-tauri-kernel/src/client/constants/index.ts+++ /dev/null@@ -1,5 +0,0 @@-export const HERO_AGENT_PRESET_SLOT = 'conversation.hero.agentPreset'-export const MODEL_KERNEL_SLOT = 'conversation.input.model'-export const NATIVE_DEFAULT_MODEL = ''-export const SIDEBAR_KERNEL_SLOT = 'sidebar.session.row.leading'-export const SIDEBAR_KERNEL_HOVER_SLOT = 'sidebar.session.row.hover'diff --git a/packages/dsh-tauri-kernel/src/client/index.ts b/packages/dsh-tauri-kernel/src/client/index.tsdeleted file mode 100644index f8366cae..00000000--- a/packages/dsh-tauri-kernel/src/client/index.ts+++ /dev/null@@ -1,12 +0,0 @@-import type { ClientContext } from 'dsh-tauri/client'-import { PLUGIN_ID } from '../shared/constants'-import { locale } from './locales'-import { kernel } from './register/kernel'--export const name = PLUGIN_ID-export const inject = ['slots', 'locale', 'sessions', 'uiWorkspace', 'layout']--export function apply(ctx: ClientContext): void {- ctx.effect(locale.registerLocale, `${PLUGIN_ID}: locale`)- ctx.effect(kernel, `${PLUGIN_ID}: kernel`)-}diff --git a/packages/dsh-tauri-kernel/src/client/locales/index.ts b/packages/dsh-tauri-kernel/src/client/locales/index.tsdeleted file mode 100644index a57f8929..00000000--- a/packages/dsh-tauri-kernel/src/client/locales/index.ts+++ /dev/null@@ -1,49 +0,0 @@-import { defineLocale } from 'dsh-tauri/client'-import { PLUGIN_ID } from '../../shared/constants'--export const locale = defineLocale(PLUGIN_ID, {- zh: {- 'kernel.label': '内核',- 'kernel.pending': '正在读取会话内核',- 'kernel.unavailable': '未安装',- 'kernel.coreUnavailable': '核心不支持桥接',- 'kernel.authMissing': '未登录',- 'kernel.authUnknown': '登录状态未知',- 'kernel.drift': '协议不兼容',- 'kernel.newSession': '新建 {backend} 会话',- 'kernel.createFailed': '新建内核会话失败',- 'kernel.readFailed': '内核检测失败',- 'kernel.fork': '派生会话不能继续原生内核',- 'kernel.creating': '正在新建会话',- 'kernel.retry': '重新检测',- 'kernel.selectorScope': '选择会新建会话,仅记住此选择器的下次选择,不更改当前会话或官方新建快捷键',- 'kernel.immutable': '此会话已绑定原生内核,不能更换内核',- 'kernel.modelNextTurn': '模型与推理深度仅影响下一完整轮次,不能更换此会话内核',- 'kernel.modelRetry': '重新加载模型',- 'kernel.modelDefault': '原生默认',- 'kernel.select': '选择内核',- 'kernel.clear': '清空内核选择',- },- en: {- 'kernel.label': 'Kernel',- 'kernel.pending': 'Reading session kernel',- 'kernel.unavailable': 'Not installed',- 'kernel.coreUnavailable': 'Bridge unavailable',- 'kernel.authMissing': 'Not signed in',- 'kernel.authUnknown': 'Sign-in status unknown',- 'kernel.drift': 'Incompatible protocol',- 'kernel.newSession': 'New {backend} session',- 'kernel.createFailed': 'Failed to create kernel session',- 'kernel.readFailed': 'Kernel detection failed',- 'kernel.fork': 'Forked sessions cannot resume the native kernel',- 'kernel.creating': 'Creating a session',- 'kernel.retry': 'Detect again',- 'kernel.selectorScope': 'Selection creates a new session and is remembered for this picker only; it does not change the current session or official new-session shortcuts',- 'kernel.immutable': 'This session is bound to a native kernel; its kernel cannot be changed',- 'kernel.modelNextTurn': 'Model and reasoning changes apply to the next complete turn; this session kernel cannot be changed',- 'kernel.modelRetry': 'Reload models',- 'kernel.modelDefault': 'Native default',- 'kernel.select': 'Select kernel',- 'kernel.clear': 'Clear kernel selection',- },-})diff --git a/packages/dsh-tauri-kernel/src/client/register/kernel-model.test.ts b/packages/dsh-tauri-kernel/src/client/register/kernel-model.test.tsdeleted file mode 100644index d6a6de46..00000000--- a/packages/dsh-tauri-kernel/src/client/register/kernel-model.test.ts+++ /dev/null@@ -1,401 +0,0 @@-import type { SessionId, SessionListState } from 'dsh-tauri/client'-import type { NativeModelDirectory, NativeTurnOptions } from '../../shared/native-model'-import type { KernelBinding } from '../../shared/types'-import type { NativeModelActions } from '../types/kernel-model'-import { defineRegister } from 'dsh-tauri/client'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { getModels, postModels } from '../apis'-import { nativeModel } from '../store/modules/native-model'-import { registerNativeModels } from './kernel-model'--vi.mock('../apis', () => ({ getModels: vi.fn(), postModels: vi.fn() }))--const BINDING: KernelBinding = { backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }-const CATALOG: NativeModelDirectory = {- backend: 'codex',- current: { model: null, reasoningEffort: null },- defaultModel: 'gpt-5.4',- models: [{ id: 'gpt-5.4', name: 'GPT-5.4', reasoning: { efforts: [{ id: 'high', name: 'High' }] } }],-}-const disposers: (() => void)[] = []--function deferred<T>() {- let resolve: (value: T) => void = () => {- throw new Error('uninitialized promise')- }- const promise = new Promise<T>((accept) => {- resolve = accept- })- return { promise, resolve }-}--function fixture(options: { list?: boolean, refresh?: boolean } = {}) {- let state: SessionListState = { ids: [], byId: {}, phase: 'ready', projectionsBySession: {} }- const refreshProjections = vi.fn(async (sessionId: string) => {- state = { ...state, projectionsBySession: { ...state.projectionsBySession, [sessionId]: {- values: { bridgeKernel: BINDING, bridgeModel: { model: 'gpt-5.4', reasoningEffort: 'high' } },- state: 'ready',- error: null,- } } }- })- const sessions = {- ...(options.list === false ? {} : { list: { subscribe: () => () => {}, getSnapshot: () => state } }),- ...(options.refresh === false ? {} : { refreshProjections }),- binding: vi.fn(),- retain: vi.fn(),- create: vi.fn(),- selectModel: vi.fn(),- }- const navigation = { openSession: vi.fn(), startSession: vi.fn() }- const ctx = { get: (name: string) => ({ sessions, uiWorkspace: navigation } as Record<string, unknown>)[name] }- let actions: NativeModelActions | undefined- const dispose = defineRegister(ctx, (controller, _ctx, adapter) => {- actions = registerNativeModels(controller, adapter)- })()- disposers.push(dispose)- if (actions === undefined)- throw new Error('native model actions unavailable')- return {- actions,- sessions,- refreshProjections,- navigation,- dispose,- setState(value: SessionListState) {- state = value- },- }-}--beforeEach(() => {- nativeModel.$patch({ generation: 0, entries: {} })- vi.mocked(getModels).mockReset().mockResolvedValue(CATALOG)- vi.mocked(postModels).mockReset().mockResolvedValue({ model: 'gpt-5.4', reasoningEffort: 'high' })-})--afterEach(() => {- for (const dispose of disposers.splice(0))- dispose()- nativeModel.$patch({ generation: 0, entries: {} })- vi.restoreAllMocks()-})--describe('registered native model lifecycle', () => {- it('does not load a native catalog until the public directory is subscribed', async () => {- const feature = fixture()- const directory = feature.actions.createNativeModelDirectory('session-a', BINDING, { model: null, reasoningEffort: null })- expect(directory.getSnapshot().current).toEqual({ provider: 'bridge/codex', model: '' })- await Promise.resolve()- expect(nativeModel.$state.entries).toEqual({})- expect(getModels).not.toHaveBeenCalled()- })-- it('initial subscriptions automatically load one catalog in the shared same-commit native scope', async () => {- const feature = fixture()- const directory = feature.actions.createNativeModelDirectory('session-a', BINDING, { model: null, reasoningEffort: null })- const first = directory.subscribe(vi.fn())- const scope = nativeModel.$state.entries['session-a']!.scope- first()- const second = directory.subscribe(vi.fn())- const third = directory.subscribe(vi.fn())- expect(getModels).not.toHaveBeenCalled()- await vi.waitFor(() => expect(directory.getSnapshot().status).toBe('ready'))- expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' })- expect(nativeModel.$state.entries['session-a']!.scope).toBe(scope)- expect(nativeModel.$state.entries['session-a']!.current).toEqual({ model: null, reasoningEffort: null })- expect(directory.getSnapshot().groups[0]!.models[0]!.name).toBe('GPT-5.4')- expect(postModels).not.toHaveBeenCalled()- expect(feature.sessions.binding).not.toHaveBeenCalled()- expect(feature.sessions.retain).not.toHaveBeenCalled()- expect(feature.sessions.create).not.toHaveBeenCalled()- expect(feature.sessions.selectModel).not.toHaveBeenCalled()- second()- third()- await Promise.resolve()- expect(nativeModel.$state.entries).toEqual({})- })-- it('does not issue the scheduled initial catalog read after unsubscription or plugin disposal', async () => {- const feature = fixture()- const directory = feature.actions.createNativeModelDirectory('session-a', BINDING, { model: null, reasoningEffort: null })- const release = directory.subscribe(vi.fn())- release()- await Promise.resolve()- expect(getModels).not.toHaveBeenCalled()- expect(nativeModel.$state.entries).toEqual({})- directory.subscribe(vi.fn())- feature.dispose()- await Promise.resolve()- expect(getModels).not.toHaveBeenCalled()- expect(nativeModel.$state.entries).toEqual({})- })-- it('initial catalog errors survive resubscription and recover only through an explicit retry', async () => {- vi.mocked(getModels).mockRejectedValueOnce(new Error('native default catalog unavailable'))- const feature = fixture()- const directory = feature.actions.createNativeModelDirectory('session-a', BINDING, { model: null, reasoningEffort: null })- const first = directory.subscribe(vi.fn())- await vi.waitFor(() => expect(directory.getSnapshot().error).toBe('native default catalog unavailable'))- first()- const second = directory.subscribe(vi.fn())- await Promise.resolve()- expect(getModels).toHaveBeenCalledTimes(1)- expect(directory.getSnapshot().status).toBe('error')- await feature.actions.loadNativeModels('session-a', BINDING)- expect(getModels).toHaveBeenCalledTimes(2)- expect(directory.getSnapshot().status).toBe('ready')- expect(directory.getSnapshot().error).toBeNull()- expect(nativeModel.$state.entries['session-a']!.current).toEqual({ model: null, reasoningEffort: null })- expect(postModels).not.toHaveBeenCalled()- second()- })-- it('requires both official list and nonactivating projection capabilities', () => {- expect(fixture().actions.canSelectNativeModel()).toBe(true)- expect(fixture({ list: false }).actions.canSelectNativeModel()).toBe(false)- expect(fixture({ refresh: false }).actions.canSelectNativeModel()).toBe(false)- })-- it('reference-counts the same native directory and closes it only after the last release', async () => {- const { actions } = fixture()- const first = actions.acquireNativeModel('session-a', BINDING)- const scope = nativeModel.$state.entries['session-a']?.scope- const second = actions.acquireNativeModel('session-a', BINDING)- expect(nativeModel.$state.entries['session-a']?.scope).toBe(scope)- first()- first()- expect(nativeModel.$state.entries['session-a']).toBeDefined()- second()- await Promise.resolve()- expect(nativeModel.$state.entries['session-a']).toBeUndefined()- })-- it('same-commit resubscription preserves the catalog snapshot and native request scope', async () => {- const feature = fixture()- const directory = feature.actions.createNativeModelDirectory('session-a', BINDING, { model: null, reasoningEffort: null })- const first = directory.subscribe(vi.fn())- await feature.actions.loadNativeModels('session-a', BINDING)- const snapshot = directory.getSnapshot()- const scope = nativeModel.$state.entries['session-a']!.scope- expect(snapshot.status).toBe('ready')- expect(snapshot.groups[0]!.models.map(model => model.id)).toEqual(['gpt-5.4'])- first()- const second = directory.subscribe(vi.fn())- expect(directory.getSnapshot()).toBe(snapshot)- expect(nativeModel.$state.entries['session-a']!.scope).toBe(scope)- await Promise.resolve()- expect(directory.getSnapshot()).toBe(snapshot)- second()- await Promise.resolve()- expect(nativeModel.$state.entries).toEqual({})- })-- it('same-commit resubscription keeps an in-flight catalog request attached to the same scope', async () => {- const feature = fixture()- const directory = feature.actions.createNativeModelDirectory('session-a', BINDING, { model: null, reasoningEffort: null })- const first = directory.subscribe(vi.fn())- const pending = deferred<NativeModelDirectory>()- vi.mocked(getModels).mockReturnValueOnce(pending.promise)- const loading = feature.actions.loadNativeModels('session-a', BINDING)- const scope = nativeModel.$state.entries['session-a']!.scope- first()- const second = directory.subscribe(vi.fn())- pending.resolve(CATALOG)- await loading- expect(directory.getSnapshot().status).toBe('ready')- expect(directory.getSnapshot().groups[0]!.models.map(model => model.id)).toEqual(['gpt-5.4'])- expect(nativeModel.$state.entries['session-a']!.scope).toBe(scope)- expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' })- second()- await Promise.resolve()- expect(nativeModel.$state.entries).toEqual({})- })-- it('the last release revokes a resolved catalog before deferred directory cleanup', async () => {- const feature = fixture()- const release = feature.actions.acquireNativeModel('session-a', BINDING)- const pending = deferred<NativeModelDirectory>()- vi.mocked(getModels).mockReturnValueOnce(pending.promise)- const loading = feature.actions.loadNativeModels('session-a', BINDING)- pending.resolve(CATALOG)- const beforeCleanup = new Promise((resolve) => {- queueMicrotask(() => {- const entry = nativeModel.$state.entries['session-a']!- resolve({ status: entry.directory.status, catalog: entry.catalog })- })- })- release()- expect(await beforeCleanup).toEqual({ status: 'loading', catalog: null })- await loading- expect(nativeModel.$state.entries).toEqual({})- })-- it('the last release revokes a resolved selection before it can refresh the projection', async () => {- const feature = fixture()- const release = feature.actions.acquireNativeModel('session-a', BINDING)- await feature.actions.loadNativeModels('session-a', BINDING)- const pending = deferred<NativeTurnOptions>()- vi.mocked(postModels).mockReturnValueOnce(pending.promise)- const selection = feature.actions.selectNativeModel('session-a', BINDING, { provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' })- pending.resolve({ model: 'gpt-5.4', reasoningEffort: 'high' })- release()- expect(await selection).toBeUndefined()- expect(feature.refreshProjections).not.toHaveBeenCalled()- expect(nativeModel.$state.entries).toEqual({})- })-- it('the public directory owns subscriptions, reads refreshed projection on reconnect, and rejects disposed listeners', async () => {- const feature = fixture()- const directory = feature.actions.createNativeModelDirectory('session-a', BINDING, { model: null, reasoningEffort: null })- const first = directory.subscribe(vi.fn())- await feature.refreshProjections('session-a')- first()- first()- await Promise.resolve()- expect(nativeModel.$state.entries).toEqual({})- const listener = vi.fn()- const second = directory.subscribe(listener)- expect(directory.getSnapshot().current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' })- feature.dispose()- listener.mockClear()- nativeModel.$patch({ generation: 99 })- await Promise.resolve()- expect(listener).not.toHaveBeenCalled()- directory.subscribe(listener)- second()- expect(nativeModel.$state.entries).toEqual({})- })-- it('syncs durable native options without issuing a request or using global model selection', () => {- const { actions, sessions } = fixture()- actions.acquireNativeModel('session-a', BINDING)- actions.syncNativeModel('session-a', BINDING, { model: 'gpt-5.4', reasoningEffort: 'high' })- const entry = nativeModel.$state.entries['session-a']- actions.syncNativeModel('session-a', BINDING, { model: 'gpt-5.4', reasoningEffort: 'high' })- expect(nativeModel.$state.entries['session-a']).toBe(entry)- expect(entry?.directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' })- expect(getModels).not.toHaveBeenCalled()- expect(postModels).not.toHaveBeenCalled()- expect(sessions.selectModel).not.toHaveBeenCalled()- })-- it('uses only generated native APIs and official projection refresh, never activation or global model RPC', async () => {- const feature = fixture()- feature.actions.acquireNativeModel('session-a', BINDING)- await feature.actions.loadNativeModels('session-a', BINDING)- expect(await feature.actions.selectNativeModel('session-a', BINDING, { provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' })).toEqual({ ok: true, value: undefined })- expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' })- expect(postModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a', model: null, reasoningEffort: 'high' })- expect(feature.refreshProjections).toHaveBeenCalledExactlyOnceWith('session-a')- expect(feature.sessions.selectModel).not.toHaveBeenCalled()- expect(feature.sessions.binding).not.toHaveBeenCalled()- expect(feature.sessions.retain).not.toHaveBeenCalled()- expect(feature.sessions.create).not.toHaveBeenCalled()- expect(feature.navigation.openSession).not.toHaveBeenCalled()- expect(feature.navigation.startSession).not.toHaveBeenCalled()- })-- it('a forked parent identity cannot acquire a child directory or issue model requests', async () => {- const { actions } = fixture()- actions.acquireNativeModel('child-session', BINDING)- actions.syncNativeModel('child-session', BINDING, { model: 'gpt-5.4', reasoningEffort: 'high' })- await actions.loadNativeModels('child-session', BINDING)- expect(await actions.selectNativeModel('child-session', BINDING, { provider: 'bridge/codex', model: 'gpt-5.4' })).toBeUndefined()- expect(nativeModel.$state.entries['child-session']).toBeUndefined()- expect(getModels).not.toHaveBeenCalled()- expect(postModels).not.toHaveBeenCalled()- })-- it('another native session identity cannot reuse an acquired lease', async () => {- const { actions } = fixture()- actions.acquireNativeModel('session-a', BINDING)- const changed = { ...BINDING, nativeSessionId: 'native-b' }- await actions.loadNativeModels('session-a', changed)- expect(await actions.selectNativeModel('session-a', changed, { provider: 'bridge/codex', model: 'gpt-5.4' })).toBeUndefined()- expect(getModels).not.toHaveBeenCalled()- expect(postModels).not.toHaveBeenCalled()- })-- it('a binding replacement isolates its scope from the old release callback and response', async () => {- const feature = fixture()- const release = feature.actions.acquireNativeModel('session-a', BINDING)- const pending = deferred<NativeModelDirectory>()- vi.mocked(getModels).mockReturnValueOnce(pending.promise)- const stale = feature.actions.loadNativeModels('session-a', BINDING)- feature.actions.acquireNativeModel('session-a', { ...BINDING, nativeSessionId: 'native-b' })- release()- pending.resolve(CATALOG)- await stale- expect(nativeModel.$state.entries['session-a']?.nativeSessionId).toBe('native-b')- expect(nativeModel.$state.entries['session-a']?.catalog).toBeNull()- })-- it('plugin disposal removes transient directories and blocks retained UI callbacks', async () => {- const feature = fixture()- feature.actions.acquireNativeModel('session-a', BINDING)- feature.dispose()- expect(feature.actions.canSelectNativeModel()).toBe(false)- feature.actions.acquireNativeModel('session-a', BINDING)- feature.actions.syncNativeModel('session-a', BINDING, { model: 'gpt-5.4', reasoningEffort: 'high' })- await feature.actions.loadNativeModels('session-a', BINDING)- expect(await feature.actions.selectNativeModel('session-a', BINDING, { provider: 'bridge/codex', model: 'gpt-5.4' })).toBeUndefined()- expect(nativeModel.$state.entries).toEqual({})- expect(getModels).not.toHaveBeenCalled()- expect(postModels).not.toHaveBeenCalled()- })-- it('a pending GET cannot resurrect a disposed directory', async () => {- const feature = fixture()- feature.actions.acquireNativeModel('session-a', BINDING)- const pending = deferred<NativeModelDirectory>()- vi.mocked(getModels).mockReturnValueOnce(pending.promise)- const stale = feature.actions.loadNativeModels('session-a', BINDING)- feature.dispose()- pending.resolve(CATALOG)- await stale- expect(nativeModel.$state.entries).toEqual({})- })-- it('a pending POST cannot refresh or mutate after plugin disposal', async () => {- const feature = fixture()- feature.actions.acquireNativeModel('session-a', BINDING)- await feature.actions.loadNativeModels('session-a', BINDING)- const pending = deferred<NativeTurnOptions>()- vi.mocked(postModels).mockReturnValueOnce(pending.promise)- const stale = feature.actions.selectNativeModel('session-a', BINDING, { provider: 'bridge/codex', model: 'gpt-5.4' })- feature.dispose()- pending.resolve({ model: 'gpt-5.4', reasoningEffort: null })- expect(await stale).toBeUndefined()- expect(feature.refreshProjections).not.toHaveBeenCalled()- expect(nativeModel.$state.entries).toEqual({})- })-- it('a refreshed projection with a different kernel cannot be accepted as selection success', async () => {- const feature = fixture()- feature.actions.acquireNativeModel('session-a', BINDING)- await feature.actions.loadNativeModels('session-a', BINDING)- feature.refreshProjections.mockImplementation(async () => {- feature.setState({ ids: [], byId: {}, phase: 'ready', projectionsBySession: { ['session-a' as SessionId]: {- values: { bridgeKernel: { ...BINDING, nativeSessionId: 'native-other' }, bridgeModel: { model: 'gpt-5.4', reasoningEffort: 'high' } },- state: 'ready',- error: null,- } } })- })- expect(await feature.actions.selectNativeModel('session-a', BINDING, { provider: 'bridge/codex', model: 'gpt-5.4' })).toEqual({ ok: false, error: { code: 'bridge/model-selection', message: 'Native model selection projection is unavailable' } })- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: null, reasoningEffort: null })- })-- it('disposal during projection refresh cannot install the returned preference', async () => {- const feature = fixture()- feature.actions.acquireNativeModel('session-a', BINDING)- await feature.actions.loadNativeModels('session-a', BINDING)- const pending = deferred<void>()- feature.refreshProjections.mockReturnValueOnce(pending.promise)- const stale = feature.actions.selectNativeModel('session-a', BINDING, { provider: 'bridge/codex', model: 'gpt-5.4' })- await vi.waitFor(() => expect(feature.refreshProjections).toHaveBeenCalledOnce())- feature.dispose()- pending.resolve()- expect(await stale).toBeUndefined()- expect(nativeModel.$state.entries).toEqual({})- })-})diff --git a/packages/dsh-tauri-kernel/src/client/register/kernel-model.ts b/packages/dsh-tauri-kernel/src/client/register/kernel-model.tsdeleted file mode 100644index 4c7087a3..00000000--- a/packages/dsh-tauri-kernel/src/client/register/kernel-model.ts+++ /dev/null@@ -1,127 +0,0 @@-import type { ClientAdapter, ISessions, RegisterController, SessionId } from 'dsh-tauri/client'-import type { NativeModelActions, NativeModelScope } from '../types/kernel-model'-import { isEqual, noop } from 'dsh-tauri/client'-import { loadNativeModels, selectNativeModel } from '../service/kernel-model'-import { isNativeTurnOptions, nativeModelDirectory } from '../service/kernel-model.utils'-import { nativeModel } from '../store/modules/native-model'--export function registerNativeModels(controller: RegisterController, adapter: ClientAdapter): NativeModelActions {- const scopes = new Map<string, { scope: number, backend: string, nativeSessionId: string, references: number }>()- const canSelectNativeModel = (): boolean => !controller.isDisposed() && adapter.has('sessions.refreshProjections')- && adapter.has('sessions.list')- const scopeOf = (sessionId: string, binding: { backend: string, nativeSessionId: string, sessionId: string }): NativeModelScope | undefined => {- const lease = scopes.get(sessionId)- return canSelectNativeModel() && binding.sessionId === sessionId && lease?.backend === binding.backend- && lease.nativeSessionId === binding.nativeSessionId- ? { sessionId, scope: lease.scope, active: () => !controller.isDisposed() && scopes.get(sessionId) === lease && lease.references > 0 }- : undefined- }- controller.add(() => {- for (const [sessionId, lease] of scopes)- nativeModel.close(sessionId, lease.scope)- scopes.clear()- })- const actions: NativeModelActions = {- canSelectNativeModel,- createNativeModelDirectory(sessionId, binding, current) {- const initial = nativeModelDirectory(binding.backend, current, null)- return {- getSnapshot: () => {- const entry = nativeModel.$state.entries[sessionId]- return scopeOf(sessionId, binding) === undefined ? initial : entry?.directory ?? initial- },- subscribe(listener) {- if (!canSelectNativeModel() || binding.sessionId !== sessionId)- return noop- const release = actions.acquireNativeModel(sessionId, binding)- const state = adapter.service<ISessions>('sessions')?.list.getSnapshot()- const values = state?.projectionsBySession?.[sessionId as SessionId]?.values ?? state?.byId[sessionId as SessionId]?.projectionValues- const latest = isEqual(values?.bridgeKernel, binding) && isNativeTurnOptions(values?.bridgeModel) ? values.bridgeModel : current- actions.syncNativeModel(sessionId, binding, latest)- const unsubscribe = nativeModel.$subscribe(listener)- const scope = scopeOf(sessionId, binding)- queueMicrotask(() => {- const entry = nativeModel.$state.entries[sessionId]- if (scope?.active() && entry?.scope === scope.scope && entry.request === 0)- void loadNativeModels(scope)- })- let stopped = false- const dispose = () => {- if (stopped)- return- stopped = true- unsubscribe()- release()- }- const unhook = controller.add(dispose)- return () => {- dispose()- unhook()- }- },- }- },- acquireNativeModel(sessionId, binding) {- if (!canSelectNativeModel() || binding.sessionId !== sessionId)- return noop- let lease = scopes.get(sessionId)- if (lease === undefined || lease.backend !== binding.backend || lease.nativeSessionId !== binding.nativeSessionId) {- const current = { model: null, reasoningEffort: null }- lease = { scope: nativeModel.nextScope(), backend: binding.backend, nativeSessionId: binding.nativeSessionId, references: 0 }- scopes.set(sessionId, lease)- nativeModel.open({ ...lease, sessionId, backend: binding.backend, request: 0, catalog: null, current, directory: nativeModelDirectory(binding.backend, current, null) })- }- lease.references += 1- const owned = lease- let released = false- return () => {- if (released || scopes.get(sessionId) !== owned)- return- released = true- if (--owned.references === 0) {- queueMicrotask(() => {- if (scopes.get(sessionId) !== owned || owned.references !== 0)- return- scopes.delete(sessionId)- nativeModel.close(sessionId, owned.scope)- })- }- }- },- syncNativeModel(sessionId, binding, current) {- const scope = scopeOf(sessionId, binding)- const entry = nativeModel.$state.entries[sessionId]- if (scope === undefined || entry === undefined || isEqual(entry.current, current))- return- nativeModel.update(sessionId, scope.scope, { current, directory: nativeModelDirectory(entry.backend, current, entry.catalog, entry.directory) })- },- async loadNativeModels(sessionId, binding) {- const scope = scopeOf(sessionId, binding)- if (scope !== undefined)- await loadNativeModels(scope)- },- async selectNativeModel(sessionId, binding, selection) {- const scope = scopeOf(sessionId, binding)- if (scope === undefined)- return undefined- return selectNativeModel({- ...scope,- selection,- async refreshProjection(id) {- if (controller.isDisposed() || !scope.active())- throw new Error('Native model selection scope is unavailable')- await adapter.sessions.refreshProjections!(id)- if (controller.isDisposed() || !scope.active())- throw new Error('Native model selection scope is unavailable')- const sessions = adapter.service<ISessions>('sessions')- const state = sessions?.list.getSnapshot()- const values = state?.projectionsBySession?.[id as SessionId]?.values ?? state?.byId[id as SessionId]?.projectionValues- if (!isEqual(values?.bridgeKernel, binding) || !isNativeTurnOptions(values?.bridgeModel))- throw new Error('Native model selection projection is unavailable')- return values.bridgeModel- },- })- },- }- return actions-}diff --git a/packages/dsh-tauri-kernel/src/client/register/kernel.test.ts b/packages/dsh-tauri-kernel/src/client/register/kernel.test.tsdeleted file mode 100644index 7262324e..00000000--- a/packages/dsh-tauri-kernel/src/client/register/kernel.test.ts+++ /dev/null@@ -1,570 +0,0 @@-import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'-import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'-import type { SessionId, SessionListState } from 'dsh-tauri/client'-import type { ComponentType } from 'react'-import type { BackendDetection, KernelBinding } from '../../shared/types'-import type { KernelActions } from '../components/slot-contract'-import { SlotCore } from '@deepseek-ai/dsh-client-ui-slots'-import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { getBackends, postSessions } from '../apis'-import { backendFromIdentity, kernelFromList } from '../service/kernel-identity'-import { kernelStore } from '../store/modules/kernel-store'-import { kernel } from './kernel'--vi.hoisted(() => vi.stubGlobal('localStorage', undefined))-vi.mock('../apis', () => ({ getBackends: vi.fn(), postSessions: vi.fn(), getModels: vi.fn(), postModels: vi.fn() }))-vi.mock('dsh-tauri-ui/client', async () => ({ ...await import('../../../../dsh-tauri-ui/src/client/register/slot-decoration') }))-vi.mock('../components/hero-kernel', () => ({ HeroKernel: () => null }))-vi.mock('../components/model-kernel', () => ({ ModelKernel: () => null }))-vi.mock('../components/session-kernel', () => ({ SessionKernel: () => null }))-vi.mock('../components/session-kernel-hover', () => ({ SessionKernelHover: () => null }))--const BACKENDS: BackendDetection[] = [- { id: 'dsh', installed: true, auth: 'ok', version: null, drift: false, hint: null },- { id: 'codex', installed: true, auth: 'ok', version: '1.0', drift: false, hint: null },- { id: 'claude', installed: false, auth: 'unknown', version: null, drift: false, hint: null },-]-const BINDING: KernelBinding = { backend: 'codex', nativeSessionId: 'native-a', sessionId: 'new-session' }-const disposers: (() => void)[] = []--function deferred<T>() {- let resolve: (value: T) => void = () => {- throw new Error('uninitialized promise')- }- let reject: (reason: unknown) => void = () => {- throw new Error('uninitialized promise')- }- const promise = new Promise<T>((accept, decline) => {- resolve = accept- reject = decline- })- return { promise, resolve, reject }-}--function fixture(options: { hero?: boolean, sidebar?: boolean, hover?: boolean, model?: boolean, unknownModel?: boolean, refresh?: boolean, create?: boolean, open?: boolean } = {}) {- const core = new SlotCore()- const register = core.register.bind(core) as unknown as (registration: Record<string, unknown>, component: ComponentType<Record<string, unknown>>) => () => void- register({ name: 'root', children: {- ...(options.hero === false ? {} : { 'conversation.hero.agentPreset': { kind: 'single', scope: 'session-maybe' } }),- ...(options.sidebar === false ? {} : { 'sidebar.session.row.leading': { kind: 'list', scope: 'root' } }),- ...(options.hover === false ? {} : { 'sidebar.session.row.hover': { kind: 'list', scope: 'root' } }),- ...(options.model === true ? { 'conversation.input.model': { kind: 'single', scope: 'session' } } : {}),- } }, () => null)- if (options.hero !== false)- register({ name: 'conversation.hero.agentPreset', locale: 'settings.agentPreset' }, () => null)- function ModelSelect() {- return null- }- function UnknownModel() {- return null- }- if (options.model === true)- register({ name: 'conversation.input.model', locale: 'model', inject: () => ({}) }, options.unknownModel === true ? UnknownModel : ModelSelect)- let state: SessionListState = { ids: [], byId: {}, phase: 'ready', projectionsBySession: {} }- function publishProjection(sessionId: string, identity: unknown, phase: 'ready' | 'error' = 'ready', error: unknown = null): void {- state = {- ...state,- projectionsBySession: {- ...state.projectionsBySession,- [sessionId]: { values: identity === undefined ? {} : { bridgeKernel: identity }, state: phase, error },- },- } as SessionListState- }- const getSnapshot = vi.fn(() => state)- const openSession = vi.fn()- const startSession = vi.fn()- const officialCreate = vi.fn(async () => 'official-new')- const refreshProjections = vi.fn(async (sessionId: string) => {- const id = sessionId as SessionId- state = {- ...state,- projectionsBySession: { [id]: { values: { bridgeKernel: { ...BINDING, sessionId } }, state: 'ready', error: null } },- }- })- const sessions: Record<string, unknown> = {- ...(options.create === false ? {} : { create: officialCreate }),- list: { getSnapshot, subscribe: () => () => {} },- refresh: vi.fn(async () => {}),- ...(options.refresh === false ? {} : { refreshProjections }),- binding: vi.fn(),- retain: vi.fn(),- }- const uiWorkspace = { ...(options.open === false ? {} : { openSession }), startSession }- const navigation = new AbortController()- const beginNavigation = vi.fn(() => navigation.signal)- const slotDisposers: ReturnType<typeof vi.fn>[] = []- const slots = {- spec: core.spec.bind(core),- entries: core.entries.bind(core),- entriesOfSlot: core.entriesOfSlot.bind(core),- subscribe: core.subscribe.bind(core),- onEntryError: core.onEntryError.bind(core),- register: vi.fn(register),- inject: vi.fn((key: string, setup: () => (() => void) | Iterable<() => void>) => {- let cleanups: (() => void)[] = []- function clear(): void {- for (const dispose of cleanups.splice(0).reverse())- dispose()- }- function sync(): void {- clear()- if (core.specDynamic(key) !== undefined) {- const effect = setup()- cleanups = typeof effect === 'function' ? [effect] : [...effect]- }- }- const unsubscribe = core.subscribeDeclaration(key, sync)- sync()- const dispose = vi.fn(() => {- unsubscribe()- clear()- })- slotDisposers.push(dispose)- return dispose- }),- }- const ctx = {- sessions,- slots,- layout: { beginNavigation },- get(name: string): unknown {- return ({ sessions, slots, uiWorkspace, layout: this.layout } as Record<string, unknown>)[name]- },- }- const dispose = kernel.call({ ctx })- disposers.push(dispose)- function hero(): KernelActions {- const entry = core.entriesOfSlot('conversation.hero.agentPreset')[0]- const read = entry?.inject as (() => KernelActions) | undefined- if (read === undefined)- throw new Error('hero kernel actions unavailable')- return read()- }- function sidebar(key = 'sidebar.session.row.leading'): Pick<KernelActions, 'ensureProjection'> {- const entry = core.entriesOfSlot(key)[0]- const read = entry?.inject as (() => Pick<KernelActions, 'ensureProjection'>) | undefined- if (read === undefined)- throw new Error('sidebar kernel actions unavailable')- return read()- }- return { core, slots, ctx, sessions, uiWorkspace, navigation, beginNavigation, officialCreate, openSession, refreshProjections, publishProjection, getSnapshot, slotDisposers, hero, sidebar, dispose }-}--beforeEach(() => {- kernelStore.$patch({ phase: 'idle', backends: [], error: null })- vi.mocked(getBackends).mockReset().mockResolvedValue(BACKENDS)- vi.mocked(postSessions).mockReset().mockResolvedValue({ sessionId: 'new-session' })- vi.spyOn(console, 'warn').mockImplementation(() => {})-})--afterEach(() => {- for (const dispose of disposers.splice(0))- dispose()- kernelStore.$patch({ phase: 'idle', backends: [], error: null })- vi.restoreAllMocks()- vi.useRealTimers()- vi.unstubAllGlobals()- vi.stubGlobal('localStorage', undefined)-})--afterAll(() => vi.unstubAllGlobals())--describe('kernel registration and lifecycle', () => {- it('decorates the terminal official hero and adds distinct ordered leading and hover list entries without activating sessions', async () => {- const feature = fixture()- await vi.waitFor(() => expect(kernelStore.$state.phase).toBe('ready'))- expect(feature.slots.register.mock.calls.map(([entry]) => ({ name: entry.name, id: entry.id, order: entry.order }))).toEqual([- { name: 'conversation.hero.agentPreset', id: undefined, order: undefined },- { name: 'sidebar.session.row.leading', id: 'dsh-tauri-kernel:kernel', order: -10 },- { name: 'sidebar.session.row.hover', id: 'dsh-tauri-kernel:kernel', order: -10 },- ])- expect(feature.openSession).not.toHaveBeenCalled()- expect(feature.sessions.binding).not.toHaveBeenCalled()- expect(feature.sessions.retain).not.toHaveBeenCalled()- expect(feature.refreshProjections).not.toHaveBeenCalled()- expect(Object.keys(feature.uiWorkspace)).toEqual(['openSession', 'startSession'])- feature.dispose()- expect(feature.core.entries('conversation.hero.agentPreset')).toHaveLength(1)- expect(feature.core.entries('sidebar.session.row.leading')).toEqual([])- expect(feature.core.entries('sidebar.session.row.hover')).toEqual([])- for (const dispose of feature.slotDisposers)- expect(dispose).toHaveBeenCalledOnce()- })-- it('wraps the verified official model seat and restores it on plugin disposal', async () => {- const feature = fixture({ model: true })- await Promise.resolve()- const entry = feature.core.entriesOfSlot('conversation.input.model')[0]- expect(entry?.registrant).toBe('dsh-tauri-kernel')- expect(entry?.options.priority).toBe(-1)- expect(entry?.locale).toBe('model')- expect(feature.core.entries('conversation.input.model')).toHaveLength(2)- feature.dispose()- await Promise.resolve()- expect(feature.core.entries('conversation.input.model')).toHaveLength(1)- expect((feature.core.entriesOfSlot('conversation.input.model')[0]?.component as ComponentType)?.name).toBe('ModelSelect')- expect(feature.openSession).not.toHaveBeenCalled()- })-- it('an unknown model renderer stays unchanged without claiming disabled support', async () => {- const feature = fixture({ model: true, unknownModel: true })- await Promise.resolve()- expect(feature.core.entries('conversation.input.model')).toHaveLength(1)- expect((feature.core.entriesOfSlot('conversation.input.model')[0]?.component as ComponentType)?.name).toBe('UnknownModel')- expect(console.warn).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-kernel] slot decoration unavailable; the official renderer capability is unverified')- expect(feature.openSession).not.toHaveBeenCalled()- })-- it('missing public slot declarations do not invent a slot or alter the official navigator', async () => {- const feature = fixture({ hero: false, sidebar: false, hover: false })- await vi.waitFor(() => expect(kernelStore.$state.phase).toBe('ready'))- expect(feature.slots.register).not.toHaveBeenCalled()- expect(feature.core.snapshot().map(item => item.name)).toEqual(['root'])- expect(Object.keys(feature.uiWorkspace)).toEqual(['openSession', 'startSession'])- expect(postSessions).not.toHaveBeenCalled()- expect(feature.officialCreate).not.toHaveBeenCalled()- })-- it('missing official projection capability renders disabled creation rather than inventing a runtime method', async () => {- const feature = fixture({ refresh: false })- await vi.waitFor(() => expect(kernelStore.$state.phase).toBe('ready'))- expect(feature.hero().canCreate()).toBe(false)- await expect(feature.hero().createSession('codex', {})).rejects.toThrow('capabilities are unavailable')- expect(postSessions).not.toHaveBeenCalled()- })-- it('explicit native selection opens a fresh verified session through the official navigator without remembering the choice', async () => {- const feature = fixture()- await vi.waitFor(() => expect(kernelStore.$state.phase).toBe('ready'))- await feature.hero().createSession('codex', { workspaceId: 'workspace-a' }, 'coding')- expect(postSessions).toHaveBeenCalledWith({ backend: 'codex', workspaceId: 'workspace-a', agentPreset: 'coding' })- expect(feature.beginNavigation).toHaveBeenCalledOnce()- expect(feature.openSession).toHaveBeenCalledWith('new-session')- expect(feature.officialCreate).not.toHaveBeenCalled()- expect(feature.uiWorkspace.startSession).not.toHaveBeenCalled()- expect(kernelStore.$state).not.toHaveProperty('selected')- })-- it('explicit DeepSeek selection creates fresh rather than rebinding or reusing the current native session', async () => {- const feature = fixture()- await vi.waitFor(() => expect(kernelStore.$state.phase).toBe('ready'))- await feature.hero().createSession('dsh', { cwd: '/ungrouped' })- expect(feature.officialCreate).toHaveBeenCalledWith({ cwd: '/ungrouped' })- expect(postSessions).not.toHaveBeenCalled()- expect(feature.openSession).toHaveBeenCalledWith('official-new')- })-- it('navigation cancellation leaves a completed creation unopened', async () => {- const feature = fixture()- await vi.waitFor(() => expect(kernelStore.$state.phase).toBe('ready'))- const pending = deferred<{ sessionId: string }>()- vi.mocked(postSessions).mockReturnValue(pending.promise)- const task = feature.hero().createSession('codex', {})- feature.navigation.abort()- pending.resolve({ sessionId: 'new-session' })- await task- expect(feature.openSession).not.toHaveBeenCalled()- })-- it('plugin disposal during an HTTP create prevents refresh and official opening', async () => {- const feature = fixture()- await vi.waitFor(() => expect(kernelStore.$state.phase).toBe('ready'))- const pending = deferred<{ sessionId: string }>()- vi.mocked(postSessions).mockReturnValue(pending.promise)- const task = feature.hero().createSession('codex', {})- feature.dispose()- pending.resolve({ sessionId: 'new-session' })- await expect(task).rejects.toThrow('creation was cancelled')- expect(feature.sessions.refresh).not.toHaveBeenCalled()- expect(feature.refreshProjections).not.toHaveBeenCalled()- expect(feature.openSession).not.toHaveBeenCalled()- })-- it('recovers when the startup route is registered after two 404 responses', async () => {- vi.useFakeTimers()- vi.mocked(getBackends)- .mockRejectedValueOnce(Object.assign(new Error('请求失败 (404): route pending'), { status: 404 }))- .mockRejectedValueOnce(Object.assign(new Error('请求失败 (404): still pending'), { status: 404 }))- .mockResolvedValueOnce(BACKENDS)- fixture()- await vi.advanceTimersByTimeAsync(0)- expect(kernelStore.$state).toMatchObject({ phase: 'loading', error: null })- expect(getBackends).toHaveBeenCalledTimes(1)- await vi.advanceTimersByTimeAsync(250)- expect(getBackends).toHaveBeenCalledTimes(2)- expect(kernelStore.$state.phase).toBe('loading')- await vi.advanceTimersByTimeAsync(500)- expect(getBackends).toHaveBeenCalledTimes(3)- expect(kernelStore.$state).toMatchObject({ phase: 'ready', backends: BACKENDS, error: null })- expect(console.warn).not.toHaveBeenCalled()- const signals = vi.mocked(getBackends).mock.calls.map(([options]) => options?.signal)- expect(signals.every(signal => signal instanceof AbortSignal && !signal.aborted)).toBe(true)- expect(new Set(signals).size).toBe(1)- })-- it.each([401, 403, 500, undefined, '404'])('never retries a startup failure with status %s', async (status) => {- vi.useFakeTimers()- const reason = Object.assign(new Error('请求失败 (404): not a missing route'), { status })- vi.mocked(getBackends).mockRejectedValue(reason)- fixture()- await vi.advanceTimersByTimeAsync(10_000)- expect(getBackends).toHaveBeenCalledTimes(1)- expect(kernelStore.$state).toMatchObject({ phase: 'error', error: reason.message })- expect(console.warn).toHaveBeenCalledWith('[dsh-tauri-kernel] kernel detection failed', reason)- expect(vi.getTimerCount()).toBe(0)- })-- it('bounds permanent startup 404 retries and preserves the final real error', async () => {- vi.useFakeTimers()- const reasons = Array.from({ length: 5 }, (_, index) => Object.assign(new Error(`请求失败 (404): route missing ${index}`), { status: 404 }))- for (const reason of reasons)- vi.mocked(getBackends).mockRejectedValueOnce(reason)- fixture()- await vi.advanceTimersByTimeAsync(10_000)- expect(getBackends).toHaveBeenCalledTimes(5)- expect(kernelStore.$state).toMatchObject({ phase: 'error', error: reasons[4]!.message })- expect(console.warn).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-kernel] kernel detection failed', reasons[4])- expect(vi.getTimerCount()).toBe(0)- })-- it('reports a non-404 encountered after a retry without hiding it behind the startup error', async () => {- vi.useFakeTimers()- const reason = Object.assign(new Error('请求失败 (403): origin blocked'), { status: 403 })- vi.mocked(getBackends)- .mockRejectedValueOnce(Object.assign(new Error('请求失败 (404): route pending'), { status: 404 }))- .mockRejectedValueOnce(reason)- fixture()- await vi.advanceTimersByTimeAsync(10_000)- expect(getBackends).toHaveBeenCalledTimes(2)- expect(kernelStore.$state).toMatchObject({ phase: 'error', error: reason.message })- expect(console.warn).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-kernel] kernel detection failed', reason)- })-- it('manual refresh uses one attempt rather than silently starting another startup retry window', async () => {- vi.useFakeTimers()- const feature = fixture()- await vi.advanceTimersByTimeAsync(0)- const reason = Object.assign(new Error('请求失败 (404): route removed'), { status: 404 })- vi.mocked(getBackends).mockRejectedValueOnce(reason)- const refresh = feature.hero().refreshBackends()- await vi.advanceTimersByTimeAsync(10_000)- await refresh- expect(getBackends).toHaveBeenCalledTimes(2)- expect(kernelStore.$state).toMatchObject({ phase: 'error', error: reason.message })- expect(vi.getTimerCount()).toBe(0)- })-- it('disposal cancels a pending startup retry and aborts its request ownership', async () => {- vi.useFakeTimers()- vi.mocked(getBackends).mockRejectedValueOnce(Object.assign(new Error('请求失败 (404): route pending'), { status: 404 }))- const feature = fixture()- await vi.advanceTimersByTimeAsync(0)- const signal = vi.mocked(getBackends).mock.calls[0]?.[0]?.signal- expect(signal).toBeInstanceOf(AbortSignal)- feature.dispose()- expect(signal?.aborted).toBe(true)- kernelStore.$patch({ phase: 'idle', backends: [], error: null })- await vi.advanceTimersByTimeAsync(10_000)- expect(getBackends).toHaveBeenCalledTimes(1)- expect(kernelStore.$state).toMatchObject({ phase: 'idle', backends: [], error: null })- expect(console.warn).not.toHaveBeenCalled()- expect(vi.getTimerCount()).toBe(0)- })-- it('manual refresh aborts and cancels an older startup retry without delaying the new roster', async () => {- vi.useFakeTimers()- vi.mocked(getBackends)- .mockRejectedValueOnce(Object.assign(new Error('请求失败 (404): route pending'), { status: 404 }))- .mockResolvedValueOnce([BACKENDS[0]!])- const feature = fixture()- await vi.advanceTimersByTimeAsync(0)- const signal = vi.mocked(getBackends).mock.calls[0]?.[0]?.signal- const pending = feature.hero().refreshBackends()- await vi.advanceTimersByTimeAsync(0)- await pending- expect(signal?.aborted).toBe(true)- await vi.advanceTimersByTimeAsync(10_000)- expect(getBackends).toHaveBeenCalledTimes(2)- expect(kernelStore.$state).toMatchObject({ phase: 'ready', backends: [BACKENDS[0]!], error: null })- expect(console.warn).not.toHaveBeenCalled()- expect(vi.getTimerCount()).toBe(0)- })-- it.each(['dispose', 'supersede'] as const)('a late startup 404 after %s cannot warn, retry or change the current store', async (action) => {- vi.useFakeTimers()- const pending = deferred<BackendDetection[]>()- vi.mocked(getBackends).mockReturnValueOnce(pending.promise).mockResolvedValueOnce([BACKENDS[0]!])- const feature = fixture()- const signal = vi.mocked(getBackends).mock.calls[0]?.[0]?.signal- expect(signal).toBeInstanceOf(AbortSignal)- if (action === 'dispose') {- feature.dispose()- kernelStore.$patch({ phase: 'idle', backends: [], error: null })- }- else {- await feature.hero().refreshBackends()- }- expect(signal?.aborted).toBe(true)- pending.reject(Object.assign(new Error('请求失败 (404): stale route response'), { status: 404 }))- await vi.advanceTimersByTimeAsync(10_000)- expect(getBackends).toHaveBeenCalledTimes(action === 'dispose' ? 1 : 2)- expect(kernelStore.$state).toMatchObject(action === 'dispose'- ? { phase: 'idle', backends: [], error: null }- : { phase: 'ready', backends: [BACKENDS[0]!], error: null })- expect(console.warn).not.toHaveBeenCalled()- expect(vi.getTimerCount()).toBe(0)- })-- it('a detection response arriving after disposal cannot update the shared store', async () => {- const pending = deferred<BackendDetection[]>()- vi.mocked(getBackends).mockReturnValue(pending.promise)- const feature = fixture()- feature.dispose()- kernelStore.$patch({ phase: 'idle', backends: [], error: null })- pending.resolve(BACKENDS)- await pending.promise- await Promise.resolve()- expect(kernelStore.$state.phase).toBe('idle')- expect(kernelStore.$state.backends).toEqual([])- })-- it('a superseded detection response cannot overwrite the newer roster', async () => {- const pending = deferred<BackendDetection[]>()- vi.mocked(getBackends).mockReturnValueOnce(pending.promise).mockResolvedValueOnce([BACKENDS[0]!])- const feature = fixture()- await feature.hero().refreshBackends()- pending.resolve(BACKENDS)- await pending.promise- await Promise.resolve()- expect(kernelStore.$state.backends).toEqual([{ id: 'dsh', installed: true, auth: 'ok', version: null, drift: false, hint: null }])- expect(kernelStore.$state.phase).toBe('ready')- })-- it('leading and hover identities invoke only the nonactivating official projection refresh', async () => {- const feature = fixture()- await feature.sidebar().ensureProjection('archived-session')- await feature.sidebar('sidebar.session.row.hover').ensureProjection('blank-session')- expect(feature.refreshProjections.mock.calls).toEqual([['archived-session'], ['blank-session']])- expect(feature.sessions.binding).not.toHaveBeenCalled()- expect(feature.sessions.retain).not.toHaveBeenCalled()- expect(feature.openSession).not.toHaveBeenCalled()- expect(postSessions).not.toHaveBeenCalled()- })-- it('a resolved projection read without a snapshot stays silent and never assumes a DeepSeek identity', async () => {- const feature = fixture()- feature.refreshProjections.mockImplementation(async () => {})- await feature.sidebar().ensureProjection('archived-session')- await feature.sidebar().ensureProjection('archived-session')- expect(console.warn).not.toHaveBeenCalled()- expect(feature.refreshProjections).toHaveBeenCalledTimes(2)- expect(backendFromIdentity(kernelFromList(feature.getSnapshot(), 'archived-session' as SessionId))).toBeUndefined()- expect(feature.openSession).not.toHaveBeenCalled()- })-- it.each([- ['missing', undefined, undefined],- ['DeepSeek', null, 'dsh'],- ['Codex', { ...BINDING, sessionId: 'session-a' }, 'codex'],- ['Claude', { ...BINDING, backend: 'claude', sessionId: 'session-a' }, 'claude'],- ] as const)('a successful %s projection stays silent and preserves its identity', async (_, identity, backend) => {- const feature = fixture()- feature.refreshProjections.mockImplementation(async id => feature.publishProjection(id, identity))- await feature.sidebar().ensureProjection('session-a')- await feature.sidebar('sidebar.session.row.hover').ensureProjection('session-a')- await feature.hero().ensureProjection('session-a')- expect(feature.refreshProjections.mock.calls).toEqual([['session-a'], ['session-a'], ['session-a']])- const projected = kernelFromList(feature.getSnapshot(), 'session-a' as SessionId)- expect(projected).toEqual(identity)- expect(backendFromIdentity(projected)).toBe(backend)- expect(console.warn).not.toHaveBeenCalled()- expect(feature.sessions.binding).not.toHaveBeenCalled()- expect(feature.sessions.retain).not.toHaveBeenCalled()- expect(feature.openSession).not.toHaveBeenCalled()- expect(postSessions).not.toHaveBeenCalled()- expect(feature.officialCreate).not.toHaveBeenCalled()- })-- it('a malformed binding warns once per session without an undefined argument', async () => {- const feature = fixture()- feature.refreshProjections.mockImplementation(async id => feature.publishProjection(id, { backend: 'codex' }))- await feature.sidebar().ensureProjection('session-a')- await feature.hero().ensureProjection('session-a')- await feature.sidebar().ensureProjection('session-b')- expect(vi.mocked(console.warn).mock.calls).toEqual([- ['[dsh-tauri-kernel] session kernel identity unavailable: session-a'],- ['[dsh-tauri-kernel] session kernel identity unavailable: session-b'],- ])- expect(backendFromIdentity(kernelFromList(feature.getSnapshot(), 'session-a' as SessionId))).toBeUndefined()- })-- it.each([undefined, null, BINDING])('a resolved error snapshot reports its cause even with cached identity %j', async (identity) => {- const feature = fixture()- const reason = Object.assign(new Error('projection request failed'), { code: 'session/not-found' })- feature.refreshProjections.mockImplementation(async id => feature.publishProjection(id, identity, 'error', reason))- await feature.sidebar().ensureProjection('session-a')- await feature.hero().ensureProjection('session-a')- expect(console.warn).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-kernel] session projection read failed: session-a', reason)- expect(feature.openSession).not.toHaveBeenCalled()- })-- it('a rejected projection refresh reports its original error once', async () => {- const feature = fixture()- const reason = new Error('projection read rejected')- feature.refreshProjections.mockRejectedValue(reason)- await feature.sidebar().ensureProjection('session-a')- await feature.hero().ensureProjection('session-a')- expect(console.warn).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-kernel] session projection read failed: session-a', reason)- })-- it('a failed projection after a silent missing identity still warns', async () => {- const feature = fixture()- feature.refreshProjections.mockImplementation(async id => feature.publishProjection(id, undefined))- await feature.sidebar().ensureProjection('session-a')- expect(console.warn).not.toHaveBeenCalled()- const reason = new Error('later projection failure')- feature.refreshProjections.mockRejectedValue(reason)- await feature.sidebar().ensureProjection('session-a')- expect(console.warn).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-kernel] session projection read failed: session-a', reason)- })-- it.each(['resolve', 'reject'] as const)('a late projection %s after disposal cannot inspect or warn', async (outcome) => {- const feature = fixture()- const pending = deferred<void>()- feature.refreshProjections.mockReturnValue(pending.promise)- const task = feature.sidebar().ensureProjection('session-a')- expect(feature.refreshProjections).toHaveBeenCalledExactlyOnceWith('session-a')- feature.dispose()- feature.getSnapshot.mockClear()- if (outcome === 'resolve')- pending.resolve(undefined)- else- pending.reject(new Error('late failure'))- await task- expect(feature.getSnapshot).not.toHaveBeenCalled()- expect(console.warn).not.toHaveBeenCalled()- })-- it('disposed UI callbacks cannot start detection or projection work', async () => {- const feature = fixture()- await vi.waitFor(() => expect(kernelStore.$state.phase).toBe('ready'))- const actions = feature.hero()- feature.dispose()- vi.mocked(getBackends).mockClear()- kernelStore.$patch({ phase: 'idle', backends: [] })- await actions.refreshBackends()- await actions.ensureProjection('archived-session')- expect(getBackends).not.toHaveBeenCalled()- expect(feature.refreshProjections).not.toHaveBeenCalled()- expect(kernelStore.$state.phase).toBe('idle')- })-- it('an unavailable projection reader warns once without treating the session as DeepSeek', async () => {- const feature = fixture({ refresh: false })- await feature.sidebar().ensureProjection('archived-session')- await feature.sidebar().ensureProjection('archived-session')- expect(console.warn).toHaveBeenCalledTimes(1)- expect(console.warn).toHaveBeenCalledWith('[dsh-tauri-kernel] sessions.refreshProjections unavailable; session kernel identity is unknown')- expect(feature.openSession).not.toHaveBeenCalled()- })-})diff --git a/packages/dsh-tauri-kernel/src/client/register/kernel.ts b/packages/dsh-tauri-kernel/src/client/register/kernel.tsdeleted file mode 100644index 86f440a9..00000000--- a/packages/dsh-tauri-kernel/src/client/register/kernel.ts+++ /dev/null@@ -1,187 +0,0 @@-import type { AdapterSessionCreateOptions, ClientContext, ISessions, SessionId, SlotRegistry } from 'dsh-tauri/client'-import type { BackendId } from '../../shared/types'-import { registerSlotDecoration } from 'dsh-tauri-ui/client'-import { defineRegister } from 'dsh-tauri/client'-import { PLUGIN_ID } from '../../shared/constants'-import { getBackends } from '../apis'-import { HeroKernel } from '../components/hero-kernel'-import { ModelKernel } from '../components/model-kernel'-import { SessionKernel } from '../components/session-kernel'-import { SessionKernelHover } from '../components/session-kernel-hover'-import { HERO_AGENT_PRESET_SLOT, MODEL_KERNEL_SLOT, SIDEBAR_KERNEL_HOVER_SLOT, SIDEBAR_KERNEL_SLOT } from '../constants'-import { backendFromIdentity, kernelFromList } from '../service/kernel-identity'-import { canLockModelEntry } from '../service/kernel-model'-import { createKernelSession } from '../service/kernel-session'-import { kernelStore } from '../store/modules/kernel-store'-import { registerNativeModels } from './kernel-model'--export const kernel = defineRegister<ClientContext>((controller, ctx, adapter) => {- let detection = 0- let cancelDetection: (() => void) | undefined- const warned = new Set<string>()- const active = (): boolean => !controller.isDisposed()-- function warn(key: string, error?: unknown): void {- if (controller.isDisposed() || warned.has(key))- return- warned.add(key)- if (error === undefined)- console.warn(`[${PLUGIN_ID}] ${key}`)- else- console.warn(`[${PLUGIN_ID}] ${key}`, error)- }-- async function refreshBackends(startup = false): Promise<void> {- if (!active())- return- cancelDetection?.()- const request = ++detection- const abort = new AbortController()- const cancel = () => abort.abort()- cancelDetection = cancel- const unhook = controller.add(cancel)- const current = (): boolean => active() && request === detection && !abort.signal.aborted- kernelStore.$patch({ phase: 'loading', error: null })- try {- for (let attempt = 0; current(); attempt++) {- try {- const backends = await getBackends({ signal: abort.signal })- if (current())- kernelStore.$patch({ backends, phase: 'ready', error: null })- return- }- catch (reason) {- if (!current())- return- if (!startup || attempt >= 4 || typeof reason !== 'object' || reason === null || !('status' in reason) || reason.status !== 404)- throw reason- await new Promise<void>((resolve) => {- let stop: (() => void) | undefined- const finish = () => {- stop?.()- abort.signal.removeEventListener('abort', finish)- resolve()- }- stop = controller.timeout(finish, 250 * 2 ** attempt)- abort.signal.addEventListener('abort', finish, { once: true })- })- }- }- }- catch (reason) {- if (current()) {- kernelStore.$patch({ phase: 'error', error: reason instanceof Error ? reason.message : String(reason) })- warn('kernel detection failed', reason)- }- }- finally {- unhook()- if (cancelDetection === cancel)- cancelDetection = undefined- }- }-- async function ensureProjection(sessionId: string): Promise<void> {- if (!active())- return- const refresh = adapter.sessions.refreshProjections- if (refresh === undefined) {- warn('sessions.refreshProjections unavailable; session kernel identity is unknown')- return- }- try {- await refresh(sessionId)- if (!active())- return- const sessions = adapter.service<ISessions>('sessions')- const state = sessions?.list.getSnapshot()- if (state === undefined)- return- const projection = state.projectionsBySession?.[sessionId as SessionId]- if (projection?.state === 'error') {- warn(`session projection read failed: ${sessionId}`, projection.error)- return- }- const identity = kernelFromList(state, sessionId as SessionId)- if (identity !== undefined && backendFromIdentity(identity) === undefined)- warn(`session kernel identity unavailable: ${sessionId}`)- }- catch (reason) {- warn(`session projection read failed: ${sessionId}`, reason)- }- }-- const canCreate = (): boolean => active()- && adapter.has('sessions.create')- && adapter.has('sessions.refresh')- && adapter.has('sessions.refreshProjections')- && adapter.has('navigation.openSession')- && typeof ctx.layout?.beginNavigation === 'function'-- async function createSession(backend: BackendId, options: AdapterSessionCreateOptions, agentPreset?: string): Promise<void> {- if (!canCreate())- throw new Error('Official kernel creation capabilities are unavailable')- const navigation = ctx.layout.beginNavigation()- const sessionId = await createKernelSession(adapter, backend, options, active, agentPreset)- if (!active() || navigation.aborted)- return- const opened = adapter.openSession(sessionId)- if (opened.status !== 'opened')- throw new Error(opened.reason)- }-- const nativeModels = registerNativeModels(controller, adapter)- const slots = adapter.service<SlotRegistry>('slots')- controller.add(registerSlotDecoration(slots, {- slot: HERO_AGENT_PRESET_SLOT,- scope: 'session-maybe',- registrant: PLUGIN_ID,- component: HeroKernel,- inject: () => ({ canCreate, createSession, ensureProjection, refreshBackends }),- warn,- }))- controller.add(registerSlotDecoration(slots, {- slot: MODEL_KERNEL_SLOT,- scope: 'session',- registrant: PLUGIN_ID,- mode: 'wrap',- component: ModelKernel,- accept: canLockModelEntry,- inject: () => ({ ensureProjection, ...nativeModels }),- warn,- }))- if (typeof slots?.inject !== 'function' || typeof slots.register !== 'function' || typeof slots.spec !== 'function') {- warn('sidebar kernel identity unavailable; official slot registration APIs are missing')- }- else {- controller.add(slots.inject(SIDEBAR_KERNEL_SLOT, () => {- const spec = slots.spec(SIDEBAR_KERNEL_SLOT)- if (spec?.kind !== 'list' || spec.scope !== 'root') {- warn('sidebar leading kernel identity unavailable; the official slot contract differs')- return () => {}- }- return slots.register({- name: SIDEBAR_KERNEL_SLOT,- id: `${PLUGIN_ID}:kernel`,- registrant: PLUGIN_ID,- order: -10,- inject: () => ({ ensureProjection }),- }, SessionKernel)- }))- controller.add(slots.inject(SIDEBAR_KERNEL_HOVER_SLOT, () => {- const spec = slots.spec(SIDEBAR_KERNEL_HOVER_SLOT)- if (spec?.kind !== 'list' || spec.scope !== 'root') {- warn('sidebar hover kernel identity unavailable; the official slot contract differs')- return () => {}- }- return slots.register({- name: SIDEBAR_KERNEL_HOVER_SLOT,- id: `${PLUGIN_ID}:kernel`,- registrant: PLUGIN_ID,- order: -10,- inject: () => ({ ensureProjection }),- }, SessionKernelHover)- }))- }- void refreshBackends(true)-})diff --git a/packages/dsh-tauri-kernel/src/client/service/kernel-identity.test.ts b/packages/dsh-tauri-kernel/src/client/service/kernel-identity.test.tsdeleted file mode 100644index c1a5823f..00000000--- a/packages/dsh-tauri-kernel/src/client/service/kernel-identity.test.ts+++ /dev/null@@ -1,63 +0,0 @@-import type { SessionId, SessionListState } from 'dsh-tauri/client'-import type { BackendDetection } from '../../shared/types'-import { describe, expect, it } from 'vitest'-import { backendFromIdentity, isBackendAvailable, isForkedIdentity, kernelFromList } from './kernel-identity'--const SESSION = 'session-a' as SessionId-const binding = { backend: 'codex' as const, nativeSessionId: 'native-a', sessionId: 'session-a' }--function list(summary: unknown, projected?: unknown): SessionListState {- return {- ids: [SESSION],- byId: { [SESSION]: { projectionValues: summary } },- projectionsBySession: projected === undefined ? {} : { [SESSION]: { values: projected } },- phase: 'ready',- } as SessionListState-}--function detection(patch: Partial<BackendDetection> = {}): BackendDetection {- return { id: 'codex', installed: true, auth: 'ok', version: '1.0', drift: false, hint: null, ...patch }-}--describe('session kernel identity', () => {- it('missing projection is unknown rather than a DeepSeek identity', () => {- expect(backendFromIdentity(undefined)).toBeUndefined()- expect(backendFromIdentity(null)).toBe('dsh')- })-- it('external identity requires a supported backend and nonempty native and owner ids', () => {- expect(backendFromIdentity(binding)).toBe('codex')- expect(backendFromIdentity({ backend: 'claude', nativeSessionId: 'native-b', sessionId: 'session-a' })).toBe('claude')- for (const value of [false, 'codex', {}, { ...binding, nativeSessionId: '' }, { ...binding, nativeSessionId: null }, { ...binding, sessionId: ' ' }, { ...binding, backend: 'gpt' }])- expect(backendFromIdentity(value)).toBeUndefined()- })-- it('list identity uses sequenced shared projection before a cached summary', () => {- expect(kernelFromList(list({ bridgeKernel: binding }, { bridgeKernel: null }), SESSION)).toBeNull()- expect(kernelFromList(list({ bridgeKernel: null }, { bridgeKernel: binding }), SESSION)).toEqual({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- })-- it('list identity retains cached whole values only when no shared key has arrived', () => {- expect(kernelFromList(list({ bridgeKernel: binding }, {}), SESSION)).toEqual({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- expect(kernelFromList(list({}), SESSION)).toBeUndefined()- })-- it('inherited identity reports a fork without changing the displayed backend', () => {- expect(isForkedIdentity(binding, 'session-other')).toBe(true)- expect(isForkedIdentity(binding, 'session-a')).toBe(false)- expect(isForkedIdentity(null, 'session-other')).toBe(false)- expect(isForkedIdentity(undefined, 'session-other')).toBe(false)- expect(backendFromIdentity(binding)).toBe('codex')- })-- it('uninstalled, incompatible, and signed-out native kernels are disabled', () => {- expect(isBackendAvailable(undefined)).toBe(false)- expect(isBackendAvailable(detection({ installed: false }))).toBe(false)- expect(isBackendAvailable(detection({ bridgeReady: false }))).toBe(false)- expect(isBackendAvailable(detection({ bridgeReady: true }))).toBe(true)- expect(isBackendAvailable(detection({ drift: true }))).toBe(false)- expect(isBackendAvailable(detection({ auth: 'missing' }))).toBe(false)- expect(isBackendAvailable(detection({ auth: 'unknown' }))).toBe(true)- expect(isBackendAvailable(detection())).toBe(true)- })-})diff --git a/packages/dsh-tauri-kernel/src/client/service/kernel-identity.ts b/packages/dsh-tauri-kernel/src/client/service/kernel-identity.tsdeleted file mode 100644index 5c8ecd84..00000000--- a/packages/dsh-tauri-kernel/src/client/service/kernel-identity.ts+++ /dev/null@@ -1,31 +0,0 @@-import type { SessionId, SessionListState } from 'dsh-tauri/client'-import type { BackendDetection, BackendId, KernelBinding } from '../../shared/types'--export function backendFromIdentity(value: unknown): BackendId | undefined {- if (value === null)- return 'dsh'- if (typeof value !== 'object')- return undefined- const binding = value as Partial<KernelBinding>- return (binding.backend === 'codex' || binding.backend === 'claude')- && typeof binding.nativeSessionId === 'string' && binding.nativeSessionId.trim() !== ''- && typeof binding.sessionId === 'string' && binding.sessionId.trim() !== ''- ? binding.backend- : undefined-}--export function kernelFromList(state: SessionListState, sessionId: SessionId): KernelBinding | null | undefined {- const projected = state.projectionsBySession?.[sessionId]?.values- const summary = state.byId[sessionId]?.projectionValues- return projected?.bridgeKernel !== undefined ? projected.bridgeKernel : summary?.bridgeKernel-}--export function isBackendAvailable(backend: BackendDetection | undefined): boolean {- return backend !== undefined && backend.installed && backend.bridgeReady !== false && !backend.drift && backend.auth !== 'missing'-}--export function isForkedIdentity(value: unknown, sessionId: string | undefined): boolean {- if (value === null || typeof value !== 'object' || backendFromIdentity(value) === undefined)- return false- return (value as KernelBinding).sessionId !== sessionId-}diff --git a/packages/dsh-tauri-kernel/src/client/service/kernel-model.test.ts b/packages/dsh-tauri-kernel/src/client/service/kernel-model.test.tsdeleted file mode 100644index 0b26fb1a..00000000--- a/packages/dsh-tauri-kernel/src/client/service/kernel-model.test.ts+++ /dev/null@@ -1,237 +0,0 @@-import type { StoredEntry } from 'dsh-tauri/client'-import type { NativeModelDirectory } from '../../shared/native-model'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { getModels, postModels } from '../apis'-import { nativeModel } from '../store/modules/native-model'-import { canLockModelEntry, hasModelLockFace, loadNativeModels, selectNativeModel } from './kernel-model'-import { nativeModelDirectory } from './kernel-model.utils'--vi.mock('../apis', () => ({ getModels: vi.fn(), postModels: vi.fn() }))--const CATALOG: NativeModelDirectory = {- backend: 'codex',- defaultModel: 'gpt-5.4',- current: { model: null, reasoningEffort: null },- models: [{ id: 'gpt-5.4', name: 'GPT-5.4', reasoning: { efforts: [{ id: 'medium', name: 'Medium' }, { id: 'high', name: 'High' }], defaultEffort: 'medium' } }],-}--function deferred<T>() {- let resolve: (value: T) => void = () => {- throw new Error('uninitialized promise')- }- const promise = new Promise<T>((accept) => {- resolve = accept- })- return { promise, resolve }-}--function open(sessionId = 'session-a', scope = 1, catalog: NativeModelDirectory | null = CATALOG) {- const current = { model: null, reasoningEffort: null }- nativeModel.open({ sessionId, scope, backend: 'codex', nativeSessionId: 'native-a', request: 0, catalog, current, directory: nativeModelDirectory('codex', current, catalog) })- return { sessionId, scope, active: () => true }-}--function entry(component = function ModelSelect() {}): StoredEntry {- return { component, options: {}, locale: 'model', inject: () => ({}) }-}--function ThirdPartyModel() {}--function readIdentity() {}--function props(): Record<string, unknown> {- return {- locked: false,- available: true,- directory: { subscribe: () => () => {}, getSnapshot: () => ({}) },- load: () => {},- select: async () => {},- useProjection: readIdentity,- }-}--beforeEach(() => {- nativeModel.$patch({ generation: 0, entries: {} })- vi.mocked(getModels).mockReset().mockResolvedValue(CATALOG)- vi.mocked(postModels).mockReset().mockResolvedValue({ model: 'gpt-5.4', reasoningEffort: 'high' })-})--afterEach(() => {- nativeModel.$patch({ generation: 0, entries: {} })- vi.restoreAllMocks()-})--describe('official model capability', () => {- it('recognizes only the verified named model renderer and its public injection', () => {- expect(canLockModelEntry(entry())).toBe(true)- expect(canLockModelEntry(entry(ThirdPartyModel))).toBe(false)- expect(canLockModelEntry({ ...entry(), locale: 'settings.model' })).toBe(false)- expect(canLockModelEntry({ ...entry(), inject: undefined })).toBe(false)- expect(canLockModelEntry({ ...entry(), component: { $$typeof: Symbol.for('react.memo') } })).toBe(false)- })-- it('requires the official locked owner and full observable directory business face', () => {- expect(hasModelLockFace(props())).toBe(true)- expect(hasModelLockFace(null)).toBe(false)- for (const key of ['locked', 'available', 'load', 'select', 'useProjection', 'directory']) {- const value = props()- delete value[key]- expect(hasModelLockFace(value)).toBe(false)- }- expect(hasModelLockFace({ ...props(), locked: 'true' })).toBe(false)- expect(hasModelLockFace({ ...props(), directory: { getSnapshot: () => ({}) } })).toBe(false)- })-- it('capability probes never invoke directory or session hooks', () => {- const getSnapshot = vi.fn(() => ({}))- const useProjection = vi.fn(() => null)- expect(hasModelLockFace({ ...props(), directory: { subscribe: () => () => {}, getSnapshot }, useProjection })).toBe(true)- expect(getSnapshot).not.toHaveBeenCalled()- expect(useProjection).not.toHaveBeenCalled()- })-})--describe('native model actions', () => {- it('loads the native-only directory and never replaces durable selection with a catalog hint', async () => {- const scope = open('session-a', 1, null)- nativeModel.update('session-a', 1, { current: { model: 'gpt-5.4', reasoningEffort: 'high' } })- await loadNativeModels(scope)- expect(getModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a' })- expect(nativeModel.$state.entries['session-a']?.directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' })- expect(nativeModel.$state.entries['session-a']?.directory.status).toBe('ready')- expect(postModels).not.toHaveBeenCalled()- })-- it('submits the default-following model and exact depth then refreshes only the durable projection', async () => {- const scope = open()- const refreshProjection = vi.fn(async () => ({ model: 'gpt-5.4', reasoningEffort: 'high' }))- expect(await selectNativeModel({ ...scope, selection: { provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' }, refreshProjection })).toEqual({ ok: true, value: undefined })- expect(postModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a', model: null, reasoningEffort: 'high' })- expect(refreshProjection).toHaveBeenCalledExactlyOnceWith('session-a')- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: 'gpt-5.4', reasoningEffort: 'high' })- expect(nativeModel.$state.entries['session-a']?.directory.pending).toBeNull()- })-- it('the single default model resets nullable preferences without persisting its displayed native baseline', async () => {- const scope = open('session-a', 1, { ...CATALOG, defaultReasoningEffort: 'high' })- const refreshProjection = vi.fn(async () => ({ model: null, reasoningEffort: null }))- await selectNativeModel({ ...scope, selection: { provider: 'bridge/codex', model: 'gpt-5.4' }, refreshProjection })- expect(postModels).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-a', model: null, reasoningEffort: null })- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: null, reasoningEffort: null })- expect(nativeModel.$state.entries['session-a']?.directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' })- expect(refreshProjection).toHaveBeenCalledExactlyOnceWith('session-a')- })-- it('backend changes and unsupported depths cannot issue a mutation', async () => {- const scope = open()- const refreshProjection = vi.fn(async () => ({ model: null, reasoningEffort: null }))- expect(await selectNativeModel({ ...scope, selection: { provider: 'openai', model: 'gpt-5.4' }, refreshProjection })).toEqual({ ok: false, error: { code: 'bridge/model-selection', message: 'Native session kernel cannot be changed' } })- expect(await selectNativeModel({ ...scope, selection: { provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'max' }, refreshProjection })).toEqual({ ok: false, error: { code: 'bridge/model-selection', message: 'Native reasoning effort is unavailable' } })- expect(postModels).not.toHaveBeenCalled()- expect(refreshProjection).not.toHaveBeenCalled()- })-- it('load failures stay visible and a retry can recover without changing native preferences', async () => {- const scope = open()- vi.mocked(getModels).mockRejectedValueOnce(new Error('CLI model catalog unavailable'))- await loadNativeModels(scope)- expect(nativeModel.$state.entries['session-a']?.directory).toMatchObject({ status: 'error', error: 'CLI model catalog unavailable', current: { provider: 'bridge/codex', model: 'gpt-5.4' } })- await loadNativeModels(scope)- expect(nativeModel.$state.entries['session-a']?.directory).toMatchObject({ status: 'ready', error: null })- })-- it('a missing native conversation reports an actionable message instead of the raw server failure', async () => {- const scope = open()- vi.mocked(getModels).mockRejectedValueOnce(new Error('请求失败 (500): BRIDGE_NATIVE_TURN'))- await loadNativeModels(scope)- expect(nativeModel.$state.entries['session-a']?.directory).toMatchObject({ status: 'error', error: 'BRIDGE_SESSION_UNRECOVERABLE: 原生会话记录已不存在,请新建会话。', current: { provider: 'bridge/codex', model: 'gpt-5.4' } })- await loadNativeModels(scope)- expect(nativeModel.$state.entries['session-a']?.directory).toMatchObject({ status: 'ready', error: null })- })-- it('catalog backend mismatch remains an error rather than making another kernel selectable', async () => {- const scope = open()- vi.mocked(getModels).mockResolvedValue({ ...CATALOG, backend: 'claude' })- await loadNativeModels(scope)- expect(nativeModel.$state.entries['session-a']?.directory.error).toBe('Native session kernel does not match the model catalog')- expect(nativeModel.$state.entries['session-a']?.directory.groups[0]?.id).toBe('bridge/codex')- })-- it('a failed POST preserves current options and exposes the actual retryable error', async () => {- const scope = open()- vi.mocked(postModels).mockRejectedValue(new Error('native session is busy'))- const refreshProjection = vi.fn(async () => ({ model: null, reasoningEffort: null }))- expect(await selectNativeModel({ ...scope, selection: { provider: 'bridge/codex', model: 'gpt-5.4' }, refreshProjection })).toEqual({ ok: false, error: { code: 'bridge/model-selection', message: 'native session is busy' } })- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: null, reasoningEffort: null })- expect(nativeModel.$state.entries['session-a']?.directory.pending).toBeNull()- expect(refreshProjection).not.toHaveBeenCalled()- })-- it('does not claim POST success if the official projection refresh fails', async () => {- const scope = open()- const refreshProjection = vi.fn(async () => {- throw new Error('projection refresh failed')- })- expect(await selectNativeModel({ ...scope, selection: { provider: 'bridge/codex', model: 'gpt-5.4' }, refreshProjection })).toEqual({ ok: false, error: { code: 'bridge/model-selection', message: 'projection refresh failed' } })- expect(nativeModel.$state.entries['session-a']?.current).toEqual({ model: null, reasoningEffort: null })- })-- it('superseded loads cannot overwrite a newer native catalog', async () => {- const scope = open()- const pending = deferred<NativeModelDirectory>()- vi.mocked(getModels).mockReturnValueOnce(pending.promise).mockResolvedValueOnce({ ...CATALOG, models: [{ id: 'gpt-next', name: 'Next' }] })- const stale = loadNativeModels(scope)- await loadNativeModels(scope)- pending.resolve(CATALOG)- await stale- expect(nativeModel.$state.entries['session-a']?.catalog?.models).toEqual([{ id: 'gpt-next', name: 'Next' }])- })-- it('a closed and reopened session cannot receive the previous load response', async () => {- const scope = open()- const pending = deferred<NativeModelDirectory>()- vi.mocked(getModels).mockReturnValueOnce(pending.promise)- const stale = loadNativeModels(scope)- nativeModel.close('session-a', 1)- open('session-a', 2, null)- pending.resolve(CATALOG)- await stale- expect(nativeModel.$state.entries['session-a']?.catalog).toBeNull()- expect(nativeModel.$state.entries['session-a']?.directory.status).toBe('idle')- })-- it('an inactive scope cannot start a GET or POST', async () => {- const scope = { ...open(), active: () => false }- await loadNativeModels(scope)- expect(await selectNativeModel({ ...scope, selection: { provider: 'bridge/codex', model: 'gpt-5.4' }, refreshProjection: vi.fn() })).toBeUndefined()- expect(getModels).not.toHaveBeenCalled()- expect(postModels).not.toHaveBeenCalled()- })-- it('a POST response after unmount cannot refresh projections or write to another session', async () => {- const scope = open()- open('session-b', 2, null)- const pending = deferred<{ model: string | null, reasoningEffort: string | null }>()- vi.mocked(postModels).mockReturnValue(pending.promise)- const refreshProjection = vi.fn(async () => ({ model: 'gpt-5.4', reasoningEffort: 'high' }))- const stale = selectNativeModel({ ...scope, selection: { provider: 'bridge/codex', model: 'gpt-5.4' }, refreshProjection })- nativeModel.close('session-a', 1)- pending.resolve({ model: 'gpt-5.4', reasoningEffort: null })- expect(await stale).toBeUndefined()- expect(refreshProjection).not.toHaveBeenCalled()- expect(nativeModel.$state.entries['session-b']?.current).toEqual({ model: null, reasoningEffort: null })- })-- it('an older selection cannot replace a newer successful native selection', async () => {- const scope = open()- const pending = deferred<{ model: string | null, reasoningEffort: string | null }>()- vi.mocked(postModels).mockReturnValueOnce(pending.promise).mockResolvedValueOnce({ model: 'gpt-5.4', reasoningEffort: 'high' })- const refreshProjection = vi.fn(async () => ({ model: 'gpt-5.4', reasoningEffort: 'high' }))- const stale = selectNativeModel({ ...scope, selection: { provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'medium' }, refreshProjection })- await selectNativeModel({ ...scope, selection: { provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' }, refreshProjection })- pending.resolve({ model: 'gpt-5.4', reasoningEffort: 'medium' })- expect(await stale).toBeUndefined()- expect(refreshProjection).toHaveBeenCalledTimes(1)- expect(nativeModel.$state.entries['session-a']?.directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' })- })-})diff --git a/packages/dsh-tauri-kernel/src/client/service/kernel-model.ts b/packages/dsh-tauri-kernel/src/client/service/kernel-model.tsdeleted file mode 100644index 7abfca3c..00000000--- a/packages/dsh-tauri-kernel/src/client/service/kernel-model.ts+++ /dev/null@@ -1,101 +0,0 @@-import type { ModelSelection } from '@deepseek-ai/dsh-api-session-controller/types'-import type { StoredEntry } from 'dsh-tauri/client'-import type { NativeModelDirectory, NativeTurnOptions } from '../../shared/native-model'-import type { NativeModelOutcome, NativeModelScope, OfficialModelSelectFace } from '../types/kernel-model'-import { getModels, postModels } from '../apis'-import { nativeModel } from '../store/modules/native-model'-import { nativeModelDirectory, nativeModelOptions } from './kernel-model.utils'--export function canLockModelEntry(entry: StoredEntry): boolean {- return entry.locale === 'model'- && typeof entry.component === 'function' && entry.component.name === 'ModelSelect'- && typeof entry.inject === 'function'-}--export function hasModelLockFace(value: unknown): value is OfficialModelSelectFace {- if (typeof value !== 'object' || value === null)- return false- const props = value as Record<string, unknown>- const directory = props.directory- return typeof props.locked === 'boolean' && typeof props.available === 'boolean'- && typeof props.load === 'function' && typeof props.select === 'function'- && typeof directory === 'object' && directory !== null- && 'subscribe' in directory && typeof directory.subscribe === 'function'- && 'getSnapshot' in directory && typeof directory.getSnapshot === 'function'- && typeof props.useProjection === 'function'-}--export async function loadNativeModels(scope: NativeModelScope): Promise<NativeModelDirectory | undefined> {- const entry = nativeModel.$state.entries[scope.sessionId]- if (!scope.active() || entry?.scope !== scope.scope)- return undefined- const request = entry.request + 1- nativeModel.update(scope.sessionId, scope.scope, { request, directory: { ...entry.directory, status: 'loading', error: null } })- const current = (): boolean => scope.active() && nativeModel.$state.entries[scope.sessionId]?.scope === scope.scope- && nativeModel.$state.entries[scope.sessionId]?.request === request- try {- const catalog = await getModels({ sessionId: scope.sessionId })- if (!current())- return undefined- if (catalog.backend !== entry.backend)- throw new Error('Native session kernel does not match the model catalog')- const latest = nativeModel.$state.entries[scope.sessionId]!- const directory = nativeModelDirectory(entry.backend, latest.current, catalog)- nativeModel.update(scope.sessionId, scope.scope, { catalog, directory: { ...directory, status: 'ready' } })- return catalog- }- catch (reason) {- if (current()) {- const latest = nativeModel.$state.entries[scope.sessionId]!- nativeModel.update(scope.sessionId, scope.scope, {- directory: { ...latest.directory, status: 'error', error: unreadableNativeRecord(reason) },- })- }- return undefined- }-}--function unreadableNativeRecord(reason: unknown): string {- const message = reason instanceof Error ? reason.message : String(reason)- return /BRIDGE_NATIVE_TURN|No conversation found/.test(message)- ? 'BRIDGE_SESSION_UNRECOVERABLE: 原生会话记录已不存在,请新建会话。'- : message-}--export async function selectNativeModel(input: NativeModelScope & {- selection: ModelSelection- refreshProjection: (sessionId: string) => Promise<NativeTurnOptions>-}): Promise<NativeModelOutcome | undefined> {- const entry = nativeModel.$state.entries[input.sessionId]- if (!input.active() || entry?.scope !== input.scope)- return undefined- const request = entry.request + 1- const current = (): boolean => input.active() && nativeModel.$state.entries[input.sessionId]?.scope === input.scope- && nativeModel.$state.entries[input.sessionId]?.request === request- nativeModel.update(input.sessionId, input.scope, { request, directory: { ...entry.directory, status: 'selecting', pending: input.selection, error: null } })- try {- if (entry.catalog === null)- throw new Error('Native model catalog is unavailable; reload models')- const options = nativeModelOptions(entry.backend, entry.catalog, input.selection)- await postModels({ sessionId: input.sessionId, ...options })- if (!current())- return undefined- const projected = await input.refreshProjection(input.sessionId)- if (!current())- return undefined- const latest = nativeModel.$state.entries[input.sessionId]!- const directory = nativeModelDirectory(entry.backend, projected, latest.catalog)- nativeModel.update(input.sessionId, input.scope, { current: projected, directory: { ...directory, status: 'ready' } })- return { ok: true, value: undefined }- }- catch (reason) {- if (!current())- return undefined- const message = reason instanceof Error ? reason.message : String(reason)- const latest = nativeModel.$state.entries[input.sessionId]!- nativeModel.update(input.sessionId, input.scope, {- directory: { ...latest.directory, status: 'error', pending: null, error: message },- })- return { ok: false, error: { code: 'bridge/model-selection', message } }- }-}diff --git a/packages/dsh-tauri-kernel/src/client/service/kernel-model.utils.test.ts b/packages/dsh-tauri-kernel/src/client/service/kernel-model.utils.test.tsdeleted file mode 100644index 3ffb5cf8..00000000--- a/packages/dsh-tauri-kernel/src/client/service/kernel-model.utils.test.ts+++ /dev/null@@ -1,191 +0,0 @@-import type { NativeModelDirectory } from '../../shared/native-model'-import { describe, expect, it } from 'vitest'-import { isNativeTurnOptions, nativeModelDirectory, nativeModelOptions } from './kernel-model.utils'--const CATALOG: NativeModelDirectory = {- backend: 'codex',- defaultModel: 'gpt-5.4',- current: { model: 'gpt-5.4', reasoningEffort: 'high' },- models: [- { id: 'gpt-5.4', name: 'GPT-5.4', reasoning: { efforts: [{ id: 'medium', name: 'Medium' }, { id: 'high', name: 'High' }], defaultEffort: 'medium' } },- { id: 'gpt-5.4-mini', name: 'GPT-5.4 Mini' },- ],-}--describe('native model directory view', () => {- it.each([null, 'deepseek'])('one exact default model row represents durable model=$0 without a second alias', (model) => {- const current = { model, reasoningEffort: null }- const directory = nativeModelDirectory('codex', current, {- backend: 'codex',- current: { model: null, reasoningEffort: null },- defaultModel: 'deepseek',- models: [{ id: 'deepseek', name: 'DeepSeek' }],- })- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'deepseek' })- expect(directory.groups).toEqual([{ id: 'bridge/codex', name: 'Codex', models: [{ id: 'deepseek', name: 'DeepSeek' }] }])- expect(current).toEqual({ model, reasoningEffort: null })- })-- it('a configured native model absent from the advertised directory appears once with its exact id', () => {- const directory = nativeModelDirectory('codex', { model: null, reasoningEffort: null }, { ...CATALOG, defaultModel: 'custom-provider/deepseek' })- expect(directory.groups[0]?.models).toEqual([- { id: 'custom-provider/deepseek', name: 'custom-provider/deepseek' },- { id: 'gpt-5.4', name: 'GPT-5.4', reasoning: { efforts: [{ id: 'medium', name: 'Medium' }, { id: 'high', name: 'High' }] } },- { id: 'gpt-5.4-mini', name: 'GPT-5.4 Mini' },- ])- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'custom-provider/deepseek' })- })-- it('names the single default row after the native alias instead of a second native-default placeholder', () => {- const catalog: NativeModelDirectory = {- backend: 'claude',- current: { model: null, reasoningEffort: null },- defaultModel: 'default',- models: [- { id: 'default', name: 'Default (recommended)' },- { id: 'opus', name: 'Opus' },- { id: 'fable', name: 'Fable' },- { id: 'sonnet', name: 'Sonnet' },- { id: 'haiku', name: 'Haiku' },- ],- }- const directory = nativeModelDirectory('claude', { model: null, reasoningEffort: null }, catalog)- expect(directory.groups).toEqual([{ id: 'bridge/claude', name: 'Claude', models: catalog.models }])- expect(directory.current).toEqual({ provider: 'bridge/claude', model: 'default' })- expect(directory.groups[0]?.models.some(model => model.name === '原生默认' || model.id === '')).toBe(false)- expect(nativeModelOptions('claude', catalog, { provider: 'bridge/claude', model: 'default' })).toEqual({ model: null, reasoningEffort: null })- })-- it('an unread native default has one explicit default placeholder instead of treating the bridge route as a model', () => {- const directory = nativeModelDirectory('codex', { model: null, reasoningEffort: null }, null)- expect(directory.groups).toEqual([{ id: 'bridge/codex', name: 'Codex', models: [{ id: '', name: 'Native default' }] }])- expect(directory.current).toEqual({ provider: 'bridge/codex', model: '' })- expect(directory.routable).toBeNull()- })-- it('shows the effective native default effort read-only even when it differs from the advertised preset', () => {- const catalog: NativeModelDirectory = { ...CATALOG, defaultReasoningEffort: 'high' }- const current = { model: null, reasoningEffort: null }- const directory = nativeModelDirectory('codex', current, catalog)- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' })- expect(directory.retainedEffort).toBe('high')- expect(directory.groups[0]?.models).toEqual([- { id: 'gpt-5.4', name: 'GPT-5.4', reasoning: { efforts: [{ id: 'medium', name: 'Medium' }, { id: 'high', name: 'High' }] } },- { id: 'gpt-5.4-mini', name: 'GPT-5.4 Mini' },- ])- expect(nativeModelOptions('codex', catalog, { provider: 'bridge/codex', model: 'gpt-5.4' })).toEqual({ model: null, reasoningEffort: null })- expect(current).toEqual({ model: null, reasoningEffort: null })- expect(catalog.models[0]?.reasoning?.defaultEffort).toBe('medium')- })-- it('a native custom model displays its actual default effort without advertising selectable depths', () => {- const catalog: NativeModelDirectory = {- backend: 'codex',- defaultModel: 'custom/deepseek',- defaultReasoningEffort: 'high',- current: { model: null, reasoningEffort: null },- models: [{ id: 'custom/deepseek', name: 'DeepSeek' }],- }- const directory = nativeModelDirectory('codex', { model: null, reasoningEffort: null }, catalog)- expect(directory.groups).toEqual([{ id: 'bridge/codex', name: 'Codex', models: [{ id: 'custom/deepseek', name: 'DeepSeek' }] }])- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'custom/deepseek', reasoningEffort: 'high' })- expect(directory.retainedEffort).toBe('high')- expect(nativeModelOptions('codex', catalog, { provider: 'bridge/codex', model: 'custom/deepseek' })).toEqual({ model: null, reasoningEffort: null })- expect(() => nativeModelOptions('codex', catalog, { provider: 'bridge/codex', model: 'custom/deepseek', reasoningEffort: 'high' })).toThrow('Native reasoning effort is unavailable')- })-- it('unknown effective effort does not borrow a model-list preset or invent a reasoning level', () => {- const directory = nativeModelDirectory('codex', { model: null, reasoningEffort: null }, CATALOG)- expect(directory.groups[0]?.models[0]).toEqual({ id: 'gpt-5.4', name: 'GPT-5.4', reasoning: { efforts: [{ id: 'medium', name: 'Medium' }, { id: 'high', name: 'High' }] } })- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4' })- expect(directory.retainedEffort).toBeUndefined()- })-- it('explicit durable efforts take precedence over the read-only native default caption', () => {- const catalog: NativeModelDirectory = { ...CATALOG, defaultReasoningEffort: 'high' }- const directory = nativeModelDirectory('codex', { model: null, reasoningEffort: 'medium' }, catalog)- expect(directory.groups[0]?.models[0]?.name).toBe('GPT-5.4')- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'medium' })- expect(nativeModelOptions('codex', catalog, { provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'medium' })).toEqual({ model: null, reasoningEffort: 'medium' })- })-- it('a nondefault model never claims the native default model effort as its own', () => {- const directory = nativeModelDirectory('codex', { model: 'gpt-5.4-mini', reasoningEffort: null }, { ...CATALOG, defaultReasoningEffort: 'high' })- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4-mini' })- expect(directory.retainedEffort).toBeUndefined()- })-- it('reading a fixed default model retains the raw preference while presenting its native effort baseline', () => {- const current = { model: 'gpt-5.4', reasoningEffort: null }- const directory = nativeModelDirectory('codex', current, { ...CATALOG, defaultReasoningEffort: 'high' })- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' })- expect(current).toEqual({ model: 'gpt-5.4', reasoningEffort: null })- })-- it('uses native routes and the durable native selection rather than the GET current hint', () => {- const directory = nativeModelDirectory('codex', { model: 'gpt-5.4-mini', reasoningEffort: null }, CATALOG)- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4-mini' })- expect(directory.groups).toEqual([{ id: 'bridge/codex', name: 'Codex', models: [- { id: 'gpt-5.4', name: 'GPT-5.4', reasoning: { efforts: [{ id: 'medium', name: 'Medium' }, { id: 'high', name: 'High' }] } },- { id: 'gpt-5.4-mini', name: 'GPT-5.4 Mini' },- ] }])- expect(directory.routable).toBe(true)- expect(directory.pending).toBeNull()- })-- it('the single default model row sends nullable resets instead of fixing catalog display hints', () => {- const directory = nativeModelDirectory('codex', { model: null, reasoningEffort: null }, CATALOG)- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'gpt-5.4' })- expect(directory.groups[0]?.models[0]?.reasoning).toEqual({ efforts: [{ id: 'medium', name: 'Medium' }, { id: 'high', name: 'High' }] })- expect(nativeModelOptions('codex', CATALOG, { provider: 'bridge/codex', model: 'gpt-5.4' })).toEqual({ model: null, reasoningEffort: null })- expect(nativeModelOptions('codex', CATALOG, { provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'high' })).toEqual({ model: null, reasoningEffort: 'high' })- })-- it('deduplicates repeated wire ids while distinguishing different models with the same label', () => {- const directory = nativeModelDirectory('codex', { model: null, reasoningEffort: null }, {- ...CATALOG,- models: [{ id: 'gpt-5.4', name: 'GPT' }, { id: 'gpt-5.4', name: 'Duplicate wire row' }, { id: 'gpt-5.4-mini', name: 'GPT' }],- })- expect(directory.groups[0]?.models).toEqual([{ id: 'gpt-5.4', name: 'GPT (gpt-5.4)' }, { id: 'gpt-5.4-mini', name: 'GPT (gpt-5.4-mini)' }])- })-- it('retains an unavailable native caption but does not claim it is routable', () => {- const directory = nativeModelDirectory('codex', { model: 'removed-native-model', reasoningEffort: 'deep' }, CATALOG)- expect(directory.current).toEqual({ provider: 'bridge/codex', model: 'removed-native-model', reasoningEffort: 'deep' })- expect(directory.retainedEffort).toBe('deep')- expect(directory.routable).toBe(false)- })-- it('a Claude model without native reasoning metadata has no client-owned depth list', () => {- const directory = nativeModelDirectory('claude', { model: 'claude-sonnet-4-6', reasoningEffort: null }, {- backend: 'claude',- current: { model: null, reasoningEffort: null },- defaultModel: 'claude-sonnet-4-6',- models: [{ id: 'claude-sonnet-4-6', name: 'Sonnet 4.6' }],- })- expect(directory.groups).toEqual([{ id: 'bridge/claude', name: 'Claude', models: [{ id: 'claude-sonnet-4-6', name: 'Sonnet 4.6' }] }])- })-- it('an unresolved default model has one placeholder with no invented reasoning metadata', () => {- const directory = nativeModelDirectory('codex', { model: null, reasoningEffort: null }, { ...CATALOG, defaultModel: undefined })- expect(directory.groups[0]?.models.map(model => model.id)).toEqual(['', 'gpt-5.4', 'gpt-5.4-mini'])- expect(directory.groups[0]?.models[0]).toEqual({ id: '', name: 'Native default' })- expect(() => nativeModelOptions('codex', { ...CATALOG, defaultModel: undefined }, { provider: 'bridge/codex', model: '', reasoningEffort: 'high' })).toThrow('Native reasoning effort is unavailable')- })-- it('resets the effort on model changes and rejects backend changes, unknown models, and unknown depths', () => {- expect(nativeModelOptions('codex', CATALOG, { provider: 'bridge/codex', model: 'gpt-5.4-mini' })).toEqual({ model: 'gpt-5.4-mini', reasoningEffort: null })- expect(() => nativeModelOptions('codex', CATALOG, { provider: 'openai', model: 'gpt-5.4' })).toThrow('Native session kernel cannot be changed')- expect(() => nativeModelOptions('codex', CATALOG, { provider: 'bridge/claude', model: 'gpt-5.4' })).toThrow('Native session kernel cannot be changed')- expect(() => nativeModelOptions('codex', CATALOG, { provider: 'bridge/codex', model: 'not-in-catalog' })).toThrow('Native model is unavailable')- expect(() => nativeModelOptions('codex', CATALOG, { provider: 'bridge/codex', model: 'gpt-5.4', reasoningEffort: 'max' })).toThrow('Native reasoning effort is unavailable')- expect(() => nativeModelOptions('codex', CATALOG, { provider: 'bridge/codex', model: 'gpt-5.4-mini', reasoningEffort: 'high' })).toThrow('Native reasoning effort is unavailable')- })-- it('requires explicit nullable native preferences instead of treating unknown values as defaults', () => {- expect(isNativeTurnOptions({ model: null, reasoningEffort: null })).toBe(true)- expect(isNativeTurnOptions({ model: 'native-model', reasoningEffort: 'native-depth' })).toBe(true)- for (const value of [undefined, null, {}, { model: null }, { model: '', reasoningEffort: null }, { model: null, reasoningEffort: 3 }])- expect(isNativeTurnOptions(value)).toBe(false)- })-})diff --git a/packages/dsh-tauri-kernel/src/client/service/kernel-model.utils.ts b/packages/dsh-tauri-kernel/src/client/service/kernel-model.utils.tsdeleted file mode 100644index 48d494e3..00000000--- a/packages/dsh-tauri-kernel/src/client/service/kernel-model.utils.ts+++ /dev/null@@ -1,65 +0,0 @@-import type { ModelCatalogModel, ModelSelection } from '@deepseek-ai/dsh-api-session-controller/types'-import type { NativeModelDirectory, NativeTurnOptions } from '../../shared/native-model'-import type { KernelBinding } from '../../shared/types'-import type { NativeModelDirectoryState } from '../types/kernel-model'-import { groupBy, uniqBy } from 'dsh-tauri/client'-import { NATIVE_DEFAULT_MODEL } from '../constants'-import { locale } from '../locales'--export function nativeModelDirectory(- backend: KernelBinding['backend'],- current: NativeTurnOptions,- catalog: NativeModelDirectory | null,- previous?: NativeModelDirectoryState,-): NativeModelDirectoryState {- const provider = `bridge/${backend}`- const defaultId = catalog?.defaultModel ?? NATIVE_DEFAULT_MODEL- const listed = uniqBy(catalog?.models ?? [], 'id')- const directory = listed.some(model => model.id === defaultId)- ? listed- : [{ id: defaultId, name: catalog?.defaultModel ?? locale.text('kernel.modelDefault') }, ...listed]- const names = groupBy(directory, 'name')- const models: ModelCatalogModel[] = directory.map(model => ({- ...model,- name: names[model.name]!.length > 1 ? `${model.name} (${model.id})` : model.name,- ...(model.reasoning === undefined ? {} : { reasoning: { efforts: model.reasoning.efforts } }),- }))- const reasoningEffort = current.reasoningEffort- ?? (current.model === null || current.model === catalog?.defaultModel ? catalog?.defaultReasoningEffort : undefined)- const selection: ModelSelection = {- provider,- model: current.model ?? defaultId,- ...(reasoningEffort === undefined ? {} : { reasoningEffort }),- }- return {- current: selection,- ...(reasoningEffort === undefined ? {} : { retainedEffort: reasoningEffort }),- routable: catalog === null ? null : models.some(model => model.id === selection.model),- groups: [{ id: provider, name: backend === 'codex' ? 'Codex' : 'Claude', models }],- failures: [],- status: previous?.status ?? 'idle',- pending: previous?.pending ?? null,- error: previous?.error ?? null,- }-}--export function nativeModelOptions(backend: KernelBinding['backend'], catalog: NativeModelDirectory, selection: ModelSelection): NativeTurnOptions {- if (selection.provider !== `bridge/${backend}`)- throw new Error('Native session kernel cannot be changed')- const model = selection.model === NATIVE_DEFAULT_MODEL || selection.model === catalog.defaultModel ? null : selection.model- const info = catalog.models.find(item => item.id === (model ?? catalog.defaultModel))- if (model !== null && info === undefined)- throw new Error('Native model is unavailable')- const reasoningEffort = selection.reasoningEffort ?? null- if (reasoningEffort !== null && !info?.reasoning?.efforts.some(effort => effort.id === reasoningEffort))- throw new Error('Native reasoning effort is unavailable')- return { model, reasoningEffort }-}--export function isNativeTurnOptions(value: unknown): value is NativeTurnOptions {- if (typeof value !== 'object' || value === null)- return false- const current = value as Record<string, unknown>- return (current.model === null || (typeof current.model === 'string' && current.model.length > 0))- && (current.reasoningEffort === null || (typeof current.reasoningEffort === 'string' && current.reasoningEffort.length > 0))-}diff --git a/packages/dsh-tauri-kernel/src/client/service/kernel-session.test.ts b/packages/dsh-tauri-kernel/src/client/service/kernel-session.test.tsdeleted file mode 100644index b8526cb4..00000000--- a/packages/dsh-tauri-kernel/src/client/service/kernel-session.test.ts+++ /dev/null@@ -1,190 +0,0 @@-import type { SessionId, SessionListState, SessionSummary } from 'dsh-tauri/client'-import type { BackendDetection, KernelBinding } from '../../shared/types'-import { defineAdapter } from 'dsh-tauri/client'-import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { postSessions } from '../apis'-import { kernelStore } from '../store/modules/kernel-store'-import { createKernelSession } from './kernel-session'--vi.hoisted(() => vi.stubGlobal('localStorage', undefined))-vi.mock('../apis', () => ({ postSessions: vi.fn() }))--const BINDING: KernelBinding = { backend: 'codex', nativeSessionId: 'native-a', sessionId: 'bridge-session' }-const BACKENDS: BackendDetection[] = [- { id: 'dsh', installed: true, auth: 'ok', version: null, drift: false, hint: null },- { id: 'codex', installed: true, auth: 'ok', version: '1.0', drift: false, hint: null },- { id: 'claude', installed: false, auth: 'unknown', version: null, drift: false, hint: null },-]--function row(id: string, identity: KernelBinding | null | undefined, patch: Partial<SessionSummary> = {}): SessionSummary {- return {- id: id as SessionId,- displayTitle: id,- blank: true,- cwd: '/project',- running: false,- retainedBy: {},- updatedAt: 1,- projectionValues: identity === undefined ? {} : { bridgeKernel: identity },- ...patch,- }-}--function fixture(rows: SessionSummary[] = [], current?: string, grouped = false) {- let state: SessionListState & { current?: SessionId } = {- ids: rows.map(item => item.id),- byId: Object.fromEntries(rows.map(item => [item.id, item])),- phase: 'ready',- projectionsBySession: {},- ...(current === undefined ? {} : { current: current as SessionId }),- }- const archivedSessionIds: SessionId[] = []- const create = vi.fn(async () => 'official-new')- const refresh = vi.fn(async () => {})- const refreshProjections = vi.fn(async () => {})- const sessions = {- list: { getSnapshot: () => state, subscribe: () => () => {} },- create,- refresh,- refreshProjections,- }- const workspaces = {- list: { getSnapshot: () => ({- items: grouped ? [{ workspaceId: 'workspace-a', path: '/project', sessionIds: rows.map(item => item.id) }] : [],- archivedSessionIds,- }), subscribe: () => () => {} },- }- const services: Record<string, unknown> = { sessions, workspaces }- const adapter = defineAdapter({ get: (name: string) => services[name] })- function publish(identity: KernelBinding | null | undefined): void {- const id = 'bridge-session' as SessionId- state = {- ...state,- ids: [...state.ids, id],- byId: { ...state.byId, [id]: row(id, identity) },- projectionsBySession: { ...state.projectionsBySession, [id]: { values: identity === undefined ? {} : { bridgeKernel: identity }, state: 'ready', error: null } },- }- }- return { adapter, sessions, services, archivedSessionIds, create, refresh, refreshProjections, publish }-}--beforeEach(() => {- kernelStore.$patch({ phase: 'ready', error: null, backends: BACKENDS })- vi.mocked(postSessions).mockReset().mockResolvedValue({ sessionId: 'bridge-session' })-})--afterEach(() => {- kernelStore.$patch({ phase: 'idle', error: null, backends: [] })- vi.restoreAllMocks()-})--afterAll(() => vi.unstubAllGlobals())--describe('explicit kernel session creation', () => {- it('deepseek uses the official fresh factory without a native HTTP request', async () => {- const { adapter, create } = fixture()- await expect(createKernelSession(adapter, 'dsh', { workspaceId: 'workspace-a' }, () => true)).resolves.toBe('official-new')- expect(create).toHaveBeenCalledWith({ workspaceId: 'workspace-a' })- expect(postSessions).not.toHaveBeenCalled()- })-- it('native creation sends the generated body then refreshes catalog and verifies the durable projection', async () => {- const { adapter, create, refresh, refreshProjections, publish } = fixture()- const calls: string[] = []- vi.mocked(postSessions).mockImplementation(async () => {- calls.push('create')- return { sessionId: 'bridge-session' }- })- refresh.mockImplementation(async () => {- calls.push('catalog')- })- refreshProjections.mockImplementation(async () => {- calls.push('projection')- publish(BINDING)- })- await expect(createKernelSession(adapter, 'codex', { workspaceId: 'workspace-a' }, () => true, 'coding')).resolves.toBe('bridge-session')- expect(postSessions).toHaveBeenCalledWith({ backend: 'codex', workspaceId: 'workspace-a', agentPreset: 'coding' })- expect(refreshProjections).toHaveBeenCalledWith('bridge-session')- expect(calls).toEqual(['create', 'catalog', 'projection'])- expect(create).not.toHaveBeenCalled()- })-- it('unavailable detection rejects before either official or native creation', async () => {- const { adapter, create } = fixture()- await expect(createKernelSession(adapter, 'claude', {}, () => true)).rejects.toThrow('selected native kernel is unavailable')- expect(postSessions).not.toHaveBeenCalled()- expect(create).not.toHaveBeenCalled()- })-- it('missing official refresh capability rejects before the native request', async () => {- const { adapter, sessions } = fixture()- Reflect.deleteProperty(sessions, 'refreshProjections')- await expect(createKernelSession(adapter, 'codex', {}, () => true)).rejects.toThrow('Official session projection refresh is unavailable')- expect(postSessions).not.toHaveBeenCalled()- })-- it('native request failure never falls back to a DeepSeek session', async () => {- const failure = new Error('native daemon refused')- const { adapter, create, refresh } = fixture()- vi.mocked(postSessions).mockRejectedValue(failure)- await expect(createKernelSession(adapter, 'codex', {}, () => true)).rejects.toBe(failure)- expect(create).not.toHaveBeenCalled()- expect(refresh).not.toHaveBeenCalled()- })-- it('empty created session identity rejects before catalog refresh', async () => {- const { adapter, refresh } = fixture()- vi.mocked(postSessions).mockResolvedValue({ sessionId: ' ' })- await expect(createKernelSession(adapter, 'codex', {}, () => true)).rejects.toThrow('returned no session identity')- expect(refresh).not.toHaveBeenCalled()- })-- it('cancelled native creation performs no catalog or projection work', async () => {- const { adapter, refresh, refreshProjections } = fixture()- let active = true- vi.mocked(postSessions).mockImplementation(async () => {- active = false- return { sessionId: 'bridge-session' }- })- await expect(createKernelSession(adapter, 'codex', {}, () => active)).rejects.toThrow('creation was cancelled')- expect(refresh).not.toHaveBeenCalled()- expect(refreshProjections).not.toHaveBeenCalled()- })-- it('disposal during catalog refresh prevents the next projection request', async () => {- const { adapter, refresh, refreshProjections } = fixture()- let active = true- refresh.mockImplementation(async () => {- active = false- })- await expect(createKernelSession(adapter, 'codex', {}, () => active)).rejects.toThrow('creation was cancelled')- expect(refreshProjections).not.toHaveBeenCalled()- })-- it.each([- ['missing', undefined],- ['deepseek', null],- ['inherited owner', { ...BINDING, sessionId: 'parent-session' }],- ['wrong kernel', { ...BINDING, backend: 'claude' }],- ['empty native id', { ...BINDING, nativeSessionId: '' }],- ] as const)('a %s projection cannot validate the created native session', async (_, identity) => {- const { adapter, create, refreshProjections, publish } = fixture()- refreshProjections.mockImplementation(async () => publish(identity))- await expect(createKernelSession(adapter, 'codex', {}, () => true)).rejects.toThrow('no verified native kernel binding')- expect(create).not.toHaveBeenCalled()- })-- it('existing-session options are rejected rather than rebinding that session', async () => {- const { adapter, create } = fixture()- await expect(createKernelSession(adapter, 'dsh', { sessionId: 'existing' }, () => true)).rejects.toThrow('Existing sessions cannot change kernels')- expect(create).not.toHaveBeenCalled()- expect(postSessions).not.toHaveBeenCalled()- })-- it('ambiguous workspace and cwd options reject before any creation', async () => {- const { adapter, create } = fixture()- await expect(createKernelSession(adapter, 'codex', { workspaceId: 'workspace-a', cwd: '/project' }, () => true)).rejects.toThrow('either workspaceId or cwd')- expect(create).not.toHaveBeenCalled()- expect(postSessions).not.toHaveBeenCalled()- })-})diff --git a/packages/dsh-tauri-kernel/src/client/service/kernel-session.ts b/packages/dsh-tauri-kernel/src/client/service/kernel-session.tsdeleted file mode 100644index 87d1a6a7..00000000--- a/packages/dsh-tauri-kernel/src/client/service/kernel-session.ts+++ /dev/null@@ -1,56 +0,0 @@-import type { AdapterSessionCreateOptions, ClientAdapter, ISessions, SessionId } from 'dsh-tauri/client'-import type { BackendId } from '../../shared/types'-import { postSessions } from '../apis'-import { kernelStore } from '../store/modules/kernel-store'-import { backendFromIdentity, isBackendAvailable, kernelFromList } from './kernel-identity'--export async function createKernelSession(- adapter: ClientAdapter,- backend: BackendId,- options: AdapterSessionCreateOptions,- active: () => boolean,- agentPreset?: string,-): Promise<string> {- if (!active())- throw new Error('Kernel session creation was cancelled')- if (options.sessionId !== undefined)- throw new Error('Existing sessions cannot change kernels')- if (options.workspaceId !== undefined && options.cwd !== undefined)- throw new Error('Session creation requires either workspaceId or cwd')- if (backend === 'dsh') {- const create = adapter.sessions.create- if (!adapter.has('sessions.create') || create === undefined)- throw new Error('Official session creation is unavailable')- return create(options)- }- const detection = kernelStore.$state.backends.find(item => item.id === backend)- if (kernelStore.$state.phase !== 'ready' || !isBackendAvailable(detection))- throw new Error('The selected native kernel is unavailable')- const refreshCatalog = adapter.sessions.refresh- if (!adapter.has('sessions.refreshProjections') || !adapter.has('sessions.refresh') || refreshCatalog === undefined)- throw new Error('Official session projection refresh is unavailable')- const response = await postSessions({- backend,- ...(options.workspaceId === undefined ? {} : { workspaceId: options.workspaceId }),- ...(options.cwd === undefined ? {} : { cwd: options.cwd }),- ...(agentPreset === undefined ? {} : { agentPreset }),- })- if (typeof response.sessionId !== 'string' || response.sessionId.trim() === '')- throw new Error('Native kernel creation returned no session identity')- if (!active())- throw new Error('Kernel session creation was cancelled')- await refreshCatalog()- if (!active())- throw new Error('Kernel session creation was cancelled')- const refresh = adapter.sessions.refreshProjections- if (refresh === undefined)- throw new Error('Official session projection refresh is unavailable')- await refresh(response.sessionId)- if (!active())- throw new Error('Kernel session creation was cancelled')- const sessions = adapter.service<ISessions>('sessions')- const identity = sessions === undefined ? undefined : kernelFromList(sessions.list.getSnapshot(), response.sessionId as SessionId)- if (backendFromIdentity(identity) !== backend || identity?.sessionId !== response.sessionId)- throw new Error('The new session has no verified native kernel binding')- return response.sessionId-}diff --git a/packages/dsh-tauri-kernel/src/client/service/kernel-version.test.ts b/packages/dsh-tauri-kernel/src/client/service/kernel-version.test.tsdeleted file mode 100644index c20f239c..00000000--- a/packages/dsh-tauri-kernel/src/client/service/kernel-version.test.ts+++ /dev/null@@ -1,41 +0,0 @@-import type { BackendDetection } from '../../shared/types'-import { describe, expect, it } from 'vitest'-import { kernelContentAvailable, kernelVersionAtLeast } from './kernel-version'--const dsh = (version: string | null): BackendDetection => ({ id: 'dsh', installed: true, auth: 'ok', version, drift: false, hint: null })-const codex = (patch: Partial<BackendDetection> = {}): BackendDetection => ({ id: 'codex', installed: true, auth: 'ok', version: '0.162.0', drift: false, hint: null, ...patch })--describe('kernel core version gate', () => {- it.each([- ['0.1.7-rc.1', false],- ['0.2.0', false],- ['0.2.1-alpha.1', false],- ['0.2.1-alpha.2', true],- ['0.2.1-alpha.2+build.7', true],- ['0.2.1-alpha.10', true],- ['0.2.1-beta.1', true],- ['0.2.1-rc.1', true],- ['0.2.1', true],- ['0.2.2-alpha.1', true],- ['0.3.0-alpha.1', true],- ['1.0.0', true],- ])('compares %s against the pinned baseline', (version, expected) => {- expect(kernelVersionAtLeast(version)).toBe(expected)- })-- it.each([null, undefined, '', 'dev', '0.2', 'v0.2.1-alpha.2'])('reports an unprovable version %s instead of guessing', (version) => {- expect(kernelVersionAtLeast(version)).toBeUndefined()- })-- it('uses the reported runtime version before any capability fallback', () => {- expect(kernelContentAvailable([dsh('0.2.1-alpha.1'), codex({ bridgeReady: true })])).toBe(false)- expect(kernelContentAvailable([dsh('0.2.1-alpha.2'), codex({ bridgeReady: false })])).toBe(true)- })-- it('falls back to the capability probe only when the runtime version is unreadable', () => {- expect(kernelContentAvailable([dsh(null), codex({ bridgeReady: true })])).toBe(true)- expect(kernelContentAvailable([dsh(null), codex({ bridgeReady: false })])).toBe(false)- expect(kernelContentAvailable([dsh(null)])).toBe(false)- expect(kernelContentAvailable([])).toBe(false)- })-})diff --git a/packages/dsh-tauri-kernel/src/client/service/kernel-version.ts b/packages/dsh-tauri-kernel/src/client/service/kernel-version.tsdeleted file mode 100644index 44b0fc9d..00000000--- a/packages/dsh-tauri-kernel/src/client/service/kernel-version.ts+++ /dev/null@@ -1,66 +0,0 @@-import type { BackendDetection } from '../../shared/types'--export const KERNEL_CORE_BASELINE = '0.2.1-alpha.2'--interface ParsedVersion {- major: number- minor: number- patch: number- pre: (string | number)[]-}--function parse(version: string): ParsedVersion | null {- const match = /^(\d+)\.(\d+)\.(\d+)(?:-([\d.a-z-]+))?(?:\+[\d.a-z-]+)?$/i.exec(version.trim())- if (match === null)- return null- return {- major: Number(match[1]),- minor: Number(match[2]),- patch: Number(match[3]),- pre: match[4] === undefined ? [] : match[4].split('.').map(part => /^\d+$/.test(part) ? Number(part) : part),- }-}--function comparePrerelease(left: (string | number)[], right: (string | number)[]): number {- if (left.length === 0 || right.length === 0)- return left.length === right.length ? 0 : left.length === 0 ? 1 : -1- for (let index = 0; index < Math.max(left.length, right.length); index++) {- const a = left[index]- const b = right[index]- if (a === undefined)- return -1- if (b === undefined)- return 1- if (a === b)- continue- if (typeof a === 'number' && typeof b === 'number')- return a < b ? -1 : 1- if (typeof a === 'number')- return -1- if (typeof b === 'number')- return 1- return a < b ? -1 : 1- }- return 0-}--export function kernelVersionAtLeast(version: string | null | undefined, baseline: string = KERNEL_CORE_BASELINE): boolean | undefined {- if (typeof version !== 'string' || version.trim() === '')- return undefined- const left = parse(version)- const right = parse(baseline)- if (left === null || right === null)- return undefined- for (const key of ['major', 'minor', 'patch'] as const) {- if (left[key] !== right[key])- return left[key] > right[key]- }- return comparePrerelease(left.pre, right.pre) >= 0-}--export function kernelContentAvailable(backends: readonly BackendDetection[]): boolean {- const verdict = kernelVersionAtLeast(backends.find(backend => backend.id === 'dsh')?.version)- if (verdict !== undefined)- return verdict- return backends.some(backend => backend.id !== 'dsh' && backend.bridgeReady !== false)-}diff --git a/packages/dsh-tauri-kernel/src/client/store/modules/kernel-store.ts b/packages/dsh-tauri-kernel/src/client/store/modules/kernel-store.tsdeleted file mode 100644index f71fa176..00000000--- a/packages/dsh-tauri-kernel/src/client/store/modules/kernel-store.ts+++ /dev/null@@ -1,10 +0,0 @@-import type { BackendDetection } from '../../../shared/types'-import { defineStore } from 'dsh-tauri/client'--export const kernelStore = defineStore({- state: () => ({- backends: [] as BackendDetection[],- phase: 'idle' as 'idle' | 'loading' | 'ready' | 'error',- error: null as string | null,- }),-})diff --git a/packages/dsh-tauri-kernel/src/client/store/modules/native-model.ts b/packages/dsh-tauri-kernel/src/client/store/modules/native-model.tsdeleted file mode 100644index a17ff19d..00000000--- a/packages/dsh-tauri-kernel/src/client/store/modules/native-model.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { NativeModelEntry } from '../../types/kernel-model'-import { defineStore } from 'dsh-tauri/client'--export const nativeModel = defineStore({- state: () => ({ generation: 0, entries: {} as Record<string, NativeModelEntry | undefined> }),- actions: {- nextScope() {- return ++this.generation- },- open(entry: NativeModelEntry) {- this.entries[entry.sessionId] = entry- },- update(sessionId: string, scope: number, patch: Partial<NativeModelEntry>) {- const entry = this.entries[sessionId]- if (entry?.scope === scope)- this.entries[sessionId] = { ...entry, ...patch }- },- close(sessionId: string, scope: number) {- if (this.entries[sessionId]?.scope === scope)- delete this.entries[sessionId]- },- },-})diff --git a/packages/dsh-tauri-kernel/src/client/types/kernel-model.ts b/packages/dsh-tauri-kernel/src/client/types/kernel-model.tsdeleted file mode 100644index ffc872bc..00000000--- a/packages/dsh-tauri-kernel/src/client/types/kernel-model.ts+++ /dev/null@@ -1,53 +0,0 @@-import type { ModelCatalogFailure, ModelProviderGroup, ModelSelection } from '@deepseek-ai/dsh-api-session-controller/types'-import type { NativeModelDirectory, NativeTurnOptions } from '../../shared/native-model'-import type { KernelBinding } from '../../shared/types'--export interface OfficialModelSelectFace {- locked: boolean- available: boolean- directory: { subscribe: (listener: () => void) => () => void, getSnapshot: () => unknown }- load: () => void- select: (selection: ModelSelection) => Promise<unknown>-}--export interface NativeModelDirectoryState {- current: ModelSelection | null- retainedEffort?: string- routable: boolean | null- groups: readonly ModelProviderGroup[]- failures: readonly ModelCatalogFailure[]- status: 'idle' | 'loading' | 'ready' | 'selecting' | 'error'- pending: ModelSelection | null- error: string | null-}--export interface NativeModelEntry {- scope: number- sessionId: string- backend: KernelBinding['backend']- nativeSessionId: string- request: number- catalog: NativeModelDirectory | null- current: NativeTurnOptions- directory: NativeModelDirectoryState-}--export interface NativeModelScope {- sessionId: string- scope: number- active: () => boolean-}--export type NativeModelOutcome = { ok: true, value: undefined } | { ok: false, error: { code: string, message: string } }--export interface NativeModelActions {- canSelectNativeModel: () => boolean- createNativeModelDirectory: (sessionId: string, binding: KernelBinding, current: NativeTurnOptions) => {- subscribe: (listener: () => void) => () => void- getSnapshot: () => NativeModelDirectoryState- }- acquireNativeModel: (sessionId: string, binding: KernelBinding) => () => void- syncNativeModel: (sessionId: string, binding: KernelBinding, current: NativeTurnOptions) => void- loadNativeModels: (sessionId: string, binding: KernelBinding) => Promise<void>- selectNativeModel: (sessionId: string, binding: KernelBinding, selection: ModelSelection) => Promise<NativeModelOutcome | undefined>-}diff --git a/packages/dsh-tauri-kernel/src/host/apply.test.ts b/packages/dsh-tauri-kernel/src/host/apply.test.tsdeleted file mode 100644index e7132dd8..00000000--- a/packages/dsh-tauri-kernel/src/host/apply.test.ts+++ /dev/null@@ -1,244 +0,0 @@-import type { Agent } from '@deepseek-ai/dsh-agent'-import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'-import type { HostContext, NativeEntry, PlatformLoader } from './types'-import { Context } from '@deepseek-ai/cordis'-import * as llmModule from '@deepseek-ai/dsh-llm'-import * as sessionModule from '@deepseek-ai/dsh-session'-import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'-import { getServerContext } from 'dsh-h3/utils'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import * as zodModule from 'zod'-import { apply } from './apply'-import { resetRuntime, runtime } from './config/runtime'-import { server } from './server'--function deferred<T>() {- let resolve!: (value: T | PromiseLike<T>) => void- const promise = new Promise<T>((accept) => {- resolve = accept- })- return { promise, resolve }-}--let context: Context-let loader: PlatformLoader-let projections: SessionProjectionRegistry-let registered: Map<string, WebRoute>-let imports: ReturnType<typeof deferred<void>>-let importStarted: ReturnType<typeof deferred<void>>-let releases: Array<() => void>-let registerAdapter: ReturnType<typeof vi.fn>-let unregisterAdapter: ReturnType<typeof vi.fn>--beforeEach(async () => {- await resetRuntime()- context = new Context()- projections = new SessionProjectionRegistry(context)- registered = new Map()- releases = []- imports = deferred<void>()- importStarted = deferred<void>()- releases.push(() => imports.resolve())- unregisterAdapter = vi.fn()- registerAdapter = vi.fn(() => unregisterAdapter)- context.provide('webServer', {- register(route: WebRoute) {- if (registered.has(route.path))- throw new Error(`duplicate route: ${route.path}`)- registered.set(route.path, route)- return () => registered.delete(route.path)- },- } as unknown as HostContext['webServer'])- loader = {- async import(id) {- if (id === 'zod')- return zodModule- importStarted.resolve()- await imports.promise- if (id === '@deepseek-ai/dsh-llm')- return llmModule- if (id === '@deepseek-ai/dsh-session')- return sessionModule- throw new Error(`unexpected module: ${id}`)- },- unwrapExports: value => value,- }- context.provide('loader', loader as HostContext['loader'])- context.provide('llm', { registerAdapter } as unknown as HostContext['llm'])-})--afterEach(async () => {- for (const release of releases)- release()- await context.fiber.dispose()- await resetRuntime()- vi.restoreAllMocks()-})--function start() {- return context.plugin((ctx) => {- apply(ctx as HostContext)- })-}--async function ready() {- const fiber = start()- await importStarted.promise- imports.resolve()- await vi.waitFor(() => expect(registerAdapter).toHaveBeenCalledOnce())- return { fiber }-}--describe('owned bridge application lifecycle', () => {- it('holds projection registration until host Zod resolves and removes the late schema on unload', async () => {- const schemaImport = deferred<typeof zodModule>()- const schemaStarted = deferred<void>()- releases.push(() => schemaImport.resolve(zodModule))- const originalImport = loader.import.bind(loader)- loader.import = vi.fn(async (id) => {- if (id !== 'zod')- return originalImport(id)- schemaStarted.resolve()- return schemaImport.promise- })- const fiber = start()- await schemaStarted.promise- const official = sessionModule.Session.create(sessionModule.SessionId('schema-startup'))- expect(getServerContext(server)).toBe(fiber.ctx)- expect(projections.stateOf(official, 'bridgeKernel')).toBeUndefined()- expect(runtime.bindingSchema).toBeUndefined()- expect(runtime.optionsSchema).toBeUndefined()- expect(runtime.catalogSchema).toBeUndefined()- const unloading = fiber.dispose()- schemaImport.resolve(zodModule)- await unloading- expect(projections.snapshot(official).values).toEqual({})- expect(runtime.bindingSchema).toBeUndefined()- expect(runtime.optionsSchema).toBeUndefined()- expect(runtime.catalogSchema).toBeUndefined()- expect(registerAdapter).not.toHaveBeenCalled()- expect(registered.size).toBe(0)- expect(() => getServerContext(server)).toThrow('dsh-h3: service is not active')- }, 10_000)-- it('rolls back already registered schemas when a later host Zod import rejects', async () => {- const failure = new Error('official model schema import refused')- loader.import = vi.fn()- .mockResolvedValueOnce(zodModule)- .mockRejectedValueOnce(failure)- const fiber = start()- await vi.waitFor(() => expect(loader.import).toHaveBeenCalledTimes(2))- await vi.waitFor(() => expect(registered.size).toBe(0))- await fiber.dispose()- const official = sessionModule.Session.create(sessionModule.SessionId('schema-failure'))- expect(vi.mocked(loader.import).mock.calls).toEqual([['zod'], ['zod']])- expect(projections.snapshot(official).values).toEqual({})- expect(runtime.bindingSchema).toBeUndefined()- expect(runtime.optionsSchema).toBeUndefined()- expect(runtime.catalogSchema).toBeUndefined()- expect(registerAdapter).not.toHaveBeenCalled()- expect(runtime.ready).toBe(false)- expect(() => getServerContext(server)).toThrow('dsh-h3: service is not active')- }, 10_000)-- it('activates the real H3 service before awaited adapter registration', async () => {- const fiber = start()- await importStarted.promise- expect(getServerContext(server)).toBe(fiber.ctx)- expect([...registered.keys()].sort()).toEqual(['/api/tauri/bridge/backends', '/api/tauri/bridge/models', '/api/tauri/bridge/sessions'])- expect(projections.stateOf(sessionModule.Session.create(sessionModule.SessionId('startup')), 'bridgeKernel')?.binding).toBeNull()- expect(registerAdapter).not.toHaveBeenCalled()- expect(runtime.ready).toBe(false)- imports.resolve()- await vi.waitFor(() => expect(registerAdapter).toHaveBeenCalledOnce())- expect(registerAdapter.mock.calls[0]![0]).toEqual(['dsh-tauri-kernel'])- expect(registerAdapter.mock.calls[0]![1]).toBeInstanceOf(llmModule.LlmAdapter)- expect(runtime.ready).toBe(true)- expect(runtime.bindingSchema?.safeParse({ backend: 'codex', nativeSessionId: 'native-startup', sessionId: 'startup' }).success).toBe(true)- expect(runtime.optionsSchema?.safeParse({ model: null, reasoningEffort: null }).success).toBe(true)- expect(runtime.catalogSchema?.safeParse({ models: [] }).success).toBe(true)- await fiber.dispose()- expect(unregisterAdapter).toHaveBeenCalledOnce()- expect(runtime.ready).toBe(false)- expect(runtime.bindingSchema).toBeUndefined()- expect(runtime.optionsSchema).toBeUndefined()- expect(runtime.catalogSchema).toBeUndefined()- expect(registered.size).toBe(0)- expect(() => getServerContext(server)).toThrow('dsh-h3: service is not active')- }, 10_000)-- it('keeps the H3 service owned until official idle and native disposal drain', async () => {- const { fiber } = await ready()- const idle = deferred<void>()- const idleStarted = deferred<void>()- const nativeDrain = deferred<void>()- const nativeStarted = deferred<void>()- releases.push(() => idle.resolve(), () => nativeDrain.resolve())- const official = sessionModule.Session.create(sessionModule.SessionId('draining'))- const agent = {- id: official.id,- session: official,- cancel: vi.fn(),- whenIdle: vi.fn(() => {- idleStarted.resolve()- return idle.promise- }),- } as unknown as Agent- const nativeDispose = vi.fn(async () => {- expect(getServerContext(server)).toBe(fiber.ctx)- nativeStarted.resolve()- await nativeDrain.promise- expect(getServerContext(server)).toBe(fiber.ctx)- })- const entry: NativeEntry = {- agent,- binding: { backend: 'codex', nativeSessionId: 'native-draining', sessionId: official.id },- session: { id: 'native-draining', submit: vi.fn(), dispose: nativeDispose },- controller: new AbortController(),- }- runtime.sessions.set(agent.id, entry)- let disposed = false- const unloading = fiber.dispose().then(() => {- disposed = true- })- await idleStarted.promise- expect(agent.cancel).toHaveBeenCalledExactlyOnceWith({ kind: 'disposed' })- expect(disposed).toBe(false)- expect(getServerContext(server)).toBe(fiber.ctx)- expect(registered.size).toBe(3)- expect(nativeDispose).not.toHaveBeenCalled()- idle.resolve()- await nativeStarted.promise- expect(disposed).toBe(false)- expect(getServerContext(server)).toBe(fiber.ctx)- expect(unregisterAdapter).not.toHaveBeenCalled()- nativeDrain.resolve()- await unloading- expect(nativeDispose).toHaveBeenCalledOnce()- expect(agent.whenIdle).toHaveBeenCalledOnce()- expect(unregisterAdapter).toHaveBeenCalledOnce()- expect(runtime.sessions.size).toBe(0)- expect(registered.size).toBe(0)- expect(projections.stateOf(official, 'bridgeKernel')).toBeUndefined()- expect(() => getServerContext(server)).toThrow('dsh-h3: service is not active')- }, 10_000)-- it('unloads an in-flight module import without leaking routes or the late adapter', async () => {- const fiber = start()- await importStarted.promise- let disposed = false- const unloading = fiber.dispose().then(() => {- disposed = true- })- expect(getServerContext(server)).toBe(fiber.ctx)- expect(disposed).toBe(false)- imports.resolve()- await unloading- expect(registerAdapter).toHaveBeenCalledOnce()- expect(unregisterAdapter).toHaveBeenCalledOnce()- expect(runtime.ready).toBe(false)- expect(runtime.lifetime.signal.aborted).toBe(true)- expect(registered.size).toBe(0)- expect(() => getServerContext(server)).toThrow('dsh-h3: service is not active')- }, 10_000)-})diff --git a/packages/dsh-tauri-kernel/src/host/apply.ts b/packages/dsh-tauri-kernel/src/host/apply.tsdeleted file mode 100644index 5452315b..00000000--- a/packages/dsh-tauri-kernel/src/host/apply.ts+++ /dev/null@@ -1,37 +0,0 @@-import type { Config } from './config/options'-import type { HostContext } from './types'-import { PLUGIN_ID } from '../shared/constants'-import { runtime } from './config/runtime'-import { server } from './server'-import { adapter } from './service/adapter'-import { checkpoint } from './service/checkpoint'-import { identity } from './service/identity'-import { model } from './service/model'-import { session } from './service/session'-import { sink } from './service/sink'--export function apply(ctx: HostContext, config: Config = {}): void {- ctx.effect(async function* () {- runtime.lifetime = new AbortController()- yield server(ctx, config)- yield () => session.dispose()- yield await identity.register()- yield await model.register()- yield await checkpoint.register()- yield ctx.provide('nativeSessionBridge', { create: session.createInherited, prepare: session.prepare })- yield ctx.on('agent/pre-step', adapter.admit, { global: true, prepend: true })- yield ctx.on('agent/request', adapter.request, { global: true, prepend: true })- yield ctx.on('llm/stream', adapter.capture, { global: true, prepend: true })- yield ctx.on('tools/pre-execute', sink.admitTool, { global: true, prepend: true })- yield ctx.on('tools/execute', sink.executeTool, { global: true, prepend: true })- yield ctx.on('tools/post-execute', sink.finishTool, { global: true, prepend: true })- yield ctx.on('tools/result', sink.acceptTool, { global: true })- yield ctx.on('agent/turn-stopping', ({ agent, turn }) => session.finish(agent, turn), { global: true })- yield ctx.on('session/event', adapter.end, { global: true })- yield ctx.on('agent/disposed', ({ agent }) => {- void adapter.remove(agent).catch((error: unknown) => ctx.logger.warn('dsh-tauri-kernel: native session disposal failed', error))- }, { global: true })- yield await adapter.register()- yield () => session.dispose()- }, `${PLUGIN_ID}: official native adapter`)-}diff --git a/packages/dsh-tauri-kernel/src/host/backends/claude.test.ts b/packages/dsh-tauri-kernel/src/host/backends/claude.test.tsdeleted file mode 100644index 9f413607..00000000--- a/packages/dsh-tauri-kernel/src/host/backends/claude.test.ts+++ /dev/null@@ -1,1140 +0,0 @@-import type { Frame } from './process.fixture'-import type { NativeAttachments, NativePermission, NativeSession, NativeSessionOpenOptions } from './types'-import { spawn } from 'node:child_process'-import { createUserMessage } from '@deepseek-ai/dsh-llm'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { createClaudeSession } from './claude'-import { createSink, ProcessFixture } from './process.fixture'--vi.mock('node:child_process', () => ({ spawn: vi.fn() }))--const command = { file: 'C:/fixture/claude.exe', args: [], env: { PATH: 'C:/fixture/bin' } }-const storedId = '11111111-1111-4111-8111-111111111111'-const sessions: NativeSession[] = []-const initialization = { subtype: 'initialize', hooks: { SessionStart: [{ hookCallbackIds: ['dsh-native-session-identity'] }] } }--function claudeProcess(options: {- acknowledge?: boolean- useSystemInit?: boolean- useSnapshot?: boolean- mismatch?: boolean- forkId?: string- model?: string- models?: Frame[]- account?: Frame- capabilities?: string[]- intercept?: (frame: Frame, fixture: ProcessFixture) => boolean-} = {}) {- const useSnapshot = options.useSnapshot ?? !options.useSystemInit- let initializationCount = 0- const fixture = new ProcessFixture((frame) => {- if (options.intercept?.(frame, fixture))- return- if (frame.type === 'control_request') {- const request = frame.request as Frame- const response: Frame = {}- if (request.subtype === 'initialize') {- initializationCount++- const args = vi.mocked(spawn).mock.calls.at(-1)![1] as string[]- const nativeId = args.find(arg => arg.startsWith('--session-id=') || arg.startsWith('--resume='))!.split('=')[1]!- const acknowledgedId = options.mismatch ? 'different-native-session' : args.includes('--fork-session') ? options.forkId ?? '22222222-2222-4222-8222-222222222222' : nativeId- response.hooks_applied = true- response.session_state = 'idle'- if (options.acknowledge !== false && !useSnapshot) {- if (options.useSystemInit)- fixture.send({ type: 'system', subtype: 'init', session_id: acknowledgedId, model: options.model, capabilities: options.capabilities ?? [] })- else- response.session_id = acknowledgedId- }- response.capabilities = options.capabilities ?? []- if (options.models)- response.models = options.models- if (options.account)- response.account = options.account- fixture.send({ type: 'control_response', response: { subtype: 'success', request_id: frame.request_id, response } })- if (useSnapshot && options.acknowledge !== false && initializationCount > 1)- fixture.send({ type: 'system', subtype: 'background_tasks_changed', tasks: [], uuid: 'native-snapshot', session_id: acknowledgedId })- return- }- fixture.send({ type: 'control_response', response: { subtype: 'success', request_id: frame.request_id, response } })- }- })- vi.mocked(spawn).mockReturnValue(fixture.child)- return fixture-}--async function open(nativeId: string | null = null, sink = createSink(), options?: NativeSessionOpenOptions, attachments?: NativeAttachments) {- const session = await createClaudeSession(command, 'C:/fixture/workspace', nativeId, sink, new AbortController().signal, options, attachments)- sessions.push(session)- return session-}--/** Official image block; the attachment brand is opaque to this package. */-const image = (attachment: { id: string, mediaType: string, bytes: number }) => createUserMessage({ source: { kind: 'user' }, content: [{ type: 'image', attachment } as never] })--const modelInfo = (value: string, levels: string[] = ['low', 'high']) => ({ value, displayName: `Native ${value}`, description: `${value} description`, supportsEffort: true, supportedEffortLevels: levels })-const user = () => createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'inspect the workspace' }] })-const result = (fixture: ProcessFixture, id: string, extra: Frame = {}) => fixture.send({ type: 'result', subtype: 'success', is_error: false, session_id: id, result: 'final text, not another assistant message', ...extra })-const stream = (fixture: ProcessFixture, event: Frame, extra: Frame = {}) => fixture.send({ type: 'stream_event', event, parent_tool_use_id: null, ...extra })--beforeEach(() => vi.mocked(spawn).mockReset())-afterEach(async () => {- for (const session of sessions.splice(0))- await session.dispose()- vi.restoreAllMocks()- vi.useRealTimers()-})--describe('claude native stream-json control contract', () => {- it('requires a native id acknowledgement before returning a newly reserved session', async () => {- const fixture = claudeProcess({ useSnapshot: false })- const session = await open()- expect(session.id).toMatch(/^[\da-f-]{36}$/)- const args = vi.mocked(spawn).mock.calls[0]![1]- expect(args).toEqual([- '--print',- '--verbose',- '--input-format',- 'stream-json',- '--output-format',- 'stream-json',- '--include-partial-messages',- '--permission-prompt-tool',- 'stdio',- '--allow-dangerously-skip-permissions',- '--settings',- '{"useAutoModeDuringPlan":false}',- `--session-id=${session.id}`,- ])- expect(spawn).toHaveBeenCalledWith('C:/fixture/claude.exe', args, {- cwd: 'C:/fixture/workspace',- env: { PATH: 'C:/fixture/bin', CLAUDE_CODE_SDK_READS_SESSION_STATE: '1' },- shell: false,- windowsHide: true,- stdio: ['pipe', 'pipe', 'pipe'],- })- expect(fixture.frames).toEqual([{ type: 'control_request', request_id: expect.any(String), request: initialization }])- })-- it.each(['create', 'resume', 'fork'] as const)('opens %s from the native repeated-initialize snapshot without a bootstrap prompt', async (mode) => {- vi.useFakeTimers()- const fixture = claudeProcess({ useSnapshot: true, models: [modelInfo('native-model')] })- const sink = createSink()- const opening = open(mode === 'resume' ? storedId : null, sink, mode === 'fork' ? { forkFrom: storedId } : undefined)- await Promise.all([- vi.advanceTimersByTimeAsync(60_000),- expect(opening).resolves.toMatchObject({ id: mode === 'resume' ? storedId : expect.any(String) }),- ])- const controls = [- { type: 'control_request', request_id: expect.any(String), request: initialization },- { type: 'control_request', request_id: expect.any(String), request: initialization },- ]- expect(fixture.frames).toEqual(controls)- const session = await opening- if (mode === 'fork')- expect(session.id).toBe('22222222-2222-4222-8222-222222222222')- const args = vi.mocked(spawn).mock.calls[0]![1] as string[]- expect(args).toContain(mode === 'create' ? `--session-id=${session.id}` : `--resume=${storedId}`)- expect(args.includes('--fork-session')).toBe(mode === 'fork')- expect(await session.models!(new AbortController().signal)).toEqual({ models: [- { id: 'native-model', name: 'Native native-model', description: 'native-model description', reasoning: { efforts: [{ id: 'low', name: 'low' }, { id: 'high', name: 'high' }] } },- ] })- expect(sink.text).not.toHaveBeenCalled()- expect(sink.assistant).not.toHaveBeenCalled()- const submitted = session.submit([user()], new AbortController().signal)- result(fixture, session.id)- await submitted- expect(fixture.frames).toEqual([- ...controls,- { type: 'user', session_id: session.id, uuid: expect.any(String), parent_tool_use_id: null, message: { role: 'user', content: [{ type: 'text', text: 'inspect the workspace' }] } },- ])- expect(fixture.kill).not.toHaveBeenCalled()- expect(spawn).toHaveBeenCalledTimes(1)- })-- it('refuses initialize without an id acknowledgement instead of binding a reserved UUID', async () => {- vi.useFakeTimers()- const fixture = claudeProcess({ acknowledge: false })- const rejected = expect(open()).rejects.toMatchObject({ code: 'BRIDGE_NATIVE_BIND_UNCONFIRMED' })- await vi.advanceTimersByTimeAsync(60_000)- await rejected- expect(fixture.frames).toEqual([- { type: 'control_request', request_id: expect.any(String), request: initialization },- { type: 'control_request', request_id: expect.any(String), request: initialization },- ])- expect(fixture.stdin.end).toHaveBeenCalledTimes(1)- expect(fixture.kill).not.toHaveBeenCalled()- })-- it('waits for the repeated-initialize snapshot after its control acknowledgement', async () => {- const fixture = claudeProcess({ acknowledge: false })- const repeated = fixture.next(frame => frame.type === 'control_request' && fixture.frames.length === 2)- const opening = open(storedId)- const settled = vi.fn()- void opening.then(settled, settled)- await repeated- expect(settled).not.toHaveBeenCalled()- expect(fixture.frames).toEqual([- { type: 'control_request', request_id: expect.any(String), request: initialization },- { type: 'control_request', request_id: expect.any(String), request: initialization },- ])- fixture.send({ type: 'system', subtype: 'background_tasks_changed', tasks: [], uuid: 'late-snapshot', session_id: storedId })- const session = await opening- expect(session.id).toBe(storedId)- expect(settled).toHaveBeenCalledTimes(1)- })-- it.each(['resume', 'fork', 'missing-id'] as const)('refuses the %s identity from the repeated-initialize snapshot', async (mode) => {- const fixture = claudeProcess({ acknowledge: false })- const repeated = fixture.next(frame => frame.type === 'control_request' && fixture.frames.length === 2)- const opening = open(mode === 'fork' ? null : storedId, createSink(), mode === 'fork' ? { forkFrom: storedId } : undefined)- const rejected = expect(opening).rejects.toMatchObject({ code: mode === 'resume' ? 'BRIDGE_RESUME_MISMATCH' : mode === 'fork' ? 'BRIDGE_FORK_MISMATCH' : 'BRIDGE_PROTOCOL' })- await repeated- fixture.send({ type: 'system', subtype: 'background_tasks_changed', tasks: [], uuid: 'invalid-snapshot', ...mode === 'missing-id' ? {} : { session_id: mode === 'fork' ? storedId : 'wrong-native' } })- await rejected- expect(fixture.frames).toEqual([- { type: 'control_request', request_id: expect.any(String), request: initialization },- { type: 'control_request', request_id: expect.any(String), request: initialization },- ])- expect(spawn).toHaveBeenCalledTimes(1)- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('refuses a fatal startup result following a matching snapshot in the same native output chunk', async () => {- const fixture = claudeProcess({ intercept: (frame, child) => {- if (frame.type !== 'control_request' || child.frames.length !== 2)- return false- child.writeChunk([- { type: 'control_response', response: { subtype: 'success', request_id: frame.request_id, response: { hooks_applied: true, session_state: 'idle' } } },- { type: 'system', subtype: 'background_tasks_changed', tasks: [], uuid: 'failed-snapshot', session_id: storedId },- { type: 'result', subtype: 'error_during_execution', is_error: true, session_id: storedId, errors: ['Native startup refused'] },- ].map(message => `${JSON.stringify(message)}\n`).join(''))- return true- } })- await expect(open(storedId)).rejects.toMatchObject({ code: 'BRIDGE_NATIVE_TURN', message: '["Native startup refused"]' })- expect(fixture.frames).toEqual([- { type: 'control_request', request_id: expect.any(String), request: initialization },- { type: 'control_request', request_id: expect.any(String), request: initialization },- ])- expect(spawn).toHaveBeenCalledTimes(1)- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('propagates a repeated-initialize control error without a prompt or a fresh-session fallback', async () => {- const fixture = claudeProcess({ intercept: (frame, child) => {- if (frame.type !== 'control_request' || child.frames.length !== 2)- return false- child.send({ type: 'control_response', response: { subtype: 'error', request_id: frame.request_id, error: 'Cannot refresh native state' } })- return true- } })- await expect(open(storedId)).rejects.toMatchObject({ code: 'BRIDGE_NATIVE_REQUEST', message: 'Cannot refresh native state' })- expect(fixture.frames).toEqual([- { type: 'control_request', request_id: expect.any(String), request: initialization },- { type: 'control_request', request_id: expect.any(String), request: initialization },- ])- expect(spawn).toHaveBeenCalledTimes(1)- expect(fixture.stdin.end).toHaveBeenCalledTimes(1)- })-- it.each(['pending-control', 'pending-snapshot'] as const)('cancels the %s refresh before accepting a native binding', async (phase) => {- const fixture = claudeProcess({ acknowledge: false, intercept: (frame, child) => phase === 'pending-control' && frame.type === 'control_request' && child.frames.length === 2 })- const repeated = fixture.next(frame => frame.type === 'control_request' && fixture.frames.length === 2)- const controller = new AbortController()- const rejected = expect(createClaudeSession(command, 'C:/fixture/workspace', storedId, createSink(), controller.signal)).rejects.toThrow('cancel native refresh')- await repeated- controller.abort(new Error('cancel native refresh'))- await rejected- expect(fixture.frames).toEqual([- { type: 'control_request', request_id: expect.any(String), request: initialization },- { type: 'control_request', request_id: expect.any(String), request: initialization },- ])- expect(fixture.stdin.end).toHaveBeenCalledTimes(1)- expect(fixture.kill).not.toHaveBeenCalled()- })-- it('bounds the total startup deadline while the repeated initialize control is unanswered', async () => {- vi.useFakeTimers()- const fixture = claudeProcess({ intercept: frame => frame.type === 'control_request' })- const opening = open(storedId)- const rejected = expect(opening).rejects.toMatchObject({ code: 'BRIDGE_NATIVE_BIND_UNCONFIRMED' })- const settled = vi.fn()- void opening.then(settled, settled)- await vi.advanceTimersByTimeAsync(30_000)- const repeated = fixture.next(frame => frame.type === 'control_request' && fixture.frames.length === 2)- fixture.send({ type: 'control_response', response: { subtype: 'success', request_id: fixture.frames[0]!.request_id, response: { hooks_applied: true, session_state: 'idle' } } })- await repeated- await vi.advanceTimersByTimeAsync(29_999)- expect(settled).not.toHaveBeenCalled()- await vi.advanceTimersByTimeAsync(1)- expect(settled).toHaveBeenCalledTimes(1)- await rejected- expect(fixture.frames).toEqual([- { type: 'control_request', request_id: expect.any(String), request: initialization },- { type: 'control_request', request_id: expect.any(String), request: initialization },- ])- expect(fixture.stdin.end).toHaveBeenCalledTimes(1)- expect(fixture.kill).not.toHaveBeenCalled()- })-- it('accepts a matching system/init before the initialize response as native acknowledgement', async () => {- const fixture = claudeProcess({ useSystemInit: true })- const session = await open(storedId)- expect(session.id).toBe(storedId)- expect(vi.mocked(spawn).mock.calls[0]![1]).toContain(`--resume=${storedId}`)- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- })-- it('waits for a real SessionStart hook after initialize and replies without injecting prompt context', async () => {- const fixture = claudeProcess({ acknowledge: false })- const opening = open(storedId)- const settled = vi.fn()- void opening.then(settled, settled)- await Promise.resolve()- await Promise.resolve()- expect(settled).not.toHaveBeenCalled()- const reply = fixture.next(frame => frame.type === 'control_response')- fixture.send({ type: 'control_request', request_id: 'native-session-start', request: { subtype: 'hook_callback', callback_id: 'dsh-native-session-identity', input: { hook_event_name: 'SessionStart', source: 'resume', session_id: storedId, cwd: 'C:/fixture/workspace' } } })- expect(await reply).toEqual({ type: 'control_response', response: { subtype: 'success', request_id: 'native-session-start', response: {} } })- const session = await opening- expect(session.id).toBe(storedId)- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- })-- it('fails closed when SessionStart reports a different native identity', async () => {- const fixture = claudeProcess({ acknowledge: false })- const rejected = expect(open(storedId)).rejects.toMatchObject({ code: 'BRIDGE_RESUME_MISMATCH' })- fixture.send({ type: 'control_request', request_id: 'wrong-session-start', request: { subtype: 'hook_callback', callback_id: 'dsh-native-session-identity', input: { hook_event_name: 'SessionStart', source: 'resume', session_id: 'replacement-native' } } })- await rejected- expect(spawn).toHaveBeenCalledTimes(1)- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- })-- it('releases a cancelled preprompt native identity wait without accepting a reservation', async () => {- const fixture = claudeProcess({ acknowledge: false })- const signal = new AbortController()- const rejected = expect(createClaudeSession(command, 'C:/fixture/workspace', null, createSink(), signal.signal)).rejects.toThrow('cancel native creation')- signal.abort(new Error('cancel native creation'))- await rejected- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- expect(fixture.stdin.end).toHaveBeenCalledTimes(1)- })-- it('rejects a resume identity mismatch without retrying with a new native session', async () => {- const fixture = claudeProcess({ mismatch: true })- await expect(open(storedId)).rejects.toMatchObject({ code: 'BRIDGE_RESUME_MISMATCH' })- expect(spawn).toHaveBeenCalledTimes(1)- expect(vi.mocked(spawn).mock.calls[0]![1]).toContain(`--resume=${storedId}`)- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- })-- it.each([- { mode: 'resume', fatalId: storedId },- { mode: 'resume', fatalId: 'error-only-native' },- { mode: 'fork', fatalId: storedId },- { mode: 'fork', fatalId: 'error-only-child' },- ] as const)('rejects $mode startup failure before confirming its error-only identity $fatalId', async ({ mode, fatalId }) => {- const fixture = claudeProcess({ intercept: (frame, child) => {- if (frame.type !== 'control_request')- return false- child.send({ type: 'result', subtype: 'error_during_execution', is_error: true, session_id: fatalId, errors: ['No conversation found'] })- return true- } })- await expect(open(mode === 'resume' ? storedId : null, createSink(), mode === 'fork' ? { forkFrom: storedId } : undefined)).rejects.toMatchObject({ code: 'BRIDGE_NATIVE_TURN', message: '["No conversation found"]' })- expect(fixture.frames).toEqual([{ type: 'control_request', request_id: expect.any(String), request: initialization }])- expect(spawn).toHaveBeenCalledTimes(1)- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('forks by official resume and fork-session flags and binds only a new acknowledgement', async () => {- const fixture = claudeProcess({ forkId: 'child-session' })- const session = await open(null, createSink(), { forkFrom: storedId })- expect(session.id).toBe('child-session')- const args = vi.mocked(spawn).mock.calls[0]![1] as string[]- expect(args).toContain(`--resume=${storedId}`)- expect(args).toContain('--fork-session')- expect(args.some(arg => arg.startsWith('--session-id='))).toBe(false)- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- })-- it('accepts a real fork SessionStart hook but rejects later identity replacement', async () => {- const fixture = claudeProcess({ acknowledge: false })- const opening = open(null, createSink(), { forkFrom: storedId })- fixture.send({ type: 'control_request', request_id: 'fork-hook', request: { subtype: 'hook_callback', callback_id: 'dsh-native-session-identity', input: { hook_event_name: 'SessionStart', source: 'fork', session_id: 'forked-native', model: 'baseline' } } })- const session = await opening- expect(session.id).toBe('forked-native')- const submitted = session.submit([user()], new AbortController().signal)- const rejected = expect(submitted).rejects.toMatchObject({ code: 'BRIDGE_RESUME_MISMATCH' })- result(fixture, storedId)- await rejected- expect(session.id).toBe('forked-native')- })-- it('refuses a fork that acknowledges only the source id with no fresh-session fallback', async () => {- const fixture = claudeProcess({ forkId: storedId })- await expect(open(null, createSink(), { forkFrom: storedId })).rejects.toMatchObject({ code: 'BRIDGE_FORK_MISMATCH' })- expect(spawn).toHaveBeenCalledTimes(1)- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- })-- it('rejects combined resume and fork options without spawning', async () => {- await expect(open(storedId, createSink(), { forkFrom: 'source' })).rejects.toMatchObject({ code: 'BRIDGE_FORK_INVALID' })- expect(spawn).not.toHaveBeenCalled()- })-- it('uses initialize supported models and only advertised effort levels without leaking account data', async () => {- const fixture = claudeProcess({- useSystemInit: true,- model: 'baseline',- models: [modelInfo('baseline', ['medium', 'xhigh']), { value: 'custom', displayName: 'Custom provider', description: 'custom description', supportsEffort: true }],- account: { email: 'private-fixture', apiKey: 'secret-fixture' },- })- const session = await open()- const catalog = await session.models!(new AbortController().signal)- expect(catalog).toEqual({ defaultModel: 'baseline', models: [- { id: 'baseline', name: 'Native baseline', description: 'baseline description', reasoning: { efforts: [{ id: 'medium', name: 'medium' }, { id: 'xhigh', name: 'xhigh' }] } },- { id: 'custom', name: 'Custom provider', description: 'custom description' },- ] })- expect(JSON.stringify(catalog)).not.toMatch(/private-fixture|secret-fixture/)- expect(fixture.frames).toHaveLength(1)- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- })-- it('keeps each Claude alias once instead of exposing its resolved model id as a duplicate row', async () => {- const fixture = claudeProcess({- models: [- { value: 'default', resolvedModel: 'claude-opus-5-5', displayName: 'Default (recommended)', description: 'Use the default model (currently Opus 5.5)', supportsEffort: true, supportedEffortLevels: ['high'] },- { value: 'opus', resolvedModel: 'claude-opus-5-5', displayName: 'Opus', description: 'Opus 5.5', supportsEffort: true, supportedEffortLevels: ['high'] },- { value: 'fable', resolvedModel: 'claude-fable-5-1', displayName: 'Fable', supportsEffort: true, supportedEffortLevels: ['high'] },- { value: 'sonnet', resolvedModel: 'claude-sonnet-5-5', displayName: 'Sonnet', supportsEffort: true, supportedEffortLevels: ['high'] },- { value: 'haiku', resolvedModel: 'claude-haiku-5-5', displayName: 'Haiku', supportsEffort: true, supportedEffortLevels: ['high'] },- ],- })- const session = await open(storedId)- const catalog = await session.models!(new AbortController().signal)- expect(catalog.models.map(model => ({ id: model.id, name: model.name }))).toEqual([- { id: 'default', name: 'Default (recommended)' },- { id: 'opus', name: 'Opus' },- { id: 'fable', name: 'Fable' },- { id: 'sonnet', name: 'Sonnet' },- { id: 'haiku', name: 'Haiku' },- ])- expect(catalog.defaultModel).toBe('default')- expect(catalog.models.some(model => model.id.startsWith('claude-'))).toBe(false)- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- })-- it('reports absent discovery as unsupported and never guesses effort levels', async () => {- const fixture = claudeProcess()- const session = await open()- await expect(session.models!(new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_MODEL_DISCOVERY_UNAVAILABLE' })- expect(fixture.frames).toHaveLength(2)- })-- it('awaits set_model and apply_flag_settings acknowledgements before the one snapshotted user frame', async () => {- const fixture = claudeProcess({- models: [modelInfo('chosen')],- intercept: frame => frame.type === 'control_request' && ['set_model', 'apply_flag_settings'].includes(String((frame.request as Frame).subtype)),- })- const session = await open()- const selection = { model: 'chosen', reasoningEffort: 'high' }- const setModel = fixture.next(frame => frame.type === 'control_request' && (frame.request as Frame).subtype === 'set_model')- const submitted = session.submit([user()], new AbortController().signal, selection)- selection.model = 'unadvertised'- selection.reasoningEffort = 'unadvertised'- const modelRequest = await setModel- expect(modelRequest.request).toEqual({ subtype: 'set_model', model: 'chosen' })- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- const setEffort = fixture.next(frame => frame.type === 'control_request' && (frame.request as Frame).subtype === 'apply_flag_settings')- fixture.send({ type: 'control_response', response: { subtype: 'success', request_id: modelRequest.request_id, response: {} } })- const effortRequest = await setEffort- expect(effortRequest.request).toEqual({ subtype: 'apply_flag_settings', settings: { effortLevel: 'high' } })- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- const input = fixture.next(frame => frame.type === 'user')- fixture.send({ type: 'control_response', response: { subtype: 'success', request_id: effortRequest.request_id, response: {} } })- expect(await input).toMatchObject({ type: 'user', session_id: session.id })- result(fixture, session.id)- await submitted- expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(1)- expect(spawn).toHaveBeenCalledTimes(1)- })-- it('retains native defaults on the first null selection and explicitly restores public defaults after overrides', async () => {- const fixture = claudeProcess({ models: [modelInfo('chosen')] })- const session = await open()- const signal = new AbortController().signal- const first = session.submit([user()], signal, { model: null, reasoningEffort: null })- result(fixture, session.id)- await first- expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([initialization, initialization])- const changedInput = fixture.next(frame => frame.type === 'user')- const changed = session.submit([user()], signal, { model: 'chosen', reasoningEffort: 'high' })- await changedInput- result(fixture, session.id)- await changed- const resetInput = fixture.next(frame => frame.type === 'user')- const reset = session.submit([user()], signal, { model: null, reasoningEffort: null })- await resetInput- result(fixture, session.id)- await reset- expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([- initialization,- initialization,- { subtype: 'set_model', model: 'chosen' },- { subtype: 'apply_flag_settings', settings: { effortLevel: 'high' } },- { subtype: 'set_model', model: null },- { subtype: 'apply_flag_settings', settings: { effortLevel: null } },- ])- })-- it.each(['resume', 'fork'] as const)('clears model and effort flags on an explicit reset after an override following %s', async (mode) => {- const fixture = claudeProcess({ useSystemInit: true, model: 'persisted-override', models: [modelInfo('chosen')] })- const session = await open(mode === 'resume' ? storedId : null, createSink(), mode === 'fork' ? { forkFrom: storedId } : undefined)- const signal = new AbortController().signal- const first = fixture.next(frame => frame.type === 'user')- const inherited = session.submit([user()], signal, { model: null, reasoningEffort: null })- await first- result(fixture, session.id)- await inherited- expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([initialization])- const changed = fixture.next(frame => frame.type === 'user')- const override = session.submit([user()], signal, { model: 'chosen', reasoningEffort: 'high' })- await changed- result(fixture, session.id)- await override- const reset = fixture.next(frame => frame.type === 'user')- const restored = session.submit([user()], signal, { model: null, reasoningEffort: null })- await reset- result(fixture, session.id)- await restored- expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([- initialization,- { subtype: 'set_model', model: 'chosen' },- { subtype: 'apply_flag_settings', settings: { effortLevel: 'high' } },- { subtype: 'set_model', model: null },- { subtype: 'apply_flag_settings', settings: { effortLevel: null } },- ])- expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(3)- expect(spawn).toHaveBeenCalledTimes(1)- })-- it('restores model-default effort when a fresh selection changes only the model', async () => {- const fixture = claudeProcess({ models: [modelInfo('chosen')] })- const session = await open()- const input = fixture.next(frame => frame.type === 'user')- const submitted = session.submit([user()], new AbortController().signal, { model: 'chosen', reasoningEffort: null })- await input- result(fixture, session.id)- await submitted- expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([- initialization,- initialization,- { subtype: 'set_model', model: 'chosen' },- { subtype: 'apply_flag_settings', settings: { effortLevel: null } },- ])- })-- it('refuses default-model effort validation against a resumed persisted model', async () => {- const fixture = claudeProcess({- useSystemInit: true,- model: 'persisted-override',- models: [modelInfo('persisted-override')],- intercept: (frame, child) => {- if (frame.type !== 'user')- return false- result(child, storedId)- return true- },- })- const session = await open(storedId)- expect((await session.models!(new AbortController().signal)).defaultModel).toBe('persisted-override')- await expect(session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: 'high' })).rejects.toMatchObject({ code: 'BRIDGE_DEFAULT_UNAVAILABLE' })- expect(fixture.frames).toHaveLength(1)- expect(session.id).toBe(storedId)- })-- it('validates default-model effort only from fresh SessionStart model metadata', async () => {- const fixture = claudeProcess({ acknowledge: false, models: [modelInfo('baseline', ['high'])] })- const opening = open()- const args = vi.mocked(spawn).mock.calls[0]![1] as string[]- const nativeId = args.find(arg => arg.startsWith('--session-id='))!.split('=')[1]!- fixture.send({ type: 'control_request', request_id: 'baseline-hook', request: { subtype: 'hook_callback', callback_id: 'dsh-native-session-identity', input: { hook_event_name: 'SessionStart', source: 'startup', session_id: nativeId, model: 'baseline' } } })- const session = await opening- const input = fixture.next(frame => frame.type === 'user')- const submitted = session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: 'high' })- await input- result(fixture, session.id)- await submitted- expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([initialization, { subtype: 'apply_flag_settings', settings: { effortLevel: 'high' } }])- })-- it.each(['with-reset', 'after-reset'] as const)('refuses unprovable CLI-default effort %s when startup settings selected another model', async (phase) => {- const cliDefault = 'different-cli-default'- let nativeModel = 'configured-startup'- const usedModels: string[] = []- const fixture = claudeProcess({- useSystemInit: true,- model: 'configured-startup',- models: [modelInfo('configured-startup', ['high']), modelInfo('chosen', ['high']), modelInfo(cliDefault, ['low'])],- intercept: (frame, child) => {- if (frame.type === 'control_request') {- const request = frame.request as Frame- if (request.subtype === 'set_model')- nativeModel = typeof request.model === 'string' ? request.model : cliDefault- }- if (frame.type !== 'user')- return false- usedModels.push(nativeModel)- result(child, String(frame.session_id))- return true- },- })- const session = await open()- const signal = new AbortController().signal- await session.submit([user()], signal, { model: 'chosen', reasoningEffort: 'high' })- if (phase === 'after-reset') {- await session.submit([user()], signal, { model: null, reasoningEffort: null })- expect(nativeModel).toBe(cliDefault)- }- const before = fixture.frames.length- await expect(session.submit([user()], signal, { model: null, reasoningEffort: 'high' })).rejects.toMatchObject({ code: 'BRIDGE_DEFAULT_UNAVAILABLE' })- expect(fixture.frames).toHaveLength(before)- if (phase === 'after-reset')- expect((await session.models!(signal)).defaultModel).toBe('configured-startup')- expect(usedModels).toEqual(phase === 'after-reset' ? ['chosen', cliDefault] : ['chosen'])- await session.submit([user()], signal, { model: cliDefault, reasoningEffort: 'low' })- expect(nativeModel).toBe(cliDefault)- expect(fixture.frames.at(-1)).toMatchObject({ type: 'user', session_id: session.id })- expect(spawn).toHaveBeenCalledTimes(1)- })-- it('rejects unadvertised effort before either control or user input', async () => {- const fixture = claudeProcess({ models: [{ value: 'custom', displayName: 'Custom', supportsEffort: true }] })- const session = await open()- await expect(session.submit([user()], new AbortController().signal, { model: 'custom', reasoningEffort: 'high' })).rejects.toMatchObject({ code: 'BRIDGE_EFFORT_UNSUPPORTED' })- expect(fixture.frames).toHaveLength(2)- expect(session.id).toMatch(/^[\da-f-]{36}$/)- })-- it('fails closed on a rejected selection control and never sends a prompt', async () => {- const fixture = claudeProcess({ models: [modelInfo('chosen')], intercept: (frame, child) => {- if (frame.type !== 'control_request' || (frame.request as Frame).subtype !== 'set_model')- return false- child.send({ type: 'control_response', response: { subtype: 'error', request_id: frame.request_id, error: 'Unsupported set_model capability' } })- return true- } })- const session = await open()- await expect(session.submit([user()], new AbortController().signal, { model: 'chosen', reasoningEffort: null })).rejects.toMatchObject({ code: 'BRIDGE_NATIVE_REQUEST', message: 'Unsupported set_model capability' })- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('guards concurrent submissions and aborts an unacknowledged model control without submitting input', async () => {- const fixture = claudeProcess({ models: [modelInfo('chosen')], intercept: frame => frame.type === 'control_request' && (frame.request as Frame).subtype === 'set_model' })- const session = await open()- const signal = new AbortController()- const pending = fixture.next(frame => frame.type === 'control_request' && (frame.request as Frame).subtype === 'set_model')- const submitted = session.submit([user()], signal.signal, { model: 'chosen', reasoningEffort: null })- const rejected = expect(submitted).rejects.toThrow('cancel selection')- await pending- await expect(session.submit([user()], new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_BUSY' })- signal.abort(new Error('cancel selection'))- await rejected- expect(fixture.frames.some(frame => frame.type === 'user' || (frame.type === 'control_request' && (frame.request as Frame).subtype === 'interrupt'))).toBe(false)- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it.each(['resume', 'fork'] as const)('preserves inherited native settings on the first null preference after %s without model discovery', async (mode) => {- const fixture = claudeProcess({ useSystemInit: true, model: 'inherited-native-model', intercept: (frame, child) => {- if (frame.type !== 'user')- return false- result(child, String(frame.session_id))- return true- } })- const session = await open(mode === 'resume' ? storedId : null, createSink(), mode === 'fork' ? { forkFrom: storedId } : undefined)- await session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: null })- expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([initialization])- expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(1)- expect(spawn).toHaveBeenCalledOnce()- })-- it('keeps live and authoritative block identities while suppressing a duplicate final frame', async () => {- const fixture = claudeProcess()- const sink = createSink()- const session = await open(null, sink)- const submitted = session.submit([user()], new AbortController().signal)- expect(fixture.frames.at(-1)).toMatchObject({ type: 'user', session_id: session.id, parent_tool_use_id: null, message: { role: 'user', content: [{ type: 'text', text: 'inspect the workspace' }] } })- stream(fixture, { type: 'message_start', message: { id: 'msg-1' } })- stream(fixture, { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '' } })- stream(fixture, { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: 'inspect first' } })- const thinking = { type: 'assistant', uuid: 'final-thinking', session_id: session.id, message: { id: 'msg-1', content: [{ type: 'thinking', thinking: 'inspect first' }] } }- fixture.send(thinking)- fixture.send(thinking)- stream(fixture, { type: 'content_block_start', index: 1, content_block: { type: 'text', text: '' } })- stream(fixture, { type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: 'hello' } })- fixture.send({ type: 'assistant', uuid: 'final-text', session_id: session.id, message: { id: 'msg-1', content: [{ type: 'text', text: 'hello' }] } })- stream(fixture, { type: 'message_stop' })- result(fixture, session.id)- await submitted- expect(sink.thinking.mock.calls).toEqual([['msg-1:block:0', 'inspect first']])- expect(sink.text.mock.calls).toEqual([['msg-1:block:1', 'hello']])- expect(sink.assistant.mock.calls).toEqual([- ['msg-1:block:0', [{ type: 'thinking', text: 'inspect first' }]],- ['msg-1:block:1', [{ type: 'text', text: 'hello' }]],- ])- })-- it('keeps repeated native message ids aligned with their individual streamed block indices', async () => {- const fixture = claudeProcess()- const sink = createSink()- const session = await open(null, sink)- const submitted = session.submit([user()], new AbortController().signal)- stream(fixture, { type: 'message_start', message: { id: 'msg-2' } })- for (const index of [0, 1]) {- stream(fixture, { type: 'content_block_start', index, content_block: { type: 'text', text: '' } })- stream(fixture, { type: 'content_block_delta', index, delta: { type: 'text_delta', text: 'identical text' } })- fixture.send({ type: 'assistant', uuid: `frame-${index}`, session_id: session.id, message: { id: 'msg-2', content: [{ type: 'text', text: 'identical text' }] } })- }- result(fixture, session.id)- await submitted- expect(sink.assistant.mock.calls).toEqual([- ['msg-2:block:0', [{ type: 'text', text: 'identical text' }]],- ['msg-2:block:1', [{ type: 'text', text: 'identical text' }]],- ])- })-- it('emits aggregate assistant tool blocks synchronously as separate presented calls', async () => {- const fixture = claudeProcess()- const sink = createSink()- const order: string[] = []- const consumed = Promise.withResolvers<string[]>()- sink.assistant.mockImplementation((id) => {- order.push(`assistant:${id}`)- if (id === 'msg-aggregate:block:0')- void Promise.resolve().then(() => consumed.resolve([...order]))- })- sink.toolStart.mockImplementation(id => order.push(`start:${id}`))- const session = await open(null, sink)- const submitted = session.submit([user()], new AbortController().signal)- const settled = vi.fn()- void submitted.then(settled, settled)- try {- fixture.send({ type: 'assistant', uuid: 'aggregate-tools', session_id: session.id, message: { id: 'msg-aggregate', content: [- { type: 'tool_use', id: 'aggregate-1', name: 'Read', input: { file_path: 'first.ts' } },- { type: 'tool_use', id: 'aggregate-2', name: 'Read', input: { file_path: 'second.ts' } },- ] } })- const expectedOrder = ['assistant:msg-aggregate:block:0', 'start:aggregate-1', 'assistant:msg-aggregate:block:1', 'start:aggregate-2']- expect(order).toEqual(expectedOrder)- expect(await consumed.promise).toEqual(expectedOrder)- expect(sink.assistant.mock.calls).toEqual([- ['msg-aggregate:block:0', [{ type: 'tool-call', id: 'aggregate-1', name: 'Read', arguments: '{"file_path":"first.ts"}' }]],- ['msg-aggregate:block:1', [{ type: 'tool-call', id: 'aggregate-2', name: 'Read', arguments: '{"file_path":"second.ts"}' }]],- ])- fixture.send({ type: 'user', message: { role: 'user', content: [- { type: 'tool_result', tool_use_id: 'aggregate-2', content: 'second output' },- { type: 'tool_result', tool_use_id: 'aggregate-1', content: 'first output' },- ] } })- }- finally {- result(fixture, session.id)- await submitted- }- expect(sink.toolEnd.mock.calls).toEqual([['aggregate-2', 'second output', false], ['aggregate-1', 'first output', false]])- expect(settled).toHaveBeenCalledTimes(1)- expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(1)- })-- it('keeps one native submit active across same-message tools separated by early results', async () => {- const fixture = claudeProcess()- const sink = createSink()- const order: string[] = []- sink.assistant.mockImplementation(id => order.push(`assistant:${id}`))- sink.toolStart.mockImplementation(id => order.push(`start:${id}`))- sink.toolEnd.mockImplementation(id => order.push(`end:${id}`))- const session = await open(null, sink)- const submitted = session.submit([user()], new AbortController().signal)- const settled = vi.fn()- void submitted.then(settled, settled)- try {- stream(fixture, { type: 'message_start', message: { id: 'msg-parallel' } })- stream(fixture, { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'parallel-1', name: 'Read', input: {} } })- stream(fixture, { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '{"file_path":' } })- expect(sink.assistant).not.toHaveBeenCalled()- expect(sink.toolStart).not.toHaveBeenCalled()- fixture.send({ type: 'assistant', uuid: 'parallel-first', session_id: session.id, message: { id: 'msg-parallel', content: [{ type: 'tool_use', id: 'parallel-1', name: 'Read', input: { file_path: 'first.ts' } }] } })- fixture.send({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'parallel-1', content: 'first output' }] } })- await Promise.resolve()- expect(order).toEqual(['assistant:msg-parallel:block:0', 'start:parallel-1', 'end:parallel-1'])- expect(settled).not.toHaveBeenCalled()- await expect(session.submit([user()], new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_BUSY' })- stream(fixture, { type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'parallel-2', name: 'Read', input: {} } })- fixture.send({ type: 'assistant', uuid: 'parallel-second', session_id: session.id, message: { id: 'msg-parallel', content: [{ type: 'tool_use', id: 'parallel-2', name: 'Read', input: { file_path: 'second.ts' } }] } })- fixture.send({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'parallel-2', content: 'second output' }] } })- await Promise.resolve()- expect(settled).not.toHaveBeenCalled()- stream(fixture, { type: 'content_block_start', index: 2, content_block: { type: 'text', text: '' } })- fixture.send({ type: 'assistant', uuid: 'parallel-tail', session_id: session.id, message: { id: 'msg-parallel', content: [{ type: 'text', text: 'both inspected' }] } })- stream(fixture, { type: 'message_delta', delta: { stop_reason: 'tool_use' } })- stream(fixture, { type: 'message_stop' })- await Promise.resolve()- expect(settled).not.toHaveBeenCalled()- expect(order).toEqual([- 'assistant:msg-parallel:block:0',- 'start:parallel-1',- 'end:parallel-1',- 'assistant:msg-parallel:block:1',- 'start:parallel-2',- 'end:parallel-2',- 'assistant:msg-parallel:block:2',- ])- expect(sink.assistant.mock.calls).toEqual([- ['msg-parallel:block:0', [{ type: 'tool-call', id: 'parallel-1', name: 'Read', arguments: '{"file_path":"first.ts"}' }]],- ['msg-parallel:block:1', [{ type: 'tool-call', id: 'parallel-2', name: 'Read', arguments: '{"file_path":"second.ts"}' }]],- ['msg-parallel:block:2', [{ type: 'text', text: 'both inspected' }]],- ])- }- finally {- result(fixture, session.id)- await submitted- }- expect(settled).toHaveBeenCalledTimes(1)- expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(1)- expect(fixture.kill).not.toHaveBeenCalled()- })-- it('records one native tool call and error result without echoing native user messages', async () => {- const fixture = claudeProcess()- const sink = createSink()- const session = await open(null, sink)- const submitted = session.submit([user()], new AbortController().signal)- const assistant = { type: 'assistant', uuid: 'tool-frame', session_id: session.id, message: { id: 'msg-tool', content: [{ type: 'tool_use', id: 'tool-1', name: 'Bash', input: { command: 'git status' } }] } }- fixture.send(assistant)- fixture.send(assistant)- fixture.send({ type: 'user', message: { role: 'user', content: 'native input echo' } })- const tool = { type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'tool-1', content: [{ type: 'text', text: 'not a git repository' }], is_error: true }] } }- fixture.send(tool)- fixture.send(tool)- result(fixture, session.id)- await submitted- expect(sink.assistant.mock.calls).toEqual([['msg-tool:block:0', [{ type: 'tool-call', id: 'tool-1', name: 'Bash', arguments: '{"command":"git status"}' }]]])- expect(sink.toolStart.mock.calls).toEqual([['tool-1', 'Bash', '{"command":"git status"}']])- expect(sink.toolEnd.mock.calls).toEqual([['tool-1', 'not a git repository', true]])- })-- it.each(['ask', 'never'] as const)('applies native planning and workspace edits with %s approvals on each turn of a resumed session', async (approval) => {- const fixture = claudeProcess({ intercept: (frame, child) => {- if (frame.type !== 'user')- return false- result(child, String(frame.session_id))- return true- } })- const session = await open(storedId, createSink(), { permission: { sandbox: 'danger-full-access', approval } })- const signal = new AbortController().signal- await session.submit([user()], signal)- await session.submit([user()], signal, undefined, { sandbox: 'read-only', approval })- await session.submit([user()], signal, undefined, { sandbox: 'workspace-write', approval })- await session.submit([user()], signal, undefined, { sandbox: 'workspace-write', approval })- await session.submit([user()], signal, undefined, { sandbox: 'danger-full-access', approval })- expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([- initialization,- initialization,- { subtype: 'set_permission_mode', mode: approval === 'never' ? 'bypassPermissions' : 'default' },- { subtype: 'set_permission_mode', mode: 'plan' },- { subtype: 'set_permission_mode', mode: 'acceptEdits' },- { subtype: 'set_permission_mode', mode: 'acceptEdits' },- { subtype: 'set_permission_mode', mode: approval === 'never' ? 'bypassPermissions' : 'default' },- ])- expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(5)- expect(session.id).toBe(storedId)- expect(spawn).toHaveBeenCalledTimes(1)- })-- it.each([- { permission: { sandbox: 'read-only', approval: 'ask' }, tool: 'Write', input: { file_path: 'inside.txt', content: 'unsafe' } },- { permission: { sandbox: 'read-only', approval: 'ask' }, tool: 'Bash', input: { command: 'touch inside.txt' } },- { permission: { sandbox: 'read-only', approval: 'ask' }, tool: 'ExitPlanMode', input: {} },- { permission: { sandbox: 'workspace-write', approval: 'never' }, tool: 'Write', input: { file_path: '../outside.txt', content: 'unsafe' } },- ] as const)('denies $tool native escalation in $permission.sandbox/$permission.approval without asking', async ({ permission, tool, input }) => {- const fixture = claudeProcess()- const sink = createSink()- sink.approval.mockResolvedValue(true)- const session = await open(null, sink)- const entered = fixture.next(frame => frame.type === 'user')- const submitted = session.submit([user()], new AbortController().signal, undefined, permission)- await Promise.race([entered, submitted])- const answered = fixture.next(frame => frame.type === 'control_response')- fixture.send({ type: 'control_request', request_id: 'restricted-tool', request: { subtype: 'can_use_tool', tool_name: tool, tool_use_id: 'restricted-call', input } })- expect(await answered).toMatchObject({ response: { request_id: 'restricted-tool', response: { behavior: 'deny' } } })- expect(sink.approval).not.toHaveBeenCalled()- result(fixture, session.id)- await submitted- })-- it('keeps an approval-only never policy in dontAsk instead of inferring full-access bypass', async () => {- const fixture = claudeProcess({ intercept: (frame, child) => {- if (frame.type !== 'user')- return false- result(child, String(frame.session_id))- return true- } })- const session = await open()- await session.submit([user()], new AbortController().signal, undefined, { approval: 'never' })- expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([initialization, initialization, { subtype: 'set_permission_mode', mode: 'dontAsk' }])- })-- it('snapshots explicit permissions and awaits each mode change on the same native session', async () => {- const fixture = claudeProcess({ intercept: frame => frame.type === 'control_request' && (frame.request as Frame).subtype === 'set_permission_mode' })- const session = await open(storedId, createSink(), { permission: { sandbox: 'danger-full-access', approval: 'ask' } })- const permission: NativePermission = { sandbox: 'danger-full-access', approval: 'never' }- const mode = fixture.next(frame => frame.type === 'control_request' && (frame.request as Frame).subtype === 'set_permission_mode')- const submitted = session.submit([user()], new AbortController().signal, undefined, permission)- permission.sandbox = 'read-only'- permission.approval = 'ask'- const control = await mode- expect(control.request).toEqual({ subtype: 'set_permission_mode', mode: 'bypassPermissions' })- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- const input = fixture.next(frame => frame.type === 'user')- fixture.send({ type: 'control_response', response: { subtype: 'success', request_id: control.request_id, response: { mode: 'bypassPermissions' } } })- await input- result(fixture, session.id)- await submitted- const reset = fixture.next(frame => frame.type === 'control_request' && (frame.request as Frame).subtype === 'set_permission_mode')- const restored = session.submit([user()], new AbortController().signal, undefined, { sandbox: 'danger-full-access', approval: 'ask' })- const resetControl = await reset- expect(resetControl.request).toEqual({ subtype: 'set_permission_mode', mode: 'default' })- expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(1)- const second = fixture.next(frame => frame.type === 'user')- fixture.send({ type: 'control_response', response: { subtype: 'success', request_id: resetControl.request_id, response: { mode: 'default' } } })- await second- result(fixture, session.id)- await restored- expect(session.id).toBe(storedId)- expect(spawn).toHaveBeenCalledTimes(1)- })-- it.each(['error', 'mismatched-mode'] as const)('fails closed on a permission control %s without submitting user input', async (outcome) => {- const fixture = claudeProcess({ intercept: (frame, child) => {- if (frame.type !== 'control_request' || (frame.request as Frame).subtype !== 'set_permission_mode')- return false- child.send({ type: 'control_response', response: outcome === 'error'- ? { subtype: 'error', request_id: frame.request_id, error: 'Mode denied by native policy' }- : { subtype: 'success', request_id: frame.request_id, response: { mode: 'bypassPermissions' } } })- return true- } })- const session = await open()- await expect(session.submit([user()], new AbortController().signal, undefined, { sandbox: 'danger-full-access', approval: 'ask' })).rejects.toMatchObject({ code: outcome === 'error' ? 'BRIDGE_NATIVE_REQUEST' : 'BRIDGE_PERMISSION_MISMATCH' })- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it.each([- { tool: 'Bash', input: { command: 'echo first\necho second', description: 'Inspect environment', dangerouslyDisableSandbox: true }, reason: '\u001B[31mOutside sandbox\u001B[0m', details: 'Outside sandbox\n\nInspect environment\n\ncommand: echo first\necho second\n\ndangerouslyDisableSandbox: true' },- { tool: 'WebSearch', input: { query: 'Claude protocol', allowed_domains: ['example.org'] }, reason: 'Network permission', details: 'Network permission\n\nquery: Claude protocol\n\nallowed_domains: [\n "example.org"\n]' },- { tool: 'Write', input: { file_path: '../outside.txt', content: 'full file contents' }, reason: 'External file write', details: 'External file write\n\nfile_path: ../outside.txt\n\ncontent: full file contents' },- ])('formats $tool approval without hiding input while preserving denial', async ({ tool, input, reason, details }) => {- const fixture = claudeProcess()- const sink = createSink()- const session = await open(null, sink)- const submitted = session.submit([user()], new AbortController().signal)- const answered = fixture.next(frame => frame.type === 'control_response')- fixture.send({ type: 'control_request', request_id: 'readable-permission', request: { subtype: 'can_use_tool', tool_name: tool, tool_use_id: 'readable-tool', input, decision_reason: reason } })- expect(await answered).toEqual({ type: 'control_response', response: { subtype: 'success', request_id: 'readable-permission', response: { behavior: 'deny', message: 'Native tool request is unavailable or cancelled' } } })- expect(sink.approval.mock.calls[0]?.[1].details).toBe(details)- result(fixture, session.id)- await submitted- })-- it('returns nested permission allow-once with the original native input', async () => {- const fixture = claudeProcess()- const sink = createSink()- sink.approval.mockResolvedValue(true)- const session = await open(null, sink)- const submitted = session.submit([user()], new AbortController().signal)- const answered = fixture.next(frame => frame.type === 'control_response' && (frame.response as Frame).request_id === 'permission-1')- fixture.send({ type: 'control_request', request_id: 'permission-1', request: { subtype: 'can_use_tool', tool_name: 'Bash', tool_use_id: 'tool-approval', input: { command: 'git status' }, title: 'Read repository state' } })- expect(await answered).toEqual({ type: 'control_response', response: { subtype: 'success', request_id: 'permission-1', response: { behavior: 'allow', updatedInput: { command: 'git status' } } } })- expect(sink.approval.mock.calls[0]?.slice(0, 2)).toEqual(['tool-approval', { kind: 'command', title: 'Read repository state', details: 'command: git status' }])- result(fixture, session.id)- await submitted- })-- it.each([undefined, { sandbox: 'read-only', approval: 'ask' }] as const)('maps AskUserQuestion multi-selection back into native updatedInput answers under %j', async (permission) => {- const fixture = claudeProcess()- const sink = createSink()- sink.questions.mockResolvedValue({ 'Which areas?': ['Events', 'Cancel'] })- const session = await open(null, sink)- const entered = fixture.next(frame => frame.type === 'user')- const submitted = session.submit([user()], new AbortController().signal, undefined, permission)- await Promise.race([entered, submitted])- const answered = fixture.next(frame => frame.type === 'control_response')- const input = { questions: [{ question: 'Which areas?', header: 'Scope', multiSelect: true, options: [{ label: 'Events', description: 'Logs and UI' }, { label: 'Cancel', description: 'Quiescence' }] }] }- fixture.send({ type: 'control_request', request_id: 'questions-1', request: { subtype: 'can_use_tool', tool_name: 'AskUserQuestion', tool_use_id: 'question-tool', input } })- expect(await answered).toEqual({ type: 'control_response', response: { subtype: 'success', request_id: 'questions-1', response: { behavior: 'allow', updatedInput: { ...input, answers: { 'Which areas?': 'Events, Cancel' } } } } })- expect(sink.questions.mock.calls[0]?.slice(0, 2)).toEqual(['question-tool', [{ id: 'Which areas?', question: 'Which areas?', multiSelect: true, options: [{ label: 'Events', description: 'Logs and UI' }, { label: 'Cancel', description: 'Quiescence' }] }]])- result(fixture, session.id)- await submitted- })-- it('withdraws native control requests so a late UI answer cannot grant permission', async () => {- const fixture = claudeProcess()- const sink = createSink()- const parked = Promise.withResolvers<boolean>()- sink.approval.mockReturnValue(parked.promise)- const session = await open(null, sink)- const submitted = session.submit([user()], new AbortController().signal)- fixture.send({ type: 'control_request', request_id: 'withdrawn-1', request: { subtype: 'can_use_tool', tool_name: 'Write', tool_use_id: 'edit-1', input: { file_path: 'fixture.txt', content: 'safe' } } })- const signal = sink.approval.mock.calls[0]![2]!- fixture.send({ type: 'control_cancel_request', request_id: 'withdrawn-1' })- parked.resolve(true)- await parked.promise- result(fixture, session.id)- await submitted- expect(signal.aborted).toBe(true)- expect(fixture.frames.some(frame => frame.type === 'control_response')).toBe(false)- })-- it('does not settle cancellation on interrupt ACK while tracked background tasks remain', async () => {- const fixture = claudeProcess({ capabilities: ['interrupt_cancel_queued_v1', 'interrupt_receipt_v1'] })- const session = await open()- const signal = new AbortController()- const submitted = session.submit([user()], signal.signal)- const rejected = expect(submitted).rejects.toThrow('cancel run')- let settled = false- void submitted.then(() => settled = true, () => settled = true)- fixture.send({ type: 'system', subtype: 'session_state_changed', state: 'running', session_id: session.id })- fixture.send({ type: 'system', subtype: 'task_started', task_id: 'task-1', session_id: session.id })- signal.abort(new Error('cancel run'))- result(fixture, session.id, { terminal_reason: 'aborted_tools' })- fixture.send({ type: 'system', subtype: 'session_state_changed', state: 'idle', session_id: session.id })- await Promise.resolve()- expect(settled).toBe(false)- const requests = fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)- expect(requests).toEqual([initialization, initialization, { subtype: 'interrupt', cancel_queued: true }, { subtype: 'stop_task', task_id: 'task-1' }])- fixture.send({ type: 'system', subtype: 'task_notification', task_id: 'task-1', status: 'stopped', session_id: session.id })- await rejected- })-- it('does not withhold a normal result forever for a background shell', async () => {- const fixture = claudeProcess()- const session = await open()- const submitted = session.submit([user()], new AbortController().signal)- const settled = vi.fn()- void submitted.then(settled, settled)- fixture.send({ type: 'system', subtype: 'task_started', task_id: 'shell-1', task_type: 'local_bash', session_id: session.id })- result(fixture, session.id)- await Promise.resolve()- await Promise.resolve()- expect(settled).toHaveBeenCalledTimes(1)- await submitted- })-- it('requires a continuation result when authoritative-only main work resumes after a result', async () => {- const fixture = claudeProcess()- const session = await open()- const submitted = session.submit([user()], new AbortController().signal)- const settled = vi.fn()- void submitted.then(settled, settled)- fixture.send({ type: 'system', subtype: 'session_state_changed', state: 'running', session_id: session.id })- fixture.send({ type: 'system', subtype: 'task_started', task_id: 'agent-1', task_type: 'local_agent', session_id: session.id })- result(fixture, session.id)- fixture.send({ type: 'assistant', uuid: 'continued-frame', session_id: session.id, message: { id: 'continued-message', content: [{ type: 'text', text: 'follow-up completed' }] } })- fixture.send({ type: 'system', subtype: 'task_notification', task_id: 'agent-1', status: 'completed', session_id: session.id })- fixture.send({ type: 'system', subtype: 'session_state_changed', state: 'idle', session_id: session.id })- await Promise.resolve()- await Promise.resolve()- expect(settled).not.toHaveBeenCalled()- result(fixture, session.id)- await submitted- expect(settled).toHaveBeenCalledTimes(1)- })-- it('refuses to reuse a native process retaining the cancelled queued input', async () => {- const fixture = claudeProcess({ capabilities: ['interrupt_receipt_v1'], intercept: (frame, child) => {- if (frame.type !== 'control_request' || (frame.request as Frame).subtype !== 'interrupt')- return false- const input = child.frames.find(frame => frame.type === 'user')!- child.send({ type: 'control_response', response: { subtype: 'success', request_id: frame.request_id, response: { still_queued: [input.uuid] } } })- return true- } })- const session = await open()- const signal = new AbortController()- const submitted = session.submit([user()], signal.signal)- const rejected = expect(submitted).rejects.toMatchObject({ code: 'BRIDGE_INTERRUPT_QUEUED_INPUT' })- signal.abort(new Error('cancel queued'))- await rejected- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('force-closes a native process that acknowledges interrupt but never settles its run', async () => {- vi.useFakeTimers()- const fixture = claudeProcess()- const session = await open()- const signal = new AbortController()- const submitted = session.submit([user()], signal.signal)- const rejected = expect(submitted).rejects.toMatchObject({ code: 'BRIDGE_INTERRUPT_TIMEOUT' })- signal.abort(new Error('cancel stuck'))- await vi.advanceTimersByTimeAsync(5000)- await rejected- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('treats native conversation_reset as failure rather than changing the official binding', async () => {- const fixture = claudeProcess()- const session = await open(storedId)- const submitted = session.submit([user()], new AbortController().signal)- const rejected = expect(submitted).rejects.toMatchObject({ code: 'BRIDGE_NATIVE_RESET' })- fixture.send({ type: 'conversation_reset', new_conversation_id: 'new-native-id' })- await rejected- expect(session.id).toBe(storedId)- expect(spawn).toHaveBeenCalledTimes(1)- })-- it('keeps the official text and image order in one mixed native prompt', async () => {- const fixture = claudeProcess()- const attachments: NativeAttachments = { path: () => undefined, read: vi.fn(async () => ({ mediaType: 'image/png', base64: 'Zm FrZQ==' })) }- const session = await open(null, createSink(), undefined, attachments)- const mixed = createUserMessage({ source: { kind: 'user' }, content: [- { type: 'text', text: 'before ' },- { type: 'image', attachment: { id: 'image-1', mediaType: 'image/png', bytes: 3 } as never },- { type: 'text', text: ' after' },- ] })- const submitted = session.submit([mixed], new AbortController().signal)- result(fixture, session.id)- await submitted- expect(fixture.frames.filter(frame => frame.type === 'user').flatMap(frame => (frame.message as Frame).content as Frame[])).toEqual([- { type: 'text', text: 'before ' },- { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'Zm FrZQ==' } },- { type: 'text', text: ' after' },- ])- })-- it('forwards an official image as an inline base64 content block', async () => {- const fixture = claudeProcess()- const attachments: NativeAttachments = { path: () => undefined, read: vi.fn(async () => ({ mediaType: 'image/png', base64: 'Zm FrZQ==' })) }- const session = await open(null, createSink(), undefined, attachments)- const submitted = session.submit([user(), image({ id: 'image-1', mediaType: 'image/png', bytes: 3 })], new AbortController().signal)- result(fixture, session.id)- await submitted- expect(fixture.frames.filter(frame => frame.type === 'user')).toEqual([- { type: 'user', session_id: session.id, uuid: expect.any(String), parent_tool_use_id: null, message: { role: 'user', content: [- { type: 'text', text: 'inspect the workspace' },- { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'Zm FrZQ==' } },- ] } },- ])- })-- it('rejects nontext input instead of sending only its text portion', async () => {- const fixture = claudeProcess()- const session = await open()- const input = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'hello' }, { type: 'reasoning', text: 'unsupported' }] })- await expect(session.submit([input], new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_UNSUPPORTED_CONTENT' })- expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)- })-- it('ends stdin on idle disposal so native transcript flushing can precede termination', async () => {- const fixture = claudeProcess()- const session = await open()- await Promise.all([session.dispose(), session.dispose()])- expect(fixture.stdin.end).toHaveBeenCalledTimes(1)- expect(fixture.kill).not.toHaveBeenCalled()- })-})diff --git a/packages/dsh-tauri-kernel/src/host/backends/claude.ts b/packages/dsh-tauri-kernel/src/host/backends/claude.tsdeleted file mode 100644index f99d82a3..00000000--- a/packages/dsh-tauri-kernel/src/host/backends/claude.ts+++ /dev/null@@ -1,750 +0,0 @@-import type { UserMessage } from '@deepseek-ai/dsh-llm'-import type { Deferred } from './transport'-import type { NativeAttachments, NativeCommand, NativeContent, NativeModelCatalog, NativeModelInfo, NativePermission, NativeQuestion, NativeSession, NativeSessionOpenOptions, NativeSink, NativeTurnOptions } from './types'-import { randomUUID } from 'node:crypto'-import { stripVTControlCharacters } from 'node:util'-import { nativeEnvironment } from '../utils/detection'-import { abortError, deferred, errorFrom, INTERRUPT_TIMEOUT_MS, JsonLinesProcess, NativeBridgeError, nativeRuns, PendingRequests, record, REQUEST_TIMEOUT_MS, stringField } from './transport'--interface ClaudeBlock {- type: string- callId?: string- final?: string-}--interface ClaudeMessage {- blocks: Map<number, ClaudeBlock>- nextFinalIndex: number-}--interface ClaudeRun {- result: Deferred<void>- signal: AbortSignal- messages: Map<string, ClaudeMessage>- finalFrames: Map<string, string>- lanes: Map<string, string>- tools: Set<string>- endedTools: Set<string>- tasks: Set<string>- deferringTasks: Set<string>- stoppedTasks: Set<string>- resultReceived: boolean- state?: string- inputId: string- error?: Error- submitted: boolean- interruptPending: boolean- interruptSent: boolean- interruptTimer?: ReturnType<typeof setTimeout>-}--const TERMINAL_TASK_STATUSES = new Set(['completed', 'failed', 'stopped', 'killed'])-const DEFERRING_TASK_TYPES = new Set(['local_agent', 'local_workflow'])-const SESSION_START_HOOK_ID = 'dsh-native-session-identity'--function questionsOf(input: Record<string, unknown>): NativeQuestion[] {- if (!Array.isArray(input.questions) || input.questions.length === 0)- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude user-input request is missing questions')- const ids = new Set<string>()- return input.questions.map((value) => {- const question = record(value)- const id = stringField(question, 'question')- if (ids.has(id))- throw new NativeBridgeError('BRIDGE_UNSUPPORTED_QUESTION', 'Claude question text must be unique to preserve answer identities')- ids.add(id)- if (question.isSecret === true)- throw new NativeBridgeError('BRIDGE_UNSUPPORTED_QUESTION', 'Secret native questions cannot be recorded in the official session log')- return {- id,- question: id,- ...typeof question.multiSelect === 'boolean' ? { multiSelect: question.multiSelect } : {},- ...Array.isArray(question.options)- ? { options: question.options.map((value) => {- const option = record(value)- return { label: stringField(option, 'label'), ...typeof option.description === 'string' ? { description: option.description } : {} }- }) }- : {},- }- })-}--function resultText(content: unknown): string {- if (typeof content === 'string')- return content- if (!Array.isArray(content))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude tool result is missing content')- return content.map((value) => {- const block = record(value)- return block.type === 'text' && typeof block.text === 'string' ? block.text : JSON.stringify(block)- }).join('\n')-}--class ClaudeSession implements NativeSession {- private readonly transport: JsonLinesProcess- private readonly requests: PendingRequests- private readonly approvals = new Map<string, AbortController>()- private nativeId: string- private active?: ClaudeRun- private failure?: Error- private disposed = false- private opening = true- private disposePromise?: Promise<void>- private readonly identity = deferred<void>()- private identityConfirmed = false- private identityTimer?: ReturnType<typeof setTimeout>- private readonly capabilities = new Set<string>()- private startupModel?: string- private effectiveModel?: string- private defaultsPending: boolean- private catalog?: NativeModelCatalog- private appliedOptions: NativeTurnOptions = { model: null, reasoningEffort: null }- private permission?: NativePermission-- constructor(command: NativeCommand, cwd: string, storedId: string | null, private readonly sink: NativeSink, private readonly options?: NativeSessionOpenOptions, private readonly attachments?: NativeAttachments) {- this.nativeId = options?.forkFrom ? '' : storedId ?? randomUUID()- this.defaultsPending = storedId !== null || options?.forkFrom !== undefined- this.permission = options?.permission ? { ...options.permission } : undefined- this.transport = new JsonLinesProcess({ ...command, env: { ...(command.env ?? nativeEnvironment()), CLAUDE_CODE_SDK_READS_SESSION_STATE: '1' } }, [- '--print',- '--verbose',- '--input-format',- 'stream-json',- '--output-format',- 'stream-json',- '--include-partial-messages',- '--permission-prompt-tool',- 'stdio',- '--allow-dangerously-skip-permissions',- '--settings',- '{"useAutoModeDuringPlan":false}',- ...options?.permission ? ['--permission-mode', 'default'] : [],- ...options?.forkFrom ? [`--resume=${options.forkFrom}`, '--fork-session'] : [storedId === null ? `--session-id=${this.id}` : `--resume=${this.id}`],- ], cwd)- this.requests = new PendingRequests(value => this.transport.write(value))- this.transport.onFailure((error) => {- this.failure = error- this.identity.reject(error)- this.requests.failAll(error)- this.active?.result.reject(error)- this.withdrawApprovals(error)- })- this.transport.onMessage(message => this.receive(message))- }-- get id(): string {- return this.nativeId- }-- async open(signal: AbortSignal): Promise<void> {- const aborted = (): void => this.identity.reject(abortError(signal))- try {- signal.throwIfAborted()- signal.addEventListener('abort', aborted, { once: true })- this.identityTimer = setTimeout(() => {- const error = new NativeBridgeError('BRIDGE_NATIVE_BIND_UNCONFIRMED', 'Claude did not acknowledge the native session before user input; a reserved UUID is not a running conversation')- this.identity.reject(error)- this.requests.failAll(error)- }, REQUEST_TIMEOUT_MS)- const initialization = { subtype: 'initialize', hooks: { SessionStart: [{ hookCallbackIds: [SESSION_START_HOOK_ID] }] } }- const response = record(await this.control(initialization, signal))- this.checkIdentity(response)- this.noteCapabilities(response)- if (response.models !== undefined)- this.catalog = this.modelCatalog(response.models, this.startupModel)- if (this.failure)- throw this.failure- if (!this.identityConfirmed) {- // Repeated initialize publishes a background-task snapshot even before the first user input.- const snapshot = record(await this.control(initialization, signal))- this.checkIdentity(snapshot)- }- await this.identity.promise- if (this.failure)- throw this.failure- signal.throwIfAborted()- this.opening = false- }- catch (error) {- await this.dispose()- throw error- }- finally {- clearTimeout(this.identityTimer)- signal.removeEventListener('abort', aborted)- }- }-- private modelCatalog(values: unknown, defaultModel: string | undefined): NativeModelCatalog {- if (!Array.isArray(values))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude initialization is missing supported models')- const models = new Map<string, NativeModelInfo>()- const resolved = new Map<string, string>()- for (const value of values) {- const model = record(value)- const id = stringField(model, 'value')- const levels = model.supportedEffortLevels- if (levels !== undefined && (!Array.isArray(levels) || levels.some(value => typeof value !== 'string' || value === '')))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude model reasoning capabilities are invalid')- const efforts = Array.isArray(levels) && model.supportsEffort !== false ? levels.map(id => ({ id: String(id), name: String(id) })) : []- const info = {- id,- name: stringField(model, 'displayName'),- ...typeof model.description === 'string' ? { description: model.description } : {},- ...efforts.length > 0 ? { reasoning: { efforts } } : {},- }- models.set(id, info)- if (typeof model.resolvedModel === 'string' && model.resolvedModel !== '')- resolved.set(model.resolvedModel, id)- if (models.size > 10_000)- throw new NativeBridgeError('BRIDGE_PROTOCOL_LIMIT', 'Claude model listing exceeded its limit')- }- const anchor = defaultModel ?? this.effectiveModel- const name = anchor === undefined ? 'default' : models.has(anchor) ? anchor : resolved.get(anchor) ?? 'default'- return { models: [...models.values()], ...models.has(name) ? { defaultModel: name } : {} }- }-- async models(signal: AbortSignal): Promise<NativeModelCatalog> {- signal.throwIfAborted()- if (this.disposed || this.failure)- throw this.failure ?? new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Claude session was disposed')- if (!this.catalog)- throw new NativeBridgeError('BRIDGE_MODEL_DISCOVERY_UNAVAILABLE', 'Claude did not expose supported models in its public initialize response')- const models = [...this.catalog.models]- for (const id of [this.startupModel, this.effectiveModel]) {- if (id && !models.some(model => model.id === id))- models.push({ id, name: id })- }- return { ...this.catalog, models }- }-- private async applyOptions(options: NativeTurnOptions, signal: AbortSignal): Promise<void> {- if (options.model === null && options.reasoningEffort === null && this.appliedOptions.model === null && this.appliedOptions.reasoningEffort === null)- return- const modelChanged = this.defaultsPending || options.model !== this.appliedOptions.model- const effortChanged = this.defaultsPending || options.reasoningEffort !== this.appliedOptions.reasoningEffort- if (!modelChanged && !effortChanged)- return- if (options.model !== null || options.reasoningEffort !== null) {- const catalog = await this.models(signal)- const model = options.model ?? (modelChanged ? undefined : this.startupModel)- if (!model)- throw new NativeBridgeError('BRIDGE_DEFAULT_UNAVAILABLE', 'Claude did not report a provable default model for reasoning validation')- const info = catalog.models.find(value => value.id === model)- if (options.model !== null && !info)- throw new NativeBridgeError('BRIDGE_MODEL_UNAVAILABLE', `Claude did not advertise model: ${options.model}`)- if (options.reasoningEffort !== null && !info?.reasoning?.efforts.some(value => value.id === options.reasoningEffort))- throw new NativeBridgeError('BRIDGE_EFFORT_UNSUPPORTED', `Claude did not advertise reasoning effort ${options.reasoningEffort} for ${model}`)- }- try {- if (modelChanged) {- await this.control({ subtype: 'set_model', model: options.model }, signal)- this.effectiveModel = options.model ?? undefined- if (options.model === null)- this.startupModel = undefined- }- // Public flag-layer null restores the model default, not a settings-file startup effort.- if (effortChanged || modelChanged)- await this.control({ subtype: 'apply_flag_settings', settings: { effortLevel: options.reasoningEffort } }, signal)- this.appliedOptions = options- this.defaultsPending = false- }- catch (error) {- // A rejected/cancelled control may already have changed the native flag layer.- // Close rather than reuse a process with an unacknowledged partial selection.- this.transport.fail(errorFrom(error))- throw error- }- }-- private async applyPermission(permission: NativePermission, signal: AbortSignal): Promise<void> {- // ponytail: native modes do not isolate preapproved tools or existing tasks; use an OS sandbox for hard boundaries.- const mode = permission.sandbox === 'read-only'- ? 'plan'- : permission.sandbox === 'workspace-write'- ? 'acceptEdits'- : permission.approval === 'never' ? permission.sandbox === 'danger-full-access' ? 'bypassPermissions' : 'dontAsk' : 'default'- try {- const response = record(await this.control({ subtype: 'set_permission_mode', mode }, signal))- if (response.mode !== undefined && response.mode !== mode)- throw new NativeBridgeError('BRIDGE_PERMISSION_MISMATCH', 'Claude 未确认请求的权限模式,已阻止本轮运行。')- }- catch (error) {- this.transport.fail(errorFrom(error))- throw error- }- }-- async submit(messages: readonly UserMessage[], signal: AbortSignal, options?: NativeTurnOptions, permission?: NativePermission): Promise<void> {- signal.throwIfAborted()- if (this.disposed || this.failure)- throw this.failure ?? new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Claude session was disposed')- if (this.active)- throw new NativeBridgeError('BRIDGE_BUSY', 'Claude native session already has an active run')- const runs = nativeRuns(messages, this.attachments)- if (runs.length === 0)- throw new NativeBridgeError('BRIDGE_EMPTY_INPUT', 'Claude native run requires a user message')- const selection = options ? { ...options } : undefined- const policy = permission ? { ...permission } : this.permission- const run: ClaudeRun = {- result: deferred<void>(),- signal,- messages: new Map(),- finalFrames: new Map(),- lanes: new Map(),- tools: new Set(),- endedTools: new Set(),- tasks: new Set(),- deferringTasks: new Set(),- stoppedTasks: new Set(),- resultReceived: false,- inputId: randomUUID(),- submitted: false,- interruptPending: false,- interruptSent: false,- }- this.active = run- const aborted = (): void => {- if (run.submitted)- this.interrupt(run)- }- signal.addEventListener('abort', aborted, { once: true })- try {- if (policy) {- await this.applyPermission(policy, signal)- this.permission = policy- }- if (selection && (this.defaultsPending || selection.model !== this.appliedOptions.model || selection.reasoningEffort !== this.appliedOptions.reasoningEffort))- await this.applyOptions(selection, signal)- signal.throwIfAborted()- const content: Record<string, unknown>[] = []- for (const run of runs.flat()) {- if (run.type === 'text') {- content.push({ type: 'text', text: run.text })- continue- }- const source = await this.attachments!.read(run.ref, signal)- if (source.base64 === undefined)- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'The official attachment store returned no readable image bytes')- content.push({ type: 'image', source: { type: 'base64', media_type: source.mediaType, data: source.base64 } })- }- signal.throwIfAborted()- run.submitted = true- this.transport.write({- type: 'user',- session_id: this.id,- uuid: run.inputId,- parent_tool_use_id: null,- message: { role: 'user', content },- })- await run.result.promise- signal.throwIfAborted()- }- catch (error) {- if (run.submitted && !signal.aborted)- this.transport.fail(errorFrom(error))- throw this.failure ?? (signal.aborted ? abortError(signal) : error)- }- finally {- signal.removeEventListener('abort', aborted)- clearTimeout(run.interruptTimer)- this.withdrawApprovals(new NativeBridgeError('BRIDGE_REQUEST_CLOSED', 'Native run has ended'))- this.active = undefined- }- }-- dispose(): Promise<void> {- this.disposePromise ??= this.close()- return this.disposePromise- }-- private async close(): Promise<void> {- this.disposed = true- const error = new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Claude native session was disposed')- this.identity.reject(error)- clearTimeout(this.identityTimer)- this.withdrawApprovals(error)- this.requests.failAll(error)- this.active?.result.reject(error)- try {- await this.transport.close(this.active === undefined)- }- catch {- // Termination is best effort: a stuck child must never fail plugin startup or teardown.- }- }-- private control(request: Record<string, unknown>, signal?: AbortSignal, timeoutMs?: number): Promise<unknown> {- const id = randomUUID()- return this.requests.request(id, { type: 'control_request', request_id: id, request }, signal, timeoutMs)- }-- private checkIdentity(message: Record<string, unknown>, required = false): void {- if (required || typeof message.session_id === 'string') {- const id = stringField(message, 'session_id')- if (this.opening && this.options?.forkFrom && this.nativeId === '') {- if (id === this.options.forkFrom)- throw new NativeBridgeError('BRIDGE_FORK_MISMATCH', 'Claude fork did not acknowledge a new native session')- this.nativeId = id- }- else if (id !== this.id) {- throw new NativeBridgeError('BRIDGE_RESUME_MISMATCH', 'Claude reported a different native session; refusing to replace the stored binding')- }- this.identityConfirmed = true- this.identity.resolve()- }- }-- private noteCapabilities(message: Record<string, unknown>): void {- if (Array.isArray(message.capabilities)) {- for (const capability of message.capabilities) {- if (typeof capability === 'string')- this.capabilities.add(capability)- }- }- }-- private receive(message: Record<string, unknown>): void {- const type = stringField(message, 'type')- if (type === 'control_response') {- const response = record(message.response)- const id = stringField(response, 'request_id')- if (response.subtype === 'success')- this.requests.settle(id, response.response ?? {})- else if (response.subtype === 'error')- this.requests.settle(id, undefined, new NativeBridgeError('BRIDGE_NATIVE_REQUEST', stringField(response, 'error')))- else- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Unsupported Claude control response')- return- }- if (type === 'control_request') {- const id = stringField(message, 'request_id')- void this.answer(id, record(message.request)).catch(error => this.transport.fail(errorFrom(error)))- return- }- if (type === 'control_cancel_request') {- const id = stringField(message, 'request_id')- this.approvals.get(id)?.abort(new NativeBridgeError('BRIDGE_REQUEST_CLOSED', 'Claude withdrew the control request'))- this.approvals.delete(id)- return- }- if (type === 'conversation_reset')- throw new NativeBridgeError('BRIDGE_NATIVE_RESET', 'Claude reset its conversation; the existing official session binding cannot be silently changed')- const run = this.active- if (type === 'result') {- const aborted = message.terminal_reason === 'aborted_streaming' || message.terminal_reason === 'aborted_tools'- const error = aborted- ? new NativeBridgeError('BRIDGE_NATIVE_INTERRUPTED', 'Claude interrupted its native turn')- : message.is_error === true || message.subtype !== 'success'- ? new NativeBridgeError('BRIDGE_NATIVE_TURN', typeof message.result === 'string' && message.result !== '' ? message.result : JSON.stringify(message.errors ?? message.subtype))- : undefined- if (!run && error) {- this.transport.fail(error)- return- }- this.checkIdentity(message, true)- if (!run) {- if (!this.opening)- throw new NativeBridgeError('BRIDGE_UNEXPECTED_TURN', 'Claude completed a run outside the official agent turn')- return- }- run.resultReceived = true- run.error = error- this.finish(run)- return- }- this.checkIdentity(message, type === 'system' && (message.subtype === 'init' || message.subtype === 'background_tasks_changed'))- if (type === 'system' && message.subtype === 'init') {- this.noteCapabilities(message)- if (this.opening && typeof message.model === 'string' && message.model !== '') {- this.effectiveModel ??= message.model- if (!this.defaultsPending)- this.startupModel ??= message.model- }- }- if (!run) {- if (type === 'assistant' || type === 'stream_event' || (type === 'system' && message.subtype === 'task_started'))- throw new NativeBridgeError('BRIDGE_UNEXPECTED_TURN', 'Claude produced work outside the official agent turn')- return- }- switch (type) {- case 'system':- if (message.subtype === 'session_state_changed') {- run.state = stringField(message, 'state')- this.finish(run)- }- else if (message.subtype === 'task_started') {- const id = stringField(message, 'task_id')- run.tasks.add(id)- if (typeof message.task_type === 'string' && DEFERRING_TASK_TYPES.has(message.task_type))- run.deferringTasks.add(id)- if (run.signal.aborted)- this.stopTask(run, id)- }- else if (message.subtype === 'task_notification' || message.subtype === 'task_updated') {- const status = message.subtype === 'task_notification' ? message.status : record(message.patch).status- if (typeof status === 'string' && TERMINAL_TASK_STATUSES.has(status)) {- const id = stringField(message, 'task_id')- run.tasks.delete(id)- run.deferringTasks.delete(id)- this.finish(run)- }- }- return- case 'stream_event':- if (message.parent_tool_use_id == null) {- run.resultReceived = false- run.error = undefined- }- this.stream(run, message)- return- case 'assistant': {- if (typeof message.uuid === 'string') {- const body = JSON.stringify(message.message)- const previous = run.finalFrames.get(message.uuid)- if (previous !== undefined) {- if (previous !== body)- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude changed a previously settled assistant frame')- return- }- run.finalFrames.set(message.uuid, body)- }- if (message.parent_tool_use_id == null) {- run.resultReceived = false- run.error = undefined- }- this.assistant(run, record(message.message))- return- }- case 'user':- this.toolResults(run, record(message.message))- }- }-- private finish(run: ClaudeRun): void {- if (!run.resultReceived || (run.signal.aborted ? run.tasks.size : run.deferringTasks.size) !== 0 || run.interruptPending || (run.state !== undefined && run.state !== 'idle'))- return- if (run.error && !run.signal.aborted)- run.result.reject(run.error)- else- run.result.resolve()- }-- private stream(run: ClaudeRun, message: Record<string, unknown>): void {- const event = record(message.event)- const lane = typeof message.parent_tool_use_id === 'string' ? message.parent_tool_use_id : ''- if (event.type === 'message_start') {- const id = stringField(record(event.message), 'id')- run.lanes.set(lane, id)- if (!run.messages.has(id))- run.messages.set(id, { blocks: new Map(), nextFinalIndex: 0 })- return- }- const id = run.lanes.get(lane)- if (!id)- return- const state = run.messages.get(id)!- if (event.type === 'content_block_start') {- const index = this.blockIndex(event)- const block = record(event.content_block)- state.blocks.set(index, { type: stringField(block, 'type'), ...typeof block.id === 'string' ? { callId: block.id } : {} })- const nativeId = `${id}:block:${index}`- if (block.type === 'text' && typeof block.text === 'string' && block.text !== '')- this.sink.text(nativeId, block.text)- else if (block.type === 'thinking' && typeof block.thinking === 'string' && block.thinking !== '')- this.sink.thinking(nativeId, block.thinking)- }- else if (event.type === 'content_block_delta') {- const index = this.blockIndex(event)- const delta = record(event.delta)- const nativeId = `${id}:block:${index}`- if (delta.type === 'text_delta' && typeof delta.text === 'string' && delta.text !== '')- this.sink.text(nativeId, delta.text)- else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string' && delta.thinking !== '')- this.sink.thinking(nativeId, delta.thinking)- }- }-- private blockIndex(event: Record<string, unknown>): number {- if (typeof event.index !== 'number' || !Number.isSafeInteger(event.index) || event.index < 0)- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude stream block index is invalid')- return event.index- }-- private assistant(run: ClaudeRun, body: Record<string, unknown>): void {- const id = stringField(body, 'id')- if (!Array.isArray(body.content))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude assistant message is missing content')- const state = run.messages.get(id) ?? { blocks: new Map<number, ClaudeBlock>(), nextFinalIndex: 0 }- run.messages.set(id, state)- const aggregate = body.content.length > 1- for (const [position, value] of body.content.entries()) {- const block = record(value)- const type = stringField(block, 'type')- const serialized = JSON.stringify(block)- const matching = [...state.blocks.entries()].find(([, existing]) => existing.final === undefined && existing.type === type && (type !== 'tool_use' || existing.callId === block.id))- const aggregateIndex = aggregate && state.blocks.get(position)?.type === type ? position : undefined- const index = aggregateIndex ?? matching?.[0] ?? state.nextFinalIndex- const existing = state.blocks.get(index)- if (existing?.final === serialized)- continue- if (existing?.final !== undefined)- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude changed a previously settled assistant block')- state.blocks.set(index, { type, final: serialized, ...typeof block.id === 'string' ? { callId: block.id } : {} })- state.nextFinalIndex = Math.max(state.nextFinalIndex, index + 1)- let content: NativeContent- if (type === 'text' && typeof block.text === 'string')- content = { type: 'text', text: block.text }- else if (type === 'thinking' && typeof block.thinking === 'string')- content = { type: 'thinking', text: block.thinking }- else if (type === 'tool_use')- content = { type: 'tool-call', id: stringField(block, 'id'), name: stringField(block, 'name'), arguments: JSON.stringify(block.input ?? {}) }- else if (type === 'redacted_thinking')- continue- else- throw new NativeBridgeError('BRIDGE_UNSUPPORTED_EVENT', `Unsupported Claude assistant content: ${type}`)- this.sink.assistant(`${id}:block:${index}`, [content])- if (content.type === 'tool-call' && !run.tools.has(content.id)) {- run.tools.add(content.id)- this.sink.toolStart(content.id, content.name, content.arguments)- }- }- }-- private toolResults(run: ClaudeRun, body: Record<string, unknown>): void {- if (!Array.isArray(body.content))- return- for (const value of body.content) {- const block = record(value)- if (block.type !== 'tool_result')- continue- const id = stringField(block, 'tool_use_id')- if (run.endedTools.has(id))- continue- if (!run.tools.has(id))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude tool result has no native tool call in the active run')- run.endedTools.add(id)- this.sink.toolEnd(id, resultText(block.content), block.is_error === true)- }- }-- private interrupt(run: ClaudeRun): void {- if (run.interruptSent)- return- run.interruptSent = true- run.interruptTimer = setTimeout(() => {- this.transport.fail(new NativeBridgeError('BRIDGE_INTERRUPT_TIMEOUT', 'Claude did not settle the interrupted run; its process was closed'))- }, INTERRUPT_TIMEOUT_MS)- run.interruptPending = true- void this.control({ subtype: 'interrupt', ...this.capabilities.has('interrupt_cancel_queued_v1') ? { cancel_queued: true } : {} }, undefined, INTERRUPT_TIMEOUT_MS).then((response) => {- const receipt = record(response ?? {})- if (Array.isArray(receipt.still_queued) && receipt.still_queued.includes(run.inputId))- throw new NativeBridgeError('BRIDGE_INTERRUPT_QUEUED_INPUT', 'Claude retained the cancelled user input in its native queue')- run.interruptPending = false- this.finish(run)- }).catch((error) => {- if (this.active === run)- this.transport.fail(errorFrom(error))- })- for (const id of run.tasks)- this.stopTask(run, id)- }-- private stopTask(run: ClaudeRun, id: string): void {- if (run.stoppedTasks.has(id))- return- run.stoppedTasks.add(id)- void this.control({ subtype: 'stop_task', task_id: id }, undefined, INTERRUPT_TIMEOUT_MS).catch((error) => {- if (this.active === run)- this.transport.fail(errorFrom(error))- })- }-- private withdrawApprovals(error: Error): void {- for (const controller of this.approvals.values())- controller.abort(error)- this.approvals.clear()- }-- private async answer(id: string, request: Record<string, unknown>): Promise<void> {- const controller = new AbortController()- this.approvals.set(id, controller)- const run = this.active- const signal = run ? AbortSignal.any([run.signal, controller.signal]) : controller.signal- try {- if (request.subtype === 'hook_callback') {- const input = record(request.input)- if (request.callback_id !== SESSION_START_HOOK_ID || input.hook_event_name !== 'SessionStart')- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude invoked an unregistered native identity hook')- this.checkIdentity(input, true)- if (this.opening && typeof input.model === 'string' && input.model !== '') {- this.effectiveModel ??= input.model- if (!this.defaultsPending)- this.startupModel ??= input.model- }- this.transport.write({ type: 'control_response', response: { subtype: 'success', request_id: id, response: {} } })- return- }- if (request.subtype !== 'can_use_tool') {- this.replyError(id, `Unsupported native control request: ${String(request.subtype)}`)- return- }- const tool = stringField(request, 'tool_name')- const input = record(request.input)- const callId = stringField(request, 'tool_use_id')- let response: Record<string, unknown> = { behavior: 'deny', message: 'Native tool request is unavailable or cancelled' }- if (run && !signal.aborted && !this.disposed) {- if (tool === 'AskUserQuestion') {- const questions = questionsOf(input)- const received = await this.sink.questions(callId, questions, signal)- const answers = Object.fromEntries(questions.map((question) => {- const value = received[question.id]- if (typeof value !== 'string' && !Array.isArray(value))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Claude question response is missing an answer')- return [question.id, Array.isArray(value) ? value.join(', ') : value]- }))- if (!signal.aborted)- response = { behavior: 'allow', updatedInput: { ...input, answers } }- }- else if (this.permission?.sandbox === 'read-only') {- response = { behavior: 'deny', message: '当前会话为只读;请先在权限菜单切换模式。' }- }- else if (this.permission?.approval !== 'never') {- const allowed = await this.sink.approval(callId, {- kind: tool === 'Bash' ? 'command' : ['Write', 'Edit', 'MultiEdit', 'NotebookEdit'].includes(tool) ? 'file' : 'tool',- title: typeof request.title === 'string' ? request.title : tool,- details: stripVTControlCharacters([- ...new Set([request.decision_reason, request.description, input.description].filter((value): value is string => typeof value === 'string' && value !== '')),- ...typeof request.blocked_path === 'string' ? [`blocked_path: ${request.blocked_path}`] : [],- ...Object.entries(input).filter(([key, value]) => key !== 'description' || typeof value !== 'string').map(([key, value]) => `${key}: ${typeof value === 'string' ? value : JSON.stringify(value, null, 2)}`),- ].join('\n\n')),- }, signal)- if (allowed && !signal.aborted)- response = { behavior: 'allow', updatedInput: input }- }- }- if (!controller.signal.aborted)- this.transport.write({ type: 'control_response', response: { subtype: 'success', request_id: id, response } })- }- catch (error) {- if (!controller.signal.aborted)- this.replyError(id, errorFrom(error).message)- if (request.subtype === 'hook_callback')- this.transport.fail(errorFrom(error))- }- finally {- this.approvals.delete(id)- }- }-- private replyError(id: string, error: string): void {- this.transport.write({ type: 'control_response', response: { subtype: 'error', request_id: id, error } })- }-}--export async function createClaudeSession(command: NativeCommand, cwd: string, nativeSessionId: string | null, sink: NativeSink, signal: AbortSignal, options?: NativeSessionOpenOptions, attachments?: NativeAttachments): Promise<NativeSession> {- if (options?.forkFrom !== undefined && (nativeSessionId !== null || options.forkFrom === ''))- throw new NativeBridgeError('BRIDGE_FORK_INVALID', 'Claude fork requires a source session and no existing native binding')- const session = new ClaudeSession(command, cwd, nativeSessionId, sink, options, attachments)- await session.open(signal)- return session-}diff --git a/packages/dsh-tauri-kernel/src/host/backends/codex.test.ts b/packages/dsh-tauri-kernel/src/host/backends/codex.test.tsdeleted file mode 100644index 9cb86697..00000000--- a/packages/dsh-tauri-kernel/src/host/backends/codex.test.ts+++ /dev/null@@ -1,1434 +0,0 @@-import type { Frame } from './process.fixture'-import type { NativeAttachments, NativePermission, NativeSession, NativeSessionOpenOptions } from './types'-import { spawn } from 'node:child_process'-import { createUserMessage } from '@deepseek-ai/dsh-llm'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { createCodexSession } from './codex'-import { createSink, ProcessFixture } from './process.fixture'--vi.mock('node:child_process', () => ({ spawn: vi.fn() }))--const command = { file: 'C:/fixture/codex.exe', args: [], env: {} }-const sessions: NativeSession[] = []--interface Terminal {- itemId: string- processId: string-}--function codexProcess(options: {- threadId?: string- model?: string- modelProvider?: string- reasoningEffort?: string | null- config?: Frame- models?: Frame[]- catalog?: { config?: Frame, models?: Frame[] }- terminals?: Terminal[]- intercept?: (frame: Frame, fixture: ProcessFixture) => boolean-} = {}) {- const terminals = options.terminals ?? []- const catalogs: ProcessFixture[] = []- function process(catalog = false) {- const source = catalog ? options.catalog ?? options : options- const fixture = new ProcessFixture((frame) => {- if (options.intercept?.(frame, fixture))- return- switch (frame.method) {- case 'initialize':- fixture.send({ id: frame.id, result: { userAgent: 'codex-cli/fixture' } })- break- case 'thread/start':- case 'thread/resume':- case 'thread/fork':- fixture.send({ id: frame.id, result: { thread: { id: options.threadId ?? 'thread-1' }, model: options.model, modelProvider: options.modelProvider, reasoningEffort: options.reasoningEffort } })- break- case 'config/read':- fixture.send({ id: frame.id, result: { config: source.config ?? {} } })- break- case 'model/list':- fixture.send({ id: frame.id, result: { data: source.models ?? [], nextCursor: null } })- break- case 'thread/backgroundTerminals/list':- fixture.send({ id: frame.id, result: { data: [...terminals], nextCursor: null } })- break- case 'thread/backgroundTerminals/terminate': {- const params = frame.params as Frame- const index = terminals.findIndex(terminal => terminal.processId === params.processId)- if (index >= 0)- terminals.splice(index, 1)- fixture.send({ id: frame.id, result: { terminated: index >= 0 } })- break- }- case 'turn/start':- fixture.send({ id: frame.id, result: { turn: { id: 'turn-1' } } })- break- case 'turn/interrupt':- fixture.send({ id: frame.id, result: {} })- }- })- return fixture- }- const fixture = process()- vi.mocked(spawn).mockImplementation(() => {- if (vi.mocked(spawn).mock.calls.length === 1)- return fixture.child- const catalog = process(true)- catalogs.push(catalog)- return catalog.child- })- return { fixture, catalogs, terminals }-}--async function open(storedId: string | null = null, sink = createSink(), options?: NativeSessionOpenOptions, attachments?: NativeAttachments) {- const session = await createCodexSession(command, 'C:/fixture/workspace', storedId, sink, new AbortController().signal, options, attachments)- sessions.push(session)- return session-}--/** Official image block; the attachment brand is opaque to this package. */-const image = (attachment: { id: string, mediaType: string, bytes: number }) => createUserMessage({ source: { kind: 'user' }, content: [{ type: 'image', attachment } as never] })--const modelInfo = (id: string, levels: string[] = ['low', 'high'], defaultEffort = 'low') => ({ id: `catalog:${id}`, model: id, displayName: `Native ${id}`, description: `${id} description`, supportedReasoningEfforts: levels.map(reasoningEffort => ({ reasoningEffort, description: `${reasoningEffort} reasoning` })), defaultReasoningEffort: defaultEffort, isDefault: false })-const user = () => createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'inspect the workspace' }] })-const completed = (fixture: ProcessFixture, status = 'completed') => fixture.send({ method: 'turn/completed', params: { threadId: 'thread-1', turn: { id: 'turn-1', status } } })-const notify = (fixture: ProcessFixture, method: string, params: Frame) => fixture.send({ method, params: { threadId: 'thread-1', turnId: 'turn-1', ...params } })--beforeEach(() => vi.mocked(spawn).mockReset())-afterEach(async () => {- for (const session of sessions.splice(0))- await session.dispose()- vi.restoreAllMocks()- vi.useRealTimers()-})--describe('codex native app-server contract', () => {- it('creates one native thread without a prompt or DSH tool injection', async () => {- const { fixture } = codexProcess()- const session = await open()- expect(session.id).toBe('thread-1')- expect(spawn).toHaveBeenCalledWith('C:/fixture/codex.exe', ['app-server', '--listen', 'stdio://'], {- cwd: 'C:/fixture/workspace',- env: {},- shell: false,- windowsHide: true,- stdio: ['pipe', 'pipe', 'pipe'],- })- expect(fixture.frames.map(frame => frame.method)).toEqual(['initialize', 'initialized', 'thread/start', 'thread/backgroundTerminals/list'])- expect(fixture.frames[2]).toEqual({ id: 2, method: 'thread/start', params: { cwd: 'C:/fixture/workspace' } })- })-- describe.each(['start', 'resume', 'fork'] as const)('thread/%s permissions', (mode) => {- it.each((['read-only', 'workspace-write', 'danger-full-access'] as const).flatMap(sandbox => (['ask', 'never'] as const).map(approval => ({ sandbox, approval }))))('sends SandboxMode $sandbox and approval $approval on the native wire', async (permission) => {- const { fixture } = codexProcess()- await open(mode === 'resume' ? 'thread-1' : null, createSink(), { ...mode === 'fork' ? { forkFrom: 'source-thread' } : {}, permission })- expect(fixture.frames[2]).toEqual({ id: 2, method: `thread/${mode}`, params: {- ...mode === 'start' ? {} : { threadId: mode === 'resume' ? 'thread-1' : 'source-thread' },- cwd: 'C:/fixture/workspace',- approvalPolicy: permission.approval === 'ask' ? 'on-request' : 'never',- sandbox: permission.sandbox,- } })- })- })-- it.each(['start', 'resume', 'fork'] as const)('applies each permission switch to the next turn of the cached %s thread', async (mode) => {- const { fixture } = codexProcess()- const session = await open(mode === 'resume' ? 'thread-1' : null, createSink(), { ...mode === 'fork' ? { forkFrom: 'source-thread' } : {}, permission: { sandbox: 'read-only', approval: 'ask' } })- const permissions: { permission: NativePermission, approvalPolicy: string, sandboxPolicy: Frame }[] = [- { permission: { sandbox: 'read-only', approval: 'ask' }, approvalPolicy: 'on-request', sandboxPolicy: { type: 'readOnly', networkAccess: false } },- { permission: { sandbox: 'danger-full-access', approval: 'never' }, approvalPolicy: 'never', sandboxPolicy: { type: 'dangerFullAccess' } },- { permission: { sandbox: 'danger-full-access', approval: 'ask' }, approvalPolicy: 'on-request', sandboxPolicy: { type: 'dangerFullAccess' } },- { permission: { sandbox: 'workspace-write', approval: 'never' }, approvalPolicy: 'never', sandboxPolicy: { type: 'workspaceWrite', writableRoots: ['C:/fixture/workspace'], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: false } },- { permission: { sandbox: 'workspace-write', approval: 'ask' }, approvalPolicy: 'on-request', sandboxPolicy: { type: 'workspaceWrite', writableRoots: ['C:/fixture/workspace'], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: false } },- { permission: { sandbox: 'read-only', approval: 'never' }, approvalPolicy: 'never', sandboxPolicy: { type: 'readOnly', networkAccess: false } },- ]- for (const { permission, approvalPolicy, sandboxPolicy } of permissions) {- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, undefined, permission)- const request = await started- completed(fixture)- await submitted- expect(request.params).toEqual({ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }], approvalPolicy, sandboxPolicy })- }- expect(fixture.frames.filter(frame => frame.method === `thread/${mode}`)).toHaveLength(1)- expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(permissions.length)- expect(spawn).toHaveBeenCalledOnce()- expect(session.id).toBe('thread-1')- })-- it.each([- { permission: { approval: 'never' } as NativePermission, policy: { approvalPolicy: 'never' } },- { permission: { sandbox: 'read-only' } as NativePermission, policy: { sandboxPolicy: { type: 'readOnly', networkAccess: false } } },- ])('leaves missing permission fields to the native defaults: $permission', async ({ permission, policy }) => {- const { fixture } = codexProcess()- const session = await open(null, createSink(), { permission })- expect(fixture.frames[2]?.params).toEqual({ cwd: 'C:/fixture/workspace', ...permission.approval ? { approvalPolicy: 'never' } : {}, ...permission.sandbox ? { sandbox: 'read-only' } : {} })- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, undefined, permission)- const request = await started- completed(fixture)- await submitted- expect(request.params).toEqual({ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }], ...policy })- })-- it('snapshots permission before waiting for native turn preparation', async () => {- const { fixture } = codexProcess()- const session = await open()- const permission: NativePermission = { sandbox: 'danger-full-access', approval: 'never' }- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, undefined, permission)- permission.sandbox = 'read-only'- permission.approval = 'ask'- const request = await started- completed(fixture)- await submitted- expect(request.params).toEqual({ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }], approvalPolicy: 'never', sandboxPolicy: { type: 'dangerFullAccess' } })- })-- it('never autoapproves a native request under never plus read-only', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const permission: NativePermission = { sandbox: 'read-only', approval: 'never' }- const session = await open(null, sink, { permission })- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, undefined, permission)- await started- const answered = fixture.next(frame => frame.id === 'readonly-approval')- fixture.send({ id: 'readonly-approval', method: 'item/commandExecution/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'write-outside', command: 'write outside workspace' } })- const response = await answered- completed(fixture)- await submitted- expect(response).toEqual({ id: 'readonly-approval', result: { decision: 'decline' } })- expect(sink.approval).toHaveBeenCalledOnce()- })-- it('resumes exactly the stored native thread without starting a replacement', async () => {- const { fixture } = codexProcess({ threadId: 'stored-thread' })- const session = await open('stored-thread')- expect(session.id).toBe('stored-thread')- expect(fixture.frames[2]).toEqual({ id: 2, method: 'thread/resume', params: { threadId: 'stored-thread', cwd: 'C:/fixture/workspace' } })- expect(fixture.frames.some(frame => frame.method === 'thread/start')).toBe(false)- })-- it('refuses a changed resume id instead of silently binding a new thread', async () => {- const { fixture } = codexProcess({ threadId: 'different-thread' })- await expect(open('stored-thread')).rejects.toMatchObject({ code: 'BRIDGE_RESUME_MISMATCH' })- expect(fixture.frames.map(frame => frame.method)).toEqual(['initialize', 'initialized', 'thread/resume'])- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('refuses an unavailable background cleanup capability before any native input', async () => {- const { fixture } = codexProcess({ intercept: (frame, child) => {- if (frame.method !== 'thread/backgroundTerminals/list')- return false- child.send({ id: frame.id, error: { code: -32601, message: 'Unknown method' } })- return true- } })- await expect(open()).rejects.toMatchObject({ code: 'BRIDGE_NATIVE_REQUEST', message: 'Unknown method' })- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('forks into a newly acknowledged thread with the new cwd and no prompt fallback', async () => {- const { fixture } = codexProcess({ threadId: 'child-thread' })- const session = await open(null, createSink(), { forkFrom: 'source-thread' })- expect(session.id).toBe('child-thread')- expect(fixture.frames[2]).toEqual({ id: 2, method: 'thread/fork', params: { threadId: 'source-thread', cwd: 'C:/fixture/workspace' } })- expect(fixture.frames.some(frame => frame.method === 'thread/start' || frame.method === 'thread/resume' || frame.method === 'turn/start')).toBe(false)- })-- it('rejects a fork returning the source identity without starting a replacement', async () => {- const { fixture } = codexProcess({ threadId: 'source-thread' })- await expect(open(null, createSink(), { forkFrom: 'source-thread' })).rejects.toMatchObject({ code: 'BRIDGE_FORK_MISMATCH' })- expect(fixture.frames.map(frame => frame.method)).toEqual(['initialize', 'initialized', 'thread/fork'])- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('rejects ambiguous resume and fork options before spawning', async () => {- await expect(open('stored-thread', createSink(), { forkFrom: 'source-thread' })).rejects.toMatchObject({ code: 'BRIDGE_FORK_INVALID' })- expect(spawn).not.toHaveBeenCalled()- })-- it('reads each model directory from a fresh app-server without replacing the native thread', async () => {- const options = {- model: 'fixture-alpha',- reasoningEffort: 'high',- config: { model: 'fixture-alpha' },- models: [modelInfo('old-gpt')],- catalog: { config: { model: 'fixture-alpha', model_reasoning_effort: 'high' }, models: [modelInfo('fixture-alpha'), modelInfo('fixture-beta')] },- }- const { fixture, catalogs } = codexProcess(options)- const session = await open()- const initialFrames = [...fixture.frames]- const directory = await session.models!(new AbortController().signal)- expect(directory.models.map(model => model.id)).toEqual(['fixture-alpha', 'fixture-beta'])- expect(directory.defaultModel).toBe('fixture-alpha')- expect(directory.defaultReasoningEffort).toBe('high')- expect(catalogs).toHaveLength(1)- expect(catalogs[0]!.frames.map(frame => frame.method)).toEqual(['initialize', 'initialized', 'config/read', 'model/list'])- expect(catalogs[0]!.frames[0]).toEqual(initialFrames[0])- expect(catalogs[0]!.stdin.end).toHaveBeenCalledOnce()- expect(fixture.frames).toEqual(initialFrames)- expect(fixture.kill).not.toHaveBeenCalled()- options.catalog.models = [modelInfo('fixture-alpha'), modelInfo('fixture-gamma')]- expect((await session.models!(new AbortController().signal)).models.map(model => model.id)).toEqual(['fixture-alpha', 'fixture-gamma'])- expect(catalogs).toHaveLength(2)- expect(catalogs.every(child => child.stdin.end.mock.calls.length === 1)).toBe(true)- expect(session.id).toBe('thread-1')- expect(spawn).toHaveBeenCalledTimes(3)- expect(fixture.frames).toEqual(initialFrames)- })-- it('refuses a changed native provider instead of applying its models to the bound thread', async () => {- const options = {- model: 'old-model',- modelProvider: 'old-provider',- catalog: { config: { model_provider: 'new-provider', model: 'new-model' }, models: [modelInfo('new-model')] },- }- const { fixture, catalogs } = codexProcess(options)- const session = await open()- await expect(session.models!(new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_PROVIDER_CHANGED' })- expect(catalogs[0]!.frames.map(frame => frame.method)).toEqual(['initialize', 'initialized', 'config/read'])- expect(catalogs[0]!.stdin.end).toHaveBeenCalledOnce()- expect(fixture.kill).not.toHaveBeenCalled()- expect(session.id).toBe('thread-1')- options.catalog.config.model_provider = 'old-provider'- expect((await session.models!(new AbortController().signal)).models.map(model => model.id)).toEqual(['new-model', 'old-model'])- expect(fixture.frames.filter(frame => frame.method === 'thread/start')).toHaveLength(1)- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- })-- it('keeps the effective native default effort distinct from the catalog preset', async () => {- const { fixture } = codexProcess({ model: 'deepseek', reasoningEffort: 'high', config: { model: 'deepseek', model_reasoning_effort: 'high' }, models: [modelInfo('deepseek', ['low', 'high'], 'low')] })- const session = await open()- const catalog = await session.models!(new AbortController().signal)- expect(catalog.defaultModel).toBe('deepseek')- expect(catalog.defaultReasoningEffort).toBe('high')- expect(catalog.models[0]?.reasoning?.defaultEffort).toBe('low')- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: null })- expect((await started).params).toEqual({ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }] })- completed(fixture)- await submitted- expect(session.id).toBe('thread-1')- })-- it('closes a failed catalog reader without closing the bound thread and can retry', async () => {- let fail = true- const { fixture, catalogs } = codexProcess({ model: 'baseline', intercept: (frame, child) => {- if (frame.method !== 'model/list' || !fail)- return false- child.send({ id: frame.id, error: { code: -32601, message: 'Catalog is unavailable' } })- return true- } })- const session = await open()- await expect(session.models!(new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_NATIVE_REQUEST', message: 'Catalog is unavailable' })- expect(catalogs).toHaveLength(1)- expect(catalogs[0]!.stdin.end).toHaveBeenCalledOnce()- expect(fixture.kill).not.toHaveBeenCalled()- fail = false- expect((await session.models!(new AbortController().signal)).defaultModel).toBe('baseline')- expect(catalogs).toHaveLength(2)- expect(session.id).toBe('thread-1')- expect(fixture.frames.filter(frame => frame.method === 'thread/start')).toHaveLength(1)- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- })-- it('cancels a catalog reader before any native input without closing the thread', async () => {- const { fixture, catalogs } = codexProcess({ intercept: frame => frame.method === 'config/read' })- const session = await open()- const controller = new AbortController()- const listed = session.models!(controller.signal)- const rejected = expect(listed).rejects.toThrow('cancel catalog')- await vi.waitFor(() => expect(catalogs[0]?.frames.map(frame => frame.method)).toEqual(['initialize', 'initialized', 'config/read']))- controller.abort(new Error('cancel catalog'))- await rejected- expect(catalogs[0]!.stdin.end).toHaveBeenCalledOnce()- expect(fixture.kill).not.toHaveBeenCalled()- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- expect(session.id).toBe('thread-1')- })-- it('disposes every pending catalog reader with its native session', async () => {- const { fixture, catalogs } = codexProcess({ intercept: frame => frame.method === 'config/read' })- const session = await open()- const listed = session.models!(new AbortController().signal)- const rejected = expect(listed).rejects.toMatchObject({ code: 'BRIDGE_PROCESS_CLOSED' })- await vi.waitFor(() => expect(catalogs[0]?.frames.map(frame => frame.method)).toEqual(['initialize', 'initialized', 'config/read']))- await session.dispose()- await rejected- expect(catalogs[0]!.kill).toHaveBeenCalledWith('SIGTERM')- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- expect(session.id).toBe('thread-1')- })-- it.each(['abort', 'dispose'] as const)('does not publish a catalog %s during its graceful close', async (mode) => {- const { fixture, catalogs } = codexProcess({ models: [modelInfo('chosen')], intercept: (frame, child) => {- if (frame.method === 'model/list')- child.stdin.end.mockImplementationOnce(() => {})- return false- } })- const session = await open()- const controller = new AbortController()- const listed = session.models!(controller.signal)- const rejected = mode === 'abort' ? expect(listed).rejects.toThrow('cancel while closing') : expect(listed).rejects.toMatchObject({ code: 'BRIDGE_PROCESS_CLOSED' })- await vi.waitFor(() => expect(catalogs[0]?.stdin.end).toHaveBeenCalledOnce())- const disposing = mode === 'dispose' ? session.dispose() : undefined- if (mode === 'abort')- controller.abort(new Error('cancel while closing'))- catalogs[0]!.exit(0)- await disposing- await rejected- expect(fixture.frames.filter(frame => frame.method === 'thread/start')).toHaveLength(1)- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- })-- it('keeps the session usable when a reader close is interrupted', async () => {- let hold = true- const { fixture, catalogs } = codexProcess({ config: { model: 'chosen', model_reasoning_effort: 'low' }, models: [modelInfo('chosen')], intercept: (frame, child) => {- if (frame.method === 'model/list' && hold)- child.stdin.end.mockImplementationOnce(() => {})- return false- } })- const session = await open()- const listed = session.models!(new AbortController().signal)- await vi.waitFor(() => expect(catalogs[0]?.stdin.end).toHaveBeenCalledOnce(), { timeout: 20_000 })- hold = false- catalogs[0]!.exit(0)- expect((await listed).defaultModel).toBe('chosen')- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, { model: 'chosen', reasoningEffort: 'low' })- expect((await Promise.race([started, submitted]))?.params).toMatchObject({ model: 'chosen', effort: 'low' })- completed(fixture)- await submitted- await session.dispose()- expect(fixture.frames.filter(frame => frame.method === 'thread/start')).toHaveLength(1)- })-- it('disposal survives a thread that refuses to terminate', async () => {- const { fixture } = codexProcess()- const session = await open()- fixture.stdin.end.mockImplementationOnce(() => {})- fixture.kill.mockImplementation(() => true)- vi.useFakeTimers()- const disposing = session.dispose()- await vi.advanceTimersByTimeAsync(20_000)- await disposing- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('keeps the newest successful catalog when an earlier reader closes late', async () => {- let hold = true- const options = { catalog: { config: { model: 'old', model_reasoning_effort: 'low' }, models: [modelInfo('old')] }, intercept: (frame: Frame, child: ProcessFixture) => {- if (frame.method === 'model/list' && hold)- child.stdin.end.mockImplementationOnce(() => {})- return false- } }- const { fixture, catalogs } = codexProcess(options)- const session = await open()- const earlier = session.models!(new AbortController().signal)- await vi.waitFor(() => expect(catalogs[0]?.stdin.end).toHaveBeenCalledOnce())- hold = false- options.catalog = { config: { model: 'new', model_reasoning_effort: 'high' }, models: [modelInfo('new')] }- const latest = await session.models!(new AbortController().signal)- catalogs[0]!.exit(0)- expect((await earlier).defaultModel).toBe('old')- expect(latest.defaultModel).toBe('new')- expect(latest.defaultReasoningEffort).toBe('high')- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, { model: 'new', reasoningEffort: 'high' })- expect((await Promise.race([started, submitted]))?.params).toMatchObject({ model: 'new', effort: 'high' })- completed(fixture)- await submitted- expect(catalogs).toHaveLength(2)- expect(session.id).toBe('thread-1')- })-- it('bounds the complete catalog operation across consecutive native requests', async () => {- let delayed = false- const { fixture, catalogs } = codexProcess({ intercept: frame => delayed && (frame.method === 'initialize' || frame.method === 'config/read') })- const session = await open()- delayed = true- vi.useFakeTimers()- const resolved = vi.fn()- const rejected = vi.fn()- const listed = session.models!(new AbortController().signal).then(resolved, rejected)- await vi.advanceTimersByTimeAsync(30_000)- catalogs[0]!.send({ id: catalogs[0]!.frames[0]!.id, result: { userAgent: 'codex-cli/fixture' } })- await vi.advanceTimersByTimeAsync(29_999)- expect(catalogs[0]!.frames.map(frame => frame.method)).toEqual(['initialize', 'initialized', 'config/read'])- expect(rejected).not.toHaveBeenCalled()- await vi.advanceTimersByTimeAsync(1)- expect(rejected).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ code: 'BRIDGE_REQUEST_TIMEOUT', message: 'Codex model discovery timed out' }))- expect(resolved).not.toHaveBeenCalled()- await listed- expect(catalogs[0]!.stdin.end).toHaveBeenCalledOnce()- expect(fixture.kill).not.toHaveBeenCalled()- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- })-- it('bounds empty catalog pages even when every cursor is distinct', async () => {- let pages = 0- const { fixture, catalogs } = codexProcess({ intercept: (frame, child) => {- if (frame.method !== 'model/list')- return false- pages++- child.send({ id: frame.id, result: { data: [], nextCursor: pages <= 100 ? `cursor-${pages}` : null } })- return true- } })- const session = await open()- await expect(session.models!(new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_PROTOCOL_LIMIT' })- expect(pages).toBe(100)- expect(catalogs[0]!.stdin.end).toHaveBeenCalledOnce()- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- })-- it('keeps a custom-provider configured model without inventing reasoning capabilities or exposing config', async () => {- const { fixture, catalogs } = codexProcess({- model: 'deepseek-flash',- config: { model: 'deepseek-flash', model_provider: 'deepseek', model_reasoning_effort: null, auth: { token: 'secret-fixture' }, model_providers: { deepseek: { api_key: 'secret-fixture' } } },- models: [modelInfo('gpt-fixture')],- })- const session = await open()- const catalog = await session.models!(new AbortController().signal)- expect(catalog.defaultModel).toBe('deepseek-flash')- expect(catalog.models.find(model => model.id === 'deepseek-flash')).toEqual({ id: 'deepseek-flash', name: 'deepseek-flash' })- expect(JSON.stringify(catalog)).not.toContain('secret-fixture')- expect(catalogs[0]!.frames.filter(frame => frame.method === 'config/read').map(frame => frame.params)).toEqual([{ includeLayers: false, cwd: 'C:/fixture/workspace' }])- expect(catalogs[0]!.frames.filter(frame => frame.method === 'model/list').map(frame => frame.params)).toEqual([{ cursor: null, limit: 100, includeHidden: false }])- expect(fixture.frames.filter(frame => frame.method === 'thread/start')).toHaveLength(1)- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- })-- it('preserves official display names and distinct advertised xhigh, max and ultra effort identities', async () => {- codexProcess({- model: 'gpt-6.1-sol',- models: [{- id: 'gpt-6.1-sol',- model: 'gpt-6.1-sol',- displayName: 'GPT-6.1-Sol',- description: 'Latest workhorse model for coding and everyday work.',- hidden: false,- isDefault: true,- supportedReasoningEfforts: [- { reasoningEffort: 'low', description: 'Fast responses with lighter reasoning' },- { reasoningEffort: 'medium', description: 'Balances speed and reasoning depth for everyday tasks' },- { reasoningEffort: 'high', description: 'Greater reasoning depth for complex problems' },- { reasoningEffort: 'xhigh', description: 'Extra high reasoning depth for complex problems' },- { reasoningEffort: 'max', description: 'Maximum reasoning depth for the hardest problems' },- { reasoningEffort: 'ultra', description: 'Maximum reasoning with automatic task delegation' },- ],- defaultReasoningEffort: 'low',- }],- })- const session = await open()- const catalog = await session.models!(new AbortController().signal)- expect(catalog).toEqual({- defaultModel: 'gpt-6.1-sol',- models: [{- id: 'gpt-6.1-sol',- name: 'GPT-6.1-Sol',- description: 'Latest workhorse model for coding and everyday work.',- reasoning: {- efforts: [- { id: 'low', name: 'Low', description: 'Fast responses with lighter reasoning' },- { id: 'medium', name: 'Medium', description: 'Balances speed and reasoning depth for everyday tasks' },- { id: 'high', name: 'High', description: 'Greater reasoning depth for complex problems' },- { id: 'xhigh', name: 'Extra High', description: 'Extra high reasoning depth for complex problems' },- { id: 'max', name: 'Max', description: 'Maximum reasoning depth for the hardest problems' },- { id: 'ultra', name: 'Ultra', description: 'Maximum reasoning with automatic task delegation' },- ],- defaultEffort: 'low',- },- }],- })- })-- it('labels advertised none as Off without changing vendor-specific reasoning ids', async () => {- codexProcess({ models: [modelInfo('vendor-model', ['none', 'minimal', 'vendor-deep'], 'none')] })- const session = await open()- const catalog = await session.models!(new AbortController().signal)- expect(catalog.models).toEqual([{- id: 'vendor-model',- name: 'Native vendor-model',- description: 'vendor-model description',- reasoning: {- efforts: [- { id: 'none', name: 'Off', description: 'none reasoning' },- { id: 'minimal', name: 'Minimal', description: 'minimal reasoning' },- { id: 'vendor-deep', name: 'vendor-deep', description: 'vendor-deep reasoning' },- ],- defaultEffort: 'none',- },- }])- })-- it.each(['none', 'xhigh', 'max', 'ultra'])('submits advertised %s effort unchanged on the Codex wire', async (effort) => {- const { fixture } = codexProcess({ model: 'chosen', reasoningEffort: 'low', models: [modelInfo('chosen', ['none', 'low', 'xhigh', 'max', 'ultra'])] })- const session = await open()- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, { model: 'chosen', reasoningEffort: effort })- expect(await started).toMatchObject({ params: { model: 'chosen', effort } })- completed(fixture)- await submitted- expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)- })-- it('rejects unadvertised Off before input instead of inferring it from other GPT models', async () => {- const { fixture } = codexProcess({ model: 'chosen', reasoningEffort: 'low', models: [modelInfo('chosen', ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'])] })- const session = await open()- await expect(session.submit([user()], new AbortController().signal, { model: 'chosen', reasoningEffort: 'none' })).rejects.toMatchObject({ code: 'BRIDGE_EFFORT_UNSUPPORTED' })- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- })-- it('paginates native models using wire model ids and rejects repeated cursors', async () => {- let repeat = false- const { fixture } = codexProcess({ intercept: (frame, child) => {- if (frame.method !== 'model/list')- return false- const cursor = (frame.params as Frame).cursor- child.send({ id: frame.id, result: { data: [modelInfo(cursor === null ? 'first' : 'second')], nextCursor: cursor === null || repeat ? 'page-2' : null } })- return true- } })- const session = await open()- expect((await session.models!(new AbortController().signal)).models.map(model => model.id)).toEqual(['first', 'second'])- repeat = true- await expect(session.models!(new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_PROTOCOL', message: 'Codex model listing repeated a cursor' })- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- })-- it('reports unsupported model discovery rather than inventing a catalog', async () => {- const { fixture } = codexProcess({ intercept: (frame, child) => {- if (frame.method !== 'model/list')- return false- child.send({ id: frame.id, error: { code: -32601, message: 'Unknown method: model/list' } })- return true- } })- const session = await open()- await expect(session.models!(new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_NATIVE_REQUEST', message: 'Unknown method: model/list' })- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- })-- it('submits snapshotted model and effort once without changing the native binding', async () => {- const { fixture } = codexProcess({ model: 'baseline', reasoningEffort: 'low', models: [modelInfo('baseline'), modelInfo('chosen')] })- const session = await open()- const selection = { model: 'chosen', reasoningEffort: 'high' }- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, selection)- selection.model = 'baseline'- selection.reasoningEffort = 'low'- expect(await started).toMatchObject({ params: { threadId: session.id, model: 'chosen', effort: 'high' } })- completed(fixture)- await submitted- expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)- expect(fixture.frames.filter(frame => frame.method === 'thread/start')).toHaveLength(1)- expect(session.id).toBe('thread-1')- })-- it('preserves CLI defaults on the first null selection and restores acknowledged defaults after an override', async () => {- const { fixture } = codexProcess({ model: 'baseline', reasoningEffort: 'low', models: [modelInfo('baseline'), modelInfo('chosen')] })- const session = await open()- const signal = new AbortController().signal- const first = fixture.next(frame => frame.method === 'turn/start')- const unchanged = session.submit([user()], signal, { model: null, reasoningEffort: null })- expect((await first).params).toEqual({ threadId: session.id, input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }] })- completed(fixture)- await unchanged- expect(fixture.frames.some(frame => frame.method === 'config/read' || frame.method === 'model/list')).toBe(false)- const changed = fixture.next(frame => frame.method === 'turn/start')- const override = session.submit([user()], signal, { model: 'chosen', reasoningEffort: 'high' })- await changed- completed(fixture)- await override- const reset = fixture.next(frame => frame.method === 'turn/start')- const restored = session.submit([user()], signal, { model: null, reasoningEffort: null })- expect(await reset).toMatchObject({ params: { threadId: session.id, model: 'baseline', effort: 'low' } })- completed(fixture)- await restored- })-- it.each(['resume', 'fork'] as const)('restores thread-agnostic defaults after an explicit override and reset following %s', async (mode) => {- const { fixture } = codexProcess({- model: 'persisted-override',- reasoningEffort: 'high',- config: { model: 'cli-default', model_reasoning_effort: 'low' },- models: [modelInfo('cli-default'), modelInfo('persisted-override')],- })- const session = await open(mode === 'resume' ? 'thread-1' : null, createSink(), mode === 'fork' ? { forkFrom: 'source-thread' } : undefined)- const signal = new AbortController().signal- const first = fixture.next(frame => frame.method === 'turn/start')- const inherited = session.submit([user()], signal, { model: null, reasoningEffort: null })- expect((await first).params).toEqual({ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }] })- completed(fixture)- await inherited- const changed = fixture.next(frame => frame.method === 'turn/start')- const override = session.submit([user()], signal, { model: 'persisted-override', reasoningEffort: 'high' })- expect((await changed).params).toMatchObject({ model: 'persisted-override', effort: 'high' })- completed(fixture)- await override- const reset = fixture.next(frame => frame.method === 'turn/start')- const restored = session.submit([user()], signal, { model: null, reasoningEffort: null })- expect((await reset).params).toMatchObject({ threadId: 'thread-1', model: 'cli-default', effort: 'low' })- completed(fixture)- await restored- expect((await session.models!(signal)).defaultModel).toBe('cli-default')- expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(3)- expect(fixture.frames.some(frame => frame.method === 'thread/start')).toBe(false)- expect(session.id).toBe('thread-1')- })-- it('refuses an explicit reset to an unknown resumed CLI default instead of guessing from the catalog', async () => {- const { fixture } = codexProcess({- model: 'persisted-override',- reasoningEffort: 'high',- models: [{ ...modelInfo('catalog-default'), isDefault: true }],- intercept: (frame, child) => {- if (frame.method !== 'turn/start')- return false- child.send({ id: frame.id, result: { turn: { id: 'turn-1' } } })- completed(child)- return true- },- })- const session = await open('thread-1')- const signal = new AbortController().signal- expect((await session.models!(signal)).defaultModel).toBeUndefined()- await session.submit([user()], signal, { model: 'catalog-default', reasoningEffort: 'high' })- await expect(session.submit([user()], signal, { model: null, reasoningEffort: null })).rejects.toMatchObject({ code: 'BRIDGE_DEFAULT_UNAVAILABLE' })- expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)- })-- it('refuses an explicit resumed effort reset when only the persisted override is known', async () => {- const { fixture } = codexProcess({- model: 'persisted-override',- reasoningEffort: 'high',- config: { model: 'custom-default', model_reasoning_effort: null },- models: [modelInfo('persisted-override')],- intercept: (frame, child) => {- if (frame.method !== 'turn/start')- return false- child.send({ id: frame.id, result: { turn: { id: 'turn-1' } } })- completed(child)- return true- },- })- const session = await open('thread-1')- const signal = new AbortController().signal- await session.submit([user()], signal, { model: 'persisted-override', reasoningEffort: 'high' })- await expect(session.submit([user()], signal, { model: null, reasoningEffort: null })).rejects.toMatchObject({ code: 'BRIDGE_DEFAULT_UNAVAILABLE' })- expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)- expect(session.id).toBe('thread-1')- })-- it('uses only the selected model advertised default effort when changing models', async () => {- const { fixture } = codexProcess({ model: 'baseline', reasoningEffort: 'high', models: [modelInfo('baseline'), modelInfo('chosen', ['medium', 'high'], 'medium')] })- const session = await open()- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, { model: 'chosen', reasoningEffort: null })- expect(await started).toMatchObject({ params: { model: 'chosen', effort: 'medium' } })- completed(fixture)- await submitted- })-- it('rejects unsupported effort before native input and keeps the binding intact', async () => {- const { fixture } = codexProcess({ model: 'deepseek-flash', config: { model: 'deepseek-flash' }, models: [modelInfo('gpt-fixture')] })- const session = await open()- await expect(session.submit([user()], new AbortController().signal, { model: 'deepseek-flash', reasoningEffort: 'high' })).rejects.toMatchObject({ code: 'BRIDGE_EFFORT_UNSUPPORTED' })- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- expect(session.id).toBe('thread-1')- })-- it('refuses an unknown effort reset instead of silently retaining a previous explicit effort', async () => {- const { fixture } = codexProcess({ model: 'custom', reasoningEffort: null, models: [modelInfo('chosen')] })- const session = await open()- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, { model: 'chosen', reasoningEffort: 'high' })- await started- completed(fixture)- await submitted- await expect(session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: null })).rejects.toMatchObject({ code: 'BRIDGE_DEFAULT_UNAVAILABLE' })- expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)- })-- it('guards concurrent submissions while waiting for catalog discovery and cancels before input', async () => {- const { fixture, catalogs } = codexProcess({ intercept: frame => frame.method === 'config/read' })- const session = await open()- const signal = new AbortController()- const submitted = session.submit([user()], signal.signal, { model: 'chosen', reasoningEffort: null })- const rejected = expect(submitted).rejects.toThrow('cancel discovery')- await vi.waitFor(() => expect(catalogs[0]?.frames.map(frame => frame.method)).toEqual(['initialize', 'initialized', 'config/read']))- await expect(session.submit([user()], new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_BUSY' })- signal.abort(new Error('cancel discovery'))- await rejected- expect(fixture.frames.some(frame => frame.method === 'turn/start' || frame.method === 'turn/interrupt')).toBe(false)- })-- it('records function-call outputs without inventing another native execution', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const item = { id: 'function-output', type: 'functionCallOutput', name: 'read_file', namespace: 'functions', output: [{ type: 'input_text', text: 'native text' }, { type: 'input_image', image_url: 'data:image/png;base64,fixture' }] }- notify(fixture, 'item/completed', { item })- notify(fixture, 'item/completed', { item })- completed(fixture)- await submitted- expect(sink.assistant.mock.calls).toEqual([['function-output', [{ type: 'text', text: '{"id":"function-output","type":"functionCallOutput","name":"read_file","namespace":"functions","output":[{"type":"input_text","text":"native text"},{"type":"input_image","image_url":"data:image/png;base64,fixture"}]}' }]]])- expect(sink.toolStart).not.toHaveBeenCalled()- expect(sink.toolEnd).not.toHaveBeenCalled()- expect(fixture.frames.some(frame => frame.method === 'turn/interrupt')).toBe(false)- expect(fixture.kill).not.toHaveBeenCalled()- })-- it('rejects a malformed completed item instead of treating it as an unknown read-only event', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- const rejected = expect(submitted).rejects.toMatchObject({ code: 'BRIDGE_PROTOCOL', message: 'Missing native protocol field: type' })- await started- notify(fixture, 'item/completed', { item: { id: 'malformed-native-item', text: 'missing type' } })- completed(fixture)- await rejected- expect(sink.assistant).not.toHaveBeenCalled()- expect(sink.toolStart).not.toHaveBeenCalled()- })-- it('records unrecognized completed native items without terminating the native turn', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- notify(fixture, 'item/completed', { item: { id: 'future-native-item', type: 'futureNativeItem', details: { text: 'native event', count: 2 } } })- completed(fixture)- await submitted- expect(sink.assistant.mock.calls).toEqual([['future-native-item', [{ type: 'text', text: '{"id":"future-native-item","type":"futureNativeItem","details":{"text":"native event","count":2}}' }]]])- expect(sink.toolStart).not.toHaveBeenCalled()- expect(sink.toolEnd).not.toHaveBeenCalled()- expect(fixture.kill).not.toHaveBeenCalled()- })-- it.each(['resume', 'fork'] as const)('preserves inherited native settings on the first null preference after %s without model discovery', async (mode) => {- const { fixture } = codexProcess({- model: 'inherited-native-model',- reasoningEffort: 'high',- intercept: (frame, child) => {- if (frame.method === 'config/read' || frame.method === 'model/list') {- child.send({ id: frame.id, error: { code: -32601, message: 'Native catalog is unavailable' } })- return true- }- if (frame.method !== 'turn/start')- return false- child.send({ id: frame.id, result: { turn: { id: 'turn-1' } } })- completed(child)- return true- },- })- const session = await open(mode === 'resume' ? 'thread-1' : null, createSink(), mode === 'fork' ? { forkFrom: 'source-thread' } : undefined)- await session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: null })- expect(fixture.frames.filter(frame => frame.method === 'turn/start').map(frame => frame.params)).toEqual([{ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }] }])- expect(fixture.frames.some(frame => frame.method === 'config/read' || frame.method === 'model/list')).toBe(false)- expect(spawn).toHaveBeenCalledOnce()- })-- it('commits authoritative assistant content once after live text and reasoning deltas', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- const request = await started- expect(request.params).toEqual({ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }] })- notify(fixture, 'item/agentMessage/delta', { itemId: 'assistant-1', delta: 'hel' })- notify(fixture, 'item/agentMessage/delta', { itemId: 'assistant-1', delta: 'lo' })- notify(fixture, 'item/reasoning/summaryTextDelta', { itemId: 'reasoning-1', delta: 'verify first' })- const assistant = { itemId: 'assistant-1', item: { id: 'assistant-1', type: 'agentMessage', text: 'hello' } }- notify(fixture, 'item/completed', assistant)- notify(fixture, 'item/completed', assistant)- notify(fixture, 'item/completed', { item: { id: 'reasoning-1', type: 'reasoning', summary: ['verify first'], content: [] } })- completed(fixture)- await submitted- expect(sink.text.mock.calls).toEqual([['assistant-1', 'hel'], ['assistant-1', 'lo']])- expect(sink.thinking.mock.calls).toEqual([['reasoning-1', 'verify first']])- expect(sink.assistant.mock.calls).toEqual([- ['assistant-1', [{ type: 'text', text: 'hello' }]],- ['reasoning-1', [{ type: 'thinking', text: 'verify first' }]],- ])- })-- it.each(['raw', 'summary'] as const)('streams only the first %s reasoning track while settling the canonical summary', async (first) => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const tracks = first === 'raw' ? ['raw', 'summary'] : ['summary', 'raw']- for (const track of tracks)- notify(fixture, track === 'raw' ? 'item/reasoning/textDelta' : 'item/reasoning/summaryTextDelta', { itemId: 'reasoning-2', delta: `${track} reasoning` })- notify(fixture, 'item/completed', { item: { id: 'reasoning-2', type: 'reasoning', summary: ['summary reasoning'], content: ['raw reasoning'] } })- completed(fixture)- await submitted- expect(sink.thinking.mock.calls).toEqual([['reasoning-2', `${first} reasoning`]])- expect(sink.assistant.mock.calls).toEqual([['reasoning-2', [{ type: 'thinking', text: 'summary reasoning' }]]])- })-- it('preserves native tool ids and error results without executing DSH tools', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const item = { id: 'command-1', type: 'commandExecution', command: 'git status', cwd: 'C:/fixture/workspace', status: 'inProgress' }- notify(fixture, 'item/started', { item })- notify(fixture, 'item/commandExecution/outputDelta', { itemId: 'command-1', delta: 'fatal:' })- notify(fixture, 'item/completed', { item: { ...item, status: 'completed', aggregatedOutput: 'fatal: not a git repository', exitCode: 128 } })- notify(fixture, 'item/completed', { item: { ...item, status: 'completed', aggregatedOutput: 'fatal: not a git repository', exitCode: 128 } })- completed(fixture)- await submitted- const arguments_ = '{"command":"git status","cwd":"C:/fixture/workspace"}'- expect(sink.assistant.mock.calls).toEqual([['command-1:call', [{ type: 'tool-call', id: 'command-1', name: 'commandExecution', arguments: arguments_ }]]])- expect(sink.toolStart.mock.calls).toEqual([['command-1', 'commandExecution', arguments_]])- expect(sink.toolEnd.mock.calls).toEqual([['command-1', 'fatal: not a git repository', true]])- })-- it.each(['completed', 'failed'])('preserves a native Node REPL MCP text-image-text result with status %s exactly once', async (status) => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const item = { id: 'node-repl-image', type: 'mcpToolCall', server: 'node_repl', tool: 'js', arguments: { code: 'await nodeRepl.emitImage(image)' }, status: 'inProgress', result: null, error: null }- const result = { content: [- { type: 'text', text: 'before image' },- { type: 'image', data: 'cG5nLWZpeHR1cmU=', mimeType: 'image/png' },- { type: 'text', text: 'after image' },- ], isError: status === 'failed' }- notify(fixture, 'item/started', { item })- notify(fixture, 'item/completed', { item: { ...item, status, result } })- notify(fixture, 'item/completed', { item: { ...item, status, result } })- completed(fixture)- await submitted- const arguments_ = '{"code":"await nodeRepl.emitImage(image)"}'- expect(sink.assistant.mock.calls).toEqual([['node-repl-image:call', [{ type: 'tool-call', id: 'node-repl-image', name: 'mcp::node_repl/js', arguments: arguments_ }]]])- expect(sink.toolStart.mock.calls).toEqual([['node-repl-image', 'mcp::node_repl/js', arguments_]])- expect(sink.toolEnd.mock.calls).toEqual([['node-repl-image', `{"content":[{"type":"text","text":"before image"},{"type":"image","data":"cG5nLWZpeHR1cmU=","mimeType":"image/png"},{"type":"text","text":"after image"}],"isError":${status === 'failed' ? 'true' : 'false'}}`, status === 'failed']])- expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)- })-- it.each(['completed', 'failed', 'declined'])('settles an announced file change from native turn items with terminal status %s', async (status) => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal, undefined, { sandbox: 'workspace-write', approval: 'ask' })- await started- const item = { id: 'edit-terminal', type: 'fileChange', status: 'inProgress', changes: [- { path: 'C:/fixture/workspace/probe.svg', kind: { type: 'add' }, diff: '<svg>probe</svg>\n' },- { path: 'C:/fixture/workspace/probe.txt', kind: { type: 'add' }, diff: 'native-capability-probe\n' },- ] }- notify(fixture, 'item/started', { item })- notify(fixture, 'item/started', { item })- fixture.send({ method: 'turn/completed', params: { threadId: 'thread-1', turn: { id: 'turn-1', status: 'completed', items: [- { ...item, status },- { id: 'unannounced-history', type: 'fileChange', status: 'completed', changes: [] },- ], itemsView: 'full' } } })- await submitted- expect(sink.toolStart).toHaveBeenCalledOnce()- expect(sink.toolStart.mock.calls[0]?.slice(0, 2)).toEqual(['edit-terminal', 'fileChange'])- expect(sink.toolEnd.mock.calls).toEqual([['edit-terminal', '[{"path":"C:/fixture/workspace/probe.svg","kind":{"type":"add"},"diff":"<svg>probe</svg>\\n"},{"path":"C:/fixture/workspace/probe.txt","kind":{"type":"add"},"diff":"native-capability-probe\\n"}]', status !== 'completed']])- expect(sink.assistant).toHaveBeenCalledOnce()- })-- it.each(['inProgress', 'unknown', undefined])('does not invent a file-change result from nonterminal turn items with status %s', async (status) => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const item = { id: 'edit-unsettled', type: 'fileChange', changes: [], status }- notify(fixture, 'item/started', { item })- fixture.send({ method: 'turn/completed', params: { threadId: 'thread-1', turn: { id: 'turn-1', status: 'completed', items: [item], itemsView: 'summary' } } })- await submitted- expect(sink.toolStart).toHaveBeenCalledExactlyOnceWith('edit-unsettled', 'fileChange', '{"changes":[]}')- expect(sink.toolEnd).not.toHaveBeenCalled()- })-- it.each(['completed', 'failed', 'declined', undefined])('settles a completed file-change notification once with status %s', async (status) => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const item = { id: 'edit-completed', type: 'fileChange', changes: [], status }- notify(fixture, 'item/started', { item: { ...item, status: 'inProgress' } })- notify(fixture, 'item/completed', { item })- notify(fixture, 'item/completed', { item })- fixture.send({ method: 'turn/completed', params: { threadId: 'thread-1', turn: { id: 'turn-1', status: 'completed', items: [{ ...item, status: 'failed' }], itemsView: 'full' } } })- await submitted- expect(sink.toolStart).toHaveBeenCalledOnce()- expect(sink.toolEnd.mock.calls).toEqual([['edit-completed', '[]', status === 'failed' || status === 'declined']])- expect(sink.assistant).toHaveBeenCalledOnce()- })-- it('leaves an announced file change unsettled when the native turn contains no result', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- notify(fixture, 'item/started', { item: { id: 'edit-missing', type: 'fileChange', changes: [], status: 'inProgress' } })- completed(fixture)- await submitted- expect(sink.toolStart).toHaveBeenCalledExactlyOnceWith('edit-missing', 'fileChange', '{"changes":[]}')- expect(sink.toolEnd).not.toHaveBeenCalled()- })-- it.each(['thread', 'turn'])('ignores terminal file-change items from another native %s', async (scope) => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const item = { id: 'edit-current', type: 'fileChange', changes: [], status: 'inProgress' }- notify(fixture, 'item/started', { item })- fixture.send({ method: 'turn/completed', params: { threadId: scope === 'thread' ? 'other-thread' : 'thread-1', turn: { id: scope === 'turn' ? 'other-turn' : 'turn-1', status: 'completed', items: [{ ...item, status: 'completed' }], itemsView: 'full' } } })- completed(fixture)- await submitted- expect(sink.toolStart).toHaveBeenCalledOnce()- expect(sink.toolEnd).not.toHaveBeenCalled()- })-- it.each([true, false])('settles a native file change after approval returns %s without substituting the decision for a result', async (allowed) => {- const { fixture } = codexProcess()- const sink = createSink()- sink.approval.mockResolvedValue(allowed)- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const item = { id: 'edit-approval', type: 'fileChange', changes: [], status: 'inProgress' }- notify(fixture, 'item/started', { item })- const answered = fixture.next(frame => frame.id === 'patch-approval')- fixture.send({ id: 'patch-approval', method: 'item/fileChange/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'edit-approval' } })- expect(await answered).toEqual({ id: 'patch-approval', result: { decision: allowed ? 'accept' : 'decline' } })- expect(sink.toolEnd).not.toHaveBeenCalled()- notify(fixture, 'item/completed', { item: { ...item, status: allowed ? 'completed' : 'declined' } })- completed(fixture)- await submitted- expect(sink.toolEnd.mock.calls).toEqual([['edit-approval', '[]', !allowed]])- })-- it('does not present a streamed patch preview as a completed native file change', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- notify(fixture, 'item/fileChange/patchUpdated', { itemId: 'edit-preview', changes: [{ path: 'C:/fixture/workspace/probe.txt', kind: { type: 'add' }, diff: 'partial patch' }] })- completed(fixture)- await submitted- expect(sink.assistant).not.toHaveBeenCalled()- expect(sink.toolStart).not.toHaveBeenCalled()- expect(sink.toolEnd).not.toHaveBeenCalled()- })-- it('preserves native file-change output deltas on a failed completion', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const item = { id: 'edit-denied', type: 'fileChange', status: 'inProgress', changes: [{ path: 'C:/fixture/workspace/probe.txt', kind: { type: 'delete' }, diff: 'probe\n' }] }- notify(fixture, 'item/started', { item })- notify(fixture, 'item/fileChange/outputDelta', { itemId: 'edit-denied', delta: 'AccessDenied: ' })- notify(fixture, 'item/fileChange/outputDelta', { itemId: 'edit-denied', delta: 'delete denied by sandbox\n' })- notify(fixture, 'item/completed', { item: { ...item, status: 'failed' } })- completed(fixture)- await submitted- expect(sink.toolEnd.mock.calls).toEqual([['edit-denied', 'AccessDenied: delete denied by sandbox\n', true]])- })-- it.each(['item/started', 'item/completed'] as const)('presents each tool before starting it when the first native notification is %s', async (first) => {- const { fixture } = codexProcess()- const sink = createSink()- const order: string[] = []- sink.assistant.mockImplementation(id => order.push(`assistant:${id}`))- sink.toolStart.mockImplementation(id => order.push(`start:${id}`))- sink.toolEnd.mockImplementation(id => order.push(`end:${id}`))- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- const settled = vi.fn()- void submitted.then(settled, settled)- await started- try {- const firstTool = { id: 'parallel-command-1', type: 'commandExecution', command: 'git status', cwd: 'C:/fixture/workspace', status: first === 'item/completed' ? 'completed' : 'inProgress', aggregatedOutput: 'first output', exitCode: 0 }- notify(fixture, first, { item: firstTool })- if (first === 'item/started')- notify(fixture, 'item/completed', { item: { ...firstTool, status: 'completed' } })- await Promise.resolve()- expect(order).toEqual(['assistant:parallel-command-1:call', 'start:parallel-command-1', 'end:parallel-command-1'])- expect(settled).not.toHaveBeenCalled()- await expect(session.submit([user()], new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_BUSY' })- const secondTool = { id: 'parallel-command-2', type: 'commandExecution', command: 'git diff', cwd: 'C:/fixture/workspace', status: first === 'item/completed' ? 'completed' : 'inProgress', aggregatedOutput: 'second output', exitCode: 0 }- notify(fixture, first, { item: secondTool })- if (first === 'item/started')- notify(fixture, 'item/completed', { item: { ...secondTool, status: 'completed' } })- await Promise.resolve()- expect(settled).not.toHaveBeenCalled()- expect(order).toEqual([- 'assistant:parallel-command-1:call',- 'start:parallel-command-1',- 'end:parallel-command-1',- 'assistant:parallel-command-2:call',- 'start:parallel-command-2',- 'end:parallel-command-2',- ])- expect(sink.assistant.mock.calls).toEqual([- ['parallel-command-1:call', [{ type: 'tool-call', id: 'parallel-command-1', name: 'commandExecution', arguments: '{"command":"git status","cwd":"C:/fixture/workspace"}' }]],- ['parallel-command-2:call', [{ type: 'tool-call', id: 'parallel-command-2', name: 'commandExecution', arguments: '{"command":"git diff","cwd":"C:/fixture/workspace"}' }]],- ])- expect(sink.toolEnd.mock.calls).toEqual([['parallel-command-1', 'first output', false], ['parallel-command-2', 'second output', false]])- }- finally {- completed(fixture)- await submitted- }- expect(settled).toHaveBeenCalledTimes(1)- expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)- expect(fixture.frames.some(frame => frame.method === 'turn/interrupt')).toBe(false)- expect(fixture.kill).not.toHaveBeenCalled()- })-- it('rejects unknown native server requests instead of granting or executing them', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const answered = fixture.next(frame => frame.id === 'unknown-control')- fixture.send({ id: 'unknown-control', method: 'futureNative/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'future-tool' } })- expect(await answered).toEqual({ id: 'unknown-control', error: { code: -32601, message: 'Unsupported native server request: futureNative/requestApproval' } })- expect(sink.approval).not.toHaveBeenCalled()- expect(sink.questions).not.toHaveBeenCalled()- expect(sink.toolStart).not.toHaveBeenCalled()- completed(fixture)- await submitted- expect(fixture.kill).not.toHaveBeenCalled()- })-- it('routes a parked approval while RPC traffic continues and returns only allow-once', async () => {- const { fixture } = codexProcess()- const sink = createSink()- let allow!: (value: boolean) => void- const asked = Promise.withResolvers<void>()- sink.approval.mockImplementation(() => {- asked.resolve()- return new Promise(resolve => allow = resolve)- })- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const answered = fixture.next(frame => frame.id === 77 && 'result' in frame)- fixture.send({ id: 77, method: 'item/commandExecution/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'command-approval', command: 'git status', cwd: 'D:\\work', reason: 'command needs to read the repository', availableDecisions: ['accept', 'cancel'] } })- await asked.promise- notify(fixture, 'item/agentMessage/delta', { itemId: 'assistant-1', delta: 'awaiting your answer' })- expect(sink.text).toHaveBeenCalledWith('assistant-1', 'awaiting your answer')- allow(true)- expect(await answered).toEqual({ id: 77, result: { decision: 'accept' } })- expect(sink.approval.mock.calls[0]?.slice(0, 2)).toEqual(['command-approval', {- kind: 'command',- title: 'git status',- details: 'command needs to read the repository\ncommand: git status\ncwd: D:\\work',- }])- expect(sink.approval.mock.calls[0]![1].details).not.toContain('threadId')- completed(fixture)- await submitted- })-- it('names the proposed files in a file-change approval prompt', async () => {- const { fixture } = codexProcess()- const sink = createSink()- sink.approval.mockResolvedValue(true)- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- notify(fixture, 'item/started', { item: { id: 'edit-1', type: 'fileChange', status: 'inProgress', changes: [- { path: 'src/harness/session.ts', kind: { type: 'update' }, diff: '@@' },- { path: 'src/harness/new.ts', kind: { type: 'add' }, diff: '@@' },- ] } })- const answered = fixture.next(frame => frame.id === 81 && 'result' in frame)- fixture.send({ id: 81, method: 'item/fileChange/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'edit-1', reason: 'edit the harness session' } })- expect(await answered).toEqual({ id: 81, result: { decision: 'accept' } })- expect(sink.approval.mock.calls[0]![1]).toEqual({- kind: 'file',- title: 'Codex file changes',- details: 'edit the harness session\nsrc/harness/session.ts\nsrc/harness/new.ts',- })- completed(fixture)- await submitted- })-- it('cancels instead of answering accept when the native decision menu offers no one-shot grant', async () => {- const { fixture } = codexProcess()- const sink = createSink()- sink.approval.mockResolvedValue(true)- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const answered = fixture.next(frame => frame.id === 79 && 'result' in frame)- fixture.send({ id: 79, method: 'item/commandExecution/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'command-approval', command: 'rm -rf build', availableDecisions: [{ acceptWithExecpolicyAmendment: { execpolicy_amendment: ['rm', '-rf', 'build'] } }, 'cancel'] } })- expect(await answered).toEqual({ id: 79, result: { decision: 'cancel' } })- completed(fixture)- await submitted- })-- it('reports requested permissions without the raw native envelope', async () => {- const { fixture } = codexProcess()- const sink = createSink()- sink.approval.mockResolvedValue(true)- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const answered = fixture.next(frame => frame.id === 80 && 'result' in frame)- fixture.send({ id: 80, method: 'item/permissions/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'permissions-1', reason: 'write access is required', permissions: { network: { enabled: false }, fileSystem: { read: ['D:\\work'] } } } })- expect(await answered).toEqual({ id: 80, result: { permissions: { network: { enabled: false }, fileSystem: { read: ['D:\\work'] } }, scope: 'turn' } })- expect(sink.approval.mock.calls[0]![1]).toEqual({- kind: 'tool',- title: 'Codex additional permissions',- details: 'write access is required\npermissions: {"network":{"enabled":false},"fileSystem":{"read":["D:\\\\work"]}}',- })- completed(fixture)- await submitted- })-- it('withdraws a resolved native approval without sending a late grant', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const parked = Promise.withResolvers<boolean>()- sink.approval.mockReturnValue(parked.promise)- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- fixture.send({ id: 78, method: 'item/fileChange/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'edit-1' } })- const signal = sink.approval.mock.calls[0]![2]!- fixture.send({ method: 'serverRequest/resolved', params: { threadId: 'thread-1', requestId: 78 } })- parked.resolve(true)- await parked.promise- completed(fixture)- await submitted- expect(signal.aborted).toBe(true)- expect(fixture.frames.some(frame => frame.id === 78)).toBe(false)- })-- it('maps native question identities to answer arrays in the official question sink', async () => {- const { fixture } = codexProcess()- const sink = createSink()- sink.questions.mockResolvedValue({ language: 'TypeScript', focus: ['Events', 'Cancel'] })- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const answered = fixture.next(frame => frame.id === 'question-1')- fixture.send({ id: 'question-1', method: 'item/tool/requestUserInput', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'question-tool', questions: [- { id: 'language', question: 'Which language?', options: [{ label: 'TypeScript', description: 'Typed code' }] },- { id: 'focus', question: 'Which areas?' },- ] } })- expect(await answered).toEqual({ id: 'question-1', result: { answers: { language: { answers: ['TypeScript'] }, focus: { answers: ['Events', 'Cancel'] } } } })- expect(sink.questions.mock.calls[0]?.slice(0, 2)).toEqual(['question-tool', [- { id: 'language', question: 'Which language?', options: [{ label: 'TypeScript', description: 'Typed code' }] },- { id: 'focus', question: 'Which areas?' },- ]])- completed(fixture)- await submitted- })-- it('rejects secret questions without persisting their answers', async () => {- const { fixture } = codexProcess()- const sink = createSink()- const session = await open(null, sink)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- await started- const answered = fixture.next(frame => frame.id === 79)- fixture.send({ id: 79, method: 'item/tool/requestUserInput', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'secret', questions: [{ id: 'password', question: 'Password?', isSecret: true }] } })- expect(await answered).toMatchObject({ id: 79, error: { code: -32603, message: 'Secret native questions cannot be recorded in the official session log' } })- expect(sink.questions).not.toHaveBeenCalled()- completed(fixture)- await submitted- })-- it('cleans only interrupted turn terminals before declaring cancellation settled', async () => {- const { fixture, terminals } = codexProcess({ terminals: [{ itemId: 'old-command', processId: 'old-process' }] })- const session = await open()- const signal = new AbortController()- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], signal.signal)- const rejected = expect(submitted).rejects.toThrow('cancel this turn')- await started- terminals.push({ itemId: 'command-1', processId: 'new-process' })- notify(fixture, 'item/started', { item: { id: 'command-1', type: 'commandExecution', command: 'watch', processId: 'new-process' } })- const interrupted = fixture.next(frame => frame.method === 'turn/interrupt')- signal.abort(new Error('cancel this turn'))- expect(await interrupted).toMatchObject({ params: { threadId: 'thread-1', turnId: 'turn-1' } })- completed(fixture, 'interrupted')- await rejected- expect(fixture.frames.filter(frame => frame.method === 'thread/backgroundTerminals/terminate').map(frame => frame.params)).toEqual([{ threadId: 'thread-1', processId: 'new-process' }])- expect(terminals).toEqual([{ itemId: 'old-command', processId: 'old-process' }])- })-- it('obtains the turn id and interrupts even when cancelled before turn/start replies', async () => {- const { fixture } = codexProcess({ intercept: frame => frame.method === 'turn/start' })- const session = await open()- const signal = new AbortController()- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], signal.signal)- const rejected = expect(submitted).rejects.toThrow('cancel early')- const request = await started- signal.abort(new Error('cancel early'))- const interrupted = fixture.next(frame => frame.method === 'turn/interrupt')- fixture.send({ method: 'turn/started', params: { threadId: 'thread-1', turn: { id: 'turn-1' } } })- fixture.send({ id: request.id, result: { turn: { id: 'turn-1' } } })- await interrupted- completed(fixture, 'interrupted')- await rejected- expect(fixture.frames.filter(frame => frame.method === 'turn/interrupt')).toHaveLength(1)- })-- it('terminates late commands belonging to a cancelled native turn', async () => {- const { fixture, terminals } = codexProcess()- const session = await open()- const signal = new AbortController()- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], signal.signal)- const rejected = expect(submitted).rejects.toThrow('cancel late test')- await started- const interrupted = fixture.next(frame => frame.method === 'turn/interrupt')- signal.abort(new Error('cancel late test'))- await interrupted- completed(fixture, 'interrupted')- await rejected- terminals.push({ itemId: 'late-command', processId: 'late-process' })- const terminated = fixture.next(frame => frame.method === 'thread/backgroundTerminals/terminate')- notify(fixture, 'item/started', { item: { id: 'late-command', type: 'commandExecution', command: 'watch', processId: 'late-process' } })- expect(await terminated).toMatchObject({ params: { threadId: 'thread-1', processId: 'late-process' } })- expect(terminals).toEqual([])- })-- it('fails closed when interrupted background terminals remain after termination', async () => {- const { fixture, terminals } = codexProcess({ intercept: (frame, child) => {- if (frame.method !== 'thread/backgroundTerminals/terminate')- return false- child.send({ id: frame.id, result: { terminated: false } })- return true- } })- const session = await open()- const signal = new AbortController()- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], signal.signal)- const rejected = expect(submitted).rejects.toMatchObject({ code: 'BRIDGE_INTERRUPT_CLEANUP_FAILED' })- await started- terminals.push({ itemId: 'stuck-command', processId: 'stuck-process' })- signal.abort(new Error('cancel'))- await rejected- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- expect(fixture.frames.some(frame => frame.method === 'turn/interrupt')).toBe(false)- })-- it('keeps the official text and image order in one mixed native prompt', async () => {- const { fixture } = codexProcess()- const attachments: NativeAttachments = { path: () => 'C:/fixture/native.png', read: vi.fn() }- const session = await open(null, createSink(), undefined, attachments)- const started = fixture.next(frame => frame.method === 'turn/start')- const mixed = createUserMessage({ source: { kind: 'user' }, content: [- { type: 'text', text: 'before ' },- { type: 'image', attachment: { id: 'image-1', mediaType: 'image/png', bytes: 3 } as never },- { type: 'text', text: ' after' },- ] })- const submitted = session.submit([mixed], new AbortController().signal)- expect((await started).params).toEqual({- threadId: 'thread-1',- input: [- { type: 'text', text: 'before ', text_elements: [] },- { type: 'localImage', path: 'C:/fixture/native.png' },- { type: 'text', text: ' after', text_elements: [] },- ],- })- completed(fixture)- await submitted- })-- it('forwards an official image as native input instead of rejecting the prompt', async () => {- const { fixture } = codexProcess()- const attachments: NativeAttachments = { path: () => 'C:/fixture/native.png', read: vi.fn() }- const session = await open(null, createSink(), undefined, attachments)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user(), image({ id: 'image-1', mediaType: 'image/png', bytes: 3 })], new AbortController().signal)- expect((await started).params).toEqual({- threadId: 'thread-1',- input: [- { type: 'text', text: 'inspect the workspace', text_elements: [] },- { type: 'localImage', path: 'C:/fixture/native.png' },- ],- })- completed(fixture)- await submitted- expect(attachments.read).not.toHaveBeenCalled()- })-- it('inlines an official image as a data URL when the provider stores no host file', async () => {- const { fixture } = codexProcess()- const attachments: NativeAttachments = { path: () => undefined, read: vi.fn(async () => ({ mediaType: 'image/png', base64: 'Zm FrZQ==' })) }- const session = await open(null, createSink(), undefined, attachments)- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([image({ id: 'image-2', mediaType: 'image/png', bytes: 3 })], new AbortController().signal)- expect((await started).params).toEqual({- threadId: 'thread-1',- input: [{ type: 'image', url: 'data:image/png;base64,Zm FrZQ==' }],- })- completed(fixture)- await submitted- })-- it('refuses nontext user content rather than submitting a partial native prompt', async () => {- const { fixture } = codexProcess()- const session = await open()- const input = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'reasoning', text: 'not user text' }] })- await expect(session.submit([input], new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_UNSUPPORTED_CONTENT' })- expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)- })-- it('propagates a native crash and clears active control waits', async () => {- const { fixture } = codexProcess()- const session = await open()- const started = fixture.next(frame => frame.method === 'turn/start')- const submitted = session.submit([user()], new AbortController().signal)- const rejected = expect(submitted).rejects.toMatchObject({ code: 'BRIDGE_PROCESS_EXIT', message: 'Native process exited (7): native crash' })- await started- fixture.stderr.write('native crash')- fixture.exit(7)- await rejected- await expect(session.submit([user()], new AbortController().signal)).rejects.toMatchObject({ code: 'BRIDGE_PROCESS_EXIT' })- })-})diff --git a/packages/dsh-tauri-kernel/src/host/backends/codex.ts b/packages/dsh-tauri-kernel/src/host/backends/codex.tsdeleted file mode 100644index 8c1b582e..00000000--- a/packages/dsh-tauri-kernel/src/host/backends/codex.ts+++ /dev/null@@ -1,794 +0,0 @@-import type { UserMessage } from '@deepseek-ai/dsh-llm'-import type { Deferred } from './transport'-import type { NativeAttachments, NativeCommand, NativeContent, NativeImageRef, NativeModelCatalog, NativeModelInfo, NativePermission, NativeQuestion, NativeSession, NativeSessionOpenOptions, NativeSink, NativeTurnOptions } from './types'-import { abortError, deferred, errorFrom, INTERRUPT_TIMEOUT_MS, JsonLinesProcess, NativeBridgeError, nativeRuns, PendingRequests, record, REQUEST_TIMEOUT_MS, stringField } from './transport'--const INITIALIZATION = {- clientInfo: { name: 'dsh-tauri-kernel', title: 'DSH native session bridge', version: '1.0.0' },- capabilities: { experimentalApi: true },-}--const CODEX_REASONING_EFFORT_NAMES = new Map([- ['none', 'Off'],- ['minimal', 'Minimal'],- ['low', 'Low'],- ['medium', 'Medium'],- ['high', 'High'],- ['xhigh', 'Extra High'],- ['max', 'Max'],- ['ultra', 'Ultra'],-])--interface ToolState {- output: string- ended: boolean-}--interface BackgroundTerminal {- itemId: string- processId: string-}--interface CodexTurn {- result: Deferred<void>- signal: AbortSignal- id?: string- submitted: boolean- interruptSent: boolean- baseline: Set<string>- commandItems: Set<string>- terminalError?: Error- cleanup?: Promise<void>- tools: Map<string, ToolState>- assistants: Set<string>- text: Map<string, string>- thinking: Map<string, string>- liveThinking: Map<string, string>- interruptTimer?: ReturnType<typeof setTimeout>-}--/**- * Human-readable approval text: the native reason plus only the fields that- * identify what is being approved. The raw request envelope (ids, timestamps,- * decision menus) is protocol plumbing and is unreadable in a permission prompt.- */-function approvalDetails(fallback: string, params: Record<string, unknown>, fields: readonly string[], extra: readonly string[] = []): string {- const lines = [typeof params.reason === 'string' && params.reason.trim() !== '' ? params.reason : fallback]- for (const field of fields) {- const value = params[field]- if (value === undefined || value === null || value === '')- continue- lines.push(`${field}: ${typeof value === 'string' ? value : JSON.stringify(value)}`)- }- return [...lines, ...extra].join('\n')-}--/**- * Read the proposed file changes a `fileChange` item carries. The approval- * request itself names no files, so the prompt can only list them from the item- * the native kernel announced for the same identity.- */-function changedLines(item: Record<string, unknown>): string[] {- if (!Array.isArray(item.changes))- return []- return item.changes.flatMap((value) => {- if (!value || typeof value !== 'object' || Array.isArray(value))- return []- const path = (value as Record<string, unknown>).path- return typeof path === 'string' && path !== '' ? [path] : []- })-}--/**- * Whether the native request still offers a plain one-shot `accept`. The DSH- * approval seam only grants `allowed-once`, so a decision menu without that- * entry cannot be answered truthfully; cancelling leaves the choice to the user- * instead of silently minting an execpolicy amendment or a session-scoped grant.- */-function acceptsOnce(params: Record<string, unknown>): boolean {- return !Array.isArray(params.availableDecisions) || params.availableDecisions.includes('accept')-}--function nativeTool(item: Record<string, unknown>): { name: string, arguments: string } | undefined {- switch (item.type) {- case 'commandExecution':- return { name: 'commandExecution', arguments: JSON.stringify({ command: item.command, cwd: item.cwd }) }- case 'fileChange':- return { name: 'fileChange', arguments: JSON.stringify({ changes: item.changes }) }- case 'mcpToolCall':- return { name: `mcp::${stringField(item, 'server')}/${stringField(item, 'tool')}`, arguments: JSON.stringify(item.arguments ?? {}) }- case 'dynamicToolCall':- return { name: stringField(item, 'tool'), arguments: JSON.stringify(item.arguments ?? {}) }- case 'collabAgentToolCall':- return { name: `collabAgent::${stringField(item, 'tool')}`, arguments: JSON.stringify({ prompt: item.prompt, receiverThreadIds: item.receiverThreadIds, model: item.model }) }- case 'webSearch':- case 'imageView':- case 'imageGeneration':- case 'sleep': {- const { id: _id, type, ...arguments_ } = item- return { name: String(type), arguments: JSON.stringify(arguments_) }- }- default:- return undefined- }-}--class CodexSession implements NativeSession {- private readonly transport: JsonLinesProcess- private readonly requests: PendingRequests- private readonly approvals = new Map<string | number, AbortController>()- private readonly catalogProcesses = new Set<JsonLinesProcess>()- private catalogRequest = 0- private requestId = 0- private nativeId = ''- private active?: CodexTurn- private failure?: Error- private disposed = false- private disposePromise?: Promise<void>- private cleanup?: Promise<void>- private readonly interruptedTurns = new Set<string>()- private backgroundBaseline?: Set<string>- private readonly commandItems = new Set<string>()- /** Proposed file changes per announced `fileChange` item, for its approval prompt. */- private readonly changedFiles = new Map<string, string[]>()- private baselineModel?: string- private baselineProvider?: string- private baselineEffort?: string | null- private effectiveModel?: string- private defaultsPending = false- private catalog?: NativeModelCatalog- private appliedOptions: NativeTurnOptions = { model: null, reasoningEffort: null }- private effortOverridden = false-- constructor(private readonly command: NativeCommand, private readonly sink: NativeSink, private readonly cwd: string, private readonly attachments?: NativeAttachments) {- this.transport = new JsonLinesProcess(command, ['app-server', '--listen', 'stdio://'], cwd)- this.requests = new PendingRequests(value => this.transport.write(value))- this.transport.onFailure((error) => {- this.failure = error- this.requests.failAll(error)- this.active?.result.reject(error)- for (const transport of this.catalogProcesses)- transport.fail(error)- for (const controller of this.approvals.values())- controller.abort(error)- this.approvals.clear()- })- this.transport.onMessage(message => this.receive(message))- }-- get id(): string {- return this.nativeId- }-- async open(cwd: string, storedId: string | null, signal: AbortSignal, options?: NativeSessionOpenOptions): Promise<void> {- signal.throwIfAborted()- try {- await this.request('initialize', INITIALIZATION, signal)- this.transport.write({ method: 'initialized', params: {} })- const forkFrom = options?.forkFrom- const permission = options?.permission- const response = record(await this.request(forkFrom ? 'thread/fork' : storedId === null ? 'thread/start' : 'thread/resume', {- ...forkFrom ? { threadId: forkFrom } : storedId === null ? {} : { threadId: storedId },- cwd,- ...permission?.approval === undefined ? {} : { approvalPolicy: permission.approval === 'never' ? 'never' : 'on-request' },- ...permission?.sandbox === undefined ? {} : { sandbox: permission.sandbox },- }, signal))- const id = stringField(record(response.thread), 'id')- if (storedId !== null && id !== storedId)- throw new NativeBridgeError('BRIDGE_RESUME_MISMATCH', 'Codex resumed a different native thread; refusing to replace the stored binding')- if (forkFrom && id === forkFrom)- throw new NativeBridgeError('BRIDGE_FORK_MISMATCH', 'Codex fork did not acknowledge a new native thread')- this.nativeId = id- if (typeof response.modelProvider === 'string' && response.modelProvider !== '')- this.baselineProvider = response.modelProvider- this.defaultsPending = storedId !== null || forkFrom !== undefined- this.effortOverridden = this.defaultsPending- if (typeof response.model === 'string' && response.model !== '') {- this.effectiveModel = response.model- if (!this.defaultsPending)- this.baselineModel = response.model- }- if (!this.defaultsPending && (response.reasoningEffort === null || typeof response.reasoningEffort === 'string'))- this.baselineEffort = response.reasoningEffort- this.backgroundBaseline = new Set((await this.listTerminals(signal)).map(terminal => terminal.processId))- signal.throwIfAborted()- }- catch (error) {- await this.dispose()- throw error- }- }-- async models(signal: AbortSignal): Promise<NativeModelCatalog> {- signal.throwIfAborted()- if (this.disposed || this.failure)- throw this.failure ?? new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Codex session was disposed')- const generation = ++this.catalogRequest- this.catalog = undefined- // Codex caches its model catalog at startup, even when config/read sees cc-switch changes.- const transport = new JsonLinesProcess(this.command, ['app-server', '--listen', 'stdio://'], this.cwd)- const requests = new PendingRequests(value => transport.write(value))- let requestId = 0- let failure: Error | undefined- let defaultModel: string | undefined- let defaultEffort: unknown- const models = new Map<string, NativeModelInfo>()- const abort = new AbortController()- const aborted = () => abort.abort(abortError(signal))- signal.addEventListener('abort', aborted, { once: true })- const timer = setTimeout(() => abort.abort(new NativeBridgeError('BRIDGE_REQUEST_TIMEOUT', 'Codex model discovery timed out')), REQUEST_TIMEOUT_MS)- this.catalogProcesses.add(transport)- transport.onFailure((error) => {- failure = error- requests.failAll(error)- })- transport.onMessage((message) => {- const id = message.id- if (typeof id === 'number' || typeof id === 'string') {- if ('result' in message || 'error' in message) {- const error = message.error ? record(message.error) : undefined- requests.settle(id, message.result, error ? new NativeBridgeError('BRIDGE_NATIVE_REQUEST', typeof error.message === 'string' ? error.message : JSON.stringify(error)) : undefined)- }- else {- transport.write({ id, error: { code: -32601, message: 'Read-only model discovery cannot handle native server requests' } })- }- }- })- function request(method: string, params: unknown): Promise<unknown> {- const id = ++requestId- return requests.request(id, { id, method, params }, abort.signal)- }- try {- await request('initialize', INITIALIZATION)- transport.write({ method: 'initialized', params: {} })- const config = record(record(await request('config/read', { includeLayers: false, cwd: this.cwd })).config)- const configuredModel = typeof config.model === 'string' && config.model !== '' ? config.model : undefined- if (this.baselineProvider !== undefined && typeof config.model_provider === 'string' && config.model_provider !== this.baselineProvider)- throw new NativeBridgeError('BRIDGE_PROVIDER_CHANGED', 'Codex provider changed after this session was created; create a new native session to use its models')- defaultModel = this.baselineModel ?? configuredModel- defaultEffort = this.baselineEffort === undefined ? config.model_reasoning_effort : this.baselineEffort- const cursors = new Set<string>()- let cursor: string | null = null- do {- if (cursors.size >= 100)- throw new NativeBridgeError('BRIDGE_PROTOCOL_LIMIT', 'Codex model listing exceeded its page limit')- const response = record(await request('model/list', { cursor, limit: 100, includeHidden: false }))- if (!Array.isArray(response.data))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Codex model listing is missing data')- for (const value of response.data) {- const model = record(value)- const id = stringField(model, 'model')- if (!Array.isArray(model.supportedReasoningEfforts))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Codex model is missing reasoning capabilities')- const efforts = model.supportedReasoningEfforts.map((value) => {- const effort = record(value)- const id = stringField(effort, 'reasoningEffort')- return { id, name: CODEX_REASONING_EFFORT_NAMES.get(id) ?? id, ...typeof effort.description === 'string' ? { description: effort.description } : {} }- })- const defaultEffort = typeof model.defaultReasoningEffort === 'string' && efforts.some(effort => effort.id === model.defaultReasoningEffort) ? model.defaultReasoningEffort : undefined- models.set(id, {- id,- name: stringField(model, 'displayName'),- ...typeof model.description === 'string' ? { description: model.description } : {},- ...efforts.length > 0 ? { reasoning: { efforts, ...defaultEffort === undefined ? {} : { defaultEffort } } } : {},- })- if (models.size > 10_000)- throw new NativeBridgeError('BRIDGE_PROTOCOL_LIMIT', 'Codex model listing exceeded its limit')- }- if (response.nextCursor !== null && response.nextCursor !== undefined && typeof response.nextCursor !== 'string')- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Codex model cursor is invalid')- cursor = typeof response.nextCursor === 'string' ? response.nextCursor : null- if (cursor !== null) {- if (cursors.has(cursor))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Codex model listing repeated a cursor')- cursors.add(cursor)- }- } while (cursor !== null)- for (const id of [configuredModel, defaultModel, this.effectiveModel]) {- if (id && !models.has(id))- models.set(id, { id, name: id })- }- abort.signal.throwIfAborted()- if (failure || this.failure || this.disposed)- throw failure ?? this.failure ?? new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Codex session was disposed')- }- catch (error) {- failure ??= errorFrom(error)- }- finally {- clearTimeout(timer)- requests.failAll(new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Codex model discovery was closed'))- }- try {- await transport.close(true)- this.catalogProcesses.delete(transport)- }- catch {- // A reader that will not exit stays owned for honest disposal; it is never a catalog failure.- }- finally {- signal.removeEventListener('abort', aborted)- }- signal.throwIfAborted()- if (failure || this.failure || this.disposed)- throw failure ?? this.failure ?? new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Codex session was disposed')- const catalog = {- models: [...models.values()],- ...defaultModel === undefined ? {} : { defaultModel },- ...defaultModel !== undefined && typeof defaultEffort === 'string' && defaultEffort !== '' ? { defaultReasoningEffort: defaultEffort } : {},- }- if (generation === this.catalogRequest) {- this.baselineModel ??= defaultModel- if (this.baselineEffort === undefined && (defaultEffort === null || typeof defaultEffort === 'string'))- this.baselineEffort = defaultEffort- this.catalog = catalog- }- return catalog- }-- private async turnOptions(options: NativeTurnOptions, signal: AbortSignal): Promise<{ model?: string, effort?: string }> {- const modelChanged = this.defaultsPending || options.model !== this.appliedOptions.model- const effortChanged = this.defaultsPending || options.reasoningEffort !== this.appliedOptions.reasoningEffort- if (options.model === null && options.reasoningEffort === null && this.appliedOptions.model === null && this.appliedOptions.reasoningEffort === null)- return {}- const catalog = this.catalog ?? await this.models(signal)- const model = options.model ?? this.baselineModel- if (!model)- throw new NativeBridgeError('BRIDGE_DEFAULT_UNAVAILABLE', 'Codex did not report its default model')- const info = catalog.models.find(value => value.id === model)- if (!info)- throw new NativeBridgeError('BRIDGE_MODEL_UNAVAILABLE', `Codex did not advertise model: ${model}`)- let effort = options.reasoningEffort- if (effort !== null && !info.reasoning?.efforts.some(value => value.id === effort))- throw new NativeBridgeError('BRIDGE_EFFORT_UNSUPPORTED', `Codex did not advertise reasoning effort ${effort} for ${model}`)- if (effort === null && (modelChanged || effortChanged)) {- effort = model === this.baselineModel ? this.baselineEffort ?? info.reasoning?.defaultEffort ?? null : info.reasoning?.defaultEffort ?? null- // Public null retains a persisted/previous effort; it is not a reset.- if (effort === null && (this.effortOverridden || model !== this.effectiveModel))- throw new NativeBridgeError('BRIDGE_DEFAULT_UNAVAILABLE', `Codex did not report a restorable default reasoning effort for ${model}`)- }- return { ...options.model !== null || modelChanged ? { model } : {}, ...effort === null ? {} : { effort } }- }-- async submit(messages: readonly UserMessage[], signal: AbortSignal, options?: NativeTurnOptions, permission?: NativePermission): Promise<void> {- signal.throwIfAborted()- if (this.disposed || this.failure)- throw this.failure ?? new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Codex session was disposed')- if (this.active)- throw new NativeBridgeError('BRIDGE_BUSY', 'Codex native session already has an active turn')- const runs = nativeRuns(messages, this.attachments)- if (runs.length === 0)- throw new NativeBridgeError('BRIDGE_EMPTY_INPUT', 'Codex native turn requires a user message')- this.changedFiles.clear()- const selection = options ? { ...options } : undefined- const policy = {- ...permission?.approval === undefined ? {} : { approvalPolicy: permission.approval === 'never' ? 'never' : 'on-request' },- ...permission?.sandbox === undefined- ? {}- : { sandboxPolicy: {- 'read-only': { type: 'readOnly', networkAccess: false },- 'workspace-write': { type: 'workspaceWrite', writableRoots: [this.cwd], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: false },- 'danger-full-access': { type: 'dangerFullAccess' },- }[permission.sandbox] },- }- const turn: CodexTurn = {- result: deferred<void>(),- signal,- submitted: false,- interruptSent: false,- baseline: new Set(),- commandItems: new Set(),- tools: new Map(),- assistants: new Set(),- text: new Map(),- thinking: new Map(),- liveThinking: new Map(),- }- this.active = turn- const aborted = (): void => {- if (turn.submitted)- this.interrupt(turn)- }- signal.addEventListener('abort', aborted, { once: true })- try {- const overrides = selection ? await this.turnOptions(selection, signal) : {}- const input: Record<string, unknown>[] = []- for (const run of runs.flat()) {- if (run.type === 'text') {- input.push({ type: 'text', text: run.text, text_elements: [] })- continue- }- input.push(await this.imageInput(run.ref, signal))- }- signal.throwIfAborted()- turn.baseline = new Set((await this.listTerminals(signal)).map(terminal => terminal.processId))- signal.throwIfAborted()- turn.submitted = true- // turn/started may precede the response; retain its id even during cancel.- const response = record(await this.request('turn/start', { threadId: this.id, input, ...overrides, ...policy }))- if (selection) {- this.appliedOptions = selection- if (overrides.model !== undefined || overrides.effort !== undefined)- this.defaultsPending = false- }- if (overrides.model !== undefined)- this.effectiveModel = overrides.model- if (overrides.effort !== undefined)- this.effortOverridden = true- const id = stringField(record(response.turn), 'id')- if (turn.id && id !== turn.id)- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Codex turn/start response disagrees with turn/started')- turn.id = id- if (signal.aborted)- this.interrupt(turn)- await turn.result.promise- if (turn.cleanup)- await turn.cleanup- if (signal.aborted) {- await this.cleanupTerminals(turn)- signal.throwIfAborted()- }- if (turn.terminalError) {- await this.cleanupTerminals(turn)- throw turn.terminalError- }- }- catch (error) {- if (turn.submitted && !signal.aborted)- this.transport.fail(errorFrom(error))- throw this.failure ?? (signal.aborted ? abortError(signal) : error)- }- finally {- signal.removeEventListener('abort', aborted)- clearTimeout(turn.interruptTimer)- for (const controller of this.approvals.values())- controller.abort(new NativeBridgeError('BRIDGE_REQUEST_CLOSED', 'Native turn has ended'))- this.approvals.clear()- this.active = undefined- }- }-- dispose(): Promise<void> {- this.disposePromise ??= this.close()- return this.disposePromise- }-- private async close(): Promise<void> {- this.disposed = true- const error = new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Codex native session was disposed')- this.active?.result.reject(error)- for (const transport of this.catalogProcesses)- transport.fail(error)- for (const controller of this.approvals.values())- controller.abort(error)- this.approvals.clear()- try {- if (this.id !== '' && this.backgroundBaseline && !this.failure)- await this.cleanupTerminals()- }- finally {- this.requests.failAll(error)- for (const transport of [this.transport, ...this.catalogProcesses]) {- try {- await transport.close()- }- catch {- // Termination is best effort: a stuck child must never fail plugin startup or teardown.- }- }- }- }-- private request(method: string, params: unknown, signal?: AbortSignal, timeoutMs?: number): Promise<unknown> {- const id = ++this.requestId- return this.requests.request(id, { id, method, params }, signal, timeoutMs)- }-- private interrupt(turn: CodexTurn): void {- if (!turn.interruptTimer) {- turn.interruptTimer = setTimeout(() => {- this.transport.fail(new NativeBridgeError('BRIDGE_INTERRUPT_TIMEOUT', 'Codex did not settle the interrupted turn; its process was closed'))- }, INTERRUPT_TIMEOUT_MS)- }- if (!turn.id || turn.interruptSent)- return- turn.interruptSent = true- this.interruptedTurns.add(turn.id)- turn.cleanup = (async () => {- await this.cleanupTerminals(turn)- await this.request('turn/interrupt', { threadId: this.id, turnId: turn.id }, undefined, INTERRUPT_TIMEOUT_MS)- await this.cleanupTerminals(turn)- })()- void turn.cleanup.catch((error) => {- if (this.active === turn)- this.transport.fail(errorFrom(error))- })- }-- private async listTerminals(signal?: AbortSignal): Promise<BackgroundTerminal[]> {- const terminals: BackgroundTerminal[] = []- const cursors = new Set<string>()- let cursor: string | null = null- do {- const response = record(await this.request('thread/backgroundTerminals/list', { threadId: this.id, cursor, limit: 100 }, signal, INTERRUPT_TIMEOUT_MS))- if (!Array.isArray(response.data))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Codex background terminal listing is missing data')- for (const value of response.data) {- const terminal = record(value)- terminals.push({ itemId: stringField(terminal, 'itemId'), processId: stringField(terminal, 'processId') })- if (terminals.length > 10_000)- throw new NativeBridgeError('BRIDGE_PROTOCOL_LIMIT', 'Codex background terminal listing exceeded its limit')- }- if (response.nextCursor !== null && response.nextCursor !== undefined && typeof response.nextCursor !== 'string')- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Codex background terminal cursor is invalid')- cursor = typeof response.nextCursor === 'string' ? response.nextCursor : null- if (cursor !== null) {- if (cursors.has(cursor))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Codex background terminal listing repeated a cursor')- cursors.add(cursor)- }- } while (cursor !== null)- return terminals- }-- private cleanupTerminals(turn?: CodexTurn): Promise<void> {- const cleanup = async (): Promise<void> => {- const owns = (terminal: BackgroundTerminal): boolean => turn- ? turn.commandItems.has(terminal.itemId) || !turn.baseline.has(terminal.processId)- : this.commandItems.has(terminal.itemId) || !this.backgroundBaseline!.has(terminal.processId)- for (const terminal of (await this.listTerminals()).filter(owns))- await this.request('thread/backgroundTerminals/terminate', { threadId: this.id, processId: terminal.processId }, undefined, INTERRUPT_TIMEOUT_MS)- if ((await this.listTerminals()).some(owns))- throw new NativeBridgeError('BRIDGE_INTERRUPT_CLEANUP_FAILED', 'Codex retained interrupted background terminals')- }- const pending = (this.cleanup ?? Promise.resolve()).then(cleanup)- this.cleanup = pending- return pending- }-- private receive(message: Record<string, unknown>): void {- const id = message.id- if ((typeof id === 'number' || typeof id === 'string') && ('result' in message || 'error' in message)) {- const error = message.error ? record(message.error) : undefined- this.requests.settle(id, message.result, error ? new NativeBridgeError('BRIDGE_NATIVE_REQUEST', typeof error.message === 'string' ? error.message : JSON.stringify(error)) : undefined)- return- }- const method = stringField(message, 'method')- const params = record(message.params ?? {})- if (typeof id === 'number' || typeof id === 'string') {- void this.answer(id, method, params).catch(error => this.transport.fail(errorFrom(error)))- return- }- if (method === 'serverRequest/resolved') {- if (params.threadId !== this.id)- return- const requestId = params.requestId- if (typeof requestId === 'number' || typeof requestId === 'string') {- this.approvals.get(requestId)?.abort(new NativeBridgeError('BRIDGE_REQUEST_CLOSED', 'Codex resolved the server request'))- this.approvals.delete(requestId)- }- return- }- if (params.threadId === this.id && method === 'item/started' && typeof params.turnId === 'string' && this.interruptedTurns.has(params.turnId)) {- const item = record(params.item)- if (item.type === 'commandExecution' && typeof item.processId === 'string') {- void (async () => {- await this.request('thread/backgroundTerminals/terminate', { threadId: this.id, processId: item.processId }, undefined, INTERRUPT_TIMEOUT_MS)- if ((await this.listTerminals()).some(terminal => terminal.processId === item.processId))- throw new NativeBridgeError('BRIDGE_INTERRUPT_CLEANUP_FAILED', 'Codex retained a late interrupted command')- })().catch(error => this.transport.fail(errorFrom(error)))- }- }- const turn = this.active- if (!turn || params.threadId !== this.id)- return- const nativeTurn = method === 'turn/started' || method === 'turn/completed' ? record(params.turn) : undefined- const turnId = nativeTurn?.id ?? params.turnId- if (typeof turnId === 'string') {- if (turn.id && turnId !== turn.id)- return- turn.id ??= turnId- }- if (turn.signal.aborted)- this.interrupt(turn)- switch (method) {- case 'turn/started':- return- case 'turn/completed': {- if (Array.isArray(nativeTurn!.items)) {- for (const value of nativeTurn!.items) {- const item = record(value)- const tool = turn.tools.get(stringField(item, 'id'))- if (tool && !tool.ended && (item.status === 'completed' || item.status === 'failed' || item.status === 'declined'))- this.item(turn, item, true)- }- }- const status = stringField(nativeTurn!, 'status')- if (status === 'interrupted' && !turn.signal.aborted)- turn.terminalError = new NativeBridgeError('BRIDGE_NATIVE_INTERRUPTED', 'Codex interrupted the native turn')- else if (status !== 'completed' && status !== 'interrupted')- turn.terminalError = new NativeBridgeError('BRIDGE_NATIVE_TURN', `Codex turn ended with ${status}: ${JSON.stringify(nativeTurn!.error ?? {})}`)- turn.result.resolve()- return- }- case 'error':- if (params.willRetry !== true)- turn.terminalError = new NativeBridgeError('BRIDGE_NATIVE_TURN', JSON.stringify(params.error ?? params))- return- case 'item/agentMessage/delta':- case 'item/plan/delta': {- const id = stringField(params, 'itemId')- const delta = stringField(params, 'delta')- turn.text.set(id, (turn.text.get(id) ?? '') + delta)- this.sink.text(id, delta)- return- }- case 'item/reasoning/summaryTextDelta':- case 'item/reasoning/textDelta': {- const id = stringField(params, 'itemId')- const delta = stringField(params, 'delta')- // Summary and raw reasoning are independent content tracks.- const track = `${id}:${method === 'item/reasoning/textDelta' ? 'raw' : 'summary'}`- turn.thinking.set(track, (turn.thinking.get(track) ?? '') + delta)- if (!turn.liveThinking.has(id))- turn.liveThinking.set(id, track)- if (turn.liveThinking.get(id) === track)- this.sink.thinking(id, delta)- return- }- case 'item/commandExecution/outputDelta':- case 'item/fileChange/outputDelta': {- const tool = turn.tools.get(stringField(params, 'itemId'))- if (tool)- tool.output += typeof params.delta === 'string' ? params.delta : ''- return- }- case 'item/started':- case 'item/completed':- this.item(turn, record(params.item), method === 'item/completed')- }- }-- private item(turn: CodexTurn, item: Record<string, unknown>, completed: boolean): void {- const id = stringField(item, 'id')- const type = stringField(item, 'type')- if (item.type === 'commandExecution') {- turn.commandItems.add(id)- this.commandItems.add(id)- }- else if (item.type === 'fileChange') {- const lines = changedLines(item)- if (lines.length > 0)- this.changedFiles.set(id, lines)- }- const tool = nativeTool(item)- if (tool) {- if (!turn.tools.has(id)) {- this.sink.assistant(`${id}:call`, [{ type: 'tool-call', id, name: tool.name, arguments: tool.arguments }])- this.sink.toolStart(id, tool.name, tool.arguments)- turn.tools.set(id, { output: '', ended: false })- }- const state = turn.tools.get(id)!- if (completed && !state.ended) {- state.ended = true- const output = typeof item.aggregatedOutput === 'string' ? item.aggregatedOutput : state.output || JSON.stringify(item.result ?? item.contentItems ?? item.changes ?? item.error ?? item)- const error = item.status === 'failed' || item.status === 'declined' || item.error != null || item.success === false || (typeof item.exitCode === 'number' && item.exitCode !== 0)- this.sink.toolEnd(id, output, error)- }- return- }- if (!completed || turn.assistants.has(id))- return- const content: NativeContent[] = []- switch (type) {- case 'agentMessage':- case 'plan':- content.push({ type: 'text', text: typeof item.text === 'string' ? item.text : turn.text.get(id) ?? '' })- break- case 'reasoning': {- const summary = Array.isArray(item.summary) ? item.summary.filter((part): part is string => typeof part === 'string').join('\n') : ''- const raw = Array.isArray(item.content) ? item.content.filter((part): part is string => typeof part === 'string').join('\n') : ''- content.push({ type: 'thinking', text: summary || turn.thinking.get(`${id}:summary`) || raw || turn.thinking.get(`${id}:raw`) || '' })- break- }- case 'userMessage': // The official inbox owns user/message exactly once.- case 'hookPrompt': // Native prompt assembly remains native-owned.- case 'contextCompaction':- case 'subAgentActivity':- return- case 'enteredReviewMode':- case 'exitedReviewMode':- content.push({ type: 'text', text: typeof item.review === 'string' ? item.review : '' })- break- default:- content.push({ type: 'text', text: JSON.stringify(item) })- break- }- turn.assistants.add(id)- this.sink.assistant(id, content)- }-- /** Official image as native `UserInput`; a host path avoids re-encoding the bytes. */- private async imageInput(ref: NativeImageRef, signal: AbortSignal): Promise<Record<string, unknown>> {- const path = this.attachments?.path(ref)- if (path !== undefined)- return { type: 'localImage', path }- const source = await this.attachments!.read(ref, signal)- if (source.base64 === undefined)- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'The official attachment store returned no readable image bytes')- return { type: 'image', url: `data:${source.mediaType};base64,${source.base64}` }- }-- private async answer(id: string | number, method: string, params: Record<string, unknown>): Promise<void> {- const controller = new AbortController()- this.approvals.set(id, controller)- const turn = this.active- const signal = turn ? AbortSignal.any([turn.signal, controller.signal]) : controller.signal- const itemId = typeof params.itemId === 'string' ? params.itemId : String(id)- let result: unknown- try {- const belongs = turn && params.threadId === this.id && (turn.id === undefined || params.turnId === turn.id) && !signal.aborted- if (method === 'item/commandExecution/requestApproval' || method === 'item/fileChange/requestApproval') {- const command = method === 'item/commandExecution/requestApproval'- const allowed = belongs- ? await this.sink.approval(itemId, {- kind: command ? 'command' : 'file',- title: command && typeof params.command === 'string' ? params.command : command ? 'Codex command execution' : 'Codex file changes',- details: approvalDetails(command ? 'Codex needs to run a command' : 'Codex needs to change files', params, command ? ['command', 'cwd'] : ['grantRoot'], command ? [] : this.changedFiles.get(itemId) ?? []),- }, signal)- : false- const once = acceptsOnce(params)- result = { decision: once ? (allowed && !signal.aborted ? 'accept' : 'decline') : 'cancel' }- }- else if (method === 'item/permissions/requestApproval') {- const allowed = belongs ? await this.sink.approval(itemId, { kind: 'tool', title: 'Codex additional permissions', details: approvalDetails('Codex requests additional permissions', params, ['permissions']) }, signal) : false- result = { permissions: allowed && !signal.aborted ? record(params.permissions) : {}, scope: 'turn' }- }- else if (method === 'item/tool/requestUserInput') {- if (!belongs)- throw new NativeBridgeError('BRIDGE_REQUEST_CLOSED', 'No active turn for the native user-input request')- if (!Array.isArray(params.questions))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Codex user-input request is missing questions')- const questions: NativeQuestion[] = params.questions.map((value) => {- const question = record(value)- if (question.isSecret === true)- throw new NativeBridgeError('BRIDGE_UNSUPPORTED_QUESTION', 'Secret native questions cannot be recorded in the official session log')- return {- id: stringField(question, 'id'),- question: stringField(question, 'question'),- ...Array.isArray(question.options)- ? { options: question.options.map((value) => {- const option = record(value)- return { label: stringField(option, 'label'), ...typeof option.description === 'string' ? { description: option.description } : {} }- }) }- : {},- }- })- const answers = await this.sink.questions(itemId, questions, signal)- result = { answers: Object.fromEntries(questions.map(question => [question.id, { answers: Array.isArray(answers[question.id]) ? answers[question.id] : [answers[question.id] ?? ''] }])) }- }- else {- // In particular item/tool/call is not an invitation to run DSH tools.- this.transport.write({ id, error: { code: -32601, message: `Unsupported native server request: ${method}` } })- return- }- if (!controller.signal.aborted)- this.transport.write({ id, result })- }- catch (error) {- if (!controller.signal.aborted)- this.transport.write({ id, error: { code: -32603, message: errorFrom(error).message } })- }- finally {- this.approvals.delete(id)- }- }-}--export async function createCodexSession(command: NativeCommand, cwd: string, nativeSessionId: string | null, sink: NativeSink, signal: AbortSignal, options?: NativeSessionOpenOptions, attachments?: NativeAttachments): Promise<NativeSession> {- if (options?.forkFrom !== undefined && (nativeSessionId !== null || options.forkFrom === ''))- throw new NativeBridgeError('BRIDGE_FORK_INVALID', 'Codex fork requires a source thread and no existing native binding')- const session = new CodexSession(command, sink, cwd, attachments)- await session.open(cwd, nativeSessionId, signal, options)- return session-}diff --git a/packages/dsh-tauri-kernel/src/host/backends/process.fixture.ts b/packages/dsh-tauri-kernel/src/host/backends/process.fixture.tsdeleted file mode 100644index 8439bf6d..00000000--- a/packages/dsh-tauri-kernel/src/host/backends/process.fixture.ts+++ /dev/null@@ -1,80 +0,0 @@-import type { ChildProcessWithoutNullStreams } from 'node:child_process'-import type { NativeSink } from './types'-import { EventEmitter } from 'node:events'-import { PassThrough } from 'node:stream'-import { vi } from 'vitest'--export type Frame = Record<string, unknown>--export function createSink() {- return {- text: vi.fn<NativeSink['text']>(),- thinking: vi.fn<NativeSink['thinking']>(),- assistant: vi.fn<NativeSink['assistant']>(),- toolStart: vi.fn<NativeSink['toolStart']>(),- toolEnd: vi.fn<NativeSink['toolEnd']>(),- approval: vi.fn<NativeSink['approval']>().mockResolvedValue(false),- questions: vi.fn<NativeSink['questions']>().mockResolvedValue({}),- }-}--export class ProcessFixture extends EventEmitter {- readonly stdout = new PassThrough()- readonly stderr = new PassThrough()- readonly frames: Frame[] = []- private readonly waiters: { matches: (frame: Frame) => boolean, resolve: (frame: Frame) => void }[] = []- private exited = false- private readonly input = new EventEmitter()- readonly stdin = Object.assign(this.input, {- writable: true,- write: vi.fn((line: string) => {- const frame = JSON.parse(line) as Frame- this.frames.push(frame)- this.onWrite?.(frame)- for (const waiter of [...this.waiters]) {- if (waiter.matches(frame)) {- this.waiters.splice(this.waiters.indexOf(waiter), 1)- waiter.resolve(frame)- }- }- return true- }),- end: vi.fn(() => this.exit(0)),- destroy: vi.fn(() => {- this.stdin.writable = false- }),- })-- readonly kill = vi.fn((_signal?: string) => {- this.exit(0)- return true- })-- constructor(private readonly onWrite?: (frame: Frame) => void) {- super()- }-- get child(): ChildProcessWithoutNullStreams {- return this as unknown as ChildProcessWithoutNullStreams- }-- send(frame: Frame): void {- this.stdout.write(`${JSON.stringify(frame)}\n`)- }-- writeChunk(chunk: string): void {- this.stdout.write(chunk)- }-- next(matches: (frame: Frame) => boolean): Promise<Frame> {- return new Promise(resolve => this.waiters.push({ matches, resolve }))- }-- exit(code: number): void {- if (this.exited)- return- this.exited = true- this.stdin.writable = false- this.emit('close', code, null)- }-}diff --git a/packages/dsh-tauri-kernel/src/host/backends/transport.test.ts b/packages/dsh-tauri-kernel/src/host/backends/transport.test.tsdeleted file mode 100644index 6e608c67..00000000--- a/packages/dsh-tauri-kernel/src/host/backends/transport.test.ts+++ /dev/null@@ -1,182 +0,0 @@-import { spawn } from 'node:child_process'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { ProcessFixture } from './process.fixture'-import { JsonLinesProcess, NativeBridgeError, PendingRequests } from './transport'--vi.mock('node:child_process', () => ({ spawn: vi.fn() }))--const command = { file: 'C:/fixture/native.exe', args: ['fixed-prefix'], env: { PATH: 'C:/fixture/bin' } }-const transports: JsonLinesProcess[] = []--function open(fixture = new ProcessFixture()) {- vi.mocked(spawn).mockReturnValue(fixture.child)- const transport = new JsonLinesProcess(command, ['--protocol'], 'C:/fixture/workspace')- transports.push(transport)- return { fixture, transport }-}--beforeEach(() => vi.mocked(spawn).mockReset())-afterEach(async () => {- for (const transport of transports.splice(0))- await transport.close()- vi.restoreAllMocks()- vi.useRealTimers()-})--describe('native JSONL process transport', () => {- it('uses direct executable argv with a replacement environment and no shell', () => {- open()- expect(spawn).toHaveBeenCalledWith('C:/fixture/native.exe', ['fixed-prefix', '--protocol'], {- cwd: 'C:/fixture/workspace',- env: { PATH: 'C:/fixture/bin' },- shell: false,- windowsHide: true,- stdio: ['pipe', 'pipe', 'pipe'],- })- })-- it('rejects Windows batch shims before creating a process', () => {- expect(() => new JsonLinesProcess({ ...command, file: 'C:/fixture/native.cmd' }, [], 'C:/fixture')).toThrowError(expect.objectContaining({ code: 'BRIDGE_UNSAFE_EXECUTABLE' }))- expect(spawn).not.toHaveBeenCalled()- })-- it('parses split CRLF frames and preserves their order across handler registration', () => {- const { fixture, transport } = open()- fixture.writeChunk('{"id":1,"result":')- fixture.writeChunk('{} }\r\n\n{"method":"ready"}\n')- const received = vi.fn()- transport.onMessage(received)- expect(received.mock.calls).toEqual([[{ id: 1, result: {} }], [{ method: 'ready' }]])- })-- it('dispatches response frames while an unrelated approval handler is still parked', async () => {- const { fixture, transport } = open()- const parked = Promise.withResolvers<void>()- const received: string[] = []- transport.onMessage((frame) => {- received.push(String(frame.method))- return frame.method === 'approval' ? parked.promise : undefined- })- fixture.send({ method: 'approval' })- fixture.send({ method: 'rpc-response' })- expect(received).toEqual(['approval', 'rpc-response'])- parked.resolve()- await parked.promise- })-- it('preserves adapter semantic error codes instead of relabelling them invalid JSON', () => {- const { fixture, transport } = open()- const failed = vi.fn()- transport.onFailure(failed)- transport.onMessage(() => {- throw new NativeBridgeError('BRIDGE_RESUME_MISMATCH', 'different thread')- })- fixture.send({ method: 'event' })- expect(failed).toHaveBeenCalledWith(expect.objectContaining({ code: 'BRIDGE_RESUME_MISMATCH', message: 'different thread' }))- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('contains a buffered frame handler failure and stops before later buffered frames', () => {- const { fixture, transport } = open()- fixture.send({ method: 'failure' })- fixture.send({ method: 'must-not-run' })- const failed = vi.fn()- const handler = vi.fn(() => {- throw new NativeBridgeError('BRIDGE_UNSUPPORTED_EVENT', 'unknown native item')- })- transport.onFailure(failed)- expect(() => transport.onMessage(handler)).not.toThrow()- expect(handler).toHaveBeenCalledTimes(1)- expect(failed).toHaveBeenCalledWith(expect.objectContaining({ code: 'BRIDGE_UNSUPPORTED_EVENT' }))- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('stops batched dispatch after a handler explicitly fails the transport', () => {- const { fixture, transport } = open()- const handler = vi.fn(() => transport.fail(new NativeBridgeError('BRIDGE_NATIVE_TURN', 'native execution failed')))- transport.onMessage(handler)- fixture.writeChunk('{"method":"failure"}\n{"method":"must-not-run"}\n')- expect(handler).toHaveBeenCalledTimes(1)- })-- it('fails closed on malformed JSON instead of dropping the frame', () => {- const { fixture, transport } = open()- const failed = vi.fn()- transport.onFailure(failed)- fixture.writeChunk('{not JSON}\n')- expect(failed).toHaveBeenCalledWith(expect.objectContaining({ code: 'BRIDGE_PROTOCOL' }))- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('bounds native frame input before an unterminated line can grow indefinitely', () => {- const { fixture, transport } = open()- const failed = vi.fn()- transport.onFailure(failed)- fixture.writeChunk('x'.repeat(8 * 1024 * 1024 + 1))- expect(failed).toHaveBeenCalledWith(expect.objectContaining({ code: 'BRIDGE_FRAME_LIMIT' }))- expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')- })-- it('waits for graceful stdin EOF before issuing a termination signal', async () => {- const { fixture, transport } = open()- await transport.close(true)- expect(fixture.stdin.end).toHaveBeenCalledTimes(1)- expect(fixture.kill).not.toHaveBeenCalled()- })-- it('escalates a non-exiting process without reporting false quiescence', async () => {- vi.useFakeTimers()- const fixture = new ProcessFixture()- fixture.kill.mockImplementation(() => true)- const { transport } = open(fixture)- const closed = transport.close()- const rejected = expect(closed).rejects.toMatchObject({ code: 'BRIDGE_PROCESS_STOP_TIMEOUT' })- await vi.advanceTimersByTimeAsync(3000)- await rejected- expect(fixture.kill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']])- transports.splice(transports.indexOf(transport), 1)- fixture.exit(0)- })-})--describe('native pending control requests', () => {- it('settles exactly the matching id without blocking other outstanding requests', async () => {- const write = vi.fn()- const requests = new PendingRequests(write)- const first = requests.request(1, { id: 1, method: 'first' })- const second = requests.request(2, { id: 2, method: 'second' })- requests.settle(2, { ok: 'second' })- requests.settle(1, { ok: 'first' })- await expect(first).resolves.toEqual({ ok: 'first' })- await expect(second).resolves.toEqual({ ok: 'second' })- expect(write.mock.calls).toEqual([[{ id: 1, method: 'first' }], [{ id: 2, method: 'second' }]])- })-- it('removes cancelled request state so a late native response cannot resettle it', async () => {- const requests = new PendingRequests(vi.fn())- const signal = new AbortController()- const waiting = requests.request('id', { method: 'request' }, signal.signal)- const rejected = expect(waiting).rejects.toThrow('cancel wait')- signal.abort(new Error('cancel wait'))- requests.settle('id', { success: true })- await rejected- })-- it('rejects timed-out requests using bounded control waits', async () => {- vi.useFakeTimers()- const requests = new PendingRequests(vi.fn())- const waiting = requests.request('id', { method: 'request' }, undefined, 100)- const rejected = expect(waiting).rejects.toMatchObject({ code: 'BRIDGE_REQUEST_TIMEOUT' })- await vi.advanceTimersByTimeAsync(100)- await rejected- })-- it('propagates every pending failure when the native process crashes', async () => {- const requests = new PendingRequests(vi.fn())- const first = requests.request(1, { method: 'first' })- const second = requests.request(2, { method: 'second' })- requests.failAll(new NativeBridgeError('BRIDGE_PROCESS_EXIT', 'native exit'))- await expect(first).rejects.toMatchObject({ code: 'BRIDGE_PROCESS_EXIT' })- await expect(second).rejects.toMatchObject({ code: 'BRIDGE_PROCESS_EXIT' })- })-})diff --git a/packages/dsh-tauri-kernel/src/host/backends/transport.ts b/packages/dsh-tauri-kernel/src/host/backends/transport.tsdeleted file mode 100644index 5c637848..00000000--- a/packages/dsh-tauri-kernel/src/host/backends/transport.ts+++ /dev/null@@ -1,315 +0,0 @@-import type { UserMessage } from '@deepseek-ai/dsh-llm'-import type { ChildProcessWithoutNullStreams } from 'node:child_process'-import type { NativeAttachments, NativeCommand, NativeImageRef } from './types'-import { spawn } from 'node:child_process'-import { nativeEnvironment } from '../utils/detection'--const MAX_FRAME_CHARS = 8 * 1024 * 1024-const MAX_STDERR_CHARS = 16 * 1024-const MAX_QUEUED_FRAMES = 8192-const CLOSE_TIMEOUT_MS = 1500-export const REQUEST_TIMEOUT_MS = 60_000-export const INTERRUPT_TIMEOUT_MS = 5000--export class NativeBridgeError extends Error {- constructor(readonly code: string, message: string) {- super(message)- this.name = 'NativeBridgeError'- }-}--export function errorFrom(value: unknown): Error {- return value instanceof Error ? value : new Error(String(value))-}--export function abortError(signal: AbortSignal): Error {- return signal.reason instanceof Error ? signal.reason : new NativeBridgeError('BRIDGE_ABORTED', 'Native turn was cancelled')-}--export function record(value: unknown): Record<string, unknown> {- if (!value || typeof value !== 'object' || Array.isArray(value))- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'Expected a native protocol object')- return value as Record<string, unknown>-}--export function stringField(value: Record<string, unknown>, key: string): string {- if (typeof value[key] !== 'string' || value[key] === '')- throw new NativeBridgeError('BRIDGE_PROTOCOL', `Missing native protocol field: ${key}`)- return value[key]-}--/** One ordered piece of an official user message handed to a native kernel. */-export type NativeRun = { type: 'text', text: string } | { type: 'image', ref: NativeImageRef }--/**- * Split official user content into ordered native runs, preserving the model's- * original text/image interleaving. Adjacent text merges into one run, an image- * keeps its durable reference so each kernel resolves the host path or the- * verified bytes it needs, and a message with no blocks keeps one empty text- * run. Content no native kernel accepts fails closed rather than submitting a- * partial prompt.- * @param messages - the admitted official user messages.- * @param attachments - official attachment access, absent without an image provider.- * @returns one ordered run list per message.- */-export function nativeRuns(messages: readonly UserMessage[], attachments: NativeAttachments | undefined): NativeRun[][] {- return messages.map((message) => {- const runs: NativeRun[] = []- for (const block of message.content) {- if (block.type === 'text') {- const last = runs.at(-1)- if (last?.type === 'text')- runs[runs.length - 1] = { type: 'text', text: last.text + block.text }- else- runs.push({ type: 'text', text: block.text })- continue- }- if (block.type === 'image' && attachments !== undefined) {- runs.push({ type: 'image', ref: block.attachment })- continue- }- throw new NativeBridgeError('BRIDGE_UNSUPPORTED_CONTENT', `Native bridge does not yet support user content: ${block.type}`)- }- return runs.length === 0 ? [{ type: 'text', text: '' }] : runs- })-}--export interface Deferred<T> {- promise: Promise<T>- resolve: (value: T) => void- reject: (error: Error) => void-}--export function deferred<T>(): Deferred<T> {- let resolve!: (value: T) => void- let reject!: (error: Error) => void- const promise = new Promise<T>((yes, no) => {- resolve = yes- reject = no- })- // State can fail between allocation and the caller's first await.- void promise.catch(() => {})- return { promise, resolve, reject }-}--export class JsonLinesProcess {- private readonly child: ChildProcessWithoutNullStreams- private readonly closed = deferred<void>()- private input = ''- private stderr = ''- private failure?: Error- private closing?: Promise<void>- private stopped = false- private exited = false- private queue: Record<string, unknown>[] = []- private draining = false- private handler?: (message: Record<string, unknown>) => void | Promise<void>- private failureHandler?: (error: Error) => void-- constructor(command: NativeCommand, args: string[], cwd: string) {- if (/\.(?:cmd|bat)$/i.test(command.file))- throw new NativeBridgeError('BRIDGE_UNSAFE_EXECUTABLE', 'Resolve Windows batch shims to the native executable or node + official entrypoint')- this.child = spawn(command.file, [...command.args, ...args], {- cwd,- env: command.env ?? nativeEnvironment(),- shell: false,- windowsHide: true,- stdio: ['pipe', 'pipe', 'pipe'],- })- this.child.stdout.setEncoding('utf8')- this.child.stderr.setEncoding('utf8')- this.child.stdout.on('data', (chunk: string) => this.readChunk(chunk))- this.child.stderr.on('data', (chunk: string) => {- this.stderr = (this.stderr + chunk).slice(-MAX_STDERR_CHARS)- })- this.child.stdout.on('error', error => this.fail(error))- this.child.stdin.on('error', error => this.fail(error))- this.child.on('error', error => this.fail(error))- this.child.once('close', (code, signal) => {- if (!this.stopped)- this.fail(new NativeBridgeError('BRIDGE_PROCESS_EXIT', `Native process exited (${signal ?? code})${this.stderr.trim() ? `: ${this.stderr.trim()}` : ''}`))- this.stopped = true- this.exited = true- this.closed.resolve()- })- }-- onMessage(handler: (message: Record<string, unknown>) => void | Promise<void>): void {- this.handler = handler- this.drain()- }-- onFailure(handler: (error: Error) => void): void {- this.failureHandler = handler- if (this.failure)- handler(this.failure)- }-- write(value: unknown): void {- if (this.failure)- throw this.failure- if (this.stopped || !this.child.stdin.writable)- throw new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Native process is not writable')- const line = `${JSON.stringify(value)}\n`- if (line.length > MAX_FRAME_CHARS)- throw new NativeBridgeError('BRIDGE_FRAME_LIMIT', 'Native protocol frame exceeds the bounded transport limit')- this.child.stdin.write(line)- }-- fail(error: Error): void {- if (this.failure)- return- this.failure = error- this.queue = []- this.failureHandler?.(error)- void this.close().catch(() => {})- }-- close(graceful = false): Promise<void> {- this.closing ??= this.stop(graceful)- return this.closing- }-- private async stop(graceful: boolean): Promise<void> {- if (this.exited)- return- this.stopped = true- this.queue = []- if (graceful) {- this.child.stdin.end()- if (await this.waitForExit())- return- }- this.child.stdin.destroy()- this.child.kill('SIGTERM')- if (await this.waitForExit())- return- this.child.kill('SIGKILL')- if (!await this.waitForExit())- throw new NativeBridgeError('BRIDGE_PROCESS_STOP_TIMEOUT', 'Native process did not exit after termination')- }-- private async waitForExit(): Promise<boolean> {- let timer: ReturnType<typeof setTimeout> | undefined- const exited = await Promise.race([- this.closed.promise.then(() => true),- new Promise<false>((resolve) => {- timer = setTimeout(resolve, CLOSE_TIMEOUT_MS, false)- }),- ])- clearTimeout(timer)- return exited- }-- private readChunk(chunk: string): void {- if (this.stopped)- return- this.input += chunk- let end = this.input.indexOf('\n')- while (end >= 0) {- const line = this.input.slice(0, end).trim()- this.input = this.input.slice(end + 1)- if (line.length > MAX_FRAME_CHARS) {- this.fail(new NativeBridgeError('BRIDGE_FRAME_LIMIT', 'Native protocol frame exceeds the bounded transport limit'))- return- }- if (line) {- try {- const message = record(JSON.parse(line))- // Calling an async handler starts request/response dispatch synchronously.- // Only notification mutation is serialized by the adapters.- const result = this.handler?.(message)- if (result)- void Promise.resolve(result).catch(error => this.fail(errorFrom(error)))- else if (!this.handler)- this.queue.push(message)- }- catch (error) {- this.fail(error instanceof NativeBridgeError ? error : new NativeBridgeError('BRIDGE_PROTOCOL', `Invalid native JSONL: ${errorFrom(error).message}`))- return- }- }- if (this.queue.length > MAX_QUEUED_FRAMES) {- this.fail(new NativeBridgeError('BRIDGE_QUEUE_LIMIT', 'Native notification queue exceeded its bounded limit'))- return- }- if (this.stopped || this.failure)- return- end = this.input.indexOf('\n')- }- if (this.input.length > MAX_FRAME_CHARS)- this.fail(new NativeBridgeError('BRIDGE_FRAME_LIMIT', 'Native protocol frame exceeds the bounded transport limit'))- }-- private drain(): void {- if (this.draining || !this.handler || this.stopped || this.failure)- return- this.draining = true- try {- for (const message of this.queue.splice(0)) {- if (this.stopped || this.failure)- break- const result = this.handler(message)- if (result)- void Promise.resolve(result).catch(error => this.fail(errorFrom(error)))- }- }- catch (error) {- this.fail(errorFrom(error))- }- finally {- this.draining = false- }- }-}--export class PendingRequests {- private requests = new Map<string | number, { result: Deferred<unknown>, timer: ReturnType<typeof setTimeout>, removeAbort: () => void }>()-- constructor(private readonly write: (value: unknown) => void) {}-- request(id: string | number, frame: unknown, signal?: AbortSignal, timeoutMs = REQUEST_TIMEOUT_MS): Promise<unknown> {- if (signal?.aborted)- return Promise.reject(abortError(signal))- const result = deferred<unknown>()- const finish = (error: Error): void => {- const pending = this.requests.get(id)- if (!pending)- return- this.requests.delete(id)- clearTimeout(pending.timer)- pending.removeAbort()- result.reject(error)- }- const aborted = (): void => finish(abortError(signal!))- const timer = setTimeout(() => finish(new NativeBridgeError('BRIDGE_REQUEST_TIMEOUT', 'Native control request timed out')), timeoutMs)- const removeAbort = (): void => signal?.removeEventListener('abort', aborted)- this.requests.set(id, { result, timer, removeAbort })- signal?.addEventListener('abort', aborted, { once: true })- try {- this.write(frame)- }- catch (error) {- finish(errorFrom(error))- }- return result.promise- }-- settle(id: string | number, value: unknown, error?: Error): void {- const pending = this.requests.get(id)- if (!pending)- return- this.requests.delete(id)- clearTimeout(pending.timer)- pending.removeAbort()- if (error)- pending.result.reject(error)- else- pending.result.resolve(value)- }-- failAll(error: Error): void {- for (const id of this.requests.keys())- this.settle(id, undefined, error)- }-}diff --git a/packages/dsh-tauri-kernel/src/host/backends/types.ts b/packages/dsh-tauri-kernel/src/host/backends/types.tsdeleted file mode 100644index 7a24ac0c..00000000--- a/packages/dsh-tauri-kernel/src/host/backends/types.ts+++ /dev/null@@ -1,75 +0,0 @@-import type { ImageBlock, UserMessage } from '@deepseek-ai/dsh-llm'-import type { NativeModelCatalog, NativeTurnOptions } from '../../shared/native-model'--export type { NativeModelCatalog, NativeModelInfo, NativeTurnOptions } from '../../shared/native-model'--export interface NativePermission {- sandbox?: 'read-only' | 'workspace-write' | 'danger-full-access'- approval?: 'ask' | 'never'-}--export interface NativeSessionOpenOptions {- forkFrom?: string- permission?: NativePermission-}--export interface NativeCommand {- file: string- args: string[]- env?: Record<string, string | undefined>-}--/** One official image resolved for a native kernel prompt. */-export interface NativeImageSource {- mediaType: string- /** Absolute host path when the mounted provider is host-file-backed. */- path?: string- /** Verified base64 bytes, used by kernels that inline the image. */- base64?: string-}--/** Durable official image reference, as carried by one user-message block. */-export type NativeImageRef = ImageBlock['attachment']--/**- * Official attachment access for native prompts. `path` is a non-reading host- * lookup; `read` verifies stored bytes for kernels that must inline the image.- * Absent when the deployment mounts no image provider.- */-export interface NativeAttachments {- path: (ref: NativeImageRef) => string | undefined- read: (ref: NativeImageRef, signal: AbortSignal) => Promise<NativeImageSource>-}--export type NativeContent- = | { type: 'text', text: string }- | { type: 'thinking', text: string }- | { type: 'tool-call', id: string, name: string, arguments: string }--export interface NativeQuestion {- id: string- question: string- options?: { label: string, description?: string }[]- multiSelect?: boolean-}--export interface NativeSink {- text: (id: string, delta: string) => void- thinking: (id: string, delta: string) => void- assistant: (id: string, content: readonly NativeContent[]) => void- toolStart: (id: string, name: string, arguments_: string) => void- toolEnd: (id: string, output: string, error?: boolean) => void- approval: (- id: string,- request: { kind: 'command' | 'file' | 'tool', title: string, details: string },- signal?: AbortSignal,- ) => Promise<boolean>- questions: (id: string, questions: NativeQuestion[], signal?: AbortSignal) => Promise<Record<string, string | string[]>>-}--export interface NativeSession {- readonly id: string- models?: (signal: AbortSignal) => Promise<NativeModelCatalog>- submit: (messages: readonly UserMessage[], signal: AbortSignal, options?: NativeTurnOptions, permission?: NativePermission) => Promise<void>- dispose: () => Promise<void>-}diff --git a/packages/dsh-tauri-kernel/src/host/config/constants.ts b/packages/dsh-tauri-kernel/src/host/config/constants.tsdeleted file mode 100644index 7ff8c52f..00000000--- a/packages/dsh-tauri-kernel/src/host/config/constants.ts+++ /dev/null@@ -1,4 +0,0 @@-export const BRIDGE_PROVIDER = 'dsh-tauri-kernel'-export const KERNEL_RECORD_TYPE = 'plugin:dsh-tauri-kernel/kernel'-export const MODEL_RECORD_TYPE = 'plugin:dsh-tauri-kernel/model'-export const SESSION_TITLE_PURPOSE = 'session-title'diff --git a/packages/dsh-tauri-kernel/src/host/config/options.ts b/packages/dsh-tauri-kernel/src/host/config/options.tsdeleted file mode 100644index 84eb206f..00000000--- a/packages/dsh-tauri-kernel/src/host/config/options.ts+++ /dev/null@@ -1,5 +0,0 @@-export interface Config {- codexPath?: string- claudePath?: string- probeTimeoutMs?: number-}diff --git a/packages/dsh-tauri-kernel/src/host/config/runtime.ts b/packages/dsh-tauri-kernel/src/host/config/runtime.tsdeleted file mode 100644index 08c3b72b..00000000--- a/packages/dsh-tauri-kernel/src/host/config/runtime.ts+++ /dev/null@@ -1,68 +0,0 @@-import type { Agent } from '@deepseek-ai/dsh-agent'-import type { z } from 'zod'-import type { NativeModelCatalog, NativeTurnOptions } from '../../shared/native-model'-import type { BackendDetection, KernelBinding } from '../../shared/types'-import type { NativeSink } from '../backends/types'-import type { OfficialSink } from '../service/sink.types'-import type { AdmittedStep, BridgeRecordType, NativeEntry, NativePending, RecordWatermark } from '../types'--export const runtime = {- detections: new Map<string, BackendDetection>(),- sessions: new Map<string, NativeEntry>(),- pending: new Map<string, NativePending>(),- removals: new Map<string, Promise<void>>(),- closings: new Map<string, Promise<void>>(),- controllers: new Map<string, AbortController>(),- claims: new Map<string, string>(),- sinks: new Map<string, NativeSink>(),- exchanges: new Map<string, OfficialSink>(),- steps: new Map<string, AdmittedStep>(),- modelWrites: new Map<Agent, Promise<void>>(),- checkpoints: new Map<Agent, Promise<void>>(),- verified: new Map<Agent, Map<BridgeRecordType, RecordWatermark>>(),- bindingSchema: undefined as z.ZodType<KernelBinding> | undefined,- optionsSchema: undefined as z.ZodType<NativeTurnOptions> | undefined,- catalogSchema: undefined as z.ZodType<NativeModelCatalog> | undefined,- ready: false,- lifetime: new AbortController(),-}--export async function resetRuntime(): Promise<void> {- runtime.ready = false- runtime.bindingSchema = undefined- runtime.optionsSchema = undefined- runtime.catalogSchema = undefined- runtime.lifetime.abort(new Error('BRIDGE_DISPOSED'))- for (const controller of runtime.controllers.values())- controller.abort(new Error('BRIDGE_DISPOSED'))- const exchanges = [...runtime.exchanges.values()]- for (const exchange of exchanges)- exchange.state.controller.abort(new Error('BRIDGE_DISPOSED'))- await Promise.allSettled([- ...[...runtime.pending.values()].map(pending => pending.task),- ...runtime.removals.values(),- ...runtime.closings.values(),- ...runtime.modelWrites.values(),- ...runtime.checkpoints.values(),- ...exchanges.map(exchange => exchange.state.task),- ])- const disposed = await Promise.allSettled(exchanges.map(exchange => exchange.dispose()))- const entries = [...runtime.sessions.values()]- runtime.sessions.clear()- runtime.pending.clear()- runtime.removals.clear()- runtime.closings.clear()- runtime.controllers.clear()- runtime.claims.clear()- runtime.sinks.clear()- runtime.exchanges.clear()- runtime.steps.clear()- runtime.modelWrites.clear()- runtime.checkpoints.clear()- runtime.verified.clear()- runtime.detections.clear()- const outcomes = await Promise.allSettled(entries.map(entry => entry.session.dispose()))- const failures = [...disposed, ...outcomes].filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')- if (failures.length > 0)- throw new AggregateError(failures.map(failure => failure.reason), 'BRIDGE_DISPOSE_FAILED')-}diff --git a/packages/dsh-tauri-kernel/src/host/server/index.test.ts b/packages/dsh-tauri-kernel/src/host/server/index.test.tsdeleted file mode 100644index 98fb165f..00000000--- a/packages/dsh-tauri-kernel/src/host/server/index.test.ts+++ /dev/null@@ -1,570 +0,0 @@-import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent'-import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'-import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'-import type { SessionHandle } from '@deepseek-ai/dsh-session-persistence'-import type { IncomingMessage, Server } from 'node:http'-import type { AddressInfo } from 'node:net'-import type { NativeModelCatalog } from '../../shared/native-model'-import type { BackendDetection } from '../../shared/types'-import type { NativeSession } from '../backends/types'-import type { HostContext, PlatformLoader } from '../types'-import { createServer } from 'node:http'-import { createRequire } from 'node:module'-import { join } from 'node:path'-import process from 'node:process'-import { pathToFileURL } from 'node:url'-import { Context } from '@deepseek-ai/cordis'-import { AgentRegistry } from '@deepseek-ai/dsh-agent'-import { AgentDefaultModelConfig } from '@deepseek-ai/dsh-agent-default-model'-import { AgentLoop } from '@deepseek-ai/dsh-agent-loop'-import * as llmModule from '@deepseek-ai/dsh-llm'-import * as sessionModule from '@deepseek-ai/dsh-session'-import { assertContiguous, materializeAppendBatch, materializeCreateHeader, SessionPersistence, SessionPersistenceRevision, validateStoredEvents } from '@deepseek-ai/dsh-session-persistence'-import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'-import { ToolRuntime } from '@deepseek-ai/dsh-tools'-import { ApprovalService } from '@deepseek-ai/dsh-user-approval'-import { UserQuestionService } from '@deepseek-ai/dsh-user-questions'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import * as zodModule from 'zod'-import * as bridge from '../../index'-import { createClaudeSession } from '../backends/claude'-import { createCodexSession } from '../backends/codex'-import { resetRuntime, runtime } from '../config/runtime'-import { identity } from '../service/identity'-import { session } from '../service/session'-import { detectBackend } from '../utils/detection'--vi.mock('../utils/detection', () => ({ detectBackend: vi.fn() }))-vi.mock('../backends/codex', () => ({ createCodexSession: vi.fn() }))-vi.mock('../backends/claude', () => ({ createClaudeSession: vi.fn() }))--const require = createRequire(import.meta.url)-const coreRequire = createRequire(require.resolve('@deepseek-ai/dsh-agent-loop'))-const promptModule: { SystemPrompt: new (ctx: Context, config: { includeHarnessIdentity: boolean, includeRuntimeContext: boolean }) => Context['systemPrompt'] } = await import(pathToFileURL(coreRequire.resolve('@deepseek-ai/dsh-system-prompt')).href)--class MemoryPersistence extends SessionPersistence {- readonly stored = new Map<Session['id'], { header: Session['header'], inheritedEventCount: Session['inheritedEventCount'], events: readonly SessionEvent[], durable: readonly SessionEvent[], owner?: symbol }>()- readonly writers = new Map<Session['id'], SessionHandle>()- barrier: () => Promise<void> = async () => {}-- async create(header: Session['header'], options?: { inheritedEventCount?: Session['inheritedEventCount'], signal?: AbortSignal }): Promise<SessionHandle> {- options?.signal?.throwIfAborted()- if (this.stored.has(header.id))- throw new Error('HTTP memory session already exists')- this.stored.set(header.id, { header: materializeCreateHeader(header), inheritedEventCount: options?.inheritedEventCount ?? sessionModule.SessionLogOffset(0), events: [], durable: [] })- return this.open(header.id, 'write', options)- }-- async open(id: Session['id'], access: SessionHandle['access'], options?: { signal?: AbortSignal }): Promise<SessionHandle> {- options?.signal?.throwIfAborted()- const stored = this.stored.get(id)- if (!stored || (access === 'write' && stored.owner !== undefined))- throw new Error('HTTP memory session unavailable')- const owner = Symbol(id)- if (access === 'write')- stored.owner = owner- let closed = false- const active = () => {- if (closed || (access === 'write' && stored.owner !== owner))- throw new Error('HTTP memory session owner closed')- }- const flush = async () => {- active()- if (access !== 'write')- throw new Error('HTTP memory session is read-only')- await this.barrier()- stored.durable = validateStoredEvents(stored.header, structuredClone([...stored.events]))- }- const close = async () => {- if (closed)- return- if (access === 'write') {- await flush()- delete stored.owner- this.writers.delete(id)- }- closed = true- }- const handle: SessionHandle = {- id,- header: stored.header,- inheritedEventCount: stored.inheritedEventCount,- access,- async read(offset = 0, length, readOptions) {- active()- readOptions?.signal?.throwIfAborted()- return { events: validateStoredEvents(stored.header, structuredClone(stored.events.slice(offset, length === undefined ? undefined : offset + length))), eventState: 'shared-frozen' }- },- async append(events, appendOptions) {- active()- appendOptions?.signal?.throwIfAborted()- if (access !== 'write')- throw new Error('HTTP memory session is read-only')- const batch = materializeAppendBatch(events)- assertContiguous(id, batch, stored.events.length)- stored.events = [...stored.events, ...batch]- },- async flush(flushOptions) {- flushOptions?.signal?.throwIfAborted()- await flush()- },- close,- [Symbol.asyncDispose]: close,- }- if (access === 'write')- this.writers.set(id, handle)- return handle- }-- async flush(): Promise<void> {- await Promise.all([...this.writers.values()].map(handle => handle.flush()))- }-- async stat(id: Session['id']) {- const stored = this.stored.get(id)- return stored === undefined ? undefined : { header: stored.header, eventCount: stored.events.length, revision: SessionPersistenceRevision(`${id}:${stored.events.length}`) }- }-- async list() {- return Promise.all([...this.stored.keys()].map(async id => (await this.stat(id))!))- }-}--const cwd = process.cwd()-const now = 1_791_576_000_000-const codex: BackendDetection = { id: 'codex', installed: true, auth: 'ok', version: '0.147.0', drift: false, hint: null }-const claude: BackendDetection = { id: 'claude', installed: false, auth: 'unknown', version: null, drift: false, hint: 'BRIDGE_EXECUTABLE_MISSING: Claude CLI is not installed' }-const dsh: BackendDetection = { id: 'dsh', installed: true, auth: 'ok', version: null, drift: false, hint: null }-const catalog: NativeModelCatalog = { defaultModel: 'native/default', models: [{ id: 'native/default', name: 'Native default', reasoning: { efforts: [{ id: 'normal', name: 'Normal' }, { id: 'deep', name: 'Deep' }], defaultEffort: 'normal' } }, { id: 'native/plain', name: 'Native plain' }] }--function deferred<T>() {- let resolve!: (value: T | PromiseLike<T>) => void- const promise = new Promise<T>((accept) => {- resolve = accept- })- return { promise, resolve }-}--function native(id = 'http-native-session') {- return { id, models: vi.fn<NonNullable<NativeSession['models']>>().mockResolvedValue(catalog), submit: vi.fn<NativeSession['submit']>().mockResolvedValue(undefined), dispose: vi.fn<NativeSession['dispose']>().mockResolvedValue(undefined) }-}--let context: Context-let agents: AgentRegistry-let sessions: InstanceType<typeof sessionModule.SessionStore>-let projections: SessionProjectionRegistry-let llm: llmModule.LlmRuntime-let persistence: MemoryPersistence-let http: Server | undefined-let rejection: 401 | 403 | undefined-let runtimeSession: unknown-let runtimeBoot: unknown-let registered: Map<string, WebRoute>-let requestRejection: ReturnType<typeof vi.fn<(request: IncomingMessage) => 401 | 403 | undefined>>-let handles: AgentHandle[]-let releases: Array<() => void>-let background: Promise<unknown>[]-let stopCheckpoint: () => void-let checkpointed: Session['id'][]--beforeEach(async () => {- vi.setSystemTime(now)- await resetRuntime()- runtimeSession = sessionModule- runtimeBoot = undefined- rejection = undefined- registered = new Map()- handles = []- releases = []- background = []- checkpointed = []- vi.mocked(createCodexSession).mockReset()- vi.mocked(createClaudeSession).mockReset()- vi.mocked(detectBackend).mockReset()- vi.mocked(detectBackend).mockImplementation(async id => ({ detection: { ...(id === 'codex' ? codex : claude) }, command: { file: 'boundary-only', args: [id] } }))- context = new Context()- agents = new AgentRegistry(context)- sessions = new sessionModule.SessionStore(context)- projections = new SessionProjectionRegistry(context)- llm = new llmModule.LlmRuntime(context)- persistence = new MemoryPersistence(context)- const create = agents.create.bind(agents)- vi.spyOn(agents, 'create').mockImplementation(async (...args) => {- const handle = await create(...args)- handles.push(handle)- return handle- })- stopCheckpoint = context.on('session/flush', checkpointOfficial)- await context.plugin(AgentDefaultModelConfig, { provider: 'global-provider', model: 'global-model', reasoningEffort: 'global-effort' }).await()- const prompt = new promptModule.SystemPrompt(context, { includeHarnessIdentity: false, includeRuntimeContext: false })- const tools = new ToolRuntime(context, { mode: 'native' })- await context.plugin(ApprovalService, { policy: 'never' }).await()- await context.plugin(UserQuestionService).await()- expect(await prompt.assemble({})).toMatchObject({ tools: [] })- expect(tools.schemas()).toEqual([])- requestRejection = vi.fn(() => rejection)- await context.plugin((ctx) => {- ctx.provide('connection', { requestRejection } as unknown as Context['connection'])- }).await()- context.provide('webServer', {- register(route: WebRoute) {- registered.set(route.path, route)- return () => registered.delete(route.path)- },- } as unknown as HostContext['webServer'])- const loader: PlatformLoader = {- async import(id) {- if (id === 'zod')- return zodModule- if (id === '@deepseek-ai/dsh-llm')- return llmModule- if (id === '@deepseek-ai/dsh-session')- return runtimeSession- if (id === '@deepseek-ai/dsh-app-boot' && runtimeBoot !== undefined)- return runtimeBoot- throw new Error(`Unexpected public runtime import: ${id}`)- },- unwrapExports: value => value,- }- context.provide('loader', loader as HostContext['loader'])- context.provide('agentPresets', { resolve: vi.fn().mockResolvedValue({ id: 'test-preset' }), mount: vi.fn().mockResolvedValue(undefined) } as unknown as HostContext['agentPresets'])- context.provide('workspaceRegistry', { get: () => undefined } as unknown as HostContext['workspaceRegistry'])- await context.plugin(AgentLoop, { agents: [] }).await()-})--afterEach(async () => {- for (const release of releases)- release()- await Promise.allSettled(background)- persistence.barrier = async () => {}- if (http) {- await new Promise<void>((resolve, reject) => {- http!.close(error => error ? reject(error) : resolve())- http!.closeAllConnections()- })- http = undefined- }- await session.dispose()- await context.fiber.dispose()- await resetRuntime()- vi.restoreAllMocks()- vi.useRealTimers()-})--async function checkpointOfficial(official: Session) {- const stored = persistence.stored.get(official.id)!- const writer = persistence.writers.get(official.id)!- const suffix = official.snapshotEvents().slice(stored.events.length)- if (suffix.length > 0)- await writer.append(suffix)- await writer.flush()- checkpointed.push(official.id)-}--async function start(): Promise<string> {- const fiber = context.plugin(bridge)- await fiber.await()- await vi.waitFor(() => expect(runtime.ready).toBe(true))- http = createServer((request, response) => {- const route = registered.get(new URL(request.url ?? '/', 'http://localhost').pathname)- if (!route) {- response.writeHead(404).end()- return- }- void Promise.resolve(route.handler(request, response)).catch(() => response.destroy())- })- await new Promise<void>(resolve => http!.listen(0, '127.0.0.1', resolve))- return `http://127.0.0.1:${(http.address() as AddressInfo).port}`-}--async function create(base: string, connection = native()) {- vi.mocked(createCodexSession).mockResolvedValueOnce(connection)- const response = await fetch(`${base}/api/tauri/bridge/sessions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ backend: 'codex', cwd }) })- expect(response.status).toBe(200)- const body = await response.json() as { sessionId: string }- const agent = agents.get(sessionModule.SessionId(body.sessionId))!- expect(agent.session).toBe(sessions.get(agent.id))- expect(identity.resolve(agent)).toEqual({ backend: 'codex', nativeSessionId: connection.id, sessionId: body.sessionId })- return { agent, connection }-}--function select(base: string, agent: Agent, model: string | null, reasoningEffort: string | null) {- const task = fetch(`${base}/api/tauri/bridge/models`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sessionId: agent.id, model, reasoningEffort }) })- background.push(task)- return task-}--function modelEvents(official: Session) {- return official.snapshotEvents().filter(event => (event.type as string) === 'plugin:dsh-tauri-kernel/model')-}--describe('exported bridge plugin HTTP dependency boundary', () => {- it('returns the kernel catalog through real Cordis inject enforcement and the shared request guard', async () => {- const base = await start()- const response = await fetch(`${base}/api/tauri/bridge/backends`)- expect(response.status).toBe(200)- expect(await response.json()).toEqual([dsh, { ...codex, bridgeReady: true }, { ...claude, bridgeReady: true }])- expect(requestRejection).toHaveBeenCalledOnce()- expect(requestRejection.mock.calls[0]![0].method).toBe('GET')- expect(vi.mocked(detectBackend).mock.calls.map(([id]) => id).sort()).toEqual(['claude', 'codex'])- expect(projections.stateOf(sessionModule.Session.create(sessionModule.SessionId('guard-regression')), 'bridgeKernel')?.binding).toBeNull()- })-- it('answers an unusable session location with the bridge reason instead of an opaque server error', async () => {- const base = await start()- const cases = [- { body: { backend: 'codex', cwd: join(cwd, 'bridge-missing-session-directory') }, reason: 'BRIDGE_CWD_INVALID: 会话目录必须是已存在的绝对目录。' },- { body: { backend: 'codex', workspaceId: 'bridge-missing-workspace' }, reason: 'BRIDGE_WORKSPACE_NOT_FOUND: 工作区不存在。' },- ] as const- for (const { body, reason } of cases) {- const response = await fetch(`${base}/api/tauri/bridge/sessions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })- expect(response.status).toBe(400)- expect(await response.json()).toMatchObject({ message: reason })- }- expect(createCodexSession).not.toHaveBeenCalled()- expect(runtime.sessions.size).toBe(0)- })-- it.each([401, 403] as const)('preserves connection rejection %s on every declared bridge route before native detection', async (status) => {- rejection = status- const base = await start()- for (const [path, method] of [['backends', 'GET'], ['sessions', 'POST'], ['models?sessionId=not-admitted', 'GET'], ['models', 'POST']] as const) {- const response = await fetch(`${base}/api/tauri/bridge/${path}`, { method })- expect(response.status).toBe(status)- expect(await response.json()).toEqual({ error: status === 401 ? 'unauthorized' : 'forbidden' })- }- expect(requestRejection).toHaveBeenCalledTimes(4)- expect(detectBackend).not.toHaveBeenCalled()- expect(createCodexSession).not.toHaveBeenCalled()- expect(createClaudeSession).not.toHaveBeenCalled()- expect(runtime.sessions.size).toBe(0)- })-- it('reports the official runtime version so the client can gate on it', async () => {- runtimeBoot = { getDshRuntimeVersion: () => '0.2.1-rc.1' }- const base = await start()- const response = await fetch(`${base}/api/tauri/bridge/backends`)- expect(response.status).toBe(200)- const payload = await response.json() as Array<Record<string, unknown>>- expect(payload[0]).toEqual({ ...dsh, version: '0.2.1-rc.1' })- })-- it('retains CLI installation status while marking the bridge unavailable when official record support is absent', async () => {- const { appendPluginRecord: _appendPluginRecord, pluginRecordOf: _pluginRecordOf, ...withoutPluginRecords } = sessionModule- runtimeSession = withoutPluginRecords- const base = await start()- const response = await fetch(`${base}/api/tauri/bridge/backends`)- expect(response.status).toBe(200)- expect(await response.json()).toEqual([- dsh,- { ...codex, bridgeReady: false, hint: 'BRIDGE_CORE_UNAVAILABLE: 当前核心未提供完整的官方内核桥接接口,不能连接本机 CLI。' },- { ...claude, bridgeReady: false },- ])- expect(requestRejection).toHaveBeenCalledOnce()- })-- it('serves native model controls and durable null reset through the literal models route without mutating the global provider route', async () => {- const base = await start()- const { agent, connection } = await create(base)- const cursor = Number(agent.session.seq)- const originalBinding = identity.resolve(agent)- const providers = llm.listProviders()- const get = await fetch(`${base}/api/tauri/bridge/models?sessionId=${encodeURIComponent(agent.id)}`)- expect(get.status).toBe(200)- expect(await get.json()).toEqual({ backend: 'codex', defaultModel: 'native/default', models: [{ id: 'native/default', name: 'Native default', reasoning: { efforts: [{ id: 'normal', name: 'Normal' }, { id: 'deep', name: 'Deep' }], defaultEffort: 'normal' } }, { id: 'native/plain', name: 'Native plain' }], current: { model: null, reasoningEffort: null } })- const post = await select(base, agent, 'native/default', 'deep')- expect(post.status).toBe(200)- expect(await post.json()).toEqual({ model: 'native/default', reasoningEffort: 'deep' })- expect(modelEvents(agent.session)).toEqual([{ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'native/default', reasoningEffort: 'deep' } }])- expect(persistence.stored.get(agent.id)?.durable.find(event => event.seq === cursor)).toEqual({ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'native/default', reasoningEffort: 'deep' } })- const reset = await select(base, agent, null, null)- expect(reset.status).toBe(200)- expect(await reset.json()).toEqual({ model: null, reasoningEffort: null })- expect(modelEvents(agent.session)).toEqual([- { seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'native/default', reasoningEffort: 'deep' } },- { seq: cursor + 1, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: null, reasoningEffort: null } },- ])- expect(checkpointed).toEqual([agent.id, agent.id])- expect(identity.resolve(agent)).toEqual(originalBinding)- expect(agent.session.requestHeader()).toBeUndefined()- expect(agent.options).toMatchObject({ provider: 'dsh-tauri-kernel', model: 'codex' })- expect(context.agentDefaultModel.currentSelection()).toEqual({ provider: 'global-provider', model: 'global-model', reasoningEffort: 'global-effort' })- expect(llm.listProviders()).toEqual(providers)- expect(connection.submit).not.toHaveBeenCalled()- expect(connection.models).toHaveBeenCalledTimes(3)- expect(createCodexSession).toHaveBeenCalledOnce()- expect(createClaudeSession).not.toHaveBeenCalled()- }, 10_000)-- it('does not return POST success until the official model record crosses the real persistence barrier', async () => {- const base = await start()- const { agent, connection } = await create(base)- const entered = deferred<void>()- const drain = deferred<void>()- releases.push(() => drain.resolve())- persistence.barrier = async () => {- entered.resolve()- await drain.promise- }- let settled = false- const request = select(base, agent, 'native/default', 'deep').then((response) => {- settled = true- return response- })- background.push(request)- await entered.promise- expect(settled).toBe(false)- expect(modelEvents(agent.session)).toHaveLength(1)- expect(persistence.stored.get(agent.id)?.durable.some(event => (event.type as string) === 'plugin:dsh-tauri-kernel/model')).toBe(false)- expect(connection.submit).not.toHaveBeenCalled()- drain.resolve()- const response = await request- expect(response.status).toBe(200)- expect(await response.json()).toEqual({ model: 'native/default', reasoningEffort: 'deep' })- expect(persistence.stored.get(agent.id)?.durable.filter(event => (event.type as string) === 'plugin:dsh-tauri-kernel/model')).toEqual(modelEvents(agent.session))- }, 10_000)-- it('supports HEAD and rejects undeclared models verbs with the actual Allow set without touching native discovery', async () => {- const base = await start()- const { agent, connection } = await create(base)- const head = await fetch(`${base}/api/tauri/bridge/models?sessionId=${encodeURIComponent(agent.id)}`, { method: 'HEAD' })- expect(head.status).toBe(200)- expect(await head.text()).toBe('')- expect(connection.models).toHaveBeenCalledOnce()- for (const method of ['OPTIONS', 'PUT', 'PATCH', 'DELETE']) {- const response = await fetch(`${base}/api/tauri/bridge/models?sessionId=${encodeURIComponent(agent.id)}`, { method })- expect(response.status).toBe(405)- expect(response.headers.get('allow')?.split(', ').sort()).toEqual(['GET', 'HEAD', 'POST'])- }- expect(connection.models).toHaveBeenCalledOnce()- expect(connection.submit).not.toHaveBeenCalled()- expect(modelEvents(agent.session)).toEqual([])- expect(checkpointed).toEqual([])- }, 10_000)-- it('rejects cross-origin model writes before body parsing, native catalog discovery, or record publication', async () => {- const base = await start()- const { agent, connection } = await create(base)- for (const origin of ['http://untrusted.invalid', 'null', 'not-an-origin']) {- const response = await fetch(`${base}/api/tauri/bridge/models`, { method: 'POST', headers: { origin, 'content-type': 'application/json' }, body: JSON.stringify({ sessionId: agent.id, model: 'native/default', reasoningEffort: 'deep' }) })- expect(response.status).toBe(403)- expect(await response.json()).toEqual({ error: 'cross-origin-request' })- }- expect(connection.models).not.toHaveBeenCalled()- expect(connection.submit).not.toHaveBeenCalled()- expect(modelEvents(agent.session)).toEqual([])- expect(checkpointed).toEqual([])- expect(createCodexSession).toHaveBeenCalledOnce()- }, 10_000)-- it.each(['', '?sessionId=', '?sessionId=%20', '?sessionId=one&sessionId=two'])('rejects malformed models query %s before native I/O', async (query) => {- const base = await start()- const response = await fetch(`${base}/api/tauri/bridge/models${query}`)- expect(response.status).toBe(400)- expect(detectBackend).not.toHaveBeenCalled()- expect(createCodexSession).not.toHaveBeenCalled()- expect(createClaudeSession).not.toHaveBeenCalled()- expect(runtime.sessions.size).toBe(0)- }, 10_000)-- it.each([- null,- {},- { sessionId: '', model: null, reasoningEffort: null },- { sessionId: 'foreign-http-session', model: '', reasoningEffort: null },- { sessionId: 'foreign-http-session', model: null },- { sessionId: 'foreign-http-session', model: null, reasoningEffort: 3 },- { sessionId: 'foreign-http-session', model: ['native/default'], reasoningEffort: null },- ])('rejects malformed models body %j before resolving any native session', async (body) => {- const base = await start()- const response = await fetch(`${base}/api/tauri/bridge/models`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })- expect(response.status).toBe(400)- expect(detectBackend).not.toHaveBeenCalled()- expect(createCodexSession).not.toHaveBeenCalled()- expect(createClaudeSession).not.toHaveBeenCalled()- expect(runtime.sessions.size).toBe(0)- }, 10_000)-- it('refuses unknown and nonnative session model actions without using another live native owner', async () => {- const base = await start()- const { agent, connection } = await create(base)- const ordinary = await agents.create({ sessionId: sessionModule.SessionId('ordinary-http-session'), meta: { cwd }, agentOptions: { provider: 'global-provider', model: 'global-model' } })- for (const id of ['foreign-http-session', ordinary.agent.id]) {- const get = await fetch(`${base}/api/tauri/bridge/models?sessionId=${encodeURIComponent(id)}`)- expect(get.status).toBe(500)- const post = await fetch(`${base}/api/tauri/bridge/models`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sessionId: id, model: null, reasoningEffort: null }) })- expect(post.status).toBe(500)- }- expect(connection.models).not.toHaveBeenCalled()- expect(connection.submit).not.toHaveBeenCalled()- expect(modelEvents(agent.session)).toEqual([])- expect(modelEvents(ordinary.agent.session)).toEqual([])- expect(checkpointed).toEqual([])- expect(createCodexSession).toHaveBeenCalledOnce()- }, 10_000)-- it('rejects unavailable models and unadvertised effort without appending or submitting', async () => {- const base = await start()- const { agent, connection } = await create(base)- for (const [chosen, effort] of [['missing-native-model', null], ['native/plain', 'deep'], ['native/default', 'xhigh']] as const) {- const response = await select(base, agent, chosen, effort)- expect(response.status).toBe(500)- }- expect(connection.models).toHaveBeenCalledTimes(3)- expect(connection.submit).not.toHaveBeenCalled()- expect(modelEvents(agent.session)).toEqual([])- expect(checkpointed).toEqual([])- expect(agent.session.requestHeader()).toBeUndefined()- expect(agent.options).toMatchObject({ provider: 'dsh-tauri-kernel', model: 'codex' })- }, 10_000)-- it('fails rather than pretending a native backend without models can accept model controls', async () => {- const base = await start()- const connection = native('http-unsupported-native')- Reflect.deleteProperty(connection, 'models')- const { agent } = await create(base, connection)- const get = await fetch(`${base}/api/tauri/bridge/models?sessionId=${encodeURIComponent(agent.id)}`)- expect(get.status).toBe(500)- const post = await select(base, agent, null, null)- expect(post.status).toBe(500)- expect(connection.submit).not.toHaveBeenCalled()- expect(modelEvents(agent.session)).toEqual([])- expect(checkpointed).toEqual([])- expect(createCodexSession).toHaveBeenCalledOnce()- }, 10_000)-- it('does not report a successful model POST without an official flush listener', async () => {- const base = await start()- const { agent, connection } = await create(base)- stopCheckpoint()- const cursor = Number(agent.session.seq)- const response = await select(base, agent, 'native/default', 'deep')- expect(response.status).toBe(500)- expect(modelEvents(agent.session)).toEqual([{ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'native/default', reasoningEffort: 'deep' } }])- expect(persistence.stored.get(agent.id)?.durable.some(event => (event.type as string) === 'plugin:dsh-tauri-kernel/model')).toBe(false)- expect(checkpointed).toEqual([])- expect(connection.submit).not.toHaveBeenCalled()- }, 10_000)-- it('keeps a failed flush POST unsuccessful and checkpoints retry without duplicating the official choice', async () => {- const base = await start()- const { agent, connection } = await create(base)- const failure = new Error('HTTP official model flush refused')- persistence.barrier = async () => {- throw failure- }- const response = await select(base, agent, 'native/default', 'deep')- expect(response.status).toBe(500)- expect(modelEvents(agent.session)).toHaveLength(1)- expect(persistence.stored.get(agent.id)?.durable.some(event => (event.type as string) === 'plugin:dsh-tauri-kernel/model')).toBe(false)- expect(connection.submit).not.toHaveBeenCalled()- persistence.barrier = async () => {}- const retry = await select(base, agent, 'native/default', 'deep')- expect(retry.status).toBe(200)- expect(await retry.json()).toEqual({ model: 'native/default', reasoningEffort: 'deep' })- expect(modelEvents(agent.session)).toHaveLength(1)- expect(persistence.stored.get(agent.id)?.durable.filter(event => (event.type as string) === 'plugin:dsh-tauri-kernel/model')).toEqual(modelEvents(agent.session))- expect(connection.submit).not.toHaveBeenCalled()- expect(createCodexSession).toHaveBeenCalledOnce()- }, 10_000)-})diff --git a/packages/dsh-tauri-kernel/src/host/server/index.ts b/packages/dsh-tauri-kernel/src/host/server/index.tsdeleted file mode 100644index e42218ff..00000000--- a/packages/dsh-tauri-kernel/src/host/server/index.ts+++ /dev/null@@ -1,15 +0,0 @@-import type { Config } from '../config/options'-import { defineWebServer } from 'dsh-h3'-import { guard } from 'dsh-tauri'-import getBackends from './routes/backends/get'-import getModels from './routes/models/get'-import postModels from './routes/models/post'-import postSessions from './routes/sessions/post'--export const server = defineWebServer<Config>((app) => {- app.use(guard)- app.get('/api/tauri/bridge/backends', getBackends)- app.get('/api/tauri/bridge/models', getModels)- app.post('/api/tauri/bridge/models', postModels)- app.post('/api/tauri/bridge/sessions', postSessions)-})diff --git a/packages/dsh-tauri-kernel/src/host/server/routes/backends/get.ts b/packages/dsh-tauri-kernel/src/host/server/routes/backends/get.tsdeleted file mode 100644index e20eb521..00000000--- a/packages/dsh-tauri-kernel/src/host/server/routes/backends/get.ts+++ /dev/null@@ -1,6 +0,0 @@-import type { EventHandlerRequest } from 'h3'-import type { BackendDetection } from '../../../../shared/types'-import { defineEventHandler } from 'h3'-import { backend } from '../../../service/backend'--export default defineEventHandler<EventHandlerRequest, Promise<BackendDetection[]>>(() => backend.getCatalog())diff --git a/packages/dsh-tauri-kernel/src/host/server/routes/models/get.ts b/packages/dsh-tauri-kernel/src/host/server/routes/models/get.tsdeleted file mode 100644index a642d8f4..00000000--- a/packages/dsh-tauri-kernel/src/host/server/routes/models/get.ts+++ /dev/null@@ -1,11 +0,0 @@-import type { EventHandlerRequest } from 'h3'-import type { NativeModelDirectory } from '../../../../shared/native-model'-import { defineEventHandler, getQuery, HTTPError } from 'h3'-import { model } from '../../../service/model'--export default defineEventHandler<EventHandlerRequest, Promise<NativeModelDirectory>>((event) => {- const query = getQuery<{ sessionId: string }>(event)- if (typeof query.sessionId !== 'string' || !query.sessionId.trim())- throw new HTTPError({ statusCode: 400, message: 'BRIDGE_SESSION_INVALID: 请指定原生会话。' })- return model.getCatalog(query.sessionId)-})diff --git a/packages/dsh-tauri-kernel/src/host/server/routes/models/post.ts b/packages/dsh-tauri-kernel/src/host/server/routes/models/post.tsdeleted file mode 100644index dcb6f668..00000000--- a/packages/dsh-tauri-kernel/src/host/server/routes/models/post.ts+++ /dev/null@@ -1,16 +0,0 @@-import type { EventHandlerRequest } from 'h3'-import type { NativeTurnOptions } from '../../../../shared/native-model'-import type { ModelBody } from '../../../types'-import { defineEventHandler, HTTPError, readBody } from 'h3'-import { model } from '../../../service/model'--export default defineEventHandler<EventHandlerRequest, Promise<NativeTurnOptions>>(async (event) => {- const body = await readBody<ModelBody>(event)- if (body === null || typeof body !== 'object' || typeof body.sessionId !== 'string' || !body.sessionId.trim())- throw new HTTPError({ statusCode: 400, message: 'BRIDGE_SESSION_INVALID: 请指定原生会话。' })- for (const key of ['model', 'reasoningEffort'] as const) {- if (body[key] !== null && (typeof body[key] !== 'string' || !body[key].trim()))- throw new HTTPError({ statusCode: 400, message: `BRIDGE_MODEL_INVALID: ${key}` })- }- return model.select(body.sessionId, { model: body.model, reasoningEffort: body.reasoningEffort })-})diff --git a/packages/dsh-tauri-kernel/src/host/server/routes/sessions/post.ts b/packages/dsh-tauri-kernel/src/host/server/routes/sessions/post.tsdeleted file mode 100644index cecacf53..00000000--- a/packages/dsh-tauri-kernel/src/host/server/routes/sessions/post.ts+++ /dev/null@@ -1,25 +0,0 @@-import type { EventHandlerRequest } from 'h3'-import type { CreateBody } from '../../../types'-import { defineEventHandler, HTTPError, readBody } from 'h3'-import { session } from '../../../service/session'--export default defineEventHandler<EventHandlerRequest, Promise<{ sessionId: string }>>(async (event) => {- const body = await readBody<CreateBody>(event)- if (body === null || typeof body !== 'object' || (body.backend !== 'codex' && body.backend !== 'claude'))- throw new HTTPError({ statusCode: 400, message: 'BRIDGE_BACKEND_INVALID: 请选择 Codex 或 Claude。' })- for (const key of ['workspaceId', 'cwd', 'agentPreset'] as const) {- if (body[key] !== undefined && (typeof body[key] !== 'string' || !body[key].trim()))- throw new HTTPError({ statusCode: 400, message: `BRIDGE_REQUEST_INVALID: ${key}` })- }- if (body.workspaceId !== undefined && body.cwd !== undefined)- throw new HTTPError({ statusCode: 400, message: 'BRIDGE_LOCATION_INVALID: workspaceId 与 cwd 不能同时指定。' })- try {- return await session.create(body.backend, body.workspaceId, body.cwd, body.agentPreset)- }- catch (error) {- const message = error instanceof Error ? error.message : ''- if (!message.startsWith('BRIDGE_'))- throw error- throw new HTTPError({ statusCode: 400, message })- }-})diff --git a/packages/dsh-tauri-kernel/src/host/service/adapter.ts b/packages/dsh-tauri-kernel/src/host/service/adapter.tsdeleted file mode 100644index 353f80b5..00000000--- a/packages/dsh-tauri-kernel/src/host/service/adapter.ts+++ /dev/null@@ -1,267 +0,0 @@-import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'-import type { GenerateOptions, LlmAdapter, LlmCallConfig, LlmModelInfo, LlmResolvedModelInfo, ResolvedRetryPolicy, StreamChunk, UserMessage } from '@deepseek-ai/dsh-llm'-import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'-import type { AdmittedStep, HostContext } from '../types'-import { Buffer } from 'node:buffer'-import { getServerContext } from 'dsh-h3/utils'-import { defineService } from 'dsh-tauri'-import { BRIDGE_PROVIDER, SESSION_TITLE_PURPOSE } from '../config/constants'-import { runtime } from '../config/runtime'-import { server } from '../server'-import { loadRuntimeModules } from '../utils/runtime-modules'-import { identity } from './identity'-import { model } from './model'-import { session } from './session'-import { sink } from './sink'--/**- * Sources that carry DSH-side environment state rather than content addressed to- * the model: policy switches, cwd notices, plugin run outcomes, and snapshots.- * The native kernel owns its own equivalents, so these never become native input- * and must not abort a running native turn. Real user instructions stay absent- * on purpose — steering a running native turn is still refused.- */-const ENVIRONMENT_SOURCES = new Set(['runtime-context', 'time-context', 'user-approval', 'working-directory', 'cordis-host-runner', 'ptc-mode', 'skill-catalog'])--export const adapter = defineService({- async register(): Promise<() => void> {- const ctx = getServerContext<HostContext>(server)- const modules = await loadRuntimeModules(ctx.loader)- runtime.lifetime.signal.throwIfAborted()- class NativeAdapter extends modules.LlmAdapter {- providerInfo(provider: string): { id: string, name: string } {- return { id: provider, name: '本机内核桥接' }- }-- providerRetryPolicy(): ResolvedRetryPolicy {- return { mode: 'normal', maxRetries: 0, retryableCodes: [], initialDelayMs: 500, maxDelayMs: 10_000, jitterRatio: 0 }- }-- async listModels(): Promise<readonly LlmModelInfo[]> {- return []- }-- async resolveModel(provider: string, model: string, signal?: AbortSignal): Promise<LlmResolvedModelInfo> {- signal?.throwIfAborted()- if (provider !== BRIDGE_PROVIDER || (model !== 'codex' && model !== 'claude'))- throw new Error('BRIDGE_ROUTE_INVALID: 原生内核路由无效。')- return { provider, id: model, name: model === 'codex' ? 'Codex' : 'Claude' }- }-- stream(options: GenerateOptions): AsyncIterable<StreamChunk> {- return adapter.stream(options)- }- }- const dispose = ctx.llm.registerAdapter([BRIDGE_PROVIDER], new NativeAdapter() as LlmAdapter)- runtime.ready = true- return () => {- runtime.ready = false- dispose()- }- },-- async admit(payload: Omit<AdmittedStep, 'request' | 'dispatched'>, next: () => Promise<PreStepDecision>): Promise<PreStepDecision> {- const closing = runtime.closings.get(payload.agent.id)- if (closing)- await closing.catch(() => undefined)- let decision: PreStepDecision- try {- decision = await next()- const current = runtime.exchanges.get(payload.agent.id)- if (current) {- const state = current.state- if (decision.kind !== 'enter' || payload.signal.aborted || state.failure !== undefined || state.input.agent !== payload.agent || state.input.turn !== payload.turn || state.input.signal !== payload.signal || payload.messages.some(message => continuationMessage(message, state.input.messages)) || decision.messages.some(message => continuationMessage(message, state.input.messages) && !payload.messages.includes(message)) || state.finalConsumed) {- state.controller.abort(state.failure ?? new Error('BRIDGE_STEERING_UNSUPPORTED: 原生回合不支持中途追加指令或提前结束。'))- await session.finish(payload.agent, state.input.turn)- throw state.signal.reason- }- }- }- catch (error) {- const current = runtime.exchanges.get(payload.agent.id)- if (current) {- current.state.controller.abort(error)- await session.finish(payload.agent, current.state.input.turn)- }- throw error- }- if (decision.kind !== 'enter' || payload.signal.aborted)- return decision- const ctx = getServerContext<HostContext>(server)- await session.repairInherited(payload.agent, payload.signal)- const binding = ctx.sessionProjections.stateOf(payload.agent.session, 'bridgeKernel')?.binding- if (binding === null || binding === undefined) {- if (payload.agent.session.requestHeader()?.config.provider === BRIDGE_PROVIDER)- throw new Error('BRIDGE_BINDING_MISSING: 原生内核的官方身份记录缺失。')- return decision- }- identity.resolve(payload.agent)- session.validateComposition(payload.agent)- assertLive(payload.agent, payload.signal)- runtime.steps.set(payload.agent.id, { ...payload, messages: decision.messages.filter(nativeMessage), dispatched: false })- return decision- },-- async request(payload: { agent: Agent, signal: AbortSignal }, next: () => Promise<LlmCallConfig>): Promise<LlmCallConfig> {- const config = await next()- const ctx = getServerContext<HostContext>(server)- const projected = ctx.sessionProjections.stateOf(payload.agent.session, 'bridgeKernel')?.binding- if (projected === null || projected === undefined) {- if (config.provider === BRIDGE_PROVIDER || payload.agent.session.requestHeader()?.config.provider === BRIDGE_PROVIDER)- throw new Error('BRIDGE_BINDING_MISSING: 原生内核的官方身份记录缺失。')- return config- }- const binding = identity.resolve(payload.agent)- assertLive(payload.agent, payload.signal)- // The API controller answers every headerless session with the deployment default route, so an- // unstarted bound session keeps its kernel instead of failing its first message on that default.- const fallback = ctx.get('agentDefaultModel')?.currentSelection()- const bound = config.provider === BRIDGE_PROVIDER && config.model === binding.backend- const ambient = payload.agent.session.requestHeader() === undefined && fallback !== undefined && config.provider === fallback.provider && config.model === fallback.model && config.reasoningEffort === fallback.reasoningEffort && config.maxTokens === undefined && config.temperature === undefined && config.stop === undefined- if (!bound && !ambient)- throw new Error(`BRIDGE_KERNEL_IMMUTABLE: 已绑定会话不能切换内核或由 DSH 覆写原生选项(请求 ${config.provider}/${config.model},当前内核 ${binding.backend})。`)- // The native kernel owns model, effort, and generation options: DSH values never reach it.- const { reasoningEffort: _effort, maxTokens: _maxTokens, temperature: _temperature, stop: _stop, ...native } = config- return { ...native, provider: BRIDGE_PROVIDER, model: binding.backend }- },-- async* capture(options: GenerateOptions, next: () => AsyncIterable<StreamChunk>): AsyncIterable<StreamChunk> {- if (options.provider !== BRIDGE_PROVIDER) {- yield* next()- return- }- if (options.purpose === SESSION_TITLE_PURPOSE) {- yield* next()- return- }- const ctx = getServerContext<HostContext>(server)- const modules = await loadRuntimeModules(ctx.loader)- if (options.purpose !== undefined || !modules.isAgentLoopRequest(options) || options.sessionId === undefined || options.signal === undefined)- throw new Error('BRIDGE_AUXILIARY_REQUEST: 原生内核仅接受官方会话回合,不支持辅助模型调用。')- const admitted = runtime.steps.get(options.sessionId)- if (!admitted || admitted.dispatched || admitted.request !== undefined || admitted.signal !== options.signal)- throw new Error('BRIDGE_STEP_UNAVAILABLE: 没有对应的官方已接纳回合。')- assertLive(admitted.agent, options.signal)- const boundary = ctx.sessionProjections.stateOf(admitted.agent.session, 'turnBoundary')- if (boundary?.lastTurn !== admitted.turn || boundary.openTurnStartSeq === null || boundary.lastStepBoundary?.kind !== 'start' || boundary.lastStepBoundary.seq !== boundary.lastStepStartSeq)- throw new Error('BRIDGE_STEP_UNAVAILABLE: 官方回合边界不再有效。')- admitted.request = options- try {- yield* next()- }- finally {- if (runtime.steps.get(options.sessionId) === admitted)- runtime.steps.delete(options.sessionId)- }- },-- async* stream(options: GenerateOptions): AsyncIterable<StreamChunk> {- if (options.purpose === SESSION_TITLE_PURPOSE) {- yield* session.title(options)- return- }- const admitted = options.sessionId === undefined ? undefined : runtime.steps.get(options.sessionId)- if (!admitted || admitted.dispatched || !admitted.request || options.purpose !== undefined || options.signal !== admitted.signal || options.provider !== BRIDGE_PROVIDER || options.model !== admitted.request.model)- throw new Error('BRIDGE_STEP_UNAVAILABLE: 原生请求未通过官方回合检查。')- const binding = identity.resolve(admitted.agent)- if (binding.backend !== options.model)- throw new Error('BRIDGE_BINDING_MISMATCH: 请求与已提交的原生内核不一致。')- assertLive(admitted.agent, admitted.signal)- admitted.dispatched = true- const optionsForTurn = runtime.exchanges.get(admitted.agent.id)?.state.input.options ?? await model.forTurn(admitted.agent, admitted.signal)- const official = await session.execute({ ...admitted, binding, options: optionsForTurn })- const state = official.state- let yieldedBoundary = false- try {- while (true) {- assertLive(admitted.agent, admitted.signal)- state.signal.throwIfAborted()- if (state.queue.length === 0) {- if (state.done) {- if (state.failure !== undefined)- throw state.failure- throw new Error('BRIDGE_STREAM_UNSETTLED: 原生回合缺少终止边界。')- }- let wake!: () => void- await new Promise<void>((resolve) => {- wake = resolve- state.wake = wake- state.signal.addEventListener('abort', wake, { once: true })- }).finally(() => {- state.signal.removeEventListener('abort', wake)- if (state.wake === wake)- state.wake = undefined- })- continue- }- const chunk = state.queue.shift()!- state.queuedBytes -= Buffer.byteLength(JSON.stringify(chunk))- if (chunk.type === 'block-end' && chunk.block.type === 'tool-call')- state.tools.get(chunk.block.id)!.step = admitted.step- if (chunk.type === 'finish') {- if (chunk.reason.kind === 'stop') {- await state.task- if (!state.done || state.failure !== undefined)- throw state.failure ?? new Error('BRIDGE_NATIVE_UNSETTLED: 原生回合尚未停止。')- state.finalConsumed = true- }- yieldedBoundary = true- }- yield chunk- if (yieldedBoundary)- return- }- }- finally {- if (!yieldedBoundary) {- state.controller.abort(new Error('BRIDGE_STREAM_CLOSED'))- await session.finish(admitted.agent, state.input.turn)- }- if (runtime.steps.get(admitted.agent.id) === admitted)- runtime.steps.delete(admitted.agent.id)- }- },-- async remove(agent: Agent): Promise<void> {- const current = runtime.exchanges.get(agent.id)- if (current?.state.input.agent === agent)- await session.finish(agent, current.state.input.turn)- const admitted = runtime.steps.get(agent.id)- if (admitted?.agent === agent)- runtime.steps.delete(agent.id)- await session.remove(agent.id, agent)- },-- end(value: Session, event: SessionEvent): void {- sink.commitTool(value, event)- if (event.type === 'step/end' || event.type === 'turn/end') {- runtime.steps.delete(value.id)- const current = runtime.exchanges.get(value.id)- if (event.type === 'turn/end' && current?.state.input.agent.session === value) {- const task = session.finish(current.state.input.agent, current.state.input.turn)- void task.catch((error: unknown) => getServerContext<HostContext>(server).logger.warn('dsh-tauri-kernel: native turn drainage failed', error))- }- }- },-})--function nativeMessage(message: UserMessage): boolean {- return !ENVIRONMENT_SOURCES.has(message.source.kind)-}--function continuationMessage(message: UserMessage, entered: readonly UserMessage[]): boolean {- const source: string = message.source.kind- if (source === 'agent-instructions')- return !entered.some(previous => JSON.stringify(previous.source) === JSON.stringify(message.source) && JSON.stringify(previous.content) === JSON.stringify(message.content))- return nativeMessage(message)-}--function assertLive(agent: Agent, signal: AbortSignal): void {- signal.throwIfAborted()- runtime.lifetime.signal.throwIfAborted()- if (!runtime.ready)- throw new Error('BRIDGE_DISPOSED: 原生桥接已卸载。')- const ctx = getServerContext<HostContext>(server)- if (ctx.agents.get(agent.id) !== agent || ctx.sessions.get(agent.id) !== agent.session || agent.status !== 'running')- throw new Error('BRIDGE_AGENT_REPLACED: 官方会话已关闭或被替换。')-}diff --git a/packages/dsh-tauri-kernel/src/host/service/backend.ts b/packages/dsh-tauri-kernel/src/host/service/backend.tsdeleted file mode 100644index 51804259..00000000--- a/packages/dsh-tauri-kernel/src/host/service/backend.ts+++ /dev/null@@ -1,41 +0,0 @@-import type { BackendDetection } from '../../shared/types'-import type { Config } from '../config/options'-import type { HostContext } from '../types'-import type { DetectedCommand } from '../utils/detection'-import { getServerContext, getServerOptions } from 'dsh-h3/utils'-import { defineService } from 'dsh-tauri'-import { runtime } from '../config/runtime'-import { server } from '../server'-import { detectBackend } from '../utils/detection'-import { loadRuntimeModules } from '../utils/runtime-modules'-import { runtimeVersion } from '../utils/runtime-version'--export const backend = defineService({- async resolve(id: 'codex' | 'claude'): Promise<DetectedCommand> {- const ctx = getServerContext<HostContext>(server)- const config = getServerOptions<Config>(server)- const result = await detectBackend(id, id === 'codex' ? config.codexPath : config.claudePath, { timeoutMs: config.probeTimeoutMs })- try {- const modules = await loadRuntimeModules(ctx.loader)- if (!runtime.ready || typeof modules.appendPluginRecord !== 'function' || typeof modules.pluginRecordOf !== 'function' || typeof ctx.sessions.get !== 'function' || typeof ctx.sessionProjections.stateOf !== 'function')- throw new Error('BRIDGE_CORE_UNAVAILABLE: 当前核心未提供完整的官方内核桥接接口。')- runtime.lifetime.signal.throwIfAborted()- result.detection.bridgeReady = true- }- catch {- result.detection.bridgeReady = false- if (result.detection.installed)- result.detection.hint = 'BRIDGE_CORE_UNAVAILABLE: 当前核心未提供完整的官方内核桥接接口,不能连接本机 CLI。'- delete result.command- }- if (!runtime.lifetime.signal.aborted)- runtime.detections.set(id, result.detection)- return result- },-- async getCatalog(): Promise<BackendDetection[]> {- const ctx = getServerContext<HostContext>(server)- const results = await Promise.all([backend.resolve('codex'), backend.resolve('claude')])- return [{ id: 'dsh', installed: true, auth: 'ok', version: await runtimeVersion(ctx.loader), drift: false, hint: null }, ...results.map(result => result.detection)]- },-})diff --git a/packages/dsh-tauri-kernel/src/host/service/checkpoint.ts b/packages/dsh-tauri-kernel/src/host/service/checkpoint.tsdeleted file mode 100644index 7604f956..00000000--- a/packages/dsh-tauri-kernel/src/host/service/checkpoint.ts+++ /dev/null@@ -1,143 +0,0 @@-import type { Agent } from '@deepseek-ai/dsh-agent'-import type { BridgeRecordType, HostContext, RecordWatermark } from '../types'-import { getServerContext } from 'dsh-h3/utils'-import { defineService } from 'dsh-tauri'-import { KERNEL_RECORD_TYPE, MODEL_RECORD_TYPE } from '../config/constants'-import { runtime } from '../config/runtime'-import { server } from '../server'-import { waitFor } from '../utils/abort'-import { loadRuntimeZod } from '../utils/runtime-modules'--export const checkpoint = defineService({- async register(): Promise<() => void> {- const ctx = getServerContext<HostContext>(server)- const lifetime = runtime.lifetime- const z = await loadRuntimeZod(ctx.loader)- lifetime.signal.throwIfAborted()- if (runtime.lifetime !== lifetime || getServerContext<HostContext>(server) !== ctx)- throw new Error('BRIDGE_DISPOSED: Checkpoint projection owner changed during registration')- const watermarkSchema = z.object({- type: z.enum([KERNEL_RECORD_TYPE, MODEL_RECORD_TYPE]),- seq: z.number().int().nonnegative(),- encodedData: z.string(),- }).strict().readonly().nullable()- return ctx.sessionProjections.register({- key: 'bridgeCheckpoint',- stateSchema: z.object({- ownerSessionId: z.string().min(1),- inheritedEventCount: z.number().int().nonnegative(),- binding: watermarkSchema,- model: watermarkSchema,- }).strict().readonly(),- init: (header, inheritedEventCount) => Object.freeze({ ownerSessionId: header.id, inheritedEventCount, binding: null, model: null }),- apply(state, event) {- const type: string = event.type- if (event.ignorable !== true || (type !== MODEL_RECORD_TYPE && type !== KERNEL_RECORD_TYPE))- return state- if (type === KERNEL_RECORD_TYPE && event.seq < state.inheritedEventCount)- return state- const watermark = Object.freeze({ type, seq: event.seq, encodedData: encode(event.data) })- return Object.freeze({ ...state, [type === MODEL_RECORD_TYPE ? 'model' : 'binding']: watermark })- },- stateVersion: 1,- })- },-- mark(agent: Agent, type: BridgeRecordType, seq: number, data: unknown): void {- const watermark = watermarks(agent).find(record => record.type === type)- if (watermark?.seq !== seq || watermark.encodedData !== encode(data))- throw new Error('BRIDGE_RECORD_NOT_COMMITTED: 官方记录的持久化水位不一致。')- runtime.verified.get(agent)?.delete(type)- },-- isVerified(agent: Agent): boolean {- return watermarks(agent).every(record => sameWatermark(record, runtime.verified.get(agent)?.get(record.type)))- },-- async flush(agent: Agent, signal: AbortSignal, force = false): Promise<void> {- const lifetime = runtime.lifetime- const scoped = AbortSignal.any([signal, lifetime.signal])- while (true) {- assertLive(agent, lifetime, scoped)- const previous = runtime.checkpoints.get(agent)- if (previous) {- await waitFor(previous.catch(() => undefined), scoped)- continue- }- const records = watermarks(agent).filter(record => !sameWatermark(record, runtime.verified.get(agent)?.get(record.type)))- if (records.length === 0 && !force)- return- const task = persist(agent, records, lifetime, scoped)- runtime.checkpoints.set(agent, task)- void task.finally(() => {- if (runtime.checkpoints.get(agent) === task)- runtime.checkpoints.delete(agent)- }).catch(() => undefined)- await waitFor(task, scoped)- force = false- }- },-})--function watermarks(agent: Agent): RecordWatermark[] {- const ctx = getServerContext<HostContext>(server)- const state = ctx.sessionProjections.stateOf(agent.session, 'bridgeCheckpoint')- if (!state || state.ownerSessionId !== agent.id || state.inheritedEventCount !== agent.session.inheritedEventCount)- throw new Error('BRIDGE_CORE_UNAVAILABLE: 官方会话记录的持久化投影不可用。')- return [state.model, agent.session.header.isSeeded ? state.binding : null].filter((value): value is RecordWatermark => value !== null)-}--async function persist(agent: Agent, records: RecordWatermark[], lifetime: AbortController, signal: AbortSignal): Promise<void> {- const ctx = getServerContext<HostContext>(server)- const persistence = ctx.get('sessionPersistence')- const refusal = records.length === 0 || records.some(record => record.type === MODEL_RECORD_TYPE) ? 'BRIDGE_MODEL_NOT_PERSISTED' : 'BRIDGE_BINDING_NOT_PERSISTED'- if (typeof persistence?.open !== 'function' || typeof persistence.flush !== 'function' || !await ctx.sessions.flush(agent.session))- throw new Error(`${refusal}: 官方会话记录无法持久保存。`)- assertLive(agent, lifetime, signal)- await persistence.flush()- assertLive(agent, lifetime, signal)- const reader = await persistence.open(agent.id, 'read', { signal })- try {- assertLive(agent, lifetime, signal)- const header = agent.session.header- if (reader.id !== agent.id || reader.header.id !== header.id || reader.header.cwd !== header.cwd || reader.header.agentPreset !== header.agentPreset || reader.header.parentSession !== header.parentSession || reader.header.isSeeded !== header.isSeeded || reader.inheritedEventCount !== agent.session.inheritedEventCount)- throw new Error(`${refusal}: 官方持久会话与当前会话身份不一致。`)- for (const record of records) {- const { events } = await reader.read(record.seq, 1, { signal })- assertLive(agent, lifetime, signal)- const event = events[0]- if (events.length !== 1 || event?.seq !== record.seq || (event.type as string) !== record.type || event.ignorable !== true || encode(event.data) !== record.encodedData)- throw new Error(`${refusal}: 官方持久记录未包含当前选择或原生绑定。`)- }- }- finally {- await reader.close()- }- assertLive(agent, lifetime, signal)- let verified = runtime.verified.get(agent)- if (!verified) {- verified = new Map()- runtime.verified.set(agent, verified)- }- for (const record of records) {- if (watermarks(agent).some(current => sameWatermark(current, record)))- verified.set(record.type, record)- }-}--function sameWatermark(left: RecordWatermark, right: RecordWatermark | undefined): boolean {- return right !== undefined && left.type === right.type && left.seq === right.seq && left.encodedData === right.encodedData-}--function encode(data: unknown): string {- if (data === null || typeof data !== 'object' || Array.isArray(data))- throw new Error('BRIDGE_RECORD_NOT_COMMITTED: 官方桥接记录必须是完整对象。')- return JSON.stringify(data, Object.keys(data).sort())-}--function assertLive(agent: Agent, lifetime: AbortController, signal: AbortSignal): void {- signal.throwIfAborted()- const ctx = getServerContext<HostContext>(server)- if (!runtime.ready || runtime.lifetime !== lifetime || ctx.agents.get(agent.id) !== agent || ctx.sessions.get(agent.id) !== agent.session)- throw new Error('BRIDGE_AGENT_REPLACED: 官方会话已关闭或被替换。')-}diff --git a/packages/dsh-tauri-kernel/src/host/service/identity-write.test.ts b/packages/dsh-tauri-kernel/src/host/service/identity-write.test.tsdeleted file mode 100644index a5cc6be9..00000000--- a/packages/dsh-tauri-kernel/src/host/service/identity-write.test.ts+++ /dev/null@@ -1,341 +0,0 @@-import type { Agent } from '@deepseek-ai/dsh-agent'-import type { Session as OfficialSession, SessionStore as OfficialSessionStore, SessionEvent } from '@deepseek-ai/dsh-session'-import type { KernelBinding } from '../../shared/types'-import type { HostContext, PlatformLoader } from '../types'-import { Context } from '@deepseek-ai/cordis'-import * as llmModule from '@deepseek-ai/dsh-llm'-import * as sessionModule from '@deepseek-ai/dsh-session'-import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'-import { getServerContext } from 'dsh-h3/utils'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import * as zodModule from 'zod'-import { resetRuntime, runtime } from '../config/runtime'-import { loadRuntimeModules } from '../utils/runtime-modules'-import { identity } from './identity'--vi.mock('dsh-h3/utils', () => ({ getServerContext: vi.fn() }))-vi.mock('../server', () => ({ server: vi.fn() }))--const { Session, SessionId, SessionLogOffset, SessionStore } = sessionModule-const binding: KernelBinding = { backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }-let context: Context-let sessions: OfficialSessionStore-let projections: SessionProjectionRegistry-let loader: PlatformLoader-let published: { sessionId: string, event: SessionEvent }[]--function agentOf(session: OfficialSession): Agent {- return { id: session.id, session } as Agent-}--function eventsOf(session: OfficialSession): SessionEvent[] {- return published.filter(value => value.sessionId === session.id).map(value => value.event)-}--function gateSessionImport(): { promise: Promise<typeof sessionModule>, resolve: (value: typeof sessionModule) => void } {- const gate = Promise.withResolvers<typeof sessionModule>()- vi.mocked(loader.import).mockImplementation(async (id) => {- if (id === '@deepseek-ai/dsh-llm')- return llmModule- if (id === '@deepseek-ai/dsh-session')- return gate.promise- throw new Error(`Unexpected public runtime import: ${id}`)- })- return gate-}--beforeEach(async () => {- await resetRuntime()- runtime.lifetime = new AbortController()- context = new Context()- sessions = new SessionStore(context)- projections = new SessionProjectionRegistry(context)- published = []- context.on('session/event', (session, event) => published.push({ sessionId: session.id, event }))- loader = {- import: vi.fn(async (id) => {- if (id === 'zod')- return zodModule- if (id === '@deepseek-ai/dsh-llm')- return llmModule- if (id === '@deepseek-ai/dsh-session')- return sessionModule- throw new Error(`Unexpected public runtime import: ${id}`)- }),- unwrapExports: value => value,- }- context.provide('loader', loader as HostContext['loader'])- vi.mocked(getServerContext).mockReturnValue(context)-})--afterEach(async () => {- await context.fiber.dispose()- await resetRuntime()- vi.restoreAllMocks()-})--describe('official Alpha2 kernel identity writer', () => {- it('loads the real public writer and reader exports through the host loader', async () => {- const modules = await loadRuntimeModules(loader)- expect(modules.appendPluginRecord).toBe(sessionModule.appendPluginRecord)- expect(modules.pluginRecordOf).toBe(sessionModule.pluginRecordOf)- expect(vi.mocked(loader.import).mock.calls).toEqual([['@deepseek-ai/dsh-llm'], ['@deepseek-ai/dsh-session']])- })-- it.each(['codex', 'claude'] as const)('commits one complete ignorable %s record using the real attached Session store', async (backend) => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessions.create(SessionId('session-a'))- const candidate: KernelBinding = { backend, nativeSessionId: `native-${backend}`, sessionId: 'session-a' }- const changed = vi.fn()- projections.onChanged(changed)- expect(await identity.append(agentOf(session), candidate)).toBe(0)- expect(session.seq).toBe(1)- const [event] = eventsOf(session)- expect(eventsOf(session)).toHaveLength(1)- expect(event).toEqual({ type: 'plugin:dsh-tauri-kernel/kernel', seq: 0, time: expect.any(Number), data: { backend, nativeSessionId: `native-${backend}`, sessionId: 'session-a' }, ignorable: true })- expect(sessionModule.pluginRecordOf(event)).toEqual({ type: 'plugin:dsh-tauri-kernel/kernel', seq: 0, time: event.time, data: candidate })- expect(Object.isFrozen(event)).toBe(true)- expect(Object.isFrozen(event.data)).toBe(true)- expect(identity.resolve(agentOf(session))).toEqual(candidate)- expect(projections.snapshot(session)).toEqual({ asOfSeq: 0, values: { bridgeKernel: candidate } })- expect(changed).toHaveBeenCalledExactlyOnceWith(session, 'bridgeKernel', candidate, 0)- expect(session.deriveMessages()).toEqual([])- })-- it('snapshots caller-owned binding input without freezing or retaining the mutable input object', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessions.create(SessionId('session-a'))- const candidate = { ...binding }- await identity.append(agentOf(session), candidate)- candidate.nativeSessionId = 'caller-edited'- expect(candidate.nativeSessionId).toBe('caller-edited')- expect(eventsOf(session)[0].data).toEqual(binding)- expect(eventsOf(session)[0].data).not.toBe(candidate)- expect(identity.resolve(agentOf(session))).toEqual(binding)- expect(Object.isFrozen(projections.stateOf(session, 'bridgeKernel'))).toBe(true)- })-- it('returns the current accepted watermark for duplicate identity without logging another record', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessions.create(SessionId('session-a'))- expect(await identity.append(agentOf(session), binding)).toBe(0)- const state = projections.stateOf(session, 'bridgeKernel')- session.append('turn/start', { turn: 0 })- session.append('turn/end', { turn: 0, reason: { kind: 'completed' } })- const changed = vi.fn()- projections.onChanged(changed)- expect(await identity.append(agentOf(session), { ...binding })).toBe(2)- expect(session.seq).toBe(3)- expect(eventsOf(session).map(event => event.type)).toEqual(['plugin:dsh-tauri-kernel/kernel', 'turn/start', 'turn/end'])- expect(projections.stateOf(session, 'bridgeKernel')).toBe(state)- expect(changed).not.toHaveBeenCalled()- })-- it.each([- { ...binding, backend: 'claude' as const },- { ...binding, nativeSessionId: 'native-b' },- ])('refuses replacing an already committed native identity before importing any writer: %j', async (different) => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessions.create(SessionId('session-a'))- await identity.append(agentOf(session), binding)- vi.mocked(loader.import).mockClear()- await expect(identity.append(agentOf(session), different)).rejects.toThrow('BRIDGE_BINDING_IMMUTABLE: The official native kernel binding cannot be replaced')- expect(loader.import).not.toHaveBeenCalled()- expect(session.seq).toBe(1)- expect(eventsOf(session)).toHaveLength(1)- expect(identity.resolve(agentOf(session))).toEqual(binding)- })-- it('rejects a foreign owner before a first native binding can enter the official log', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessions.create(SessionId('session-a'))- await expect(identity.append(agentOf(session), { ...binding, sessionId: 'session-other' })).rejects.toThrow('BRIDGE_INHERITED_SESSION: A native binding must belong to the exact official session')- expect(loader.import).not.toHaveBeenCalled()- expect(session.seq).toBe(0)- expect(eventsOf(session)).toEqual([])- expect(projections.stateOf(session, 'bridgeKernel')?.binding).toBeNull()- })-- it('binds a real fork to its own distinct native identity without changing its parent', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const parent = sessions.create(SessionId('session-a'))- await identity.append(agentOf(parent), binding)- const child = sessions.fork(parent, undefined, SessionId('session-child'))- const before = child.seq- const candidate: KernelBinding = { backend: 'codex', nativeSessionId: 'native-child', sessionId: 'session-child' }- expect(projections.snapshot(child).values.bridgeKernel).toBeNull()- expect(() => identity.resolve(agentOf(child))).toThrow('BRIDGE_BINDING_MISSING')- expect(identity.inherited(child)).toEqual(binding)- vi.mocked(loader.import).mockClear()- expect(await identity.append(agentOf(child), candidate)).toBe(before)- expect(child.seq).toBe(before + 1)- expect(eventsOf(child).at(-1)).toMatchObject({ type: 'plugin:dsh-tauri-kernel/kernel', seq: before, data: candidate, ignorable: true })- expect(identity.resolve(agentOf(child))).toEqual(candidate)- expect(projections.snapshot(child).values.bridgeKernel).toEqual(candidate)- expect(identity.resolve(agentOf(parent))).toEqual(binding)- expect(parent.seq).toBe(1)- expect(eventsOf(parent)).toHaveLength(1)- })-- it('rejects taking over the parent native id before importing any child writer', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const parent = sessions.create(SessionId('session-a'))- await identity.append(agentOf(parent), binding)- const child = sessions.fork(parent, undefined, SessionId('session-child'))- const before = child.seq- vi.mocked(loader.import).mockClear()- await expect(identity.append(agentOf(child), { ...binding, sessionId: 'session-child' })).rejects.toThrow('BRIDGE_INHERITED_SESSION: A fork must receive a distinct native session identity')- expect(child.seq).toBe(before)- expect(loader.import).not.toHaveBeenCalled()- expect(projections.snapshot(child).values.bridgeKernel).toBeNull()- expect(identity.inherited(child)).toEqual(binding)- expect(identity.resolve(agentOf(parent))).toEqual(binding)- expect(eventsOf(parent)).toHaveLength(1)- })-- it('freezes the first real child binding against a second native fork assignment', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const parent = sessions.create(SessionId('session-a'))- await identity.append(agentOf(parent), binding)- const child = sessions.fork(parent, undefined, SessionId('session-child'))- const childBinding: KernelBinding = { backend: 'codex', nativeSessionId: 'native-child', sessionId: 'session-child' }- await identity.append(agentOf(child), childBinding)- const before = child.seq- vi.mocked(loader.import).mockClear()- await expect(identity.append(agentOf(child), { ...childBinding, nativeSessionId: 'native-second' })).rejects.toThrow('BRIDGE_BINDING_IMMUTABLE')- expect(loader.import).not.toHaveBeenCalled()- expect(child.seq).toBe(before)- expect(identity.resolve(agentOf(child))).toEqual(childBinding)- expect(identity.resolve(agentOf(parent))).toEqual(binding)- })-- it('cold-restores a repaired child and real descendant without reusing ancestor native ids', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const parent = sessions.create(SessionId('session-a'))- await identity.append(agentOf(parent), binding)- const child = sessions.fork(parent, undefined, SessionId('session-child'))- const childBinding: KernelBinding = { backend: 'codex', nativeSessionId: 'native-child', sessionId: 'session-child' }- await identity.append(agentOf(child), childBinding)- const descendant = sessions.fork(child, undefined, SessionId('session-grandchild'))- const descendantBinding: KernelBinding = { backend: 'codex', nativeSessionId: 'native-grandchild', sessionId: 'session-grandchild' }- expect(identity.inherited(descendant)).toEqual(childBinding)- expect(projections.snapshot(descendant).values.bridgeKernel).toBeNull()- await identity.append(agentOf(descendant), descendantBinding)- const events: SessionEvent[] = JSON.parse(JSON.stringify(descendant.snapshotEvents()))- const checkpoint = JSON.parse(JSON.stringify(projections.checkpoint(descendant)))- const cold = Session.create(SessionId('session-grandchild'), events, JSON.parse(JSON.stringify(descendant.header)), descendant.inheritedEventCount)- vi.mocked(loader.import).mockClear()- expect(projections.hydrate(cold, checkpoint, events, SessionLogOffset(0)).values.bridgeKernel).toEqual(descendantBinding)- expect(identity.resolve(agentOf(cold))).toEqual(descendantBinding)- expect(identity.inherited(cold)).toEqual(childBinding)- expect(projections.stateOf(cold, 'bridgeKernel')).toEqual({ ownerSessionId: 'session-grandchild', inheritedEventCount: descendant.inheritedEventCount, inheritedBinding: childBinding, binding: descendantBinding })- expect(loader.import).not.toHaveBeenCalled()- expect(identity.resolve(agentOf(child))).toEqual(childBinding)- expect(identity.resolve(agentOf(parent))).toEqual(binding)- })-- it('allows only the first conflicting binding after concurrently awaited runtime imports', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessions.create(SessionId('session-a'))- const gate = gateSessionImport()- const results = Promise.allSettled([- identity.append(agentOf(session), binding),- identity.append(agentOf(session), { ...binding, nativeSessionId: 'native-second' }),- ])- expect(session.seq).toBe(0)- expect(projections.stateOf(session, 'bridgeKernel')?.binding).toBeNull()- gate.resolve(sessionModule)- const [first, second] = await results- expect(first).toEqual({ status: 'fulfilled', value: 0 })- expect(second.status).toBe('rejected')- if (second.status !== 'rejected')- throw new Error('A conflicting concurrent identity write unexpectedly committed')- expect(second.reason).toBeInstanceOf(Error)- expect(second.reason.message).toBe('BRIDGE_BINDING_IMMUTABLE: The official native kernel binding cannot be replaced')- expect(session.seq).toBe(1)- expect(eventsOf(session)).toHaveLength(1)- expect(identity.resolve(agentOf(session))).toEqual(binding)- })-- it('deduplicates concurrently awaited identical bindings into one real log commit', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessions.create(SessionId('session-a'))- const gate = gateSessionImport()- const results = Promise.all([- identity.append(agentOf(session), binding),- identity.append(agentOf(session), { ...binding }),- ])- gate.resolve(sessionModule)- expect(await results).toEqual([0, 0])- expect(session.seq).toBe(1)- expect(eventsOf(session)).toHaveLength(1)- expect(projections.snapshot(session)).toEqual({ asOfSeq: 0, values: { bridgeKernel: binding } })- })-- it('rechecks projection capability after awaited imports and refuses writes after unregister', async () => {- const unregister = await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessions.create(SessionId('session-a'))- const gate = gateSessionImport()- const pending = identity.append(agentOf(session), binding)- const rejection = expect(pending).rejects.toThrow('BRIDGE_CORE_UNAVAILABLE: The official kernel projection was unregistered')- unregister()- gate.resolve(sessionModule)- await rejection- expect(session.seq).toBe(0)- expect(eventsOf(session)).toEqual([])- expect(projections.snapshot(session).values).toEqual({})- })-- it('recovers exact identity from real written log bytes without consulting any backend catalog', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const original = sessions.create(SessionId('session-a'))- await identity.append(agentOf(original), binding)- const events: SessionEvent[] = JSON.parse(JSON.stringify(eventsOf(original)))- const cold = Session.create(SessionId('session-a'), events, JSON.parse(JSON.stringify(original.header)), SessionLogOffset(0))- vi.mocked(loader.import).mockClear()- expect(identity.resolve(agentOf(cold))).toEqual(binding)- expect(loader.import).not.toHaveBeenCalled()- expect(Object.isFrozen(projections.stateOf(cold, 'bridgeKernel'))).toBe(true)- expect(cold.deriveMessages()).toEqual([])- expect(await identity.append(agentOf(cold), { ...binding })).toBe(cold.seq - 1)- expect(cold.seq).toBe(events.length + 1)- expect(eventsOf(original)).toHaveLength(1)- })-- it('hydrates a usable detached checkpoint over real published events and freezes the canonical restored binding', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const original = sessions.create(SessionId('session-a'))- await identity.append(agentOf(original), binding)- original.append('turn/start', { turn: 0 })- original.append('turn/end', { turn: 0, reason: { kind: 'completed' } })- const checkpoint = JSON.parse(JSON.stringify(projections.checkpoint(original)))- const events: SessionEvent[] = JSON.parse(JSON.stringify(eventsOf(original)))- expect(checkpoint.bridgeKernel).toEqual({ ver: 2, seq: 2, val: { ownerSessionId: 'session-a', inheritedEventCount: 0, inheritedBinding: null, binding } })- expect(Object.isFrozen(checkpoint.bridgeKernel.val)).toBe(false)- const cold = Session.create(SessionId('session-a'), events, JSON.parse(JSON.stringify(original.header)), SessionLogOffset(0))- vi.mocked(loader.import).mockClear()- expect(projections.hydrate(cold, checkpoint, events, SessionLogOffset(0))).toEqual({ asOfSeq: 2, values: { bridgeKernel: binding } })- const state = projections.stateOf(cold, 'bridgeKernel')- expect(Object.isFrozen(state)).toBe(true)- expect(Object.isFrozen(state!.binding)).toBe(true)- expect(Reflect.set(state!.binding!, 'nativeSessionId', 'checkpoint-mutation')).toBe(false)- expect(Object.isFrozen(projections.snapshot(cold).values.bridgeKernel)).toBe(true)- expect(identity.resolve(agentOf(cold))).toEqual(binding)- expect(loader.import).not.toHaveBeenCalled()- expect(projections.viewCheckpoint(checkpoint)).toEqual({ bridgeKernel: binding })- })-})diff --git a/packages/dsh-tauri-kernel/src/host/service/identity.test.ts b/packages/dsh-tauri-kernel/src/host/service/identity.test.tsdeleted file mode 100644index df6b792c..00000000--- a/packages/dsh-tauri-kernel/src/host/service/identity.test.ts+++ /dev/null@@ -1,391 +0,0 @@-import type { Agent } from '@deepseek-ai/dsh-agent'-import type { SessionEvent } from '@deepseek-ai/dsh-session'-import type { KernelBinding } from '../../shared/types'-import type { HostContext, PlatformLoader } from '../types'-import { Context } from '@deepseek-ai/cordis'-import * as llmModule from '@deepseek-ai/dsh-llm'-import { Session, SessionId, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'-import * as sessionModule from '@deepseek-ai/dsh-session'-import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'-import { getServerContext } from 'dsh-h3/utils'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import * as zodModule from 'zod'-import { resetRuntime, runtime } from '../config/runtime'-import { identity } from './identity'--vi.mock('dsh-h3/utils', () => ({ getServerContext: vi.fn() }))-vi.mock('../server', () => ({ server: vi.fn() }))--const binding: KernelBinding = { backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' }-let context: Context-let projections: SessionProjectionRegistry-let loader: PlatformLoader--function kernelEvent(value: unknown, seq = 0, options: { type?: string, ignorable?: true } = { ignorable: true }): SessionEvent {- return {- type: options.type ?? 'plugin:dsh-tauri-kernel/kernel',- seq: SessionSeq(seq),- time: 1000 + seq,- data: value,- ...(options.ignorable === true ? { ignorable: true } : {}),- } as unknown as SessionEvent-}--function sessionFrom(events: readonly SessionEvent[] = [], id = 'session-a'): Session {- return Session.create(SessionId(id), events)-}--function agentOf(session: Session): Agent {- return { id: session.id, session } as Agent-}--beforeEach(async () => {- await resetRuntime()- runtime.lifetime = new AbortController()- context = new Context()- projections = new SessionProjectionRegistry(context)- loader = {- import: vi.fn(async id => id === 'zod' ? zodModule : id === '@deepseek-ai/dsh-llm' ? llmModule : sessionModule),- unwrapExports: value => value,- }- context.provide('loader', loader as HostContext['loader'])- vi.mocked(getServerContext).mockReturnValue(context)-})--afterEach(async () => {- await context.fiber.dispose()- await resetRuntime()- vi.restoreAllMocks()-})--describe('official kernel identity projection', () => {- it('refuses a late schema registration after the captured bridge lifetime is aborted', async () => {- const schemaImport = Promise.withResolvers<typeof zodModule>()- vi.mocked(loader.import).mockImplementation(() => schemaImport.promise)- const registering = identity.register()- const rejection = expect(registering).rejects.toThrow('BRIDGE_DISPOSED')- await resetRuntime()- schemaImport.resolve(zodModule)- await rejection- expect(projections.snapshot(sessionFrom()).values).toEqual({})- expect(runtime.bindingSchema).toBeUndefined()- })-- it('refuses a late schema registration after a new bridge lifetime supersedes it', async () => {- const schemaImport = Promise.withResolvers<typeof zodModule>()- vi.mocked(loader.import).mockImplementation(() => schemaImport.promise)- const registering = identity.register()- const rejection = expect(registering).rejects.toThrow('BRIDGE_DISPOSED: Kernel projection owner changed during registration')- runtime.lifetime = new AbortController()- schemaImport.resolve(zodModule)- await rejection- expect(projections.snapshot(sessionFrom()).values).toEqual({})- expect(runtime.bindingSchema).toBeUndefined()- })-- it('registers a nullable complete wire value rather than inferring native identity from model routes', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = Session.create(SessionId('session-a'))- expect(projections.stateOf(session, 'bridgeKernel')?.binding).toBeNull()- expect(projections.snapshot(session)).toEqual({ asOfSeq: -1, values: { bridgeKernel: null } })- const agent = { ...agentOf(session), options: { provider: 'dsh-tauri-kernel', model: 'codex' } } as Agent- expect(() => identity.resolve(agent)).toThrow('BRIDGE_BINDING_MISSING')- })-- it('reads the exact native and owner identity from a legal ignorable official log record', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessionFrom([kernelEvent(binding)])- expect(identity.resolve(agentOf(session))).toEqual({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- expect(projections.snapshot(session).values).toEqual({ bridgeKernel: { backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' } })- expect(session.deriveMessages()).toEqual([])- expect(Object.isFrozen(projections.stateOf(session, 'bridgeKernel'))).toBe(true)- })-- it('restores the whole identity after cold JSON roundtrip using the real official projection restore API', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const events: SessionEvent[] = JSON.parse(JSON.stringify([kernelEvent({ backend: 'claude', nativeSessionId: 'native-cold', sessionId: 'session-a' })]))- const session = sessionFrom(events)- const restored = projections.restore({}, events, SessionLogOffset(0), session.header, session.inheritedEventCount)- expect(restored.snapshot).toEqual({ asOfSeq: 0, values: { bridgeKernel: { backend: 'claude', nativeSessionId: 'native-cold', sessionId: 'session-a' } } })- expect(restored.checkpoint.bridgeKernel).toEqual({ ver: 2, seq: 0, val: { ownerSessionId: 'session-a', inheritedEventCount: 0, inheritedBinding: null, binding: { backend: 'claude', nativeSessionId: 'native-cold', sessionId: 'session-a' } } })- expect(projections.viewCheckpoint(restored.checkpoint)).toEqual({ bridgeKernel: { backend: 'claude', nativeSessionId: 'native-cold', sessionId: 'session-a' } })- })-- it('freezes the official binding when a cold checkpoint is parsed and hydrated into the registry', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const events: SessionEvent[] = [- kernelEvent(binding),- { type: 'session/end-seed', seq: SessionSeq(1), time: 1001, data: {} },- ]- const original = sessionFrom(events)- const checkpoint = JSON.parse(JSON.stringify(projections.checkpoint(original)))- const restored = sessionFrom(events)- expect(Object.isFrozen(checkpoint.bridgeKernel.val)).toBe(false)- projections.hydrate(restored, checkpoint, events, SessionLogOffset(0))- const state = projections.stateOf(restored, 'bridgeKernel')- expect(state).toEqual({ ownerSessionId: 'session-a', inheritedEventCount: 0, inheritedBinding: null, binding })- expect(Object.isFrozen(state)).toBe(true)- expect(Object.isFrozen(state!.binding)).toBe(true)- expect(Reflect.set(state!.binding!, 'nativeSessionId', 'replaced-native')).toBe(false)- expect(Reflect.set(state!, 'ownerSessionId', 'replaced-owner')).toBe(false)- expect(identity.resolve(agentOf(restored))).toEqual({ backend: 'codex', nativeSessionId: 'native-a', sessionId: 'session-a' })- expect(Object.isFrozen(projections.snapshot(restored).values.bridgeKernel)).toBe(true)- })-- it('ignores foreign record types and records without the legal ignorable marker', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const events = [- kernelEvent({ backend: 'codex' }, 0, { type: 'plugin:other/kernel', ignorable: true }),- kernelEvent(binding, 1, { type: 'turn/start' }),- ]- const session = sessionFrom(events)- expect(projections.stateOf(session, 'bridgeKernel')?.binding).toBeNull()- const unmarked = [kernelEvent(binding, 0, {})]- const restored = projections.restore({}, unmarked, SessionLogOffset(0), Session.create(SessionId('unmarked')).header, SessionLogOffset(0))- expect(restored.snapshot.values.bridgeKernel).toBeNull()- })-- it.each([- {},- null,- { backend: 'codex', nativeSessionId: 'native-a' },- { ...binding, backend: 'dsh' },- { ...binding, backend: 'unknown' },- { ...binding, nativeSessionId: '' },- { ...binding, nativeSessionId: ' ' },- { ...binding, sessionId: '' },- { ...binding, sessionId: '\t' },- { ...binding, delta: true },- ])('rejects malformed or incomplete plugin identity without accepting a partial payload: %j', async (value) => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessionFrom([kernelEvent(value)])- expect(() => projections.stateOf(session, 'bridgeKernel')).toThrow('BRIDGE_BINDING_INVALID')- })-- it('reuses the same state reference for duplicate complete records and unrelated official events', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const first = kernelEvent(binding)- const second = kernelEvent({ ...binding }, 1)- const third: SessionEvent = { type: 'turn/start', seq: SessionSeq(2), time: 1002, data: { turn: 0 } }- const initial = projections.restore({}, [first], SessionLogOffset(0), Session.create(SessionId('session-a')).header, SessionLogOffset(0))- const session = sessionFrom([first, second, third])- projections.hydrate(session, initial.checkpoint, [first], SessionLogOffset(0))- const changed = vi.fn()- projections.onChanged(changed)- context.emit('session/event', session, second)- context.emit('session/event', session, third)- expect(changed).not.toHaveBeenCalled()- expect(projections.stateOf(session, 'bridgeKernel')).toEqual({ ownerSessionId: 'session-a', inheritedEventCount: 0, inheritedBinding: null, binding })- expect(projections.checkpoint(session).bridgeKernel!.val).toEqual({ ownerSessionId: 'session-a', inheritedEventCount: 0, inheritedBinding: null, binding })- })-- it.each([- { ...binding, backend: 'claude' as const },- { ...binding, nativeSessionId: 'native-b' },- ])('refuses conflicting complete binding history on cold replay: %j', async (different) => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessionFrom([kernelEvent(binding), kernelEvent(different, 1)])- expect(() => projections.stateOf(session, 'bridgeKernel')).toThrow('BRIDGE_BINDING_IMMUTABLE')- })-- it('retains an inherited parent identity only as a non-executable fork source', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const parent = sessionFrom([kernelEvent(binding)])- const child = Session.create(SessionId('session-child'), [kernelEvent(binding)], {- ...parent.header,- id: SessionId('session-child'),- parentSession: parent.id,- isSeeded: true,- }, SessionLogOffset(1))- const before = child.seq- const append = vi.spyOn(child, 'append')- expect(projections.stateOf(child, 'bridgeKernel')).toEqual({ ownerSessionId: 'session-child', inheritedEventCount: 1, inheritedBinding: binding, binding: null })- expect(projections.snapshot(child).values.bridgeKernel).toBeNull()- expect(identity.inherited(child)).toEqual(binding)- expect(() => identity.resolve(agentOf(child))).toThrow('BRIDGE_BINDING_MISSING')- expect(child.seq).toBe(before)- expect(append).not.toHaveBeenCalled()- expect(loader.import).not.toHaveBeenCalled()- expect(identity.resolve(agentOf(parent))).toEqual(binding)- })-- it('rejects a foreign owner record outside the exact inherited prefix on cold replay', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const foreign = { ...binding, sessionId: 'session-other' }- const original = sessionFrom([kernelEvent(foreign)])- expect(() => projections.stateOf(original, 'bridgeKernel')).toThrow('BRIDGE_INHERITED_SESSION')- const events: SessionEvent[] = [kernelEvent(binding), { type: 'session/end-seed', seq: SessionSeq(1), time: 1001, data: { inherited: true } }, kernelEvent(foreign, 2)]- const child = Session.create(SessionId('session-child'), events, {- ...original.header,- id: SessionId('session-child'),- parentSession: SessionId('session-a'),- isSeeded: true,- }, SessionLogOffset(1))- expect(() => projections.restore({}, events, SessionLogOffset(0), child.header, child.inheritedEventCount)).toThrow('BRIDGE_INHERITED_SESSION')- })-- it('accepts the first child-owned record at the exact fork cut and keeps it immutable', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const parent = sessionFrom([kernelEvent(binding)])- const childBinding: KernelBinding = { backend: 'codex', nativeSessionId: 'native-child', sessionId: 'session-child' }- const child = Session.create(SessionId('session-child'), [kernelEvent(binding)], {- ...parent.header,- id: SessionId('session-child'),- parentSession: parent.id,- isSeeded: true,- }, SessionLogOffset(1))- const events = [kernelEvent(binding), kernelEvent(childBinding, 1)]- const restored = projections.restore({}, events, SessionLogOffset(0), child.header, child.inheritedEventCount)- expect(restored.snapshot.values.bridgeKernel).toEqual(childBinding)- expect(restored.checkpoint.bridgeKernel.val).toEqual({ ownerSessionId: 'session-child', inheritedEventCount: 1, inheritedBinding: binding, binding: childBinding })- const conflicting = [...events, kernelEvent({ ...childBinding, nativeSessionId: 'native-replacement' }, 2)]- expect(() => projections.restore({}, conflicting, SessionLogOffset(0), child.header, child.inheritedEventCount)).toThrow('BRIDGE_BINDING_IMMUTABLE')- const foreign = [...events, kernelEvent(binding, 2)]- expect(() => projections.restore({}, foreign, SessionLogOffset(0), child.header, child.inheritedEventCount)).toThrow('BRIDGE_INHERITED_SESSION')- expect(identity.resolve(agentOf(parent))).toEqual(binding)- })-- it('rejects a child-owned record that tries to reuse its inherited native session', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const parent = sessionFrom([kernelEvent(binding)])- const events = [kernelEvent(binding), kernelEvent({ ...binding, sessionId: 'session-child' }, 1)]- expect(() => projections.restore({}, events, SessionLogOffset(0), {- ...parent.header,- id: SessionId('session-child'),- parentSession: parent.id,- isSeeded: true,- }, SessionLogOffset(1))).toThrow('BRIDGE_INHERITED_SESSION: A fork must receive a distinct native session identity')- })-- it('does not mistake a grandparent prefix binding for an unbound immediate fork parent', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const parent = sessionFrom([kernelEvent(binding)])- const child = Session.create(SessionId('session-grandchild'), [kernelEvent(binding)], {- ...parent.header,- id: SessionId('session-grandchild'),- parentSession: SessionId('session-child'),- isSeeded: true,- }, SessionLogOffset(1))- expect(projections.snapshot(child).values.bridgeKernel).toBeNull()- expect(() => identity.inherited(child)).toThrow('BRIDGE_INHERITED_SESSION: The inherited native binding must belong to the exact official fork parent')- expect(() => identity.resolve(agentOf(child))).toThrow('BRIDGE_BINDING_MISSING')- })-- it('cold-restores a descendant using only its own identity while retaining the exact immediate fork parent', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const childBinding: KernelBinding = { backend: 'codex', nativeSessionId: 'native-child', sessionId: 'session-child' }- const descendantBinding: KernelBinding = { backend: 'codex', nativeSessionId: 'native-grandchild', sessionId: 'session-grandchild' }- const events: SessionEvent[] = JSON.parse(JSON.stringify([kernelEvent(binding), kernelEvent(childBinding, 1), { type: 'session/end-seed', seq: 2, time: 1002, data: { inherited: true } }, kernelEvent(descendantBinding, 3)]))- const descendant = Session.create(SessionId('session-grandchild'), events, {- ...Session.create(SessionId('session-grandchild')).header,- parentSession: SessionId('session-child'),- isSeeded: true,- }, SessionLogOffset(2))- const restored = projections.restore({}, events, SessionLogOffset(0), descendant.header, descendant.inheritedEventCount)- const expectedState = { ownerSessionId: 'session-grandchild', inheritedEventCount: 2, inheritedBinding: childBinding, binding: descendantBinding }- expect(restored.snapshot.values.bridgeKernel).toEqual(descendantBinding)- expect(restored.checkpoint.bridgeKernel).toEqual({ ver: 2, seq: 3, val: expectedState })- const checkpoint = JSON.parse(JSON.stringify(restored.checkpoint))- expect(projections.viewCheckpoint(checkpoint)).toEqual({ bridgeKernel: descendantBinding })- projections.hydrate(descendant, checkpoint, events, SessionLogOffset(0))- expect(projections.stateOf(descendant, 'bridgeKernel')).toEqual(expectedState)- expect(identity.inherited(descendant)).toEqual(childBinding)- expect(identity.resolve(agentOf(descendant))).toEqual(descendantBinding)- expect(Object.isFrozen(projections.stateOf(descendant, 'bridgeKernel')!.binding)).toBe(true)- expect(Object.isFrozen(projections.stateOf(descendant, 'bridgeKernel')!.inheritedBinding)).toBe(true)- })-- it('discards old version-one checkpoints instead of exposing an inherited binding as the child identity', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const events = [kernelEvent(binding)]- const child = Session.create(SessionId('session-child'), events, {- ...Session.create(SessionId('session-child')).header,- parentSession: SessionId('session-a'),- isSeeded: true,- }, SessionLogOffset(1))- const checkpoint = { bridgeKernel: { ver: 1, seq: SessionSeq(0), val: binding } }- expect(projections.viewCheckpoint(checkpoint)).toEqual({})- expect(projections.restoreFloor(checkpoint)).toBe(0)- const restored = projections.restore(checkpoint, events, SessionLogOffset(0), child.header, child.inheritedEventCount)- expect(restored.snapshot).toEqual({ asOfSeq: 0, values: { bridgeKernel: null } })- expect(restored.checkpoint.bridgeKernel).toEqual({ ver: 2, seq: 0, val: { ownerSessionId: 'session-child', inheritedEventCount: 1, inheritedBinding: binding, binding: null } })- })-- it('removes the projection capability when its registering contribution unloads', async () => {- const unregister = await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessionFrom([kernelEvent(binding)])- expect(identity.resolve(agentOf(session))).toEqual(binding)- unregister()- expect(projections.stateOf(session, 'bridgeKernel')).toBeUndefined()- expect(projections.snapshot(session).values).toEqual({})- expect(() => identity.resolve(agentOf(session))).toThrow('BRIDGE_CORE_UNAVAILABLE')- })-- it.each(['appendPluginRecord', 'pluginRecordOf'] as const)('fails before any append when the host lacks %s', async (missing) => {- await identity.register()- vi.mocked(loader.import).mockImplementation(async id => id === 'zod' ? zodModule : id === '@deepseek-ai/dsh-llm' ? llmModule : { ...sessionModule, [missing]: undefined })- const session = Session.create(SessionId('session-a'))- const append = vi.spyOn(session, 'append')- const before = session.seq- await expect(identity.append(agentOf(session), binding)).rejects.toThrow('BRIDGE_CORE_UNAVAILABLE')- expect(session.seq).toBe(before)- expect(append).not.toHaveBeenCalled()- expect(projections.stateOf(session, 'bridgeKernel')?.binding).toBeNull()- })-- it('rejects a different binding before importing runtime capabilities or modifying the log', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = sessionFrom([kernelEvent(binding)])- const before = session.seq- const append = vi.spyOn(session, 'append')- await expect(identity.append(agentOf(session), { ...binding, nativeSessionId: 'native-b' })).rejects.toThrow('BRIDGE_BINDING_IMMUTABLE')- expect(loader.import).not.toHaveBeenCalled()- expect(append).not.toHaveBeenCalled()- expect(session.seq).toBe(before)- expect(identity.resolve(agentOf(session))).toEqual(binding)- })-- it('rejects a requested foreign owner before importing runtime capabilities or modifying the log', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = Session.create(SessionId('session-a'))- const append = vi.spyOn(session, 'append')- await expect(identity.append(agentOf(session), { ...binding, sessionId: 'session-other' })).rejects.toThrow('BRIDGE_INHERITED_SESSION')- expect(loader.import).not.toHaveBeenCalled()- expect(append).not.toHaveBeenCalled()- expect(session.seq).toBe(0)- })-- it('requires the registered projection instead of treating capability absence as an empty identity', async () => {- const session = Session.create(SessionId('session-a'))- await expect(identity.append(agentOf(session), binding)).rejects.toThrow('BRIDGE_CORE_UNAVAILABLE')- expect(loader.import).not.toHaveBeenCalled()- expect(session.seq).toBe(0)- })-- it('rejects invalid append payloads before any log write', async () => {- await identity.register()- vi.mocked(loader.import).mockClear()- const session = Session.create(SessionId('session-a'))- await expect(identity.append(agentOf(session), { ...binding, nativeSessionId: ' ' })).rejects.toThrow('BRIDGE_BINDING_INVALID')- expect(loader.import).not.toHaveBeenCalled()- expect(session.seq).toBe(0)- })-})diff --git a/packages/dsh-tauri-kernel/src/host/service/identity.ts b/packages/dsh-tauri-kernel/src/host/service/identity.tsdeleted file mode 100644index f372a304..00000000--- a/packages/dsh-tauri-kernel/src/host/service/identity.ts+++ /dev/null@@ -1,190 +0,0 @@-import type { Agent } from '@deepseek-ai/dsh-agent'-import type { Session } from '@deepseek-ai/dsh-session'-import type { KernelBinding, KernelProjectionState } from '../../shared/types'-import type { HostContext } from '../types'-import { getServerContext } from 'dsh-h3/utils'-import { defineService } from 'dsh-tauri'-import { BRIDGE_PROVIDER, KERNEL_RECORD_TYPE } from '../config/constants'-import { runtime } from '../config/runtime'-import { server } from '../server'-import { loadRuntimeModules, loadRuntimeZod } from '../utils/runtime-modules'--export const identity = defineService({- async register(): Promise<() => void> {- const ctx = getServerContext<HostContext>(server)- const lifetime = runtime.lifetime- const z = await loadRuntimeZod(ctx.loader)- lifetime.signal.throwIfAborted()- if (runtime.lifetime !== lifetime || getServerContext<HostContext>(server) !== ctx)- throw new Error('BRIDGE_DISPOSED: Kernel projection owner changed during registration')- const nonemptyId = z.string().min(1).refine(value => value.trim().length > 0)- const bindingSchema = z.object({- backend: z.enum(['codex', 'claude']),- nativeSessionId: nonemptyId,- sessionId: nonemptyId,- }).strict().readonly()- const viewSchema = bindingSchema.nullable()- const stateSchema = z.object({- ownerSessionId: nonemptyId,- inheritedEventCount: z.number().int().nonnegative(),- inheritedBinding: viewSchema,- binding: viewSchema,- }).strict().readonly()- const projections = ctx.get('sessionProjections')- if (typeof projections?.register !== 'function')- throw new Error('BRIDGE_CORE_UNAVAILABLE: The official session projection registry is unavailable')- const unregister = projections.register({- key: 'bridgeKernel',- stateSchema,- init: (header, inheritedEventCount) => Object.freeze({ ownerSessionId: header.id, inheritedEventCount, inheritedBinding: null, binding: null }),- apply(state, event) {- const type: string = event.type- if (type !== KERNEL_RECORD_TYPE || event.ignorable !== true)- return state- const candidate = parseBinding(event.data)- if (event.seq < state.inheritedEventCount) {- if (state.inheritedBinding !== null && sameBinding(state.inheritedBinding, candidate))- return state- return Object.freeze({ ...state, inheritedBinding: candidate })- }- if (candidate.sessionId !== state.ownerSessionId)- throw new Error('BRIDGE_INHERITED_SESSION: An inherited native binding cannot execute for a different official session')- if (state.binding !== null) {- assertSameBinding(state.binding, candidate)- return state- }- assertDistinctNative(state.inheritedBinding, candidate)- return Object.freeze({ ...state, binding: candidate })- },- wire: { viewSchema, view: state => state.binding },- stateVersion: 2,- })- runtime.bindingSchema = bindingSchema- const dispose = ctx.on('agent/created', ({ agent, source }) => {- if (source !== 'resume' || projections.stateOf(agent.session, 'bridgeKernel')?.binding == null)- return- const binding = identity.resolve(agent)- const fallback = ctx.get('agentDefaultModel')?.currentSelection()- if ((agent.options.provider === undefined && agent.options.model === undefined) || (agent.options.provider === fallback?.provider && agent.options.model === fallback?.model)) {- identity.hydrate(agent)- }- else if (agent.options.provider === BRIDGE_PROVIDER && agent.options.model === binding.backend) {- identity.hydrate(agent)- }- return undefined- }, { global: true })- return () => {- dispose()- unregister()- if (runtime.bindingSchema === bindingSchema)- runtime.bindingSchema = undefined- }- },-- hydrate(agent: Agent): void {- const binding = identity.resolve(agent)- agent.options.provider = BRIDGE_PROVIDER- agent.options.model = binding.backend- },-- async append(agent: Agent, binding: KernelBinding): Promise<number> {- const candidate = parseBinding(binding)- if (candidate.sessionId !== agent.session.id)- throw new Error('BRIDGE_INHERITED_SESSION: A native binding must belong to the exact official session')- const ctx = getServerContext<HostContext>(server)- const projections = ctx.get('sessionProjections')- if (typeof projections?.stateOf !== 'function')- throw new Error('BRIDGE_CORE_UNAVAILABLE: The official session projection registry is unavailable')- const previous = projections.stateOf(agent.session, 'bridgeKernel')- if (previous === undefined)- throw new Error('BRIDGE_CORE_UNAVAILABLE: The official kernel projection is not registered')- assertOwner(previous, agent.session)- if (previous.binding !== null)- assertSameBinding(parseBinding(previous.binding), candidate)- assertDistinctNative(previous.inheritedBinding, candidate)- const modules = await loadRuntimeModules(ctx.loader)- if (typeof modules.appendPluginRecord !== 'function' || typeof modules.pluginRecordOf !== 'function')- throw new Error('BRIDGE_CORE_UNAVAILABLE: The official ignorable plugin record capability is unavailable')- const current = projections.stateOf(agent.session, 'bridgeKernel')- if (current === undefined)- throw new Error('BRIDGE_CORE_UNAVAILABLE: The official kernel projection was unregistered')- assertOwner(current, agent.session)- if (current.binding !== null) {- assertSameBinding(parseBinding(current.binding), candidate)- return agent.session.seq - 1- }- assertDistinctNative(current.inheritedBinding, candidate)- const nextSeq = agent.session.seq- const committedSeq = modules.appendPluginRecord(agent.session, KERNEL_RECORD_TYPE, candidate)- if (!Number.isSafeInteger(committedSeq) || committedSeq !== nextSeq || agent.session.seq !== nextSeq + 1)- throw new Error('BRIDGE_BINDING_NOT_COMMITTED: The official plugin record was not appended at the session cursor')- const committed = projections.stateOf(agent.session, 'bridgeKernel')- if (committed === undefined || committed.binding === null)- throw new Error('BRIDGE_BINDING_NOT_COMMITTED: The native identity is absent from the official projection')- assertOwner(committed, agent.session)- assertSameBinding(parseBinding(committed.binding), candidate)- return committedSeq- },-- resolve(agent: Agent): KernelBinding {- const ctx = getServerContext<HostContext>(server)- const projections = ctx.get('sessionProjections')- if (typeof projections?.stateOf !== 'function')- throw new Error('BRIDGE_CORE_UNAVAILABLE: The official session projection registry is unavailable')- const state = projections.stateOf(agent.session, 'bridgeKernel')- if (state === undefined)- throw new Error('BRIDGE_CORE_UNAVAILABLE: The official kernel projection is not registered')- assertOwner(state, agent.session)- if (state.binding === null)- throw new Error('BRIDGE_BINDING_MISSING: The official session has no native kernel binding')- const binding = parseBinding(state.binding)- if (binding.sessionId !== agent.session.id)- throw new Error('BRIDGE_INHERITED_SESSION: An inherited native binding cannot execute for a different official session')- return binding- },-- inherited(value: Session): KernelBinding | null {- const ctx = getServerContext<HostContext>(server)- const projections = ctx.get('sessionProjections')- if (typeof projections?.stateOf !== 'function')- throw new Error('BRIDGE_CORE_UNAVAILABLE: The official session projection registry is unavailable')- const state = projections.stateOf(value, 'bridgeKernel')- if (state === undefined)- throw new Error('BRIDGE_CORE_UNAVAILABLE: The official kernel projection is not registered')- assertOwner(state, value)- if (state.inheritedBinding === null)- return null- const binding = parseBinding(state.inheritedBinding)- if (value.header.isSeeded !== true || !value.header.parentSession || state.inheritedEventCount === 0 || binding.sessionId !== value.header.parentSession)- throw new Error('BRIDGE_INHERITED_SESSION: The inherited native binding must belong to the exact official fork parent')- return binding- },-})--function parseBinding(value: unknown): KernelBinding {- if (!runtime.bindingSchema)- throw new Error('BRIDGE_CORE_UNAVAILABLE: The official kernel projection is not registered')- const parsed = runtime.bindingSchema.safeParse(value)- if (!parsed.success)- throw new Error('BRIDGE_BINDING_INVALID: Expected a complete supported backend, nonempty native session id, and nonempty official session id')- return parsed.data-}--function assertSameBinding(current: KernelBinding, candidate: KernelBinding): void {- if (!sameBinding(current, candidate))- throw new Error('BRIDGE_BINDING_IMMUTABLE: The official native kernel binding cannot be replaced')-}--function sameBinding(current: KernelBinding, candidate: KernelBinding): boolean {- return current.backend === candidate.backend && current.nativeSessionId === candidate.nativeSessionId && current.sessionId === candidate.sessionId-}--function assertOwner(state: KernelProjectionState, session: Session): void {- if (state.ownerSessionId !== session.id || state.inheritedEventCount !== session.inheritedEventCount)- throw new Error('BRIDGE_INHERITED_SESSION: The native projection must belong to the exact official session and fork boundary')-}--function assertDistinctNative(inherited: KernelBinding | null, candidate: KernelBinding): void {- if (inherited?.backend === candidate.backend && inherited.nativeSessionId === candidate.nativeSessionId)- throw new Error('BRIDGE_INHERITED_SESSION: A fork must receive a distinct native session identity')-}diff --git a/packages/dsh-tauri-kernel/src/host/service/model.test.ts b/packages/dsh-tauri-kernel/src/host/service/model.test.tsdeleted file mode 100644index 2c5013f5..00000000--- a/packages/dsh-tauri-kernel/src/host/service/model.test.ts+++ /dev/null@@ -1,898 +0,0 @@-import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent'-import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'-import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'-import type { SessionHandle } from '@deepseek-ai/dsh-session-persistence'-import type { NativeModelCatalog, NativeTurnOptions } from '../../shared/native-model'-import type { NativeSession } from '../backends/types'-import type { HostContext, PlatformLoader } from '../types'-import { createRequire } from 'node:module'-import process from 'node:process'-import { pathToFileURL } from 'node:url'-import { Context } from '@deepseek-ai/cordis'-import { AgentRegistry } from '@deepseek-ai/dsh-agent'-import { AgentDefaultModelConfig } from '@deepseek-ai/dsh-agent-default-model'-import { AgentLoop } from '@deepseek-ai/dsh-agent-loop'-import * as llmModule from '@deepseek-ai/dsh-llm'-import * as sessionModule from '@deepseek-ai/dsh-session'-import { assertContiguous, materializeAppendBatch, materializeCreateHeader, SessionPersistence, SessionPersistenceRevision, validateStoredEvents } from '@deepseek-ai/dsh-session-persistence'-import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'-import { ToolRuntime } from '@deepseek-ai/dsh-tools'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import * as zodModule from 'zod'-import { apply } from '../apply'-import { createClaudeSession } from '../backends/claude'-import { createCodexSession } from '../backends/codex'-import { resetRuntime, runtime } from '../config/runtime'-import { detectBackend } from '../utils/detection'-import { identity } from './identity'-import { model } from './model'-import { session } from './session'--vi.mock('../utils/detection', () => ({ detectBackend: vi.fn() }))-vi.mock('../backends/codex', () => ({ createCodexSession: vi.fn() }))-vi.mock('../backends/claude', () => ({ createClaudeSession: vi.fn() }))--const require = createRequire(import.meta.url)-const coreRequire = createRequire(require.resolve('@deepseek-ai/dsh-agent-loop'))-const promptModule: { SystemPrompt: new (ctx: Context, config: { includeHarnessIdentity: boolean, includeRuntimeContext: boolean }) => Context['systemPrompt'] } = await import(pathToFileURL(coreRequire.resolve('@deepseek-ai/dsh-system-prompt')).href)-interface StoredSession { header: Session['header'], inheritedEventCount: Session['inheritedEventCount'], events: readonly SessionEvent[], durable: readonly SessionEvent[], owner?: symbol }--class MemoryPersistence extends SessionPersistence {- readonly stored = new Map<Session['id'], StoredSession>()- readonly writers = new Map<Session['id'], SessionHandle>()- barrier: () => Promise<void> = async () => {}-- async create(header: Session['header'], options?: { inheritedEventCount?: Session['inheritedEventCount'], signal?: AbortSignal }): Promise<SessionHandle> {- options?.signal?.throwIfAborted()- if (this.stored.has(header.id))- throw new Error('memory session already exists')- const stored: StoredSession = { header: materializeCreateHeader(header), inheritedEventCount: options?.inheritedEventCount ?? sessionModule.SessionLogOffset(0), events: [], durable: [] }- this.stored.set(header.id, stored)- return this.open(header.id, 'write', options)- }-- async open(id: Session['id'], access: SessionHandle['access'], options?: { signal?: AbortSignal }): Promise<SessionHandle> {- options?.signal?.throwIfAborted()- const stored = this.stored.get(id)- if (!stored)- throw new Error('memory session missing')- if (access === 'write' && stored.owner !== undefined)- throw new Error('memory session already owned')- const owner = Symbol(id)- if (access === 'write')- stored.owner = owner- let closed = false- const active = () => {- if (closed)- throw new Error('memory session handle closed')- if (access === 'write' && stored.owner !== owner)- throw new Error('memory session ownership lost')- }- const flush = async () => {- active()- if (access !== 'write')- throw new Error('memory session is read-only')- await this.barrier()- stored.durable = validateStoredEvents(stored.header, structuredClone([...stored.events]))- }- const close = async () => {- if (closed)- return- if (access === 'write') {- await flush()- if (stored.owner === owner)- delete stored.owner- this.writers.delete(id)- }- closed = true- }- const handle: SessionHandle = {- id,- header: stored.header,- inheritedEventCount: stored.inheritedEventCount,- access,- async read(offset = 0, length, readOptions) {- active()- readOptions?.signal?.throwIfAborted()- return { events: validateStoredEvents(stored.header, structuredClone(stored.events.slice(offset, length === undefined ? undefined : offset + length))), eventState: 'shared-frozen' }- },- async append(events, appendOptions) {- active()- appendOptions?.signal?.throwIfAborted()- if (access !== 'write')- throw new Error('memory session is read-only')- const batch = materializeAppendBatch(events)- assertContiguous(id, batch, stored.events.length)- stored.events = [...stored.events, ...batch]- },- async flush(flushOptions) {- flushOptions?.signal?.throwIfAborted()- await flush()- },- close,- [Symbol.asyncDispose]: close,- }- if (access === 'write')- this.writers.set(id, handle)- return handle- }-- async flush(): Promise<void> {- await Promise.all([...this.writers.values()].map(handle => handle.flush()))- }-- async stat(id: Session['id']) {- const stored = this.stored.get(id)- return stored === undefined ? undefined : { header: stored.header, eventCount: stored.events.length, revision: SessionPersistenceRevision(`${id}:${stored.events.length}`) }- }-- async list() {- return Promise.all([...this.stored.keys()].map(async id => (await this.stat(id))!))- }-}--const cwd = process.cwd()-const now = 1_791_576_000_000-const initial: NativeTurnOptions = { model: null, reasoningEffort: null }-const selected: NativeTurnOptions = { model: 'vendor/reasoning-model', reasoningEffort: 'deep' }-const directory: NativeModelCatalog = {- defaultModel: 'vendor/reasoning-model',- models: [- { id: 'vendor/reasoning-model', name: 'Native reasoning model', reasoning: { defaultEffort: 'standard', efforts: [{ id: 'standard', name: 'Standard' }, { id: 'deep', name: 'Deep' }] } },- { id: 'vendor/plain-model', name: 'Native plain model' },- { id: 'gpt-5.4', name: 'Native custom GPT route' },- ],-}--function deferred<T>() {- let resolve!: (value: T | PromiseLike<T>) => void- const promise = new Promise<T>((accept) => {- resolve = accept- })- return { promise, resolve }-}--function native(id: string, catalog: NativeModelCatalog = directory) {- return {- id,- models: vi.fn<NonNullable<NativeSession['models']>>().mockResolvedValue(catalog),- submit: vi.fn<NativeSession['submit']>().mockResolvedValue(undefined),- dispose: vi.fn<NativeSession['dispose']>().mockResolvedValue(undefined),- }-}--let context: Context-let agents: AgentRegistry-let sessions: InstanceType<typeof sessionModule.SessionStore>-let projections: SessionProjectionRegistry-let llm: llmModule.LlmRuntime-let handles: AgentHandle[]-let errors: unknown[]-let persisted: Map<string, readonly SessionEvent[]>-let persistence: MemoryPersistence-let checkpoints: string[]-let stopCheckpoint: () => void-let releases: Array<() => void>-let background: Promise<unknown>[]-let disposeBridge: () => Promise<void>--async function mountBridge() {- const bridge = context.plugin((ctx) => {- apply(ctx as HostContext)- })- disposeBridge = () => bridge.dispose()- await bridge.await()- await vi.waitFor(() => expect(runtime.ready).toBe(true))-}--beforeEach(async () => {- vi.setSystemTime(now)- await resetRuntime()- vi.mocked(createCodexSession).mockReset()- vi.mocked(createClaudeSession).mockReset()- vi.mocked(detectBackend).mockReset()- vi.mocked(detectBackend).mockImplementation(async id => ({- detection: { id, installed: true, auth: 'ok', version: 'test', drift: false, hint: null },- command: { file: 'boundary-only', args: [id] },- }))- context = new Context()- agents = new AgentRegistry(context)- sessions = new sessionModule.SessionStore(context)- projections = new SessionProjectionRegistry(context)- llm = new llmModule.LlmRuntime(context)- handles = []- errors = []- persisted = new Map()- persistence = new MemoryPersistence(context)- checkpoints = []- releases = []- background = []- const create = agents.create.bind(agents)- vi.spyOn(agents, 'create').mockImplementation(async (...args) => {- const handle = await create(...args)- handles.push(handle)- return handle- })- context.on('agent/error', ({ error }) => errors.push(error))- stopCheckpoint = context.on('session/flush', checkpointOfficial)- await context.plugin(AgentDefaultModelConfig, { provider: 'global-provider', model: 'global-model', reasoningEffort: 'global-effort' }).await()- const prompt = new promptModule.SystemPrompt(context, { includeHarnessIdentity: false, includeRuntimeContext: false })- const tools = new ToolRuntime(context, { mode: 'native' })- expect(await prompt.assemble({})).toMatchObject({ tools: [] })- expect(tools.schemas()).toEqual([])- const routes = new Map<string, WebRoute>()- context.provide('webServer', {- register(route: WebRoute) {- routes.set(route.path, route)- return () => routes.delete(route.path)- },- } as unknown as HostContext['webServer'])- const loader: PlatformLoader = {- async import(id) {- if (id === '@deepseek-ai/dsh-session')- return sessionModule- if (id === 'zod')- return zodModule- if (id === '@deepseek-ai/dsh-llm')- return llmModule- throw new Error(`unexpected module: ${id}`)- },- unwrapExports: value => value,- }- context.provide('loader', loader as HostContext['loader'])- context.provide('agentPresets', { resolve: vi.fn().mockResolvedValue({ id: 'test-preset' }), mount: vi.fn().mockResolvedValue(undefined) } as unknown as HostContext['agentPresets'])- context.provide('workspaceRegistry', { get: () => undefined } as unknown as HostContext['workspaceRegistry'])- await context.plugin(AgentLoop, { agents: [] }).await()- await mountBridge()-})--afterEach(async () => {- for (const release of releases)- release()- await Promise.allSettled(background)- persistence.barrier = async () => {}- await session.dispose()- await context.fiber.dispose()- await resetRuntime()- vi.restoreAllMocks()- vi.useRealTimers()-})--async function checkpointOfficial(official: Session) {- const handle = persistence.writers.get(official.id)- if (!handle)- throw new Error('official session has no memory write owner')- const stored = persistence.stored.get(official.id)!- const suffix = official.snapshotEvents().slice(stored.events.length)- if (suffix.length > 0)- await handle.append(suffix)- await handle.flush()- checkpoints.push(official.id)- persisted.set(official.id, structuredClone(stored.durable))-}--async function create(connection = native('model-native'), backend: 'codex' | 'claude' = 'codex') {- vi.mocked(backend === 'codex' ? createCodexSession : createClaudeSession).mockResolvedValueOnce(connection)- const result = await session.create(backend, undefined, cwd)- const agent = agents.get(sessionModule.SessionId(result.sessionId))!- expect(agent.session).toBe(sessions.get(agent.id))- return { agent, connection }-}--function modelEvents(official: Session) {- return official.snapshotEvents().filter(event => (event.type as string) === 'plugin:dsh-tauri-kernel/model')-}--function followup(agent: Agent, text: string) {- agent.followup(llmModule.createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text }] }))- const task = agent.whenIdle()- background.push(task)- return task-}--function checkUnchangedRoute(agent: Agent, started = false) {- expect(agent.options).toMatchObject({ provider: 'dsh-tauri-kernel', model: 'codex' })- expect(agent.session.requestHeader()?.config).toEqual(started ? { provider: 'dsh-tauri-kernel', model: 'codex' } : undefined)- expect(context.agentDefaultModel.currentSelection()).toEqual({ provider: 'global-provider', model: 'global-model', reasoningEffort: 'global-effort' })-}--describe('official native skill catalog admission', () => {- it.each(['codex', 'claude'] as const)('omits DSH skill catalogs from %s input without cancelling catalog updates or removing explicit instructions', async (backend) => {- const catalogText = '<available_skills>find-skills</available_skills>'- const catalog = llmModule.createUserMessage({- source: { kind: 'skill-catalog', form: 'catalog', entries: [{ name: 'find-skills', description: 'DSH-only skill' }] } as unknown as llmModule.UserMessage['source'],- content: [{ type: 'text', text: catalogText }],- })- const update = llmModule.createUserMessage({- source: { ...catalog.source, update: true } as unknown as llmModule.UserMessage['source'],- content: [{ type: 'text', text: '<available_skills>replacement</available_skills>' }],- })- const invocation = llmModule.createUserMessage({- source: { kind: 'skill-invocation', name: 'find-skills', form: 'instructions' } as unknown as llmModule.UserMessage['source'],- content: [{ type: 'text', text: '<skill_content name="find-skills">explicit instructions</skill_content>' }],- })- context.on('agent/pre-step', async ({ step }, next) => {- const decision = await next()- return decision.kind === 'reject' ? decision : { ...decision, messages: [...decision.messages, ...step === 1 ? [catalog, invocation] : [update]] }- })- const connection = native(`skills-${backend}`)- vi.mocked(backend === 'codex' ? createCodexSession : createClaudeSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => {- output.assistant('native-skill-call', [{ type: 'tool-call', id: 'native-skill', name: 'Skill', arguments: '{"skill":"keybindings-help"}' }])- output.toolStart('native-skill', 'Skill', '{"skill":"keybindings-help"}')- output.toolEnd('native-skill', 'native skill instructions')- output.assistant('native-skill-finished', [{ type: 'text', text: 'native skill finished' }])- })- return connection- })- const created = await session.create(backend, undefined, cwd)- const agent = agents.get(sessionModule.SessionId(created.sessionId))!- await followup(agent, catalogText)- expect(connection.submit).toHaveBeenCalledOnce()- expect(connection.submit.mock.calls[0]![0].map(message => ({ source: message.source, content: message.content }))).toEqual([- { source: { kind: 'user' }, content: [{ type: 'text', text: catalogText }] },- { source: invocation.source, content: [{ type: 'text', text: '<skill_content name="find-skills">explicit instructions</skill_content>' }] },- ])- expect(agent.session.snapshotEvents().filter(event => event.type === 'step/start').map(event => event.data)).toEqual([{ turn: 1, step: 1 }, { turn: 1, step: 2 }])- expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/end').map(event => event.data)).toEqual([{ turn: 1, reason: { kind: 'completed' } }])- expect(errors).toEqual([])- }, 10_000)-})--describe('official native model selection', () => {- it.each(['codex', 'claude'] as const)('reads the actual %s catalog without submitting or creating model records', async (backend) => {- const { agent, connection } = await create(native(`catalog-${backend}`), backend)- const cursor = Number(agent.session.seq)- expect(await model.getCatalog(agent.id)).toEqual({- backend,- defaultModel: 'vendor/reasoning-model',- models: [- { id: 'vendor/reasoning-model', name: 'Native reasoning model', reasoning: { defaultEffort: 'standard', efforts: [{ id: 'standard', name: 'Standard' }, { id: 'deep', name: 'Deep' }] } },- { id: 'vendor/plain-model', name: 'Native plain model' },- { id: 'gpt-5.4', name: 'Native custom GPT route' },- ],- current: { model: null, reasoningEffort: null },- })- expect(connection.models).toHaveBeenCalledExactlyOnceWith(expect.any(AbortSignal))- expect(connection.submit).not.toHaveBeenCalled()- expect(modelEvents(agent.session)).toEqual([])- expect(agent.session.seq).toBe(cursor)- expect(createCodexSession).toHaveBeenCalledTimes(backend === 'codex' ? 1 : 0)- expect(createClaudeSession).toHaveBeenCalledTimes(backend === 'claude' ? 1 : 0)- }, 10_000)-- it('preserves acknowledged native defaults without treating a catalog preset as the effective effort', async () => {- const catalog: NativeModelCatalog = { ...directory, defaultReasoningEffort: 'deep' }- const { agent, connection } = await create(native('effective-default-native', catalog))- expect(await model.getCatalog(agent.id)).toEqual({ ...catalog, backend: 'codex', current: initial })- expect(model.resolve(agent)).toEqual(initial)- expect(modelEvents(agent.session)).toEqual([])- expect(connection.submit).not.toHaveBeenCalled()- checkUnchangedRoute(agent)- }, 10_000)-- it('preserves a configured default effort without inventing selectable reasoning controls', async () => {- const catalog: NativeModelCatalog = { defaultModel: 'custom-model', defaultReasoningEffort: 'high', models: [{ id: 'custom-model', name: 'custom-model' }] }- const { agent, connection } = await create(native('configured-effort-native', catalog))- expect(await model.getCatalog(agent.id)).toEqual({ ...catalog, backend: 'codex', current: initial })- await expect(model.select(agent.id, { model: null, reasoningEffort: 'high' })).rejects.toThrow('BRIDGE_REASONING_UNAVAILABLE')- expect(modelEvents(agent.session)).toEqual([])- expect(connection.submit).not.toHaveBeenCalled()- checkUnchangedRoute(agent)- }, 10_000)-- it('commits exactly one ignorable record and an awaited official durability checkpoint without changing DSH defaults', async () => {- const { agent, connection } = await create()- const cursor = Number(agent.session.seq)- const binding = identity.resolve(agent)- const providers = llm.listProviders()- expect(await model.select(agent.id, selected)).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(modelEvents(agent.session)).toEqual([{ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'vendor/reasoning-model', reasoningEffort: 'deep' } }])- expect(model.resolve(agent)).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(projections.stateOf(agent.session, 'bridgeModel')).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(agent.session.seq).toBe(cursor + 1)- expect(checkpoints).toEqual([agent.id])- expect(persisted.get(agent.id)?.find(event => event.seq === cursor)).toEqual({ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'vendor/reasoning-model', reasoningEffort: 'deep' } })- expect(identity.resolve(agent)).toEqual(binding)- checkUnchangedRoute(agent)- expect(llm.listProviders()).toEqual(providers)- expect(connection.submit).not.toHaveBeenCalled()- expect(createCodexSession).toHaveBeenCalledOnce()- }, 10_000)-- it('resets both controls to the native defaults without rewriting identity or the route', async () => {- const { agent, connection } = await create()- await model.select(agent.id, selected)- const cursor = Number(agent.session.seq)- expect(await model.select(agent.id, initial)).toEqual({ model: null, reasoningEffort: null })- expect(modelEvents(agent.session).map(event => ({ seq: event.seq, data: event.data }))).toEqual([- { seq: cursor - 1, data: { model: 'vendor/reasoning-model', reasoningEffort: 'deep' } },- { seq: cursor, data: { model: null, reasoningEffort: null } },- ])- expect(model.resolve(agent)).toEqual({ model: null, reasoningEffort: null })- expect(checkpoints).toEqual([agent.id, agent.id])- checkUnchangedRoute(agent)- expect(connection.submit).not.toHaveBeenCalled()- }, 10_000)-- it('checkpoints an unchanged choice without adding a duplicate official record', async () => {- const { agent, connection } = await create()- await model.select(agent.id, selected)- const cursor = Number(agent.session.seq)- const first = modelEvents(agent.session)- await model.select(agent.id, { model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(modelEvents(agent.session)).toEqual(first)- expect(agent.session.seq).toBe(cursor)- expect(checkpoints).toEqual([agent.id, agent.id])- expect(connection.models).toHaveBeenCalledTimes(2)- expect(connection.submit).not.toHaveBeenCalled()- }, 10_000)-- it.each([- [{ model: 'missing-model', reasoningEffort: null }, 'BRIDGE_MODEL_UNAVAILABLE'],- [{ model: 'vendor/reasoning-model', reasoningEffort: 'high' }, 'BRIDGE_REASONING_UNAVAILABLE'],- [{ model: 'vendor/plain-model', reasoningEffort: 'deep' }, 'BRIDGE_REASONING_UNAVAILABLE'],- [{ model: 'gpt-5.4', reasoningEffort: 'xhigh' }, 'BRIDGE_REASONING_UNAVAILABLE'],- [{ model: null, reasoningEffort: 'xhigh' }, 'BRIDGE_REASONING_UNAVAILABLE'],- ] satisfies Array<[NativeTurnOptions, string]>)('rejects unadvertised native choice %j before records, flush, or submit', async (options, error) => {- const { agent, connection } = await create()- const cursor = Number(agent.session.seq)- await expect(model.select(agent.id, options)).rejects.toThrow(error)- expect(modelEvents(agent.session)).toEqual([])- expect(model.resolve(agent)).toEqual({ model: null, reasoningEffort: null })- expect(agent.session.seq).toBe(cursor)- expect(checkpoints).toEqual([])- expect(connection.submit).not.toHaveBeenCalled()- checkUnchangedRoute(agent)- }, 10_000)-- it('uses only the advertised custom default model for a null model plus explicit effort', async () => {- const catalog: NativeModelCatalog = { defaultModel: 'custom/private-default', models: [{ id: 'custom/private-default', name: 'Custom provider default', reasoning: { efforts: [{ id: 'careful', name: 'Careful' }] } }] }- const { agent, connection } = await create(native('custom-default-native', catalog))- await expect(model.select(agent.id, { model: null, reasoningEffort: 'high' })).rejects.toThrow('BRIDGE_REASONING_UNAVAILABLE')- expect(await model.select(agent.id, { model: null, reasoningEffort: 'careful' })).toEqual({ model: null, reasoningEffort: 'careful' })- expect(modelEvents(agent.session).map(event => event.data)).toEqual([{ model: null, reasoningEffort: 'careful' }])- expect(connection.submit).not.toHaveBeenCalled()- checkUnchangedRoute(agent)- }, 10_000)-- it('does not invent a default model when the native catalog advertises none', async () => {- const { agent, connection } = await create(native('no-default-native', { models: [{ id: 'only-explicit', name: 'Explicit model', reasoning: { efforts: [{ id: 'deep', name: 'Deep' }] } }] }))- await expect(model.select(agent.id, { model: null, reasoningEffort: 'deep' })).rejects.toThrow('BRIDGE_REASONING_UNAVAILABLE')- expect(await model.select(agent.id, initial)).toEqual({ model: null, reasoningEffort: null })- expect(modelEvents(agent.session)).toEqual([])- expect(checkpoints).toEqual([agent.id])- expect(connection.submit).not.toHaveBeenCalled()- }, 10_000)-- it('refuses a native backend without model discovery rather than guessing supported controls', async () => {- const connection = native('unsupported-catalog')- Reflect.deleteProperty(connection, 'models')- const { agent } = await create(connection)- await expect(model.getCatalog(agent.id)).rejects.toThrow('BRIDGE_MODEL_UNSUPPORTED')- await expect(model.select(agent.id, initial)).rejects.toThrow('BRIDGE_MODEL_UNSUPPORTED')- expect(modelEvents(agent.session)).toEqual([])- expect(checkpoints).toEqual([])- expect(connection.submit).not.toHaveBeenCalled()- expect(createCodexSession).toHaveBeenCalledOnce()- }, 10_000)-- it.each([- { defaultModel: 'not-in-directory', models: [{ id: 'valid', name: 'Valid model' }] },- { defaultReasoningEffort: 'high', models: [{ id: 'valid', name: 'Valid model' }] },- { models: [{ id: 'duplicate', name: 'One' }, { id: 'duplicate', name: 'Two' }] },- { models: [{ id: 'bad-efforts', name: 'Bad', reasoning: { efforts: [{ id: 'deep', name: 'One' }, { id: 'deep', name: 'Two' }] } }] },- { models: [{ id: 'bad-default-effort', name: 'Bad', reasoning: { defaultEffort: 'high', efforts: [{ id: 'deep', name: 'Deep' }] } }] },- ] satisfies NativeModelCatalog[])('rejects an inconsistent native catalog %j without recording speculative options', async (catalog) => {- const { agent, connection } = await create(native('invalid-directory', catalog))- await expect(model.getCatalog(agent.id)).rejects.toThrow('BRIDGE_MODEL_CATALOG_INVALID')- await expect(model.select(agent.id, initial)).rejects.toThrow('BRIDGE_MODEL_CATALOG_INVALID')- expect(modelEvents(agent.session)).toEqual([])- expect(checkpoints).toEqual([])- expect(connection.submit).not.toHaveBeenCalled()- }, 10_000)-- it('rejects unknown and ordinary DSH sessions instead of using another native owner', async () => {- const { agent, connection } = await create()- const ordinary = await agents.create({ sessionId: sessionModule.SessionId('ordinary-model-session'), meta: { cwd }, agentOptions: { provider: 'global-provider', model: 'global-model' } })- await expect(model.getCatalog('foreign-model-session')).rejects.toThrow('BRIDGE_SESSION_UNAVAILABLE')- await expect(model.select('foreign-model-session', selected)).rejects.toThrow('BRIDGE_SESSION_UNAVAILABLE')- await expect(model.getCatalog(ordinary.agent.id)).rejects.toThrow('BRIDGE_BINDING_MISSING')- await expect(model.select(ordinary.agent.id, selected)).rejects.toThrow('BRIDGE_BINDING_MISSING')- expect(connection.models).not.toHaveBeenCalled()- expect(connection.submit).not.toHaveBeenCalled()- expect(modelEvents(agent.session)).toEqual([])- expect(modelEvents(ordinary.agent.session)).toEqual([])- expect(createCodexSession).toHaveBeenCalledOnce()- expect(createClaudeSession).not.toHaveBeenCalled()- }, 10_000)-- it('fails a read-only checkpoint without reporting a successful selection', async () => {- const { agent, connection } = await create()- stopCheckpoint()- const cursor = Number(agent.session.seq)- await expect(model.select(agent.id, selected)).rejects.toThrow('BRIDGE_MODEL_NOT_PERSISTED')- expect(modelEvents(agent.session)).toEqual([{ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'vendor/reasoning-model', reasoningEffort: 'deep' } }])- expect(persisted.has(agent.id)).toBe(false)- expect(checkpoints).toEqual([])- expect(connection.submit).not.toHaveBeenCalled()- checkUnchangedRoute(agent)- }, 10_000)-- it('propagates flush failure and retries the same official choice without duplicating its event', async () => {- const { agent, connection } = await create()- stopCheckpoint()- const failure = new Error('native model durability refused')- const stopFailure = context.on('session/flush', async () => {- throw failure- })- const cursor = Number(agent.session.seq)- await expect(model.select(agent.id, selected)).rejects.toBe(failure)- expect(modelEvents(agent.session)).toEqual([{ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'vendor/reasoning-model', reasoningEffort: 'deep' } }])- expect(persisted.has(agent.id)).toBe(false)- expect(connection.submit).not.toHaveBeenCalled()- stopFailure()- context.on('session/flush', checkpointOfficial)- expect(await model.select(agent.id, selected)).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(agent.session.seq).toBe(cursor + 1)- expect(modelEvents(agent.session)).toHaveLength(1)- expect(checkpoints).toEqual([agent.id])- expect(persisted.get(agent.id)?.find(event => event.seq === cursor)).toEqual({ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'vendor/reasoning-model', reasoningEffort: 'deep' } })- expect(connection.submit).not.toHaveBeenCalled()- }, 10_000)-- it('keeps a real native first turn behind an unfinished model persistence checkpoint', async () => {- const connection = native('pending-model-native')- const submitted = deferred<void>()- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => {- submitted.resolve()- output.assistant('pending-model-answer', [{ type: 'text', text: 'durable controls admitted' }])- })- return connection- })- const result = await session.create('codex', undefined, cwd)- const agent = agents.get(sessionModule.SessionId(result.sessionId))!- const entered = deferred<void>()- const drain = deferred<void>()- releases.push(() => drain.resolve())- persistence.barrier = async () => {- entered.resolve()- await drain.promise- }- const selection = model.select(agent.id, selected)- background.push(selection)- await entered.promise- let idle = false- const turn = followup(agent, 'wait for the native controls to become durable').then(() => {- idle = true- })- background.push(turn)- await vi.waitFor(() => expect(runtime.steps.has(agent.id)).toBe(true))- expect(idle).toBe(false)- expect(connection.submit).not.toHaveBeenCalled()- expect(runtime.exchanges.size).toBe(0)- expect(persistence.stored.get(agent.id)?.durable.some(event => (event.type as string) === 'plugin:dsh-tauri-kernel/model')).toBe(false)- drain.resolve()- expect(await selection).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- await submitted.promise- await turn- expect(connection.submit).toHaveBeenCalledOnce()- expect(connection.submit.mock.calls[0]![0]).toMatchObject([{ source: { kind: 'user' }, content: [{ type: 'text', text: 'wait for the native controls to become durable' }] }])- expect(connection.submit.mock.calls[0]![2]).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(checkpoints).toEqual([agent.id])- expect(errors).toEqual([])- expect(createCodexSession).toHaveBeenCalledOnce()- checkUnchangedRoute(agent, true)- }, 10_000)-- it('blocks actual native admission after a failed checkpoint and retries the same official record before submitting', async () => {- const connection = native('failed-checkpoint-native')- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => output.assistant('retry-checkpoint-answer', [{ type: 'text', text: 'durable retry admitted' }]))- return connection- })- const created = await session.create('codex', undefined, cwd)- const agent = agents.get(sessionModule.SessionId(created.sessionId))!- const cursor = Number(agent.session.seq)- const failure = new Error('first native model durability checkpoint refused')- persistence.barrier = async () => {- throw failure- }- await expect(model.select(agent.id, selected)).rejects.toBe(failure)- await followup(agent, 'must not submit the unpersisted choice')- expect(connection.submit).not.toHaveBeenCalled()- expect(errors).toHaveLength(1)- expect(errors[0]).toMatchObject({ name: 'LlmError', code: 'UNKNOWN', message: 'first native model durability checkpoint refused', failure: { code: 'UNKNOWN', message: 'first native model durability checkpoint refused' } })- expect(runtime.exchanges.size).toBe(0)- expect(modelEvents(agent.session)).toEqual([{ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'vendor/reasoning-model', reasoningEffort: 'deep' } }])- persistence.barrier = async () => {}- expect(await model.select(agent.id, selected)).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(modelEvents(agent.session)).toHaveLength(1)- expect(persistence.stored.get(agent.id)?.durable.find(event => event.seq === cursor)).toEqual({ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'vendor/reasoning-model', reasoningEffort: 'deep' } })- await followup(agent, 'submit only after the saved choice is proven')- expect(connection.submit).toHaveBeenCalledOnce()- expect(connection.submit.mock.calls[0]![2]).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(errors).toHaveLength(1)- expect(errors[0]).toMatchObject({ name: 'LlmError', code: 'UNKNOWN', message: 'first native model durability checkpoint refused', failure: { code: 'UNKNOWN', message: 'first native model durability checkpoint refused' } })- expect(createCodexSession).toHaveBeenCalledOnce()- checkUnchangedRoute(agent, true)- }, 10_000)-- it('rejects a no-op flush observer that settles true without storing the official model record', async () => {- const { agent, connection } = await create()- stopCheckpoint()- const observer = vi.fn().mockResolvedValue(undefined)- context.on('session/flush', observer)- const cursor = Number(agent.session.seq)- await expect(model.select(agent.id, selected)).rejects.toThrow('BRIDGE_MODEL_NOT_PERSISTED')- expect(observer).toHaveBeenCalledOnce()- expect(observer.mock.calls[0]![0]).toBe(agent.session)- expect(modelEvents(agent.session)).toEqual([{ seq: cursor, time: now, type: 'plugin:dsh-tauri-kernel/model', ignorable: true, data: { model: 'vendor/reasoning-model', reasoningEffort: 'deep' } }])- expect(persistence.stored.get(agent.id)?.events).toHaveLength(cursor)- expect(persistence.stored.get(agent.id)?.durable).toHaveLength(cursor)- expect(connection.submit).not.toHaveBeenCalled()- expect(createCodexSession).toHaveBeenCalledOnce()- }, 10_000)-- it('reconstructs an unsaved choice after bridge remount and refuses native admission until official persistence proves it', async () => {- const { agent, connection } = await create(native('remount-model-native'))- stopCheckpoint()- await expect(model.select(agent.id, selected)).rejects.toThrow('BRIDGE_MODEL_NOT_PERSISTED')- const before = modelEvents(agent.session)- await disposeBridge()- expect(connection.dispose).toHaveBeenCalledOnce()- expect(agents.get(agent.id)).toBe(agent)- expect(sessions.get(agent.id)).toBe(agent.session)- await mountBridge()- expect(model.resolve(agent)).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- await followup(agent, 'no remount may bypass the failed model write')- expect(errors).toHaveLength(1)- expect(errors[0]).toMatchObject({ message: expect.stringContaining('BRIDGE_MODEL_NOT_PERSISTED') })- expect(createCodexSession).toHaveBeenCalledOnce()- expect(connection.submit).not.toHaveBeenCalled()- expect(modelEvents(agent.session)).toEqual(before)- context.on('session/flush', checkpointOfficial)- const restored = native('remount-model-native')- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- restored.submit.mockImplementation(async () => output.assistant('remount-model-answer', [{ type: 'text', text: 'canonical saved choice restored' }]))- return restored- })- await followup(agent, 'admit the now durable canonical choice')- expect(restored.submit).toHaveBeenCalledOnce()- expect(restored.submit.mock.calls[0]![2]).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(vi.mocked(createCodexSession).mock.calls[1]![2]).toBe('remount-model-native')- expect(vi.mocked(createCodexSession).mock.calls[1]![5]).toBeUndefined()- expect(modelEvents(agent.session)).toEqual(before)- expect(persistence.stored.get(agent.id)?.durable.filter(event => (event.type as string) === 'plugin:dsh-tauri-kernel/model')).toEqual(before)- expect(errors).toHaveLength(1)- checkUnchangedRoute(agent, true)- }, 10_000)-- it.each(['catalog', 'selection'] as const)('never adopts an old %s catalog result after unload and remount', async (operation) => {- const { agent, connection } = await create(native(`old-${operation}-native`))- const entered = deferred<void>()- const finish = deferred<void>()- const catalog = deferred<NativeModelCatalog>()- releases.push(() => catalog.resolve(directory))- connection.models.mockImplementationOnce(async () => {- entered.resolve()- const value = await catalog.promise- finish.resolve()- return value- })- const cursor = Number(agent.session.seq)- const request = operation === 'catalog' ? model.getCatalog(agent.id) : model.select(agent.id, selected)- const rejected = expect(request).rejects.toThrow('BRIDGE_DISPOSED')- background.push(rejected)- await entered.promise- await disposeBridge()- await rejected- expect(connection.dispose).toHaveBeenCalledOnce()- await mountBridge()- catalog.resolve(directory)- await finish.promise- expect(modelEvents(agent.session)).toEqual([])- expect(agent.session.seq).toBe(cursor)- expect(model.resolve(agent)).toEqual({ model: null, reasoningEffort: null })- expect(checkpoints).toEqual([])- expect(connection.submit).not.toHaveBeenCalled()- expect(createCodexSession).toHaveBeenCalledOnce()- expect(createClaudeSession).not.toHaveBeenCalled()- expect(agents.get(agent.id)).toBe(agent)- expect(sessions.get(agent.id)).toBe(agent.session)- checkUnchangedRoute(agent)- }, 10_000)-- it('hydrates frozen model options from a cold official session and restores only its committed native id', async () => {- const { agent, connection } = await create(native('cold-model-native'))- await model.select(agent.id, selected)- const oldHandle = handles.find(handle => handle.agent === agent)!- const cursor = Number(agent.session.seq)- await oldHandle.dispose()- await session.remove(agent.id)- const open = vi.spyOn(persistence, 'open')- const createStored = vi.spyOn(persistence, 'create')- const restored = await agents.resume({ resumeSessionId: agent.id, agentOptions: { provider: 'dsh-tauri-kernel', model: 'codex' } })- const restoredWrite = persistence.writers.get(agent.id)!- const close = vi.spyOn(restoredWrite, 'close')- expect(open).toHaveBeenCalledExactlyOnceWith(agent.id, 'write', { signal: expect.any(AbortSignal) })- expect(persistence.stored.get(agent.id)?.durable).toEqual(persisted.get(agent.id))- expect(createStored).not.toHaveBeenCalled()- expect(restored.agent.session).not.toBe(agent.session)- expect(restored.agent.session.seq).toBe(cursor + 1)- expect(restored.agent.session.snapshotEvents()).toEqual([...agent.session.snapshotEvents(), { seq: cursor, time: now, type: 'session/end-seed', data: {} }])- const options = model.resolve(restored.agent)- expect(options).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(Object.isFrozen(options)).toBe(true)- expect(Reflect.set(options, 'model', 'unadvertised-replacement')).toBe(false)- expect(model.resolve(restored.agent)).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- const resumed = native('cold-model-native')- vi.mocked(createCodexSession).mockResolvedValueOnce(resumed)- expect(await model.getCatalog(restored.agent.id)).toMatchObject({ backend: 'codex', current: { model: 'vendor/reasoning-model', reasoningEffort: 'deep' } })- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(vi.mocked(createCodexSession).mock.calls[1]![2]).toBe('cold-model-native')- expect(vi.mocked(createCodexSession).mock.calls[1]![5]).toBeUndefined()- expect(resumed.models).toHaveBeenCalledOnce()- expect(resumed.submit).not.toHaveBeenCalled()- expect(modelEvents(restored.agent.session)).toEqual(modelEvents(agent.session))- expect(connection.dispose).toHaveBeenCalledOnce()- await restored.dispose()- await session.remove(restored.agent.id)- expect(close).toHaveBeenCalledOnce()- expect(resumed.dispose).toHaveBeenCalledOnce()- }, 10_000)-- it('finishes two native tool continuations with the original options after a concurrent selection fails to flush', async () => {- const firstTool = deferred<void>()- const secondTool = deferred<void>()- const stepTwo = deferred<void>()- const stepThree = deferred<void>()- releases.push(() => firstTool.resolve(), () => secondTool.resolve())- const connection = native('failed-mid-turn-selection')- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementationOnce(async () => {- output.assistant('before-failed-selection', [{ type: 'tool-call', id: 'failed-selection-one', name: 'native_one', arguments: '{}' }])- output.toolStart('failed-selection-one', 'native_one', '{}')- output.toolEnd('failed-selection-one', 'first result before failed choice')- await firstTool.promise- output.assistant('after-failed-selection', [{ type: 'tool-call', id: 'failed-selection-two', name: 'native_two', arguments: '{}' }])- output.toolStart('failed-selection-two', 'native_two', '{}')- output.toolEnd('failed-selection-two', 'second result after failed choice')- await secondTool.promise- output.assistant('original-options-complete', [{ type: 'text', text: 'original whole turn completed' }])- }).mockImplementation(async () => output.assistant('saved-new-options', [{ type: 'text', text: 'next durable choice used' }]))- return connection- })- const created = await session.create('codex', undefined, cwd)- const agent = agents.get(sessionModule.SessionId(created.sessionId))!- const events: SessionEvent[] = []- const snapshots: Array<NativeTurnOptions | undefined> = []- agent.ctx.on('session/event', (official, event) => {- if (official !== agent.session)- return- events.push(event)- if (event.type === 'step/start' && event.data.turn === 1 && event.data.step === 2) {- snapshots.push(runtime.exchanges.get(agent.id)?.state.input.options)- stepTwo.resolve()- }- if (event.type === 'step/start' && event.data.turn === 1 && event.data.step === 3) {- snapshots.push(runtime.exchanges.get(agent.id)?.state.input.options)- stepThree.resolve()- }- })- await model.select(agent.id, selected)- const turn = followup(agent, 'keep the already admitted whole-turn options')- await stepTwo.promise- const failure = new Error('concurrent native selection could not become durable')- persistence.barrier = async () => {- throw failure- }- await expect(model.select(agent.id, { model: 'vendor/plain-model', reasoningEffort: null })).rejects.toBe(failure)- expect(connection.submit).toHaveBeenCalledOnce()- firstTool.resolve()- await stepThree.promise- expect(connection.submit).toHaveBeenCalledOnce()- secondTool.resolve()- await turn- expect(snapshots).toEqual([{ model: 'vendor/reasoning-model', reasoningEffort: 'deep' }, { model: 'vendor/reasoning-model', reasoningEffort: 'deep' }])- expect(connection.submit.mock.calls[0]![2]).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(events.filter(event => event.type === 'step/start').map(event => event.data)).toEqual([{ turn: 1, step: 1 }, { turn: 1, step: 2 }, { turn: 1, step: 3 }])- expect(events.filter(event => event.type === 'tool/result').map(event => event.data.message.toolCallId)).toEqual(['failed-selection-one', 'failed-selection-two'])- expect(events.filter(event => event.type === 'turn/end').map(event => event.data)).toEqual([{ turn: 1, reason: { kind: 'completed' } }])- expect(errors).toEqual([])- expect(model.resolve(agent)).toEqual({ model: 'vendor/plain-model', reasoningEffort: null })- await followup(agent, 'cannot admit the failed replacement options yet')- expect(errors).toHaveLength(1)- expect(errors[0]).toMatchObject({ name: 'LlmError', code: 'UNKNOWN', message: 'concurrent native selection could not become durable', failure: { code: 'UNKNOWN', message: 'concurrent native selection could not become durable' } })- expect(connection.submit).toHaveBeenCalledOnce()- persistence.barrier = async () => {}- await model.select(agent.id, { model: 'vendor/plain-model', reasoningEffort: null })- await followup(agent, 'admit the retry-proven replacement options')- expect(connection.submit).toHaveBeenCalledTimes(2)- expect(connection.submit.mock.calls[1]![2]).toEqual({ model: 'vendor/plain-model', reasoningEffort: null })- expect(modelEvents(agent.session).map(event => event.data)).toEqual([{ model: 'vendor/reasoning-model', reasoningEffort: 'deep' }, { model: 'vendor/plain-model', reasoningEffort: null }])- expect(createCodexSession).toHaveBeenCalledOnce()- expect(runtime.exchanges.size).toBe(0)- checkUnchangedRoute(agent, true)- }, 10_000)-- it('keeps one immutable native option snapshot across three official steps and applies concurrent selections only to the next turn', async () => {- const firstTool = deferred<void>()- const secondTool = deferred<void>()- const stepTwo = deferred<void>()- const stepThree = deferred<void>()- releases.push(() => firstTool.resolve(), () => secondTool.resolve())- const connection = native('snapshot-native')- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementationOnce(async () => {- output.assistant('first-work', [{ type: 'tool-call', id: 'snapshot-first', name: 'native_first', arguments: '{"path":"one"}' }])- output.toolStart('snapshot-first', 'native_first', '{"path":"one"}')- output.toolEnd('snapshot-first', 'first native result')- await firstTool.promise- output.assistant('second-work', [{ type: 'tool-call', id: 'snapshot-second', name: 'native_second', arguments: '{"path":"two"}' }])- output.toolStart('snapshot-second', 'native_second', '{"path":"two"}')- output.toolEnd('snapshot-second', 'second native result')- await secondTool.promise- output.assistant('finished', [{ type: 'text', text: 'both native steps finished' }])- }).mockImplementation(async () => output.assistant('next-turn', [{ type: 'text', text: 'next options applied' }]))- return connection- })- const created = await session.create('codex', undefined, cwd)- const agent = agents.get(sessionModule.SessionId(created.sessionId))!- const events: SessionEvent[] = []- const snapshots: Array<NativeTurnOptions | undefined> = []- agent.ctx.on('session/event', (official, event) => {- if (official !== agent.session)- return- events.push(event)- if (event.type === 'step/start' && event.data.turn === 1 && event.data.step === 2) {- snapshots.push(runtime.exchanges.get(agent.id)?.state.input.options)- stepTwo.resolve()- }- if (event.type === 'step/start' && event.data.turn === 1 && event.data.step === 3) {- snapshots.push(runtime.exchanges.get(agent.id)?.state.input.options)- stepThree.resolve()- }- })- await model.select(agent.id, selected)- const turn = followup(agent, 'run two consecutive native tool steps')- await stepTwo.promise- expect(connection.submit).toHaveBeenCalledOnce()- expect(connection.submit.mock.calls[0]![0]).toMatchObject([{ source: { kind: 'user' }, content: [{ type: 'text', text: 'run two consecutive native tool steps' }] }])- expect(connection.submit.mock.calls[0]![2]).toEqual({ model: 'vendor/reasoning-model', reasoningEffort: 'deep' })- expect(Object.isFrozen(connection.submit.mock.calls[0]![2])).toBe(true)- await model.select(agent.id, { model: 'vendor/plain-model', reasoningEffort: null })- expect(connection.submit).toHaveBeenCalledOnce()- firstTool.resolve()- await stepThree.promise- await model.select(agent.id, { model: null, reasoningEffort: 'standard' })- expect(connection.submit).toHaveBeenCalledOnce()- secondTool.resolve()- await turn- expect(snapshots).toEqual([{ model: 'vendor/reasoning-model', reasoningEffort: 'deep' }, { model: 'vendor/reasoning-model', reasoningEffort: 'deep' }])- expect(events.filter(event => event.type === 'step/start').map(event => event.data)).toEqual([{ turn: 1, step: 1 }, { turn: 1, step: 2 }, { turn: 1, step: 3 }])- expect(events.filter(event => event.type === 'tool/call').map(event => event.data)).toEqual([- { turn: 1, step: 1, callId: 'snapshot-first', name: 'native_first', arguments: '{"path":"one"}' },- { turn: 1, step: 2, callId: 'snapshot-second', name: 'native_second', arguments: '{"path":"two"}' },- ])- expect(events.filter(event => event.type === 'tool/result').map(event => ({ turn: event.data.turn, step: event.data.step, callId: event.data.message.toolCallId, content: event.data.message.content }))).toEqual([- { turn: 1, step: 1, callId: 'snapshot-first', content: [{ type: 'text', text: 'first native result' }] },- { turn: 1, step: 2, callId: 'snapshot-second', content: [{ type: 'text', text: 'second native result' }] },- ])- checkUnchangedRoute(agent, true)- await followup(agent, 'use the newly selected native controls')- expect(connection.submit).toHaveBeenCalledTimes(2)- expect(connection.submit.mock.calls[1]![0]).toMatchObject([{ source: { kind: 'user' }, content: [{ type: 'text', text: 'use the newly selected native controls' }] }])- expect(connection.submit.mock.calls[1]![2]).toEqual({ model: null, reasoningEffort: 'standard' })- expect(modelEvents(agent.session).map(event => event.data)).toEqual([- { model: 'vendor/reasoning-model', reasoningEffort: 'deep' },- { model: 'vendor/plain-model', reasoningEffort: null },- { model: null, reasoningEffort: 'standard' },- ])- expect(createCodexSession).toHaveBeenCalledOnce()- expect(errors).toEqual([])- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-})diff --git a/packages/dsh-tauri-kernel/src/host/service/model.ts b/packages/dsh-tauri-kernel/src/host/service/model.tsdeleted file mode 100644index efe5f0fa..00000000--- a/packages/dsh-tauri-kernel/src/host/service/model.ts+++ /dev/null@@ -1,212 +0,0 @@-import type { Agent } from '@deepseek-ai/dsh-agent'-import type { SessionId } from '@deepseek-ai/dsh-session'-import type { NativeModelCatalog, NativeModelDirectory, NativeTurnOptions } from '../../shared/native-model'-import type { HostContext } from '../types'-import { getServerContext } from 'dsh-h3/utils'-import { defineService } from 'dsh-tauri'-import { MODEL_RECORD_TYPE } from '../config/constants'-import { runtime } from '../config/runtime'-import { server } from '../server'-import { waitFor } from '../utils/abort'-import { loadRuntimeModules, loadRuntimeZod } from '../utils/runtime-modules'-import { checkpoint } from './checkpoint'-import { identity } from './identity'-import { session } from './session'--export const model = defineService({- async register(): Promise<() => void> {- const ctx = getServerContext<HostContext>(server)- const lifetime = runtime.lifetime- const z = await loadRuntimeZod(ctx.loader)- lifetime.signal.throwIfAborted()- if (runtime.lifetime !== lifetime || getServerContext<HostContext>(server) !== ctx)- throw new Error('BRIDGE_DISPOSED: Model projection owner changed during registration')- const identifier = z.string().min(1).max(512).refine(value => value.trim().length > 0)- const optionsSchema = z.object({ model: identifier.nullable(), reasoningEffort: identifier.nullable() }).strict().readonly()- const catalogSchema = z.object({- models: z.array(z.object({- id: identifier,- name: z.string().min(1),- description: z.string().optional(),- reasoning: z.object({- efforts: z.array(z.object({ id: identifier, name: z.string().min(1), description: z.string().optional() })).min(1),- defaultEffort: identifier.optional(),- }).optional(),- })).max(2048),- defaultModel: identifier.optional(),- defaultReasoningEffort: identifier.optional(),- })- const unregister = ctx.sessionProjections.register({- key: 'bridgeModel',- stateSchema: optionsSchema,- init: () => ({ model: null, reasoningEffort: null }),- apply(state, event) {- if ((event.type as string) !== MODEL_RECORD_TYPE || event.ignorable !== true)- return state- const next = parseOptions(event.data)- return sameOptions(state, next) ? state : next- },- wire: { viewSchema: optionsSchema, view: state => state },- stateVersion: 1,- })- runtime.optionsSchema = optionsSchema- runtime.catalogSchema = catalogSchema- return () => {- unregister()- if (runtime.optionsSchema === optionsSchema)- runtime.optionsSchema = undefined- if (runtime.catalogSchema === catalogSchema)- runtime.catalogSchema = undefined- }- },-- resolve(agent: Agent): NativeTurnOptions {- const ctx = getServerContext<HostContext>(server)- const value = ctx.sessionProjections.stateOf(agent.session, 'bridgeModel')- if (value === undefined)- throw new Error('BRIDGE_CORE_UNAVAILABLE: 原生模型投影不可用。')- return parseOptions(value)- },-- async forTurn(agent: Agent, signal: AbortSignal): Promise<NativeTurnOptions> {- const lifetime = runtime.lifetime- const scoped = AbortSignal.any([signal, lifetime.signal])- while (true) {- const pending = runtime.modelWrites.get(agent)- if (pending)- await waitFor(pending.catch(() => undefined), scoped)- await checkpoint.flush(agent, scoped)- assertLive(agent, lifetime)- scoped.throwIfAborted()- if (!runtime.modelWrites.has(agent) && checkpoint.isVerified(agent))- return model.resolve(agent)- }- },-- async getCatalog(sessionId: string): Promise<NativeModelDirectory> {- const lifetime = runtime.lifetime- const agent = await resolveAgent(sessionId, lifetime)- const binding = identity.resolve(agent)- const catalog = await getCatalog(agent, lifetime)- assertLive(agent, lifetime)- return { ...catalog, backend: binding.backend, current: model.resolve(agent) }- },-- async select(sessionId: string, options: NativeTurnOptions): Promise<NativeTurnOptions> {- const next = parseOptions(options)- const lifetime = runtime.lifetime- const agent = await resolveAgent(sessionId, lifetime)- identity.resolve(agent)- const previous = runtime.modelWrites.get(agent)- const task = (async () => {- if (previous)- await waitFor(previous.catch(() => undefined), lifetime.signal)- const catalog = await getCatalog(agent, lifetime)- assertSelection(catalog, next)- assertLive(agent, lifetime)- const ctx = getServerContext<HostContext>(server)- const modules = await waitFor(loadRuntimeModules(ctx.loader), lifetime.signal)- assertLive(agent, lifetime)- if (typeof modules.appendPluginRecord !== 'function' || typeof modules.pluginRecordOf !== 'function')- throw new Error('BRIDGE_CORE_UNAVAILABLE: 原生模型选择的官方记录接口不可用。')- const current = model.resolve(agent)- if (!sameOptions(current, next)) {- const cursor = agent.session.seq- const seq = modules.appendPluginRecord(agent.session, MODEL_RECORD_TYPE, next)- checkpoint.mark(agent, MODEL_RECORD_TYPE, seq, next)- if (seq !== cursor || agent.session.seq !== cursor + 1 || !sameOptions(model.resolve(agent), next))- throw new Error('BRIDGE_MODEL_NOT_COMMITTED: 原生模型选择未写入官方会话。')- }- await checkpoint.flush(agent, lifetime.signal, true)- assertLive(agent, lifetime)- })()- runtime.modelWrites.set(agent, task)- try {- await task- return next- }- finally {- if (runtime.modelWrites.get(agent) === task)- runtime.modelWrites.delete(agent)- }- },-})--function parseOptions(value: unknown): NativeTurnOptions {- if (!runtime.optionsSchema)- throw new Error('BRIDGE_CORE_UNAVAILABLE: 原生模型投影不可用。')- const parsed = runtime.optionsSchema.safeParse(value)- if (!parsed.success)- throw new Error('BRIDGE_MODEL_INVALID: 模型与推理深度必须是完整的原生选项。')- return parsed.data-}--async function resolveAgent(sessionId: string, lifetime: AbortController): Promise<Agent> {- const ctx = getServerContext<HostContext>(server)- lifetime.signal.throwIfAborted()- let agent = ctx.agents.get(sessionId as SessionId)- if (!agent) {- const controller = ctx.get('sessionController')- if (typeof controller?.resolveAgent !== 'function')- throw new Error('BRIDGE_SESSION_UNAVAILABLE: 无法恢复官方会话。')- const resolved = await waitFor<Awaited<ReturnType<HostContext['sessionController']['resolveAgent']>>>(controller.resolveAgent(sessionId as SessionId), lifetime.signal)- if ('error' in resolved)- throw resolved.error- agent = resolved.agent- }- if (!agent)- throw new Error('BRIDGE_SESSION_UNAVAILABLE: 官方会话未返回有效的代理。')- assertLive(agent, lifetime)- identity.resolve(agent)- return agent-}--async function getCatalog(agent: Agent, lifetime: AbortController): Promise<NativeModelCatalog> {- assertLive(agent, lifetime)- const native = await waitFor(session.connect(agent, lifetime.signal), lifetime.signal)- assertLive(agent, lifetime)- if (typeof native.models !== 'function')- throw new Error('BRIDGE_MODEL_UNSUPPORTED: 当前本机内核未提供模型目录。')- const catalogSchema = runtime.catalogSchema- if (!catalogSchema)- throw new Error('BRIDGE_CORE_UNAVAILABLE: 原生模型投影不可用。')- const parsed = catalogSchema.safeParse(await waitFor(native.models(lifetime.signal), lifetime.signal))- assertLive(agent, lifetime)- if (!parsed.success)- throw new Error('BRIDGE_MODEL_CATALOG_INVALID: 本机内核返回了不完整的模型目录。')- const catalog = parsed.data- const ids = new Set<string>()- for (const entry of catalog.models) {- if (ids.has(entry.id))- throw new Error('BRIDGE_MODEL_CATALOG_INVALID: 本机模型目录包含重复标识。')- ids.add(entry.id)- const efforts = entry.reasoning?.efforts- if (efforts && (new Set(efforts.map(effort => effort.id)).size !== efforts.length || (entry.reasoning?.defaultEffort !== undefined && !efforts.some(effort => effort.id === entry.reasoning?.defaultEffort))))- throw new Error('BRIDGE_MODEL_CATALOG_INVALID: 本机模型的推理深度目录不一致。')- }- if (catalog.defaultModel !== undefined && !ids.has(catalog.defaultModel))- throw new Error('BRIDGE_MODEL_CATALOG_INVALID: 原生默认模型未包含在模型目录中。')- if (catalog.defaultReasoningEffort !== undefined && catalog.defaultModel === undefined)- throw new Error('BRIDGE_MODEL_CATALOG_INVALID: 原生默认推理深度未关联默认模型。')- return catalog-}--function assertSelection(catalog: NativeModelCatalog, options: NativeTurnOptions): void {- const id = options.model ?? catalog.defaultModel- const entry = catalog.models.find(item => item.id === id)- if (options.model !== null && entry === undefined)- throw new Error('BRIDGE_MODEL_UNAVAILABLE: 请选择当前原生内核支持的模型。')- if (options.reasoningEffort !== null && !entry?.reasoning?.efforts.some(effort => effort.id === options.reasoningEffort))- throw new Error('BRIDGE_REASONING_UNAVAILABLE: 当前原生模型不支持该推理深度。')-}--function sameOptions(left: NativeTurnOptions, right: NativeTurnOptions): boolean {- return left.model === right.model && left.reasoningEffort === right.reasoningEffort-}--function assertLive(agent: Agent, lifetime: AbortController): void {- lifetime.signal.throwIfAborted()- const ctx = getServerContext<HostContext>(server)- if (!runtime.ready || runtime.lifetime !== lifetime || ctx.agents.get(agent.id) !== agent || ctx.sessions.get(agent.id) !== agent.session)- throw new Error('BRIDGE_AGENT_REPLACED: 原生会话已关闭或被替换。')-}diff --git a/packages/dsh-tauri-kernel/src/host/service/session.test.ts b/packages/dsh-tauri-kernel/src/host/service/session.test.tsdeleted file mode 100644index ffe6a1a4..00000000--- a/packages/dsh-tauri-kernel/src/host/service/session.test.ts+++ /dev/null@@ -1,1869 +0,0 @@-import type { Agent, AgentHandle, AgentSetup, AssistantStreamFrame } from '@deepseek-ai/dsh-agent'-import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'-import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'-import type { SessionHandle } from '@deepseek-ai/dsh-session-persistence'-import type { ToolDefinition } from '@deepseek-ai/dsh-tools'-import type { NativeSession } from '../backends/types'-import type { HostContext, PlatformLoader } from '../types'-import type { DetectedCommand } from '../utils/detection'-import { createRequire } from 'node:module'-import { join } from 'node:path'-import process from 'node:process'-import { pathToFileURL } from 'node:url'-import { Context } from '@deepseek-ai/cordis'-import { AgentRegistry } from '@deepseek-ai/dsh-agent'-import { AgentLoop } from '@deepseek-ai/dsh-agent-loop'-import * as llmModule from '@deepseek-ai/dsh-llm'-import { PermissionPresetService } from '@deepseek-ai/dsh-permission-presets'-import * as sessionModule from '@deepseek-ai/dsh-session'-import { assertContiguous, materializeAppendBatch, materializeCreateHeader, SessionPersistence, SessionPersistenceRevision, validateStoredEvents } from '@deepseek-ai/dsh-session-persistence'-import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'-import { ToolRuntime } from '@deepseek-ai/dsh-tools'-import { ApprovalService } from '@deepseek-ai/dsh-user-approval'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import * as zodModule from 'zod'-import { apply } from '../apply'-import { createClaudeSession } from '../backends/claude'-import { createCodexSession } from '../backends/codex'-import { BRIDGE_PROVIDER, SESSION_TITLE_PURPOSE } from '../config/constants'-import { resetRuntime, runtime } from '../config/runtime'-import { detectBackend } from '../utils/detection'-import { adapter } from './adapter'-import { identity } from './identity'-import { session } from './session'--vi.mock('../utils/detection', () => ({ detectBackend: vi.fn() }))-vi.mock('../backends/codex', () => ({ createCodexSession: vi.fn() }))-vi.mock('../backends/claude', () => ({ createClaudeSession: vi.fn() }))--const require = createRequire(import.meta.url)-const coreRequire = createRequire(require.resolve('@deepseek-ai/dsh-agent-loop'))-const { sessionFormatCatalog } = await import(pathToFileURL(coreRequire.resolve('@deepseek-ai/dsh-session-format-catalog')).href)-const { SessionQueryEngine } = await import(pathToFileURL(coreRequire.resolve('@deepseek-ai/dsh-session-query')).href)-const controllerEntry = pathToFileURL(require.resolve('@deepseek-ai/dsh-api-session-controller'))-const { ApiSessionAgentController } = await import(new URL('./types/agent.js', controllerEntry).href)-const { installModelSelectionProjection } = await import(new URL('./types/model-selection-projection.js', controllerEntry).href)-const promptModule: { SystemPrompt: new (ctx: Context, config: { includeHarnessIdentity: boolean, includeRuntimeContext: boolean }) => Context['systemPrompt'] } = await import(pathToFileURL(coreRequire.resolve('@deepseek-ai/dsh-system-prompt')).href)-const cwd = process.cwd()-const now = 1_791_576_000_000--class MemoryPersistence extends SessionPersistence {- readonly stored = new Map<Session['id'], { header: Session['header'], inheritedEventCount: Session['inheritedEventCount'], events: readonly SessionEvent[], durable: readonly SessionEvent[], owner?: symbol }>()- readonly writers = new Map<Session['id'], SessionHandle>()- barrier: () => Promise<void> = async () => {}-- async create(header: Session['header'], options?: { inheritedEventCount?: Session['inheritedEventCount'], signal?: AbortSignal }): Promise<SessionHandle> {- options?.signal?.throwIfAborted()- if (this.stored.has(header.id))- throw new Error('worktree memory session already exists')- this.stored.set(header.id, { header: materializeCreateHeader(header), inheritedEventCount: options?.inheritedEventCount ?? sessionModule.SessionLogOffset(0), events: [], durable: [] })- return this.open(header.id, 'write', options)- }-- async open(id: Session['id'], access: SessionHandle['access'], options?: { signal?: AbortSignal }): Promise<SessionHandle> {- options?.signal?.throwIfAborted()- const stored = this.stored.get(id)- if (!stored || (access === 'write' && stored.owner !== undefined))- throw new Error('worktree memory session unavailable')- const owner = Symbol(id)- if (access === 'write')- stored.owner = owner- let closed = false- const active = () => {- if (closed || (access === 'write' && stored.owner !== owner))- throw new Error('worktree memory session owner closed')- }- const flush = async () => {- active()- if (access !== 'write')- throw new Error('worktree memory session is read-only')- await this.barrier()- stored.durable = validateStoredEvents(stored.header, structuredClone([...stored.events]))- }- const close = async () => {- if (closed)- return- if (access === 'write') {- await flush()- delete stored.owner- this.writers.delete(id)- }- closed = true- }- const handle: SessionHandle = {- id,- header: stored.header,- inheritedEventCount: stored.inheritedEventCount,- access,- async read(offset = 0, length, readOptions) {- active()- readOptions?.signal?.throwIfAborted()- return { events: validateStoredEvents(stored.header, structuredClone(stored.events.slice(offset, length === undefined ? undefined : offset + length))), eventState: 'shared-frozen' }- },- async append(events, appendOptions) {- active()- appendOptions?.signal?.throwIfAborted()- if (access !== 'write')- throw new Error('worktree memory session is read-only')- const batch = materializeAppendBatch(events)- assertContiguous(id, batch, stored.events.length)- stored.events = [...stored.events, ...batch]- },- async flush(flushOptions) {- flushOptions?.signal?.throwIfAborted()- await flush()- },- close,- [Symbol.asyncDispose]: close,- }- if (access === 'write')- this.writers.set(id, handle)- return handle- }-- async flush(): Promise<void> {- await Promise.all([...this.writers.values()].map(handle => handle.flush()))- }-- async stat(id: Session['id']) {- const stored = this.stored.get(id)- return stored === undefined ? undefined : { header: stored.header, eventCount: stored.events.length, revision: SessionPersistenceRevision(`${id}:${stored.events.length}`) }- }-- async list() {- return Promise.all([...this.stored.keys()].map(async id => (await this.stat(id))!))- }-}--function deferred<T>() {- let resolve!: (value: T | PromiseLike<T>) => void- const promise = new Promise<T>((accept) => {- resolve = accept- })- return { promise, resolve }-}--function native(id: string) {- return { id, submit: vi.fn<NativeSession['submit']>().mockResolvedValue(undefined), dispose: vi.fn<NativeSession['dispose']>().mockResolvedValue(undefined) }-}--let context: Context-let agents: AgentRegistry-let sessions: InstanceType<typeof sessionModule.SessionStore>-let projections: SessionProjectionRegistry-let prepared: Session[]-let announced: Agent[]-let errors: unknown[]-let releases: Array<() => void>-let background: Promise<unknown>[]-let mount: ReturnType<typeof vi.fn>-let attachSession: ReturnType<typeof vi.fn>-let officialHandle: AgentHandle | undefined-let disposeLoop: () => Promise<void>-let createAgent: AgentRegistry['create']-let persistence: MemoryPersistence | undefined--beforeEach(async () => {- await resetRuntime()- vi.mocked(createCodexSession).mockReset()- vi.mocked(createClaudeSession).mockReset()- vi.mocked(detectBackend).mockReset()- vi.mocked(detectBackend).mockImplementation(async (id): Promise<DetectedCommand> => ({- detection: { id, installed: true, auth: 'ok', version: 'test', drift: false, hint: null },- command: { file: 'boundary-only', args: [id] },- }))- context = new Context()- agents = new AgentRegistry(context)- sessions = new sessionModule.SessionStore(context)- projections = new SessionProjectionRegistry(context)- const llm = new llmModule.LlmRuntime(context)- expect(llm.listProviders()).toEqual([])- releases = []- background = []- prepared = []- announced = []- errors = []- officialHandle = undefined- persistence = undefined- const prepare = sessions.prepare.bind(sessions)- vi.spyOn(sessions, 'prepare').mockImplementation((...args) => {- const official = prepare(...args)- prepared.push(official)- return official- })- context.on('agent/created', ({ agent }) => {- announced.push(agent)- return undefined- })- context.on('agent/error', ({ error }) => {- errors.push(error)- })- createAgent = agents.create.bind(agents)- vi.spyOn(agents, 'create').mockImplementation(async (...args) => {- officialHandle = await createAgent(...args)- return officialHandle- })- const prompt = new promptModule.SystemPrompt(context, { includeHarnessIdentity: false, includeRuntimeContext: false })- const tools = new ToolRuntime(context, { mode: 'native' })- expect(await prompt.assemble({})).toMatchObject({ tools: [] })- expect(tools.schemas()).toEqual([])- const routes = new Map<string, WebRoute>()- context.provide('webServer', {- register(route: WebRoute) {- routes.set(route.path, route)- return () => routes.delete(route.path)- },- } as unknown as HostContext['webServer'])- const loader: PlatformLoader = {- async import(id) {- if (id === '@deepseek-ai/dsh-session')- return sessionModule- if (id === 'zod')- return zodModule- if (id === '@deepseek-ai/dsh-llm')- return llmModule- throw new Error(`unexpected module: ${id}`)- },- unwrapExports: value => value,- }- context.provide('loader', loader as HostContext['loader'])- mount = vi.fn().mockResolvedValue(undefined)- context.provide('agentPresets', {- resolve: vi.fn().mockResolvedValue({ id: 'test-preset' }),- mount,- } as unknown as HostContext['agentPresets'])- attachSession = vi.fn().mockResolvedValue(undefined)- context.provide('workspaceRegistry', {- get: vi.fn(id => id === 'test-workspace' ? { id, path: cwd, attachSession } : undefined),- } as unknown as HostContext['workspaceRegistry'])- const loop = context.plugin(AgentLoop, { agents: [] })- disposeLoop = () => loop.dispose()- await loop.await()- context.plugin((ctx) => {- apply(ctx as HostContext)- })- await vi.waitFor(() => expect(runtime.ready).toBe(true))-})--afterEach(async () => {- for (const release of releases)- release()- await Promise.allSettled(background)- if (persistence)- persistence.barrier = async () => {}- await session.dispose()- await context.fiber.dispose()- await resetRuntime()- vi.restoreAllMocks()- vi.useRealTimers()-})--function creating(id: 'codex' | 'claude' = 'codex', workspace?: string) {- const task = workspace === undefined ? session.create(id, undefined, cwd) : session.create(id, workspace)- const observed = task.then(value => ({ value, error: undefined }), error => ({ value: undefined, error }))- background.push(observed)- return task-}--function followup(agent: Agent, text: string) {- agent.followup(llmModule.createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text }] }))- const idle = agent.whenIdle()- background.push(idle)- return idle-}--function restoreSerialized(official: Session) {- const text = [- sessionFormatCatalog.encodeCurrentHeader({ ...official.header, delegationDepth: official.header.delegationDepth ?? 0 }, official.inheritedEventCount),- ...official.snapshotEvents().map(event => sessionFormatCatalog.encodeCurrentEvent(event)),- ].map(row => JSON.stringify(row)).join('\n')- const [header, ...events] = text.split('\n').map(row => JSON.parse(row))- const restore = sessionFormatCatalog.createRestore(header, { recovery: 'strict', validation: 'current' })- for (const event of events)- restore.decodeRow(event)- const stored = restore.finish()- const restored = sessionModule.Session.fromRestore(sessionModule.SessionId(stored.header.id), stored.events, stored.header, sessionModule.SessionLogOffset(stored.inheritedEventCount), 'detached')- expect(restored.header).toEqual({ ...official.header, delegationDepth: official.header.delegationDepth ?? 0 })- expect(restored.inheritedEventCount).toBe(official.inheritedEventCount)- expect(restored.snapshotEvents().slice(0, stored.events.length)).toEqual(official.snapshotEvents())- expect(restored.requestHeader()).toEqual(official.requestHeader())- expect(restored.deriveMessages()).toEqual(official.deriveMessages())- return restored-}--function records(official: Session) {- return official.snapshotEvents().flatMap((event) => {- const record = sessionModule.pluginRecordOf!(event)- return record === undefined ? [] : [record]- })-}--async function conversation(id: 'codex' | 'claude' = 'codex') {- const connection = native(`worktree-parent-${id}`)- vi.mocked(id === 'codex' ? createCodexSession : createClaudeSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => output.assistant('worktree-source-answer', [{ type: 'text', text: 'source conversation already settled' }]))- return connection- })- await creating(id)- const handle = officialHandle!- await followup(handle.agent, 'create the worktree from this real human conversation')- expect(handle.agent.session.deriveMessages().map(message => ({ role: message.role, content: message.content }))).toEqual([- { role: 'user', content: [{ type: 'text', text: 'create the worktree from this real human conversation' }] },- { role: 'assistant', content: [{ type: 'text', text: 'source conversation already settled' }] },- ])- expect(connection.submit).toHaveBeenCalledOnce()- return { handle, connection }-}--function fork(source: Agent, target: string, signal = new AbortController().signal, setup?: AgentSetup) {- const task = context.nativeSessionBridge.create(source.session, (sourceSignal) => {- const scoped = sourceSignal === undefined ? signal : AbortSignal.any([signal, sourceSignal])- const seed = source.session.snapshotEvents()- return agents.create({- sessionId: sessionModule.SessionId(target),- seed,- inheritedEventCount: sessionModule.SessionLogOffset(seed.length),- meta: { cwd, parentSession: source.id, isSeeded: true },- agentOptions: source.options,- signal: scoped,- async setup(agentCtx, child) {- const startup = new AbortController()- agentCtx.effect(() => () => startup.abort(new Error('worktree test setup disposed')))- const commit = await context.nativeSessionBridge.prepare(source.session, child, AbortSignal.any([scoped, startup.signal]))- await setup?.(agentCtx, child)- return commit- },- })- })- background.push(task.then(value => ({ value }), error => ({ error })))- return task-}--function observe(agent: Agent) {- const events: SessionEvent[] = []- const frames: AssistantStreamFrame[] = []- const endEvents: Array<SessionEvent | undefined> = []- agent.ctx.on('session/event', (official, event) => {- if (official === agent.session)- events.push(event)- })- agent.ctx.on('agent/assistant-stream', ({ frame }) => {- frames.push(frame)- if (frame.type === 'end' && frame.outcome.kind === 'committed') {- const seq = frame.outcome.seq- endEvents.push(events.find(event => event.seq === seq))- }- })- return { events, frames, endEvents }-}--describe('native session title requests', () => {- it('still rejects non-title auxiliary requests before opening a native session', async () => {- const connection = native('auxiliary-owner')- vi.mocked(createCodexSession).mockResolvedValueOnce(connection)- await creating()- const agent = officialHandle!.agent- const signal = new AbortController().signal- const call = await context.llm.prepareCall({ provider: BRIDGE_PROVIDER, model: 'codex' }, signal)- const request = async () => {- for await (const chunk of call.stream({ ...call.config, messages: [], purpose: 'compaction', sessionId: agent.id, signal }))- expect.fail(`unexpected auxiliary chunk: ${JSON.stringify(chunk)}`)- }- await expect(request()).rejects.toThrow('BRIDGE_AUXILIARY_REQUEST')- expect(createCodexSession).toHaveBeenCalledOnce()- expect(connection.submit).not.toHaveBeenCalled()- })-- it.each(['codex', 'claude'] as const)('routes %s titles to the default model without opening another native session', async (id) => {- const connection = native(`conversation-${id}`)- const factory = vi.mocked(id === 'codex' ? createCodexSession : createClaudeSession)- factory.mockResolvedValueOnce(connection)- await creating(id)- const agent = officialHandle!.agent- const before = agent.session.snapshotEvents()- const requests: llmModule.GenerateOptions[] = []- class TitleAdapter extends llmModule.LlmAdapter {- async* stream(options: llmModule.GenerateOptions): AsyncIterable<llmModule.StreamChunk> {- requests.push(options)- yield { type: 'block-start', index: 0, blockType: 'text' }- yield { type: 'text-delta', index: 0, text: '修复会话标题' }- yield { type: 'block-end', index: 0, block: { type: 'text', text: '修复会话标题' } }- yield { type: 'finish', reason: { kind: 'stop' } }- }- }- context.llm.registerAdapter(['title-provider'], new TitleAdapter())- context.provide('agentDefaultModel', { currentSelection: () => ({ provider: 'title-provider', model: 'title-model' }) } as HostContext['agentDefaultModel'])- const controller = new AbortController()- const signal = controller.signal- const call = await context.llm.prepareCall({ provider: BRIDGE_PROVIDER, model: id, maxTokens: 64 }, signal)- const input: llmModule.GenerateOptions = {- ...call.config,- messages: [llmModule.createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'name this session' }] })],- system: 'Return only a short title.',- purpose: SESSION_TITLE_PURPOSE,- sessionId: agent.id,- signal,- }- const assembler = new llmModule.BlockAssembler()- for await (const chunk of call.stream(input))- assembler.push(chunk)- expect(assembler.blocks()).toEqual([{ type: 'text', text: '修复会话标题' }])- expect(assembler.finish).toEqual({ kind: 'stop' })- expect(requests).toHaveLength(1)- expect(requests[0]).toMatchObject({ ...input, provider: 'title-provider', model: 'title-model', signal: expect.any(AbortSignal) })- expect(factory).toHaveBeenCalledOnce()- expect(connection.submit).not.toHaveBeenCalled()- expect(agent.session.snapshotEvents()).toEqual(before)- expect(runtime.sessions.get(agent.id)!.session).toBe(connection)- controller.abort(new Error('cancel title'))- expect(requests[0]!.signal!.aborted).toBe(true)- expect(connection.dispose).not.toHaveBeenCalled()- })-- it.each([undefined, { provider: BRIDGE_PROVIDER, model: 'codex' }])('rejects unavailable or recursive default title routes: %j', async (route) => {- vi.mocked(createCodexSession).mockResolvedValueOnce(native('title-owner'))- await creating()- context.provide('agentDefaultModel', { currentSelection: () => route } as HostContext['agentDefaultModel'])- const signal = new AbortController().signal- const call = await context.llm.prepareCall({ provider: BRIDGE_PROVIDER, model: 'codex' }, signal)- const request = async () => {- for await (const chunk of call.stream({ ...call.config, messages: [], purpose: SESSION_TITLE_PURPOSE, sessionId: officialHandle!.agent.id, signal }))- expect.fail(`unexpected title chunk: ${JSON.stringify(chunk)}`)- }- await expect(request()).rejects.toThrow('BRIDGE_TITLE_MODEL_UNAVAILABLE')- expect(createCodexSession).toHaveBeenCalledOnce()- })-})--describe('independent native worktree session setup', () => {- beforeEach(() => {- vi.setSystemTime(now)- persistence = new MemoryPersistence(context)- context.on('session/flush', async (official) => {- const stored = persistence!.stored.get(official.id)!- const writer = persistence!.writers.get(official.id)!- const suffix = official.snapshotEvents().slice(stored.events.length)- if (suffix.length > 0)- await writer.append(suffix)- await writer.flush()- })- })-- it.each(['codex', 'claude'] as const)('round-trips the official V4 serializer before and after the first %s worktree turn', async (id) => {- const { handle: parent, connection: original } = await conversation(id)- const prefix = parent.agent.session.snapshotEvents()- const connection = native(`serialized-worktree-child-${id}`)- const factory = vi.mocked(id === 'codex' ? createCodexSession : createClaudeSession)- factory.mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => output.assistant('serialized-worktree-answer', [{ type: 'text', text: 'independent serialized worktree reply' }]))- return connection- })- const child = await fork(parent.agent, `serialized-worktree-official-${id}`)- const cut = child.agent.session.inheritedEventCount- expect(() => restoreSerialized(child.agent.session)).not.toThrow()- expect(child.agent.session.snapshotEvents().slice(cut).map(event => event.type)).toEqual(['session/end-seed', 'plugin:dsh-tauri-kernel/kernel'])- expect(child.agent.session.requestHeader()).toEqual(parent.agent.session.requestHeader())- await followup(child.agent, 'persist the first independent worktree reply')- expect(errors).toEqual([])- expect(connection.submit).toHaveBeenCalledOnce()- expect(original.submit).toHaveBeenCalledOnce()- expect(parent.agent.session.snapshotEvents()).toEqual(prefix)- expect(child.agent.session.snapshotEvents().slice(cut).filter(event => event.type === 'request/header').map(event => event.data.reason)).toEqual(['resume'])- const restored = restoreSerialized(child.agent.session)- expect(records(restored)).toEqual(records(child.agent.session))- expect(restored.deriveMessages().map(message => ({ role: message.role, content: message.content }))).toEqual([- { role: 'user', content: [{ type: 'text', text: 'create the worktree from this real human conversation' }] },- { role: 'assistant', content: [{ type: 'text', text: 'source conversation already settled' }] },- { role: 'user', content: [{ type: 'text', text: 'persist the first independent worktree reply' }] },- { role: 'assistant', content: [{ type: 'text', text: 'independent serialized worktree reply' }] },- ])- }, 10_000)-- it.each(['codex', 'claude'] as const)('publishes a %s child only after a distinct native fork ACK and its own official identity commit', async (id) => {- const { handle: parent, connection: original } = await conversation(id)- const source = parent.agent.session- const prefix = source.snapshotEvents()- const cut = source.seq- const ack = deferred<NativeSession>()- const started = deferred<void>()- const childConnection = native(`worktree-child-${id}`)- releases.push(() => ack.resolve(childConnection))- const factory = vi.mocked(id === 'codex' ? createCodexSession : createClaudeSession)- factory.mockImplementationOnce(async () => {- started.resolve()- return ack.promise- })- const task = fork(parent.agent, `worktree-official-${id}`)- await started.promise- const child = prepared[1]!- expect(child.id).toBe(`worktree-official-${id}`)- expect(child.header).toMatchObject({ parentSession: source.id, isSeeded: true, cwd })- expect(child.inheritedEventCount).toBe(cut)- expect(child.snapshotEvents()).toEqual([...prefix, { seq: cut, time: now, type: 'session/end-seed', data: { inherited: true } }])- expect(projections.stateOf(child, 'bridgeKernel')).toEqual({- ownerSessionId: `worktree-official-${id}`,- inheritedEventCount: cut,- inheritedBinding: { backend: id, nativeSessionId: `worktree-parent-${id}`, sessionId: source.id },- binding: null,- })- expect(agents.get(child.id)).toBeUndefined()- expect(sessions.get(child.id)).toBeUndefined()- expect(announced).toEqual([parent.agent])- expect(factory).toHaveBeenCalledTimes(2)- expect(factory.mock.calls[1]![2]).toBeNull()- expect(factory.mock.calls[1]![5]).toEqual({ forkFrom: `worktree-parent-${id}` })- expect(childConnection.submit).not.toHaveBeenCalled()- ack.resolve(childConnection)- const owned = await task- expect(owned.agent.session).toBe(child)- expect(agents.get(child.id)).toBe(owned.agent)- expect(sessions.get(child.id)).toBe(child)- expect(announced).toEqual([parent.agent, owned.agent])- expect(child.snapshotEvents().slice(cut)).toEqual([- { seq: cut, time: now, type: 'session/end-seed', data: { inherited: true } },- { seq: cut + 1, time: now, type: 'plugin:dsh-tauri-kernel/kernel', ignorable: true, data: { backend: id, nativeSessionId: `worktree-child-${id}`, sessionId: `worktree-official-${id}` } },- ])- expect(identity.resolve(owned.agent)).toEqual({ backend: id, nativeSessionId: `worktree-child-${id}`, sessionId: `worktree-official-${id}` })- expect(identity.resolve(parent.agent)).toEqual({ backend: id, nativeSessionId: `worktree-parent-${id}`, sessionId: source.id })- expect(source.snapshotEvents()).toEqual(prefix)- expect(source.seq).toBe(cut)- expect(runtime.claims.get(`${id}:worktree-parent-${id}`)).toBe(source.id)- expect(runtime.claims.get(`${id}:worktree-child-${id}`)).toBe(`worktree-official-${id}`)- expect(original.submit).toHaveBeenCalledOnce()- expect(original.dispose).not.toHaveBeenCalled()- expect(childConnection.submit).not.toHaveBeenCalled()- expect(errors).toEqual([])- }, 10_000)-- it('submits the first published worktree prompt exactly once to the new identity through three official native steps', async () => {- const { handle: parent, connection: original } = await conversation()- const connection = native('worktree-three-step-child')- const next = deferred<void>()- const tail = deferred<void>()- const stepTwo = deferred<void>()- const stepThree = deferred<void>()- releases.push(() => next.resolve(), () => tail.resolve())- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => {- output.assistant('child-first', [{ type: 'tool-call', id: 'child-call-one', name: 'native_one', arguments: '{}' }])- output.toolStart('child-call-one', 'native_one', '{}')- output.toolEnd('child-call-one', 'first child result')- await next.promise- output.assistant('child-second', [{ type: 'tool-call', id: 'child-call-two', name: 'native_two', arguments: '{}' }])- output.toolStart('child-call-two', 'native_two', '{}')- output.toolEnd('child-call-two', 'second child result')- await tail.promise- output.assistant('child-final', [{ type: 'text', text: 'the independent worktree finished' }])- })- return connection- })- const child = await fork(parent.agent, 'worktree-three-step-official')- const { events } = observe(child.agent)- child.agent.ctx.on('session/event', (official, event) => {- if (official !== child.agent.session)- return- if (event.type === 'step/start' && event.data.step === 2)- stepTwo.resolve()- if (event.type === 'step/start' && event.data.step === 3)- stepThree.resolve()- })- const turn = followup(child.agent, 'first worktree prompt after setup publication')- await stepTwo.promise- expect(connection.submit).toHaveBeenCalledOnce()- next.resolve()- await stepThree.promise- expect(connection.submit).toHaveBeenCalledOnce()- tail.resolve()- await turn- expect(connection.submit).toHaveBeenCalledOnce()- expect(connection.submit.mock.calls[0]![0]).toMatchObject([{ source: { kind: 'user' }, content: [{ type: 'text', text: 'first worktree prompt after setup publication' }] }])- expect(connection.submit.mock.calls[0]![2]).toEqual({ model: null, reasoningEffort: null })- expect(events.filter(event => event.type === 'step/start').map(event => event.data)).toEqual([{ turn: 2, step: 1 }, { turn: 2, step: 2 }, { turn: 2, step: 3 }])- expect(events.filter(event => event.type === 'tool/call').map(event => event.data.callId)).toEqual(['child-call-one', 'child-call-two'])- expect(events.filter(event => event.type === 'tool/result').map(event => event.data.message.toolCallId)).toEqual(['child-call-one', 'child-call-two'])- expect(events.filter(event => event.type === 'turn/end').map(event => event.data)).toEqual([{ turn: 2, reason: { kind: 'completed' } }])- expect(identity.resolve(child.agent)).toEqual({ backend: 'codex', nativeSessionId: 'worktree-three-step-child', sessionId: 'worktree-three-step-official' })- expect(original.submit).toHaveBeenCalledOnce()- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(createClaudeSession).not.toHaveBeenCalled()- expect(errors).toEqual([])- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it('cold-restores only a child-owned native id without restoring or forking its parent again', async () => {- const { handle: parent, connection: original } = await conversation()- const childConnection = native('worktree-cold-child-native')- vi.mocked(createCodexSession).mockResolvedValueOnce(childConnection)- const child = await fork(parent.agent, 'worktree-cold-child-official')- const before = records(child.agent.session)- await child.dispose()- await session.remove(child.agent.id)- const open = vi.spyOn(persistence!, 'open')- const createStored = vi.spyOn(persistence!, 'create')- const restored = await agents.resume({ resumeSessionId: child.agent.id, agentOptions: { provider: 'dsh-tauri-kernel', model: 'codex' } })- const close = vi.spyOn(persistence!.writers.get(child.agent.id)!, 'close')- expect(open).toHaveBeenCalledExactlyOnceWith(child.agent.id, 'write', { signal: expect.any(AbortSignal) })- const resumed = native('worktree-cold-child-native')- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- resumed.submit.mockImplementation(async () => output.assistant('child-cold-answer', [{ type: 'text', text: 'only child history restored' }]))- return resumed- })- await followup(restored.agent, 'continue only the independent child history')- expect(open).toHaveBeenCalledTimes(2)- expect(open.mock.calls[1]).toEqual([child.agent.id, 'read', { signal: expect.any(AbortSignal) }])- expect(createStored).not.toHaveBeenCalled()- expect(createCodexSession).toHaveBeenCalledTimes(3)- expect(vi.mocked(createCodexSession).mock.calls[2]![2]).toBe('worktree-cold-child-native')- expect(vi.mocked(createCodexSession).mock.calls[2]![5]).toBeUndefined()- expect(resumed.submit).toHaveBeenCalledOnce()- expect(original.submit).toHaveBeenCalledOnce()- expect(original.dispose).not.toHaveBeenCalled()- expect(identity.resolve(restored.agent)).toEqual({ backend: 'codex', nativeSessionId: 'worktree-cold-child-native', sessionId: 'worktree-cold-child-official' })- expect(records(restored.agent.session)).toEqual(before)- expect(projections.stateOf(restored.agent.session, 'bridgeKernel')?.inheritedBinding).toEqual({ backend: 'codex', nativeSessionId: 'worktree-parent-codex', sessionId: parent.agent.id })- expect(errors).toEqual([])- await restored.dispose()- await session.remove(restored.agent.id)- expect(close).toHaveBeenCalledOnce()- expect(resumed.dispose).toHaveBeenCalledOnce()- }, 10_000)-- it.each([false, true])('rejects parent-id ACK without a fallback when parent native ownership was closed=%s', async (closed) => {- const { handle: parent, connection: original } = await conversation()- const prefix = parent.agent.session.snapshotEvents()- if (closed)- await session.remove(parent.agent.id)- const duplicate = native('worktree-parent-codex')- vi.mocked(createCodexSession).mockResolvedValueOnce(duplicate)- await expect(fork(parent.agent, 'worktree-invalid-same-id')).rejects.toThrow(closed ? 'BRIDGE_FORK_MISMATCH' : 'BRIDGE_NATIVE_OWNER_CONFLICT')- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(vi.mocked(createCodexSession).mock.calls[1]![2]).toBeNull()- expect(vi.mocked(createCodexSession).mock.calls[1]![5]).toEqual({ forkFrom: 'worktree-parent-codex' })- expect(createClaudeSession).not.toHaveBeenCalled()- expect(duplicate.dispose).toHaveBeenCalledOnce()- expect(duplicate.submit).not.toHaveBeenCalled()- expect(original.submit).toHaveBeenCalledOnce()- expect(agents.get(sessionModule.SessionId('worktree-invalid-same-id'))).toBeUndefined()- expect(sessions.get(sessionModule.SessionId('worktree-invalid-same-id'))).toBeUndefined()- expect(prepared[1]!.snapshotEvents()).toEqual([...prefix, { seq: prefix.length, time: now, type: 'session/end-seed', data: { inherited: true } }])- expect(announced).toEqual([parent.agent])- expect(identity.resolve(parent.agent)).toEqual({ backend: 'codex', nativeSessionId: 'worktree-parent-codex', sessionId: parent.agent.id })- }, 10_000)-- it('reports a native conversation that no longer exists instead of opening a replacement', async () => {- const { handle, connection } = await conversation()- await session.remove(handle.agent.id, handle.agent)- expect(connection.dispose).toHaveBeenCalledOnce()- vi.mocked(createCodexSession).mockRejectedValueOnce(new Error('["No conversation found with session ID: gone-native"]'))- await expect(session.connect(handle.agent, new AbortController().signal)).rejects.toThrow('BRIDGE_SESSION_UNRECOVERABLE: 原生会话记录已不存在,请新建会话。')- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(vi.mocked(createCodexSession).mock.calls[1]![2]).toBe('worktree-parent-codex')- expect(runtime.sessions.size).toBe(0)- }, 10_000)-- it('rolls back a rejected native fork without reusing or restoring the parent native session', async () => {- const { handle: parent, connection: original } = await conversation()- const prefix = parent.agent.session.snapshotEvents()- const failure = new Error('native fork refused the source conversation')- vi.mocked(createCodexSession).mockRejectedValueOnce(failure)- await expect(fork(parent.agent, 'worktree-refused')).rejects.toBe(failure)- expect(prepared[1]!.snapshotEvents()).toEqual([...prefix, { seq: prefix.length, time: now, type: 'session/end-seed', data: { inherited: true } }])- expect(agents.get(sessionModule.SessionId('worktree-refused'))).toBeUndefined()- expect(sessions.get(sessionModule.SessionId('worktree-refused'))).toBeUndefined()- expect(announced).toEqual([parent.agent])- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(vi.mocked(createCodexSession).mock.calls[1]![2]).toBeNull()- expect(vi.mocked(createCodexSession).mock.calls[1]![5]).toEqual({ forkFrom: 'worktree-parent-codex' })- expect(createClaudeSession).not.toHaveBeenCalled()- expect(original.dispose).not.toHaveBeenCalled()- expect(original.submit).toHaveBeenCalledOnce()- expect(runtime.sessions.size).toBe(1)- expect(runtime.claims.size).toBe(1)- }, 10_000)-- it('awaits native disposal when a later unpublished setup hook rejects after the independent ACK', async () => {- const { handle: parent, connection: original } = await conversation()- const connection = native('worktree-post-ack-failure')- const failure = new Error('later unpublished worktree setup refused')- vi.mocked(createCodexSession).mockResolvedValueOnce(connection)- await expect(fork(parent.agent, 'worktree-unpublished-failure', new AbortController().signal, async () => {- throw failure- })).rejects.toBe(failure)- expect(connection.dispose).toHaveBeenCalledOnce()- expect(connection.submit).not.toHaveBeenCalled()- expect(agents.get(sessionModule.SessionId('worktree-unpublished-failure'))).toBeUndefined()- expect(sessions.get(sessionModule.SessionId('worktree-unpublished-failure'))).toBeUndefined()- expect(runtime.claims.has('codex:worktree-post-ack-failure')).toBe(false)- expect(runtime.sessions.has('worktree-unpublished-failure')).toBe(false)- expect(announced).toEqual([parent.agent])- expect(original.dispose).not.toHaveBeenCalled()- expect(original.submit).toHaveBeenCalledOnce()- }, 10_000)-- it('does not publish a distinct native ACK when official storage rejects the child seed and setup suffix', async () => {- const { handle: parent, connection: original } = await conversation()- const connection = native('worktree-storage-failure')- const failure = new Error('official worktree append refused')- const close = vi.fn().mockResolvedValue(undefined)- const append = vi.fn().mockRejectedValue(failure)- const createStored = persistence!.create.bind(persistence!)- vi.spyOn(persistence!, 'create').mockImplementationOnce(async (...args) => {- const handle = await createStored(...args)- handle.append = append- vi.spyOn(handle, 'close').mockImplementation(async () => {- await close()- await handle[Symbol.asyncDispose]()- })- return handle- })- vi.mocked(createCodexSession).mockResolvedValueOnce(connection)- await expect(fork(parent.agent, 'worktree-storage-official')).rejects.toBe(failure)- expect(append).toHaveBeenCalledOnce()- expect(append.mock.calls[0]![0]).toEqual(prepared[1]!.snapshotEvents())- expect(close).toHaveBeenCalledOnce()- expect(connection.dispose).toHaveBeenCalledOnce()- expect(connection.submit).not.toHaveBeenCalled()- expect(agents.get(sessionModule.SessionId('worktree-storage-official'))).toBeUndefined()- expect(sessions.get(sessionModule.SessionId('worktree-storage-official'))).toBeUndefined()- expect(announced).toEqual([parent.agent])- expect(runtime.claims.has('codex:worktree-storage-failure')).toBe(false)- expect(original.dispose).not.toHaveBeenCalled()- expect(original.submit).toHaveBeenCalledOnce()- expect(createCodexSession).toHaveBeenCalledTimes(2)- }, 10_000)-- it('blocks the first published child prompt after its own binding checkpoint fails and retries without re-forking', async () => {- const { handle: parent, connection: original } = await conversation()- const connection = native('worktree-binding-checkpoint-native')- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => output.assistant('child-durable-answer', [{ type: 'text', text: 'the child-owned binding was saved' }]))- return connection- })- const child = await fork(parent.agent, 'worktree-binding-checkpoint-official')- const cut = child.agent.session.inheritedEventCount- const binding = { backend: 'codex', nativeSessionId: 'worktree-binding-checkpoint-native', sessionId: 'worktree-binding-checkpoint-official' }- const before = records(child.agent.session)- const failure = new Error('worktree own binding durability refused')- persistence!.barrier = async () => {- throw failure- }- await followup(child.agent, 'must not run without the saved child identity')- expect(connection.submit).not.toHaveBeenCalled()- expect(original.submit).toHaveBeenCalledOnce()- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(errors).toHaveLength(1)- expect(errors[0]).toMatchObject({ name: 'LlmError', code: 'UNKNOWN', message: 'worktree own binding durability refused', failure: { code: 'UNKNOWN', message: 'worktree own binding durability refused' } })- expect(persistence!.stored.get(child.agent.id)?.durable.some(event => event.seq === cut + 1)).toBe(false)- expect(identity.resolve(child.agent)).toEqual(binding)- expect(records(child.agent.session)).toEqual(before)- expect(runtime.exchanges.size).toBe(0)- persistence!.barrier = async () => {}- await followup(child.agent, 'run the same child once its identity is durable')- expect(connection.submit).toHaveBeenCalledOnce()- expect(connection.submit.mock.calls[0]![2]).toEqual({ model: null, reasoningEffort: null })- expect(original.submit).toHaveBeenCalledOnce()- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(vi.mocked(createCodexSession).mock.calls[1]![2]).toBeNull()- expect(vi.mocked(createCodexSession).mock.calls[1]![5]).toEqual({ forkFrom: 'worktree-parent-codex' })- expect(persistence!.stored.get(child.agent.id)?.durable.find(event => event.seq === cut + 1)).toEqual({ seq: cut + 1, time: now, type: 'plugin:dsh-tauri-kernel/kernel', ignorable: true, data: binding })- expect(records(child.agent.session)).toEqual(before)- expect(errors).toHaveLength(1)- expect(identity.resolve(parent.agent)).toEqual({ backend: 'codex', nativeSessionId: 'worktree-parent-codex', sessionId: parent.agent.id })- }, 10_000)-- it('aborts the whole unpublished factory after native ACK when bridge scope ends during a later setup hook', async () => {- const { handle: parent, connection: original } = await conversation()- const connection = native('worktree-whole-factory-aborted')- const setupStarted = deferred<void>()- const setupGate = deferred<void>()- const setupFinished = deferred<void>()- const drainStarted = deferred<void>()- const drain = deferred<void>()- releases.push(() => setupGate.resolve(), () => drain.resolve())- connection.dispose.mockImplementation(async () => {- drainStarted.resolve()- await drain.promise- })- vi.mocked(createCodexSession).mockResolvedValueOnce(connection)- const task = fork(parent.agent, 'worktree-whole-factory-official', new AbortController().signal, async () => {- setupStarted.resolve()- await setupGate.promise- setupFinished.resolve()- })- const rejected = expect(task).rejects.toThrow('BRIDGE_DISPOSED')- background.push(rejected)- let settled = false- const observed = task.then(() => {- settled = true- }, () => {- settled = true- })- background.push(observed)- await setupStarted.promise- const child = prepared[1]!- const before = child.snapshotEvents()- expect(agents.get(child.id)).toBeUndefined()- expect(sessions.get(child.id)).toBeUndefined()- expect(announced).toEqual([parent.agent])- const closing = session.dispose()- background.push(closing)- await drainStarted.promise- expect(settled).toBe(false)- expect(vi.mocked(createCodexSession).mock.calls[1]![4].aborted).toBe(true)- expect(connection.submit).not.toHaveBeenCalled()- setupGate.resolve()- await setupFinished.promise- expect(agents.get(child.id)).toBeUndefined()- expect(sessions.get(child.id)).toBeUndefined()- expect(child.snapshotEvents()).toEqual(before)- drain.resolve()- await Promise.all([rejected, observed, closing])- expect(connection.dispose).toHaveBeenCalledOnce()- expect(connection.submit).not.toHaveBeenCalled()- expect(announced).toEqual([parent.agent])- expect(runtime.sessions.has(child.id)).toBe(false)- expect(runtime.claims.has('codex:worktree-whole-factory-aborted')).toBe(false)- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(original.submit).toHaveBeenCalledOnce()- expect(errors).toEqual([])- }, 10_000)-- it('refuses a stale inherited cut before contacting the native fork boundary', async () => {- const { handle: parent } = await conversation()- const stale = parent.agent.session.snapshotEvents()- sessionModule.appendPluginRecord!(parent.agent.session, 'plugin:dsh-tauri-kernel/kernel', identity.resolve(parent.agent))- const task = context.nativeSessionBridge.create(parent.agent.session, () => agents.create({- sessionId: sessionModule.SessionId('worktree-stale-cut'),- seed: stale,- inheritedEventCount: sessionModule.SessionLogOffset(stale.length),- meta: { cwd, parentSession: parent.agent.id, isSeeded: true },- agentOptions: parent.agent.options,- setup: (_ctx, agent) => context.nativeSessionBridge.prepare(parent.agent.session, agent, new AbortController().signal),- }))- await expect(task).rejects.toThrow('BRIDGE_FORK_SOURCE_CHANGED')- expect(createCodexSession).toHaveBeenCalledOnce()- expect(createClaudeSession).not.toHaveBeenCalled()- expect(agents.get(sessionModule.SessionId('worktree-stale-cut'))).toBeUndefined()- expect(sessions.get(sessionModule.SessionId('worktree-stale-cut'))).toBeUndefined()- expect(announced).toEqual([parent.agent])- }, 10_000)-- it('refuses a parent changed during native fork instead of silently inheriting a newer history', async () => {- const { handle: parent, connection: original } = await conversation()- const ack = deferred<NativeSession>()- const started = deferred<void>()- const connection = native('worktree-raced-source')- releases.push(() => ack.resolve(connection))- vi.mocked(createCodexSession).mockImplementationOnce(async () => {- started.resolve()- return ack.promise- })- const task = fork(parent.agent, 'worktree-raced-official')- const rejected = expect(task).rejects.toThrow('BRIDGE_FORK_SOURCE_CHANGED')- background.push(rejected)- await started.promise- sessionModule.appendPluginRecord!(parent.agent.session, 'plugin:dsh-tauri-kernel/kernel', identity.resolve(parent.agent))- ack.resolve(connection)- await rejected- expect(connection.dispose).toHaveBeenCalledOnce()- expect(connection.submit).not.toHaveBeenCalled()- expect(prepared[1]!.snapshotEvents().slice(prepared[1]!.inheritedEventCount)).toEqual([{ seq: prepared[1]!.inheritedEventCount, time: now, type: 'session/end-seed', data: { inherited: true } }])- expect(agents.get(sessionModule.SessionId('worktree-raced-official'))).toBeUndefined()- expect(sessions.get(sessionModule.SessionId('worktree-raced-official'))).toBeUndefined()- expect(original.dispose).not.toHaveBeenCalled()- expect(original.submit).toHaveBeenCalledOnce()- expect(createCodexSession).toHaveBeenCalledTimes(2)- }, 10_000)-- it.each(['cancel', 'unload'] as const)('aborts an unpublished worktree fork on %s and awaits disposal of a late distinct ACK', async (reason) => {- const { handle: parent, connection: original } = await conversation()- const ack = deferred<NativeSession>()- const started = deferred<void>()- const drain = deferred<void>()- const drainStarted = deferred<void>()- const connection = native(`worktree-late-${reason}`)- const controller = new AbortController()- releases.push(() => ack.resolve(connection), () => drain.resolve())- vi.mocked(createCodexSession).mockImplementationOnce(async () => {- started.resolve()- return ack.promise- })- connection.dispose.mockImplementation(async () => {- drainStarted.resolve()- await drain.promise- })- const task = fork(parent.agent, `worktree-late-official-${reason}`, controller.signal)- const rejected = expect(task).rejects.toThrow(reason === 'cancel' ? 'worktree creation cancelled' : 'BRIDGE_DISPOSED')- background.push(rejected)- await started.promise- const child = prepared[1]!- let settled = false- const observed = task.then(() => {- settled = true- }, () => {- settled = true- })- background.push(observed)- let closing: Promise<void> | undefined- if (reason === 'cancel') {- controller.abort(new Error('worktree creation cancelled'))- }- else {- closing = session.dispose()- background.push(closing)- }- expect(vi.mocked(createCodexSession).mock.calls[1]![4].aborted).toBe(true)- expect(agents.get(child.id)).toBeUndefined()- expect(sessions.get(child.id)).toBeUndefined()- ack.resolve(connection)- await drainStarted.promise- expect(settled).toBe(false)- expect(connection.submit).not.toHaveBeenCalled()- expect(child.snapshotEvents().slice(child.inheritedEventCount)).toEqual([{ seq: child.inheritedEventCount, time: now, type: 'session/end-seed', data: { inherited: true } }])- drain.resolve()- await Promise.all([rejected, observed, closing])- expect(connection.dispose).toHaveBeenCalledOnce()- expect(connection.submit).not.toHaveBeenCalled()- expect(original.submit).toHaveBeenCalledOnce()- expect(announced).toEqual([parent.agent])- expect(runtime.pending.size).toBe(0)- expect(runtime.sessions.has(child.id)).toBe(false)- expect(runtime.claims.has(`codex:worktree-late-${reason}`)).toBe(false)- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(createClaudeSession).not.toHaveBeenCalled()- }, 10_000)-})--describe('official cold native route restoration', () => {- let controller: InstanceType<typeof ApiSessionAgentController>- let query: InstanceType<typeof SessionQueryEngine>- const defaultSelection = { provider: 'cloud-provider', model: 'global-default' }-- beforeEach(() => {- persistence = new MemoryPersistence(context)- context.on('session/flush', async (official) => {- const stored = persistence!.stored.get(official.id)!- const writer = persistence!.writers.get(official.id)!- const suffix = official.snapshotEvents().slice(stored.events.length)- if (suffix.length > 0)- await writer.append(suffix)- await writer.flush()- })- installModelSelectionProjection(context)- context.provide('agentDefaultModel', { currentSelection: () => defaultSelection } as HostContext['agentDefaultModel'])- context.provide('typert', {- lookups: { configure: vi.fn() },- contexts: { configureHost: vi.fn() },- } as unknown as HostContext['typert'])- query = new SessionQueryEngine(context)- controller = new ApiSessionAgentController(context)- context.provide('sessionController', { resolveAgent: controller.resolveAgent.bind(controller) } as HostContext['sessionController'])- })-- it.each(['codex', 'claude'] as const)('restores the first %s cold request through the real API controller without a setup header', async (id) => {- const factory = vi.mocked(id === 'codex' ? createCodexSession : createClaudeSession)- const original = native(`api-cold-${id}`)- factory.mockResolvedValueOnce(original)- await creating(id)- const previous = officialHandle!- const before = restoreSerialized(previous.agent.session)- const binding = { backend: id, nativeSessionId: original.id, sessionId: previous.agent.id }- expect(before.requestHeader()).toBeUndefined()- await previous.dispose()- await session.remove(previous.agent.id)- expect(sessions.get(previous.agent.id)).toBeUndefined()- expect(agents.get(previous.agent.id)).toBeUndefined()- const observed = await query.observeSession(previous.agent.id)- expect(observed.header.id).toBe(previous.agent.id)- expect(observed.events).toEqual(previous.agent.session.snapshotEvents())- observed[Symbol.dispose]()- const found = await controller.resolveAgent(previous.agent.id)- expect(found).not.toHaveProperty('error')- if ('error' in found)- throw found.error- const restored = found.agent- expect(restored.session.requestHeader()).toBeUndefined()- expect(identity.resolve(restored)).toEqual(binding)- expect(factory).toHaveBeenCalledOnce()- expect(restored.session.requestHeader()).toBeUndefined()- const resumed = native(original.id)- factory.mockImplementationOnce(async (_command, _cwd, storedId, output) => {- expect(storedId).toBe(original.id)- resumed.submit.mockImplementation(async () => output.assistant('api-cold-answer', [{ type: 'text', text: 'the bound native session continued' }]))- return resumed- })- await followup(restored, 'continue the cold native session')- expect(errors).toEqual([])- expect(restored.options).toMatchObject({ provider: BRIDGE_PROVIDER, model: id })- expect(factory).toHaveBeenCalledTimes(2)- expect(resumed.submit).toHaveBeenCalledOnce()- expect(resumed.submit.mock.calls[0]![2]).toEqual({ model: null, reasoningEffort: null })- const replayed = restoreSerialized(restored.session)- expect(replayed.requestHeader()?.config).toEqual({ provider: BRIDGE_PROVIDER, model: id })- expect(replayed.snapshotEvents().filter(event => event.type === 'request/header').map(event => event.data.reason)).toEqual(['initial'])- expect(records(replayed)).toEqual(records(before))- expect(replayed.deriveMessages().map(message => ({ role: message.role, content: message.content }))).toEqual([- { role: 'user', content: [{ type: 'text', text: 'continue the cold native session' }] },- { role: 'assistant', content: [{ type: 'text', text: 'the bound native session continued' }] },- ])- }, 10_000)-- it('rejects a bound-session kernel switch before its first request', async () => {- const original = native('api-cold-selected')- vi.mocked(createCodexSession).mockResolvedValueOnce(original)- await creating()- const previous = officialHandle!- await previous.dispose()- await session.remove(previous.agent.id)- const found = await controller.resolveAgent(previous.agent.id)- expect(found).not.toHaveProperty('error')- if ('error' in found)- throw found.error- const selected = { provider: BRIDGE_PROVIDER, model: 'claude' }- controller.selectForNextRequest(found.agent, selected)- await followup(found.agent, 'reject switching the bound native kernel')- expect(errors).toEqual([expect.objectContaining({ message: expect.stringContaining('BRIDGE_KERNEL_IMMUTABLE') })])- expect(createCodexSession).toHaveBeenCalledOnce()- expect(createClaudeSession).not.toHaveBeenCalled()- expect(original.submit).not.toHaveBeenCalled()- expect(found.agent.session.requestHeader()).toBeUndefined()- expect(found.agent.session.snapshotEvents().filter((event: SessionEvent) => event.type === 'model/selection').map((event: SessionEvent) => event.data)).toEqual([selected])- expect(identity.resolve(found.agent)).toEqual({ backend: 'codex', nativeSessionId: original.id, sessionId: previous.agent.id })- expect(() => restoreSerialized(found.agent.session)).not.toThrow()- }, 10_000)-- it('keeps the bound kernel when a created session still receives the deployment default route', async () => {- const original = native('api-created-default-route')- vi.mocked(createCodexSession).mockResolvedValueOnce(original)- await creating()- const agent = officialHandle!.agent- const started = deferred<AbortSignal>()- const gate = deferred<void>()- releases.push(() => gate.resolve())- context.on('agent/pre-step', async ({ signal }) => {- started.resolve(signal)- await gate.promise- return { kind: 'reject' }- }, { global: true, prepend: true })- const turn = followup(agent, 'keep the kernel the session was created with')- const signal = await started.promise- await expect(adapter.request({ agent, signal }, async () => defaultSelection)).resolves.toEqual({ provider: BRIDGE_PROVIDER, model: 'codex' })- expect(identity.resolve(agent)).toEqual({ backend: 'codex', nativeSessionId: original.id, sessionId: agent.id })- gate.resolve()- await turn- expect(errors).toEqual([])- }, 10_000)-- it('drops a DSH reasoning effort on the bound native route instead of failing the first turn', async () => {- const original = native('api-native-effort')- const resumed = native(original.id)- vi.mocked(createCodexSession).mockResolvedValueOnce(original).mockResolvedValueOnce(resumed)- await creating()- const previous = officialHandle!- await previous.dispose()- await session.remove(previous.agent.id)- const found = await controller.resolveAgent(previous.agent.id)- expect(found).not.toHaveProperty('error')- if ('error' in found)- throw found.error- const selected = { provider: BRIDGE_PROVIDER, model: 'codex', reasoningEffort: llmModule.ReasoningEffortId('high') }- controller.selectForNextRequest(found.agent, selected)- await followup(found.agent, 'keep the native kernel while DSH proposes an effort')- expect(errors).toEqual([])- expect(resumed.submit).toHaveBeenCalledOnce()- expect(resumed.submit.mock.calls[0]![2]).toEqual({ model: null, reasoningEffort: null })- expect(found.agent.session.requestHeader()?.config).toEqual({ provider: BRIDGE_PROVIDER, model: 'codex' })- expect(found.agent.session.snapshotEvents().filter((event: SessionEvent) => event.type === 'model/selection').map((event: SessionEvent) => event.data)).toEqual([selected])- expect(identity.resolve(found.agent)).toEqual({ backend: 'codex', nativeSessionId: original.id, sessionId: previous.agent.id })- expect(() => restoreSerialized(found.agent.session)).not.toThrow()- }, 10_000)-- it.each([- { provider: 'foreign-provider', model: 'global-default' },- { provider: 'cloud-provider', model: 'foreign-model' },- { provider: 'cloud-provider', model: 'global-default', reasoningEffort: llmModule.ReasoningEffortId('high') },- { provider: 'cloud-provider', model: 'global-default', maxTokens: 1 },- { provider: 'cloud-provider', model: 'global-default', temperature: 0 },- { provider: 'cloud-provider', model: 'global-default', stop: ['stop'] },- ])('rejects nondefault cold request overrides without a native submission: %j', async (override) => {- const original = native('api-cold-overrides')- vi.mocked(createCodexSession).mockResolvedValueOnce(original)- await creating()- const previous = officialHandle!- await previous.dispose()- await session.remove(previous.agent.id)- const found = await controller.resolveAgent(previous.agent.id)- expect(found).not.toHaveProperty('error')- if ('error' in found)- throw found.error- const started = deferred<AbortSignal>()- const gate = deferred<void>()- releases.push(() => gate.resolve())- context.on('agent/pre-step', async ({ signal }) => {- started.resolve(signal)- await gate.promise- return { kind: 'reject' }- }, { global: true, prepend: true })- const turn = followup(found.agent, 'reject overriding native options during cold resume')- const signal = await started.promise- await expect(adapter.request({ agent: found.agent, signal }, async () => override)).rejects.toThrow(expect.objectContaining({ message: expect.stringContaining(`BRIDGE_KERNEL_IMMUTABLE: 已绑定会话不能切换内核或由 DSH 覆写原生选项(请求 ${override.provider}/${override.model},当前内核 codex)。`) }))- expect(createCodexSession).toHaveBeenCalledOnce()- expect(original.submit).not.toHaveBeenCalled()- expect(found.agent.session.requestHeader()).toBeUndefined()- expect(identity.resolve(found.agent)).toEqual({ backend: 'codex', nativeSessionId: original.id, sessionId: previous.agent.id })- gate.resolve()- await turn- expect(errors).toEqual([])- expect(() => restoreSerialized(found.agent.session)).not.toThrow()- }, 10_000)-- it.each(['codex', 'claude'] as const)('hydrates an empty %s worktree route from its committed child binding', async (id) => {- const factory = vi.mocked(id === 'codex' ? createCodexSession : createClaudeSession)- const original = native(`api-empty-parent-${id}`)- factory.mockResolvedValueOnce(original)- await creating(id)- const previous = officialHandle!- await previous.dispose()- await session.remove(previous.agent.id)- const found = await controller.resolveAgent(previous.agent.id)- expect(found).not.toHaveProperty('error')- if ('error' in found)- throw found.error- const source = found.agent.session- const connection = native(`api-empty-child-${id}`)- factory.mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => output.assistant('api-empty-child-answer', [{ type: 'text', text: 'the independent empty-source worktree continued' }]))- return connection- })- const child = await context.nativeSessionBridge.create(source, signal => agents.create({- sessionId: sessionModule.SessionId(`api-empty-child-official-${id}`),- seed: source.snapshotEvents(),- inheritedEventCount: source.seq,- meta: { cwd, parentSession: source.id, isSeeded: true },- agentOptions: {},- signal,- setup: (_agentCtx, agent) => context.nativeSessionBridge.prepare(source, agent, signal!),- }))- expect(identity.resolve(child.agent)).toEqual({ backend: id, nativeSessionId: connection.id, sessionId: child.agent.id })- expect(child.agent.session.requestHeader()).toBeUndefined()- expect(() => restoreSerialized(child.agent.session)).not.toThrow()- await followup(child.agent, 'continue the cold empty-source worktree')- expect(errors).toEqual([])- expect(child.agent.options).toEqual({ provider: BRIDGE_PROVIDER, model: id })- expect(connection.submit).toHaveBeenCalledOnce()- expect(original.submit).not.toHaveBeenCalled()- expect(factory).toHaveBeenCalledTimes(2)- expect(factory.mock.calls[1]![5]).toBeUndefined()- expect(restoreSerialized(child.agent.session).requestHeader()?.config).toEqual({ provider: BRIDGE_PROVIDER, model: id })- }, 10_000)-})--describe('official native session lifecycle', () => {- it.each(['codex', 'claude'] as const)('round-trips the official V4 serializer before and after the first %s native turn', async (id) => {- const connection = native(`serialized-native-${id}`)- const factory = vi.mocked(id === 'codex' ? createCodexSession : createClaudeSession)- factory.mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => output.assistant('serialized-native-answer', [{ type: 'text', text: 'serialized native reply' }]))- return connection- })- await creating(id)- const agent = officialHandle!.agent- expect(() => restoreSerialized(agent.session)).not.toThrow()- expect(agent.session.snapshotEvents().map(event => event.type)).toEqual(['plugin:dsh-tauri-kernel/kernel'])- expect(agent.session.requestHeader()).toBeUndefined()- expect(agent.options).toMatchObject({ provider: BRIDGE_PROVIDER, model: id })- expect(connection.submit).not.toHaveBeenCalled()- await followup(agent, 'persist one real native reply')- expect(errors).toEqual([])- expect(connection.submit).toHaveBeenCalledOnce()- expect(agent.session.snapshotEvents().filter(event => event.type === 'request/header').map(event => event.data.reason)).toEqual(['initial'])- const restored = restoreSerialized(agent.session)- expect(restored.requestHeader()?.config).toEqual({ provider: BRIDGE_PROVIDER, model: id })- expect(records(restored)).toEqual(records(agent.session))- expect(restored.deriveMessages().map(message => ({ role: message.role, content: message.content }))).toEqual([- { role: 'user', content: [{ type: 'text', text: 'persist one real native reply' }] },- { role: 'assistant', content: [{ type: 'text', text: 'serialized native reply' }] },- ])- }, 10_000)-- it('connects Codex with unknown login status and leaves provider authentication native-owned', async () => {- vi.mocked(detectBackend).mockResolvedValue({- detection: { id: 'codex', installed: true, auth: 'unknown', version: 'test', drift: false, hint: 'Check native provider authentication' },- command: { file: 'boundary-only', args: ['codex'] },- })- const connection = native('custom-provider-thread')- vi.mocked(createCodexSession).mockResolvedValue(connection)- const result = await creating()- expect(identity.resolve(officialHandle!.agent)).toEqual({ backend: 'codex', nativeSessionId: 'custom-provider-thread', sessionId: result.sessionId })- expect(createCodexSession).toHaveBeenCalledOnce()- expect(createClaudeSession).not.toHaveBeenCalled()- expect(connection.submit).not.toHaveBeenCalled()- }, 10_000)-- it('rejects explicitly missing Claude authentication before starting a native process', async () => {- vi.mocked(detectBackend).mockResolvedValue({- detection: { id: 'claude', installed: true, auth: 'missing', version: 'test', drift: false, hint: '请先在终端运行 claude auth login。' },- command: { file: 'boundary-only', args: ['claude'] },- })- await expect(creating('claude')).rejects.toThrow('请先在终端运行 claude auth login。')- expect(createClaudeSession).not.toHaveBeenCalled()- expect(createCodexSession).not.toHaveBeenCalled()- expect(runtime.sessions.size).toBe(0)- }, 10_000)-- it('rejects a session directory that does not exist with the location error instead of a filesystem error', async () => {- await expect(session.create('codex', undefined, join(cwd, 'bridge-missing-session-directory'))).rejects.toThrow('BRIDGE_CWD_INVALID: 会话目录必须是已存在的绝对目录。')- expect(createCodexSession).not.toHaveBeenCalled()- expect(runtime.sessions.size).toBe(0)- }, 10_000)-- it('refreshes official permission presets for each turn on a cached native connection', async () => {- context.provide('shell', { sandboxMode: 'workspace-write' })- await context.plugin(ApprovalService, { policy: 'ask' }).await()- await context.plugin(PermissionPresetService).await()- const connection = native('permission-native')- vi.mocked(createCodexSession).mockImplementation(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => output.assistant('permission-answer', [{ type: 'text', text: 'permission reply' }]))- return connection- })- await creating()- const agent = officialHandle!.agent- await followup(agent, 'use the pinned initial permissions')- context.permissionPresets.set(agent.session, 'danger-full-access')- await followup(agent, 'use full permissions without reconnecting')- context.permissionPresets.set(agent.session, 'workspace-write')- await followup(agent, 'restore approval mode without reconnecting')- expect(errors).toEqual([])- expect(createCodexSession).toHaveBeenCalledOnce()- expect(connection.submit.mock.calls.map(call => call[3])).toEqual([- { sandbox: 'workspace-write', approval: 'ask' },- { sandbox: 'danger-full-access', approval: 'never' },- { sandbox: 'workspace-write', approval: 'ask' },- ])- await session.remove(agent.id, agent)- vi.mocked(createCodexSession).mockClear()- await session.connect(agent, new AbortController().signal)- expect(vi.mocked(createCodexSession).mock.calls[0]![5]).toEqual({ permission: { sandbox: 'workspace-write', approval: 'ask' } })- }, 10_000)-- it.each(['codex', 'claude'] as const)('publishes %s only after native ACK and official identity commit', async (id) => {- const ack = deferred<NativeSession>()- const started = deferred<void>()- const connection = native(`native-${id}`)- releases.push(() => ack.resolve(connection))- const factory = vi.mocked(id === 'codex' ? createCodexSession : createClaudeSession)- factory.mockImplementation(async () => {- started.resolve()- return ack.promise- })- const task = creating(id, 'test-workspace')- await started.promise- expect(prepared).toHaveLength(1)- const official = prepared[0]!- expect(records(official)).toEqual([])- expect(projections.stateOf(official, 'bridgeKernel')?.binding).toBeNull()- expect(official.requestHeader()).toBeUndefined()- expect(agents.get(official.id)).toBeUndefined()- expect(sessions.get(official.id)).toBeUndefined()- expect(announced).toEqual([])- expect(attachSession).not.toHaveBeenCalled()- expect(mount).toHaveBeenCalledOnce()- expect(factory.mock.calls[0]![2]).toBeNull()- ack.resolve(connection)- const result = await task- expect(result).toEqual({ sessionId: official.id })- expect(officialHandle!.agent.session).toBe(official)- expect(agents.get(official.id)).toBe(officialHandle!.agent)- expect(sessions.get(official.id)).toBe(official)- const binding = { backend: id, nativeSessionId: connection.id, sessionId: official.id }- expect(records(official)).toMatchObject([{ type: 'plugin:dsh-tauri-kernel/kernel', data: binding }])- expect(official.snapshotEvents().find(event => (event.type as string) === 'plugin:dsh-tauri-kernel/kernel')).toMatchObject({ ignorable: true, data: binding })- expect(identity.resolve(officialHandle!.agent)).toEqual(binding)- expect(official.requestHeader()).toBeUndefined()- expect(officialHandle!.agent.options).toMatchObject({ provider: BRIDGE_PROVIDER, model: id })- expect(announced).toEqual([officialHandle!.agent])- expect(attachSession).toHaveBeenCalledExactlyOnceWith(official.id)- expect(connection.submit).not.toHaveBeenCalled()- }, 10_000)-- it('drives two native tool calls through core-owned steps with one native submission', async () => {- const connection = native('multi-tool-native')- vi.mocked(createCodexSession).mockImplementation(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => {- output.text('work', 'before tools')- output.assistant('work', [- { type: 'text', text: 'before tools' },- { type: 'tool-call', id: 'native-call-1', name: 'native_first', arguments: '{"path":"one"}' },- { type: 'tool-call', id: 'native-call-2', name: 'native_second', arguments: '{"path":"two"}' },- ])- output.toolStart('native-call-1', 'native_first', '{"path":"one"}')- output.toolEnd('native-call-1', 'first native result')- output.toolStart('native-call-2', 'native_second', '{"path":"two"}')- output.toolEnd('native-call-2', 'second native result')- output.assistant('tail', [{ type: 'text', text: 'after tools' }])- })- return connection- })- await creating()- const agent = officialHandle!.agent- const { events } = observe(agent)- await followup(agent, 'complete the native work')- expect(errors).toEqual([])- expect(createCodexSession).toHaveBeenCalledOnce()- expect(connection.submit).toHaveBeenCalledOnce()- expect(connection.submit.mock.calls[0]![0]).toMatchObject([{ content: [{ type: 'text', text: 'complete the native work' }] }])- expect(events.filter(event => event.type === 'step/start').map(event => event.data)).toEqual([{ turn: 1, step: 1 }, { turn: 1, step: 2 }])- expect(events.filter(event => event.type === 'step/end').map(event => event.data)).toEqual([{ turn: 1, step: 1 }, { turn: 1, step: 2 }])- expect(events.filter(event => event.type === 'assistant/message').map(event => ({ turn: event.data.turn, step: event.data.step, content: event.data.message.content }))).toEqual([- { turn: 1, step: 1, content: [- { type: 'text', text: 'before tools' },- { type: 'tool-call', id: 'native-call-1', name: 'native_first', arguments: '{"path":"one"}' },- { type: 'tool-call', id: 'native-call-2', name: 'native_second', arguments: '{"path":"two"}' },- ] },- { turn: 1, step: 2, content: [{ type: 'text', text: 'after tools' }] },- ])- expect(events.filter(event => event.type === 'tool/call').map(event => event.data)).toEqual([- { turn: 1, step: 1, callId: 'native-call-1', name: 'native_first', arguments: '{"path":"one"}' },- { turn: 1, step: 1, callId: 'native-call-2', name: 'native_second', arguments: '{"path":"two"}' },- ])- expect(events.filter(event => event.type === 'tool/result').map(event => ({ turn: event.data.turn, step: event.data.step, id: event.data.message.toolCallId, content: event.data.message.content, isError: event.data.message.isError === true }))).toEqual([- { turn: 1, step: 1, id: 'native-call-1', content: [{ type: 'text', text: 'first native result' }], isError: false },- { turn: 1, step: 1, id: 'native-call-2', content: [{ type: 'text', text: 'second native result' }], isError: false },- ])- const firstToolCall = events.findIndex(event => event.type === 'tool/call')- const lastToolResult = events.findLastIndex(event => event.type === 'tool/result')- expect(events[firstToolCall - 1]?.type).toBe('assistant/message')- expect(events.findIndex(event => event.type === 'step/start' && event.data.step === 2)).toBeGreaterThan(lastToolResult)- expect(events.filter(event => event.type === 'turn/start').map(event => event.data)).toEqual([{ turn: 1 }])- expect(events.filter(event => event.type === 'turn/end').map(event => event.data)).toEqual([{ turn: 1, reason: { kind: 'completed' } }])- expect(runtime.exchanges.size).toBe(0)- expect(connection.dispose).not.toHaveBeenCalled()- }, 10_000)-- it('waits for native tool results without running a registered DSH tool body', async () => {- const body = vi.fn().mockResolvedValue('DSH must never execute this')- const tool: ToolDefinition = {- name: 'native_file',- description: 'a real globally registered DSH body',- parameters: { type: 'object', additionalProperties: true },- output: { schema: { type: 'string' }, render: (_args: unknown, value: unknown) => [{ type: 'text' as const, text: String(value) }] },- execute: body,- }- context.tools.register(tool)- const delivered = deferred<void>()- const connection = native('wait-only-native')- releases.push(() => delivered.resolve())- vi.mocked(createCodexSession).mockImplementation(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => {- output.assistant('tool-request', [{ type: 'tool-call', id: 'native-wait', name: 'native_file', arguments: '{"path":"file.txt"}' }])- output.toolStart('native-wait', 'native_file', '{"path":"file.txt"}')- await delivered.promise- output.toolEnd('native-wait', 'native file content')- output.assistant('finished', [{ type: 'text', text: 'native task finished' }])- })- return connection- })- await creating()- const agent = officialHandle!.agent- const { events } = observe(agent)- let idle = false- const turn = followup(agent, 'read through the native kernel').then(() => {- idle = true- })- background.push(turn)- await vi.waitFor(() => expect(events.filter(event => event.type === 'tool/call').map(event => event.data.callId)).toEqual(['native-wait']))- expect(idle).toBe(false)- expect(body).not.toHaveBeenCalled()- expect(connection.submit).toHaveBeenCalledOnce()- expect(events.filter(event => event.type === 'tool/result')).toEqual([])- expect(agent.ctx.tools.get('native_file', agent)?.description).toBe('等待本机内核已经发起的工具结果;不执行 DSH 工具。')- delivered.resolve()- await turn- expect(errors).toEqual([])- expect(body).not.toHaveBeenCalled()- expect(events.filter(event => event.type === 'tool/result').map(event => event.data.message)).toMatchObject([- { role: 'tool', toolCallId: 'native-wait', content: [{ type: 'text', text: 'native file content' }] },- ])- expect(agent.ctx.tools.get('native_file', agent)?.description).toBe(tool.description)- expect(context.tools.get('native_file')?.execute).toBe(body)- expect(runtime.exchanges.size).toBe(0)- expect(connection.dispose).not.toHaveBeenCalled()- }, 10_000)-- it('publishes standard assistant stream frames matching each durable core settlement', async () => {- const connection = native('stream-frames-native')- vi.mocked(createCodexSession).mockImplementation(async (_command, _cwd, _storedId, output) => {- connection.submit.mockImplementation(async () => {- output.thinking('thought-and-call', 'native reasoning')- output.text('thought-and-call', 'native preface')- output.assistant('thought-and-call', [- { type: 'thinking', text: 'native reasoning' },- { type: 'text', text: 'native preface' },- { type: 'tool-call', id: 'frame-call', name: 'native_status', arguments: '{}' },- ])- output.toolStart('frame-call', 'native_status', '{}')- output.toolEnd('frame-call', 'native status ready')- output.text('final-frame', 'native conclusion')- output.assistant('final-frame', [{ type: 'text', text: 'native conclusion' }])- })- return connection- })- await creating()- const agent = officialHandle!.agent- const { events, frames, endEvents } = observe(agent)- await followup(agent, 'stream the native task')- expect(errors).toEqual([])- expect(connection.submit).toHaveBeenCalledOnce()- const starts = frames.filter(frame => frame.type === 'start')- const ends = frames.filter(frame => frame.type === 'end')- const assistants = events.filter(event => event.type === 'assistant/message')- expect(starts.map(frame => ({ revision: frame.revision, turn: frame.turn, step: frame.step }))).toEqual([{ revision: 1, turn: 1, step: 1 }, { revision: 13, turn: 1, step: 2 }])- expect(frames.map(frame => frame.revision)).toEqual(Array.from({ length: 18 }, (_, index) => index + 1))- expect(new Set(starts.map(frame => frame.attemptId)).size).toBe(2)- expect(ends).toHaveLength(2)- expect(assistants).toHaveLength(2)- expect(endEvents).toEqual(assistants)- expect(events.filter(event => event.type === 'assistant/attempt')).toEqual([])- for (const [index, start] of starts.entries()) {- const chunks = frames.filter((frame): frame is Extract<AssistantStreamFrame, { type: 'chunk' }> => frame.type === 'chunk' && frame.attemptId === start.attemptId)- const end = ends[index]!- const assistant = assistants[index]!- expect(chunks.map(frame => frame.index)).toEqual(chunks.map((_, chunkIndex) => chunkIndex))- expect(chunks.map(frame => frame.revision)).toEqual(chunks.map((_, chunkIndex) => start.revision + chunkIndex + 1))- expect(end).toMatchObject({ attemptId: start.attemptId, revision: start.revision + chunks.length + 1, index: index === 0 ? 10 : 4, outcome: { kind: 'committed', eventType: 'assistant/message', seq: assistant.seq } })- expect(llmModule.expandAssistantStream(assistant.data.stream)).toEqual(chunks.map(frame => ({ time: frame.time, chunk: frame.chunk })))- expect(chunks.filter(frame => frame.chunk.type === 'finish').map(frame => frame.chunk)).toEqual([{ type: 'finish', reason: { kind: index === 0 ? 'tool-calls' : 'stop' } }])- expect(frames.indexOf(end)).toBeGreaterThan(frames.indexOf(chunks[chunks.length - 1]!))- }- expect(assistants.map(event => event.data.message.content)).toEqual([- [{ type: 'reasoning', text: 'native reasoning' }, { type: 'text', text: 'native preface' }, { type: 'tool-call', id: 'frame-call', name: 'native_status', arguments: '{}' }],- [{ type: 'text', text: 'native conclusion' }],- ])- expect(events.filter(event => event.type === 'tool/result').map(event => event.data.message.toolCallId)).toEqual(['frame-call'])- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it('resumes only the committed native identity through an official followup', async () => {- const original = native('restored-native')- const resumed = native(original.id)- vi.mocked(createCodexSession).mockResolvedValueOnce(original).mockResolvedValueOnce(resumed)- await creating()- const agent = officialHandle!.agent- const recordsBefore = records(agent.session)- await session.remove(agent.id)- expect(original.dispose).toHaveBeenCalledOnce()- await followup(agent, 'resume the native session')- expect(errors).toEqual([])- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(vi.mocked(createCodexSession).mock.calls[1]![2]).toBe(original.id)- expect(resumed.submit).toHaveBeenCalledOnce()- expect(resumed.submit.mock.calls[0]![0]).toMatchObject([{ content: [{ type: 'text', text: 'resume the native session' }] }])- expect(records(agent.session)).toEqual(recordsBefore)- expect(identity.resolve(agent).nativeSessionId).toBe(original.id)- expect(createClaudeSession).not.toHaveBeenCalled()- }, 10_000)-- it('rejects a restore ACK for another native identity without fallback or rebind', async () => {- const original = native('bound-native')- const foreign = native('foreign-native')- vi.mocked(createCodexSession).mockResolvedValueOnce(original).mockResolvedValueOnce(foreign)- await creating()- const agent = officialHandle!.agent- const recordsBefore = records(agent.session)- await session.remove(agent.id)- await followup(agent, 'restore strictly')- expect(errors).toHaveLength(1)- expect(errors[0]).toMatchObject({ message: expect.stringContaining('BRIDGE_RESUME_MISMATCH') })- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(vi.mocked(createCodexSession).mock.calls[1]![2]).toBe(original.id)- expect(foreign.dispose).toHaveBeenCalledOnce()- expect(foreign.submit).not.toHaveBeenCalled()- expect(createClaudeSession).not.toHaveBeenCalled()- expect(records(agent.session)).toEqual(recordsBefore)- expect(identity.resolve(agent).nativeSessionId).toBe(original.id)- expect(agents.get(agent.id)).toBe(agent)- }, 10_000)-- it('aborts a pending strict restore and drains its ACK without changing the committed identity', async () => {- const original = native('aborted-restore')- const resumed = native(original.id)- const ack = deferred<NativeSession>()- const started = deferred<void>()- const drain = deferred<void>()- const drainStarted = deferred<void>()- releases.push(() => ack.resolve(resumed), () => drain.resolve())- resumed.dispose.mockImplementation(async () => {- drainStarted.resolve()- await drain.promise- })- vi.mocked(createCodexSession).mockResolvedValueOnce(original).mockImplementationOnce(async () => {- started.resolve()- return ack.promise- })- await creating()- const agent = officialHandle!.agent- const recordsBefore = records(agent.session)- await session.remove(agent.id)- const turn = followup(agent, 'restore then close')- await started.promise- let closed = false- const closing = session.remove(agent.id).then(() => {- closed = true- })- background.push(closing)- expect(vi.mocked(createCodexSession).mock.calls[1]![2]).toBe(original.id)- expect(vi.mocked(createCodexSession).mock.calls[1]![4].aborted).toBe(true)- expect(closed).toBe(false)- ack.resolve(resumed)- await drainStarted.promise- expect(closed).toBe(false)- expect(resumed.submit).not.toHaveBeenCalled()- expect(records(agent.session)).toEqual(recordsBefore)- drain.resolve()- await Promise.all([closing, turn])- expect(closed).toBe(true)- expect(resumed.dispose).toHaveBeenCalledOnce()- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(errors).toHaveLength(1)- expect(errors[0]).toMatchObject({ message: expect.stringContaining('BRIDGE_SESSION_DISPOSED') })- expect(identity.resolve(agent).nativeSessionId).toBe(original.id)- expect(agents.get(agent.id)).toBe(agent)- }, 10_000)-- it('restores the committed native identity from a cold official session', async () => {- const original = native('cold-restored-native')- const resumed = native(original.id)- vi.mocked(createCodexSession).mockResolvedValueOnce(original)- await creating()- const previous = officialHandle!- const stored = structuredClone(previous.agent.session.snapshotEvents())- const recordsBefore = records(previous.agent.session)- await previous.dispose()- await session.remove(previous.agent.id)- const close = vi.fn().mockResolvedValue(undefined)- const handle = {- id: previous.agent.id,- header: previous.agent.session.header,- inheritedEventCount: previous.agent.session.inheritedEventCount,- access: 'write',- read: vi.fn().mockResolvedValue({ events: stored, eventState: 'detached' }),- append: vi.fn().mockResolvedValue(undefined),- flush: vi.fn().mockResolvedValue(undefined),- close,- [Symbol.asyncDispose]: close,- }- const open = vi.fn().mockResolvedValue(handle)- const create = vi.fn().mockRejectedValue(new Error('cold resume must not create a new stored session'))- context.extend().provide('sessionPersistence', { open, create })- const restored = await agents.resume({ resumeSessionId: previous.agent.id, agentOptions: { provider: BRIDGE_PROVIDER, model: 'codex' } })- expect(open).toHaveBeenCalledExactlyOnceWith(previous.agent.id, 'write', { signal: expect.any(AbortSignal) })- expect(handle.read).toHaveBeenCalledExactlyOnceWith(0, undefined, { signal: expect.any(AbortSignal) })- expect(create).not.toHaveBeenCalled()- expect(restored.agent).not.toBe(previous.agent)- expect(restored.agent.session).not.toBe(previous.agent.session)- expect(restored.agent.session.header.cwd).toBe(cwd)- expect(identity.resolve(restored.agent)).toEqual({ backend: 'codex', nativeSessionId: 'cold-restored-native', sessionId: previous.agent.id })- expect(records(restored.agent.session)).toEqual(recordsBefore)- expect(createCodexSession).toHaveBeenCalledOnce()- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, storedId, output) => {- expect(storedId).toBe('cold-restored-native')- resumed.submit.mockImplementation(async () => output.assistant('cold-answer', [{ type: 'text', text: 'restored from native history' }]))- return resumed- })- await followup(restored.agent, 'continue the cold session')- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(resumed.submit).toHaveBeenCalledOnce()- expect(errors).toEqual([])- expect(records(restored.agent.session)).toEqual(recordsBefore)- expect(agents.get(previous.agent.id)).toBe(restored.agent)- await restored.dispose()- await session.remove(restored.agent.id)- expect(close).toHaveBeenCalledOnce()- expect(resumed.dispose).toHaveBeenCalledOnce()- }, 10_000)-- it('keeps a recreated official owner behind the old native close barrier', async () => {- const original = native('recreated-native')- const drain = deferred<void>()- const drainStarted = deferred<void>()- releases.push(() => drain.resolve())- original.dispose.mockImplementation(async () => {- drainStarted.resolve()- await drain.promise- })- vi.mocked(createCodexSession).mockResolvedValueOnce(original)- await creating()- const oldHandle = officialHandle!- const seed = oldHandle.agent.session.snapshotEvents()- const recordsBefore = records(oldHandle.agent.session)- let closed = false- const oldClosing = oldHandle.dispose().then(() => {- closed = true- })- background.push(oldClosing)- await drainStarted.promise- expect(closed).toBe(false)- expect(agents.get(oldHandle.agent.id)).toBe(oldHandle.agent)- expect(sessions.get(oldHandle.agent.id)).toBe(oldHandle.agent.session)- const nativeClosing = session.remove(oldHandle.agent.id)- background.push(nativeClosing)- await expect(agents.create({ sessionId: oldHandle.agent.id, seed, meta: { cwd }, agentOptions: { provider: BRIDGE_PROVIDER, model: 'codex' } })).rejects.toThrow(`session "${oldHandle.agent.id}" already exists`)- expect(createCodexSession).toHaveBeenCalledOnce()- expect(original.submit).not.toHaveBeenCalled()- drain.resolve()- await Promise.all([oldClosing, nativeClosing])- expect(closed).toBe(true)- expect(agents.get(oldHandle.agent.id)).toBeUndefined()- expect(sessions.get(oldHandle.agent.id)).toBeUndefined()- const replacement = await agents.create({ sessionId: oldHandle.agent.id, seed, meta: { cwd }, agentOptions: { provider: BRIDGE_PROVIDER, model: 'codex' } })- expect(identity.resolve(replacement.agent)).toEqual({ backend: 'codex', nativeSessionId: 'recreated-native', sessionId: oldHandle.agent.id })- expect(errors).toEqual([])- const resumed = native(original.id)- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {- resumed.submit.mockImplementation(async () => output.assistant('resumed-answer', [{ type: 'text', text: 'native owner restored' }]))- return resumed- })- await followup(replacement.agent, 'restore after drain')- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(vi.mocked(createCodexSession).mock.calls[1]![2]).toBe(original.id)- expect(resumed.submit).toHaveBeenCalledOnce()- await followup(replacement.agent, 'reuse the restored owner')- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(resumed.submit).toHaveBeenCalledTimes(2)- expect(errors).toEqual([])- expect(records(replacement.agent.session)).toEqual(recordsBefore)- expect(agents.get(replacement.agent.id)).toBe(replacement.agent)- expect(resumed.dispose).not.toHaveBeenCalled()- expect(original.dispose).toHaveBeenCalledOnce()- }, 10_000)-- it('ignores a late native remove from the previous official owner of the same session id', async () => {- const original = native('same-id-native')- const resumed = native(original.id)- vi.mocked(createCodexSession).mockResolvedValueOnce(original)- await creating()- const previous = officialHandle!- const seed = previous.agent.session.snapshotEvents()- const recordsBefore = records(previous.agent.session)- await previous.dispose()- await session.remove(previous.agent.id)- expect(original.dispose).toHaveBeenCalledOnce()- const replacement = await agents.create({ sessionId: previous.agent.id, seed, meta: { cwd }, agentOptions: { provider: BRIDGE_PROVIDER, model: 'codex' } })- vi.mocked(createCodexSession).mockImplementationOnce(async (_command, _cwd, storedId, output) => {- expect(storedId).toBe('same-id-native')- resumed.submit.mockImplementation(async () => output.assistant(`same-id-answer-${resumed.submit.mock.calls.length}`, [{ type: 'text', text: 'current native owner' }]))- return resumed- })- await followup(replacement.agent, 'restore the replacement owner')- expect(errors).toEqual([])- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(resumed.submit).toHaveBeenCalledOnce()- await session.remove(previous.agent.id, previous.agent)- expect(resumed.dispose).not.toHaveBeenCalled()- await followup(replacement.agent, 'reuse after stale owner cleanup')- expect(errors).toEqual([])- expect(createCodexSession).toHaveBeenCalledTimes(2)- expect(resumed.submit).toHaveBeenCalledTimes(2)- expect(resumed.dispose).not.toHaveBeenCalled()- expect(records(replacement.agent.session)).toEqual(recordsBefore)- expect(identity.resolve(replacement.agent)).toEqual({ backend: 'codex', nativeSessionId: 'same-id-native', sessionId: previous.agent.id })- expect(agents.get(previous.agent.id)).toBe(replacement.agent)- expect(sessions.get(previous.agent.id)).toBe(replacement.agent.session)- expect(original.dispose).toHaveBeenCalledOnce()- }, 10_000)-- it('never opens or binds native state after the official factory closes during preset setup', async () => {- const gate = deferred<void>()- const started = deferred<void>()- const finished = deferred<void>()- const setupFinished: Array<Promise<{ value: Awaited<ReturnType<AgentSetup>> } | { error: unknown }>> = []- releases.push(() => gate.resolve())- mount.mockImplementation(async () => {- started.resolve()- await gate.promise- finished.resolve()- })- vi.mocked(agents.create).mockImplementation(async (options) => {- const setup = options.setup!- return createAgent({- ...options,- setup(agentCtx, agent) {- const observed = Promise.resolve(setup(agentCtx, agent)).then(value => ({ value }), error => ({ error }))- setupFinished.push(observed)- background.push(observed)- return observed.then((result) => {- if ('error' in result)- throw result.error- return result.value- })- },- })- })- vi.mocked(createCodexSession).mockResolvedValue(native('must-not-open'))- const task = creating()- const rejection = expect(task).rejects.toThrow('agent loop is not active')- background.push(rejection)- await started.promise- expect(prepared).toHaveLength(1)- await disposeLoop()- await rejection- expect(runtime.ready).toBe(true)- expect(createCodexSession).not.toHaveBeenCalled()- gate.resolve()- await finished.promise- const [settled] = await Promise.all(setupFinished)- expect(settled).toHaveProperty('error')- expect(records(prepared[0]!)).toEqual([])- expect(prepared[0]!.requestHeader()).toBeUndefined()- expect(createCodexSession).not.toHaveBeenCalled()- expect(createClaudeSession).not.toHaveBeenCalled()- expect(agents.list()).toEqual([])- expect(sessions.list()).toEqual([])- expect(runtime.sessions.size).toBe(0)- expect(announced).toEqual([])- }, 10_000)-- it('rolls back a rejected native initialization without publishing or binding', async () => {- const error = new Error('native initialization rejected')- vi.mocked(createCodexSession).mockRejectedValue(error)- await expect(creating()).rejects.toBe(error)- expect(prepared).toHaveLength(1)- expect(records(prepared[0]!)).toEqual([])- expect(agents.list()).toEqual([])- expect(sessions.list()).toEqual([])- expect(announced).toEqual([])- expect(runtime.sessions.size).toBe(0)- }, 10_000)-- it('disposes a native ACK with no identity rather than starting a fallback thread', async () => {- const connection = native('')- vi.mocked(createCodexSession).mockResolvedValue(connection)- await expect(creating()).rejects.toThrow('BRIDGE_RESUME_MISMATCH')- expect(records(prepared[0]!)).toEqual([])- expect(connection.dispose).toHaveBeenCalledOnce()- expect(connection.submit).not.toHaveBeenCalled()- expect(createCodexSession).toHaveBeenCalledOnce()- expect(createClaudeSession).not.toHaveBeenCalled()- expect(agents.list()).toEqual([])- expect(sessions.list()).toEqual([])- }, 10_000)-- it('rolls back official publication and native ownership after workspace attachment fails', async () => {- const connection = native('attachment-failure')- const failure = new Error('workspace attachment failed')- vi.mocked(createCodexSession).mockResolvedValue(connection)- attachSession.mockRejectedValue(failure)- await expect(creating('codex', 'test-workspace')).rejects.toBe(failure)- expect(officialHandle).toBeDefined()- expect(agents.list()).toEqual([])- expect(sessions.list()).toEqual([])- expect(connection.dispose).toHaveBeenCalledOnce()- expect(runtime.sessions.size).toBe(0)- expect(runtime.claims.size).toBe(0)- const replacement = native(connection.id)- vi.mocked(createCodexSession).mockResolvedValue(replacement)- attachSession.mockResolvedValue(undefined)- const result = await creating('codex', 'test-workspace')- expect(agents.get(sessionModule.SessionId(result.sessionId))).toBe(officialHandle!.agent)- expect(connection.dispose).toHaveBeenCalledOnce()- expect(replacement.dispose).not.toHaveBeenCalled()- }, 10_000)-- it('rejects a second official owner of the same backend-native identity', async () => {- const first = native('single-owner')- const second = native('single-owner')- vi.mocked(createCodexSession).mockResolvedValueOnce(first).mockResolvedValueOnce(second)- const original = await creating()- await expect(creating()).rejects.toThrow('BRIDGE_NATIVE_OWNER_CONFLICT')- expect(agents.list()).toHaveLength(1)- expect(sessions.list()).toHaveLength(1)- expect(agents.get(sessionModule.SessionId(original.sessionId))?.session).toBe(prepared[0])- expect(records(prepared[1]!)).toEqual([])- expect(first.dispose).not.toHaveBeenCalled()- expect(second.dispose).toHaveBeenCalledOnce()- expect(second.submit).not.toHaveBeenCalled()- }, 10_000)-- it('holds concurrent remove calls until a pending ACK is disposed', async () => {- const ack = deferred<NativeSession>()- const started = deferred<void>()- const connection = native('late-ack')- const drain = deferred<void>()- const drainStarted = deferred<void>()- releases.push(() => ack.resolve(connection), () => drain.resolve())- connection.dispose.mockImplementation(async () => {- drainStarted.resolve()- await drain.promise- })- vi.mocked(createCodexSession).mockImplementation(async () => {- started.resolve()- return ack.promise- })- const task = creating()- const rejection = expect(task).rejects.toThrow('BRIDGE_SESSION_DISPOSED')- await started.promise- const official = prepared[0]!- const signal = vi.mocked(createCodexSession).mock.calls[0]![4]- let removed = 0- const first = session.remove(official.id).then(() => {- removed++- })- const second = session.remove(official.id).then(() => {- removed++- })- background.push(first, second, rejection)- expect(signal.aborted).toBe(true)- expect(removed).toBe(0)- ack.resolve(connection)- await drainStarted.promise- expect(removed).toBe(0)- expect(records(official)).toEqual([])- expect(connection.dispose).toHaveBeenCalledOnce()- drain.resolve()- await Promise.all([first, second, rejection])- expect(removed).toBe(2)- expect(agents.list()).toEqual([])- expect(sessions.list()).toEqual([])- expect(announced).toEqual([])- expect(runtime.sessions.size).toBe(0)- expect(runtime.pending.size).toBe(0)- expect(connection.dispose).toHaveBeenCalledOnce()- }, 10_000)-- it('aborts a pending create on application disposal and drains a late native ACK', async () => {- const ack = deferred<NativeSession>()- const started = deferred<void>()- const connection = native('shutdown-ack')- const drain = deferred<void>()- const drainStarted = deferred<void>()- releases.push(() => ack.resolve(connection), () => drain.resolve())- vi.mocked(createCodexSession).mockImplementation(async () => {- started.resolve()- return ack.promise- })- connection.dispose.mockImplementation(async () => {- drainStarted.resolve()- await drain.promise- })- const task = creating()- const rejection = expect(task).rejects.toThrow('BRIDGE_DISPOSED')- await started.promise- let disposed = false- const closing = session.dispose().then(() => {- disposed = true- })- background.push(closing, rejection)- expect(vi.mocked(createCodexSession).mock.calls[0]![4].aborted).toBe(true)- expect(disposed).toBe(false)- ack.resolve(connection)- await drainStarted.promise- expect(disposed).toBe(false)- expect(records(prepared[0]!)).toEqual([])- drain.resolve()- await Promise.all([closing, rejection])- expect(connection.dispose).toHaveBeenCalledOnce()- expect(agents.list()).toEqual([])- expect(sessions.list()).toEqual([])- expect(runtime.sessions.size).toBe(0)- }, 10_000)-})diff --git a/packages/dsh-tauri-kernel/src/host/service/session.ts b/packages/dsh-tauri-kernel/src/host/service/session.tsdeleted file mode 100644index 627c4ebb..00000000--- a/packages/dsh-tauri-kernel/src/host/service/session.ts+++ /dev/null@@ -1,557 +0,0 @@-import type { Agent, AgentHandle, AgentSetupCommit } from '@deepseek-ai/dsh-agent'-import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'-import type { Session, SessionId } from '@deepseek-ai/dsh-session'-import type { WorkspaceId } from '@deepseek-ai/dsh-workspace'-import type { KernelBinding } from '../../shared/types'-import type { NativeAttachments, NativePermission, NativeSession, NativeSessionOpenOptions, NativeSink } from '../backends/types'-import type { HostContext, NativeEntry, NativeExecution } from '../types'-import type { OfficialSink } from './sink.types'-import { Buffer } from 'node:buffer'-import { randomUUID } from 'node:crypto'-import { mkdir, realpath, stat } from 'node:fs/promises'-import { isAbsolute } from 'node:path'-import { getServerContext } from 'dsh-h3/utils'-import { defineService, resolveUngroupedSessionPath } from 'dsh-tauri'-import { createClaudeSession } from '../backends/claude'-import { createCodexSession } from '../backends/codex'-import { NativeBridgeError } from '../backends/transport'-import { BRIDGE_PROVIDER, KERNEL_RECORD_TYPE, SESSION_TITLE_PURPOSE } from '../config/constants'-import { resetRuntime, runtime } from '../config/runtime'-import { server } from '../server'-import { waitFor } from '../utils/abort'-import { backend } from './backend'-import { checkpoint } from './checkpoint'-import { identity } from './identity'-import { sink } from './sink'--export const session = defineService({- async create(id: KernelBinding['backend'], workspaceId?: string, directory?: string, agentPreset?: string): Promise<{ sessionId: string }> {- const ctx = getServerContext<HostContext>(server)- const lifetime = runtime.lifetime- if (!runtime.ready)- throw new Error('BRIDGE_CORE_UNAVAILABLE: 原生桥接尚未就绪。')- if (workspaceId !== undefined && directory !== undefined)- throw new Error('BRIDGE_LOCATION_CONFLICT: 不能同时指定工作区与目录。')- const resolved = await backend.resolve(id)- if (!resolved.detection.installed || !resolved.command || resolved.detection.auth === 'missing')- throw new Error(resolved.detection.hint ?? 'BRIDGE_BACKEND_UNAVAILABLE: 本机内核不可用。')- const workspace = workspaceId === undefined ? undefined : ctx.workspaceRegistry.get(workspaceId as WorkspaceId)- if (workspaceId !== undefined && !workspace)- throw new Error('BRIDGE_WORKSPACE_NOT_FOUND: 工作区不存在。')- let cwd = workspace?.path ?? directory- if (cwd === undefined) {- cwd = resolveUngroupedSessionPath()- await mkdir(cwd, { recursive: true })- }- const location = await stat(cwd).catch(() => undefined)- if (!isAbsolute(cwd) || location?.isDirectory() !== true)- throw new Error('BRIDGE_CWD_INVALID: 会话目录必须是已存在的绝对目录。')- cwd = await realpath(cwd)- lifetime.signal.throwIfAborted()- const preset = await ctx.agentPresets.resolve(agentPreset)- lifetime.signal.throwIfAborted()- if (preset.broken)- throw new Error(`BRIDGE_PRESET_UNAVAILABLE: ${preset.broken}`)- const sessionId = `session-${randomUUID()}` as SessionId- let handle: AgentHandle | undefined- try {- handle = await ctx.agents.withoutInitiator(() => ctx.agents.create({- sessionId,- agentOptions: { provider: BRIDGE_PROVIDER, model: id },- meta: { cwd, agentPreset: preset.id },- signal: lifetime.signal,- async setup(agentCtx, agent) {- const startup = new AbortController()- agentCtx.effect(() => async () => {- startup.abort(new Error('BRIDGE_SETUP_CLOSED'))- await session.remove(agent.id, agent)- }, 'bridge native session setup')- const signal = AbortSignal.any([startup.signal, lifetime.signal])- signal.throwIfAborted()- await ctx.agentPresets.mount(agentCtx, preset.id)- signal.throwIfAborted()- agentCtx.fiber.assertActive()- session.validateComposition(agent)- const entry = await open(agent, id, null, signal)- signal.throwIfAborted()- agentCtx.fiber.assertActive()- await identity.append(agent, entry.binding)- signal.throwIfAborted()- agentCtx.fiber.assertActive()- return {- commit(): void {- signal.throwIfAborted()- agentCtx.fiber.assertActive()- if (runtime.lifetime !== lifetime || !runtime.ready || !sameBinding(identity.resolve(agent), entry.binding) || agent.options.provider !== BRIDGE_PROVIDER || agent.options.model !== id)- throw new Error('BRIDGE_BINDING_NOT_COMMITTED: 原生身份未写入官方投影。')- },- }- },- }))- runtime.lifetime.signal.throwIfAborted()- if (workspace)- await workspace.attachSession(sessionId)- runtime.lifetime.signal.throwIfAborted()- if (ctx.agents.get(sessionId) !== handle.agent || ctx.sessions.get(sessionId) !== handle.agent.session)- throw new Error('BRIDGE_AGENT_REPLACED: 新会话已关闭或被替换。')- return { sessionId }- }- catch (error) {- const outcomes = await Promise.allSettled([handle?.dispose(), session.remove(sessionId)])- const failures = outcomes.filter((result): result is PromiseRejectedResult => result.status === 'rejected')- if (failures.length > 0)- throw new AggregateError([error, ...failures.map(result => result.reason)], 'BRIDGE_CREATION_ROLLBACK_FAILED')- throw error- }- },-- async createInherited(source: Session, create: (signal?: AbortSignal) => Promise<AgentHandle>): Promise<AgentHandle> {- const ctx = getServerContext<HostContext>(server)- const state = ctx.sessionProjections.stateOf(source, 'bridgeKernel')- if (state?.binding === null || state?.binding === undefined) {- if ((state?.inheritedBinding !== null && state?.inheritedBinding !== undefined) || source.requestHeader()?.config.provider === BRIDGE_PROVIDER)- throw new Error('BRIDGE_BINDING_MISSING: 源会话尚未完成原生绑定,不能派生工作树会话。')- return create()- }- const lifetime = runtime.lifetime- const parent = await resolveParent(source.id, lifetime.signal)- await waitFor(parent.whenIdle(), lifetime.signal)- lifetime.signal.throwIfAborted()- if (parent.session !== source)- throw new Error('BRIDGE_FORK_SOURCE_CHANGED: 源会话实例已被替换,请重新创建工作树会话。')- return parent.runMaintenance(async (signal) => {- signal.throwIfAborted()- lifetime.signal.throwIfAborted()- if (runtime.lifetime !== lifetime)- throw new Error('BRIDGE_DISPOSED: 原生派生的桥接生命周期已结束。')- const cursor = source.seq- const handle = await create(AbortSignal.any([signal, lifetime.signal]))- try {- signal.throwIfAborted()- lifetime.signal.throwIfAborted()- if (runtime.lifetime !== lifetime || source.seq !== cursor || ctx.agents.get(source.id) !== parent)- throw new Error('BRIDGE_FORK_SOURCE_CHANGED: 源会话在原生派生期间发生变化。')- return handle- }- catch (error) {- await handle.dispose()- throw error- }- })- },-- async prepare(source: Session, agent: Agent, signal: AbortSignal): Promise<AgentSetupCommit | void> {- const ctx = getServerContext<HostContext>(server)- const state = ctx.sessionProjections.stateOf(source, 'bridgeKernel')- const binding = state?.binding- if (binding === null || binding === undefined) {- if ((state?.inheritedBinding !== null && state?.inheritedBinding !== undefined) || source.requestHeader()?.config.provider === BRIDGE_PROVIDER)- throw new Error('BRIDGE_BINDING_MISSING: 源会话尚未完成原生绑定,不能派生工作树会话。')- return- }- if (binding.sessionId !== source.id || agent.session.header.parentSession !== source.id || !agent.session.header.isSeeded)- throw new Error('BRIDGE_FORK_INVALID: 原生派生必须来自当前官方父会话。')- const inherited = identity.inherited(agent.session)- if (!inherited || !sameBinding(inherited, binding))- throw new Error('BRIDGE_FORK_INVALID: 原生派生与官方继承前缀不一致。')- return bindFork(agent, binding, signal, source)- },-- async repairInherited(agent: Agent, signal: AbortSignal): Promise<void> {- const ctx = getServerContext<HostContext>(server)- const state = ctx.sessionProjections.stateOf(agent.session, 'bridgeKernel')- const scoped = AbortSignal.any([signal, runtime.lifetime.signal])- if (state?.binding !== null && state?.binding !== undefined)- return- const inherited = identity.inherited(agent.session)- if (!inherited)- return- const parent = await resolveParent(inherited.sessionId, scoped)- await waitFor(parent.whenIdle(), scoped)- const cursor = agent.session.inheritedEventCount- await waitFor(parent.runMaintenance(async (maintenance) => {- const repairing = AbortSignal.any([scoped, maintenance])- if (parent.session.seq !== cursor)- throw new Error('BRIDGE_FORK_SOURCE_CHANGED: 父会话已改变,不能将较新的原生历史替代继承前缀。')- const commit = await bindFork(agent, inherited, repairing, parent.session)- commit.commit()- await checkpoint.flush(agent, repairing)- repairing.throwIfAborted()- if (parent.session.seq !== cursor)- throw new Error('BRIDGE_FORK_SOURCE_CHANGED: 父会话在原生派生期间发生变化。')- }), scoped)- signal.throwIfAborted()- if (ctx.agents.get(agent.id) !== agent || ctx.sessions.get(agent.id) !== agent.session)- throw new Error('BRIDGE_AGENT_REPLACED: 工作树会话已关闭或被替换。')- },-- async* title(options: GenerateOptions): AsyncIterable<StreamChunk> {- const ctx = getServerContext<HostContext>(server)- const agent = options.sessionId === undefined ? undefined : ctx.agents.get(options.sessionId as SessionId)- if (!runtime.ready || options.provider !== BRIDGE_PROVIDER || options.purpose !== SESSION_TITLE_PURPOSE || !agent || ctx.sessions.get(agent.id) !== agent.session || options.signal === undefined || identity.resolve(agent).backend !== options.model)- throw new Error('BRIDGE_TITLE_REQUEST_INVALID: 标题请求缺少对应的原生会话。')- const route = ctx.get('agentDefaultModel')?.currentSelection()- if (!route || route.provider === BRIDGE_PROVIDER)- throw new Error('BRIDGE_TITLE_MODEL_UNAVAILABLE: 标题生成需要可用的 DSH 默认模型。')- const signal = AbortSignal.any([options.signal, runtime.lifetime.signal])- signal.throwIfAborted()- const call = await ctx.llm.prepareCall({- provider: route.provider,- model: route.model,- reasoningEffort: route.reasoningEffort,- maxTokens: options.maxTokens,- temperature: options.temperature,- stop: options.stop,- }, signal)- yield* call.stream({ ...options, ...call.config, signal })- },-- async connect(agent: Agent, signal: AbortSignal): Promise<NativeSession> {- const binding = identity.resolve(agent)- try {- const entry = await open(agent, binding.backend, binding.nativeSessionId, signal)- return entry.session- }- catch (error) {- if (/BRIDGE_NATIVE_TURN|No conversation found/.test(error instanceof Error ? error.message : String(error)))- throw new Error('BRIDGE_SESSION_UNRECOVERABLE: 原生会话记录已不存在,请新建会话。')- throw error- }- },-- validateComposition(agent: Agent): void {- const ctx = getServerContext<HostContext>(server)- if (typeof ctx.agentPresets.inspectCompositions !== 'function')- return- for (const composition of ctx.agentPresets.inspectCompositions(agent.ctx)) {- if (composition.modules.some(module => module.moduleName === '@deepseek-ai/dsh-hooks-codex' || module.moduleName === '@deepseek-ai/dsh-hooks-claude-code'))- throw new Error('BRIDGE_HOOK_COMPOSITION_UNSUPPORTED: 原生会话不能叠加官方 Codex / Claude hooks,避免重复执行本机配置。')- }- },-- async execute(input: NativeExecution): Promise<OfficialSink> {- const ctx = getServerContext<HostContext>(server)- if (input.binding.sessionId !== input.agent.session.id || !sameBinding(ctx.sessionProjections.stateOf(input.agent.session, 'bridgeKernel')?.binding, input.binding))- throw new Error('BRIDGE_BINDING_MISMATCH: 不能替换已有会话的原生内核。')- input.signal.throwIfAborted()- const current = runtime.exchanges.get(input.agent.id)- if (current) {- const state = current.state- if (state.input.agent !== input.agent || state.input.turn !== input.turn || state.input.signal !== input.signal || input.step <= state.lastStep || !sameBinding(state.input.binding, input.binding) || state.finalConsumed)- throw new Error('BRIDGE_TURN_MISMATCH: 原生回合不能重试、替换或跨回合复用。')- for (const tool of state.tools.values()) {- if (tool.step !== undefined && tool.step <= state.lastStep && !tool.committed)- throw new Error('BRIDGE_TOOL_RESULT_REJECTED: 官方工具结果尚未完整提交。')- }- state.signal.throwIfAborted()- if (state.failure !== undefined)- throw state.failure- state.lastStep = input.step- return current- }- const official = await sink.create(input)- const state = official.state- runtime.sinks.set(input.agent.id, state.native)- state.task = (async () => {- try {- const entry = await open(input.agent, input.binding.backend, input.binding.nativeSessionId, state.signal)- state.signal.throwIfAborted()- if (!sameBinding(entry.binding, input.binding))- throw new Error('BRIDGE_RESUME_MISMATCH: 原生内核未恢复已绑定的会话。')- await entry.session.submit(input.messages, state.signal, input.options, permissionOf(input.agent.session))- official.settle()- }- catch (error) {- official.settle(error)- }- finally {- if (runtime.sinks.get(input.agent.id) === state.native)- runtime.sinks.delete(input.agent.id)- }- })()- return official- },-- async finish(agent: Agent, turn: number): Promise<void> {- const official = runtime.exchanges.get(agent.id)- if (!official || official.state.input.agent !== agent || official.state.input.turn !== turn)- return- const previous = runtime.closings.get(agent.id)- if (previous)- return previous- const task = drainTurn(official)- runtime.closings.set(agent.id, task)- try {- await task- }- finally {- if (runtime.closings.get(agent.id) === task)- runtime.closings.delete(agent.id)- }- },-- async remove(sessionId: string, owner?: Agent): Promise<void> {- if (owner !== undefined && !ownsSession(sessionId, owner))- return- const previous = runtime.removals.get(sessionId)- if (previous)- return previous- const task = close(sessionId, owner)- runtime.removals.set(sessionId, task)- try {- await task- }- finally {- if (runtime.removals.get(sessionId) === task)- runtime.removals.delete(sessionId)- }- },-- async dispose(): Promise<void> {- runtime.lifetime.abort(new Error('BRIDGE_DISPOSED'))- const agents = new Set([...runtime.sessions.values()].map(entry => entry.agent))- for (const step of runtime.steps.values())- agents.add(step.agent)- for (const agent of agents)- agent.cancel({ kind: 'disposed' })- const idle = await Promise.allSettled([...agents].map(agent => agent.whenIdle()))- await resetRuntime()- const failures = idle.filter((result): result is PromiseRejectedResult => result.status === 'rejected')- if (failures.length > 0)- throw new AggregateError(failures.map(result => result.reason), 'BRIDGE_IDLE_FAILED')- },-})--async function drainTurn(official: OfficialSink): Promise<void> {- const state = official.state- const complete = state.done && state.finalConsumed && !state.signal.aborted && state.failure === undefined && [...state.tools.values()].every(tool => tool.committed)- if (!complete)- state.controller.abort(state.failure ?? new Error('BRIDGE_PREMATURE_TURN_END: 官方回合提前结束,已停止原生内核。'))- try {- await state.task- if (!complete)- throw state.failure ?? state.signal.reason ?? new Error('BRIDGE_PREMATURE_TURN_END')- }- finally {- try {- if (!complete)- await session.remove(state.input.agent.id, state.input.agent)- }- finally {- await official.dispose()- }- }-}--async function bindFork(agent: Agent, source: KernelBinding, signal: AbortSignal, parent: Session): Promise<AgentSetupCommit> {- const lifetime = runtime.lifetime- const startup = new AbortController()- agent.ctx.effect(() => async () => {- startup.abort(new Error('BRIDGE_SETUP_CLOSED'))- await session.remove(agent.id, agent)- }, 'bridge native fork setup')- const scoped = AbortSignal.any([signal, startup.signal, lifetime.signal])- const ctx = getServerContext<HostContext>(server)- try {- scoped.throwIfAborted()- agent.ctx.fiber.assertActive()- session.validateComposition(agent)- assertForkSource(parent, agent, source)- const hasConversation = parent.deriveMessages().some(message => message.role === 'assistant' || message.role === 'tool' || (message.role === 'user' && message.source.kind === 'user'))- const entry = await open(agent, source.backend, null, scoped, hasConversation ? { forkFrom: source.nativeSessionId } : undefined)- assertForkSource(parent, agent, source)- scoped.throwIfAborted()- agent.ctx.fiber.assertActive()- if (entry.binding.nativeSessionId === source.nativeSessionId)- throw new Error('BRIDGE_FORK_MISMATCH: 工作树必须获得独立的原生会话身份。')- const seq = await identity.append(agent, entry.binding)- if (agent.options.provider === undefined && agent.options.model === undefined)- identity.hydrate(agent)- if (ctx.agents.get(agent.id) === agent && ctx.sessions.get(agent.id) === agent.session)- checkpoint.mark(agent, KERNEL_RECORD_TYPE, seq, entry.binding)- scoped.throwIfAborted()- agent.ctx.fiber.assertActive()- return {- commit(): void {- scoped.throwIfAborted()- agent.ctx.fiber.assertActive()- assertForkSource(parent, agent, source)- if (runtime.lifetime !== lifetime || !runtime.ready || !sameBinding(identity.resolve(agent), entry.binding) || ctx.sessionProjections.stateOf(agent.session, 'bridgeKernel')?.inheritedBinding?.sessionId !== agent.session.header.parentSession)- throw new Error('BRIDGE_BINDING_NOT_COMMITTED: 工作树原生身份未写入官方投影。')- },- }- }- catch (error) {- await session.remove(agent.id, agent)- throw error- }-}--async function resolveParent(sessionId: string, signal: AbortSignal): Promise<Agent> {- const ctx = getServerContext<HostContext>(server)- runtime.lifetime.signal.throwIfAborted()- const live = ctx.agents.get(sessionId as SessionId)- if (live)- return live- const controller = ctx.get('sessionController')- if (typeof controller?.resolveAgent !== 'function')- throw new Error('BRIDGE_FORK_SOURCE_UNAVAILABLE: 无法读取原生派生的官方父会话。')- const result = await waitFor<Awaited<ReturnType<HostContext['sessionController']['resolveAgent']>>>(controller.resolveAgent(sessionId as SessionId), signal)- signal.throwIfAborted()- if ('error' in result)- throw result.error- runtime.lifetime.signal.throwIfAborted()- if (!result.agent)- throw new Error('BRIDGE_FORK_SOURCE_UNAVAILABLE: 官方父会话无法恢复。')- return result.agent-}--function assertForkSource(parent: Session, child: Agent, binding: KernelBinding): void {- const ctx = getServerContext<HostContext>(server)- if (parent.id !== child.session.header.parentSession || parent.seq !== child.session.inheritedEventCount || !sameBinding(ctx.sessionProjections.stateOf(parent, 'bridgeKernel')?.binding, binding))- throw new Error('BRIDGE_FORK_SOURCE_CHANGED: 父会话与当前继承前缀不一致,请重新创建工作树会话。')-}--async function close(sessionId: string, owner?: Agent): Promise<void> {- if (owner !== undefined && !ownsSession(sessionId, owner))- return- const controller = runtime.controllers.get(sessionId)- controller?.abort(new Error('BRIDGE_SESSION_DISPOSED'))- const pending = runtime.pending.get(sessionId)- if (pending)- await pending.task.catch(() => undefined)- const entry = runtime.sessions.get(sessionId)- if (entry) {- try {- await entry.session.dispose()- }- catch (error) {- getServerContext<HostContext>(server).logger?.warn?.('dsh-tauri-kernel: native process termination failed', error)- }- if (runtime.sessions.get(sessionId) === entry)- runtime.sessions.delete(sessionId)- if (runtime.claims.get(keyOf(entry.binding)) === sessionId)- runtime.claims.delete(keyOf(entry.binding))- }- if (runtime.controllers.get(sessionId) === controller)- runtime.controllers.delete(sessionId)-}--async function open(agent: Agent, id: KernelBinding['backend'], storedId: string | null, signal: AbortSignal, options?: NativeSessionOpenOptions): Promise<NativeEntry> {- signal.throwIfAborted()- runtime.lifetime.signal.throwIfAborted()- if (runtime.removals.has(agent.id))- throw new Error('BRIDGE_SESSION_CLOSING: 原生会话正在关闭。')- const current = runtime.sessions.get(agent.id)- if (current) {- if (current.agent !== agent || current.binding.backend !== id || (storedId !== null && current.binding.nativeSessionId !== storedId))- throw new Error('BRIDGE_NATIVE_OWNER_CONFLICT: 原生会话已有其它所有者。')- return current- }- const pending = runtime.pending.get(agent.id)- if (pending) {- if (pending.agent !== agent)- throw new Error('BRIDGE_NATIVE_OWNER_CONFLICT: 待连接的原生会话属于其它所有者。')- const entry = await pending.task- signal.throwIfAborted()- if (entry.agent !== agent || entry.binding.backend !== id || (storedId !== null && entry.binding.nativeSessionId !== storedId))- throw new Error('BRIDGE_NATIVE_OWNER_CONFLICT: 待连接的原生会话属于其它所有者。')- return entry- }- const controller = new AbortController()- runtime.controllers.set(agent.id, controller)- const task = connect(agent, id, storedId, controller, AbortSignal.any([runtime.lifetime.signal, controller.signal, signal]), options)- const opening = { agent, controller, task }- runtime.pending.set(agent.id, opening)- try {- return await task- }- finally {- if (runtime.pending.get(agent.id) === opening)- runtime.pending.delete(agent.id)- if (!runtime.sessions.has(agent.id) && runtime.controllers.get(agent.id) === controller)- runtime.controllers.delete(agent.id)- }-}--async function connect(agent: Agent, id: KernelBinding['backend'], storedId: string | null, controller: AbortController, signal: AbortSignal, options?: NativeSessionOpenOptions): Promise<NativeEntry> {- const resolved = await backend.resolve(id)- signal.throwIfAborted()- if (!resolved.detection.installed || !resolved.command || resolved.detection.auth === 'missing')- throw new Error(resolved.detection.hint ?? 'BRIDGE_BACKEND_UNAVAILABLE: 本机内核不可用。')- const nativeSink: NativeSink = {- text: (...args) => activeSink(agent, controller).text(...args),- thinking: (...args) => activeSink(agent, controller).thinking(...args),- assistant: (...args) => activeSink(agent, controller).assistant(...args),- toolStart: (...args) => activeSink(agent, controller).toolStart(...args),- toolEnd: (...args) => activeSink(agent, controller).toolEnd(...args),- approval: (...args) => activeSink(agent, controller).approval(...args),- questions: (...args) => activeSink(agent, controller).questions(...args),- }- const factory = id === 'codex' ? createCodexSession : createClaudeSession- const permission = permissionOf(agent.session)- const native = await factory(resolved.command, agent.session.header.cwd!, storedId, nativeSink, signal, permission === undefined ? options : { ...options, permission }, nativeAttachments(getServerContext<HostContext>(server)))- try {- signal.throwIfAborted()- if (!native.id || (storedId !== null && storedId !== native.id))- throw new Error('BRIDGE_RESUME_MISMATCH: 原生内核返回了不同的会话身份。')- const binding: KernelBinding = { backend: id, nativeSessionId: native.id, sessionId: agent.session.id }- const owner = runtime.claims.get(keyOf(binding))- if (owner !== undefined && owner !== agent.id)- throw new Error('BRIDGE_NATIVE_OWNER_CONFLICT: 原生会话已绑定其它官方会话。')- const entry = { agent, binding, session: native, controller }- runtime.claims.set(keyOf(binding), agent.id)- runtime.sessions.set(agent.id, entry)- return entry- }- catch (error) {- await native.dispose()- throw error- }-}--/** Official attachment access for native prompts; absent without an image provider. */-function nativeAttachments(ctx: HostContext): NativeAttachments | undefined {- const store = ctx.get('attachments')- if (store === undefined)- return undefined- return {- path: ref => store.imageHostPath(ref),- async read(ref, signal) {- const stored = await store.readImage(ref, signal)- if (!(stored.data instanceof Uint8Array) || stored.ref.mediaType.length === 0)- throw new NativeBridgeError('BRIDGE_PROTOCOL', 'The official attachment store returned an unreadable image')- return { mediaType: stored.ref.mediaType, base64: Buffer.from(stored.data).toString('base64') }- },- }-}--function ownsSession(sessionId: string, owner: Agent): boolean {- const entry = runtime.sessions.get(sessionId)- const pending = runtime.pending.get(sessionId)- return entry?.agent === owner || pending?.agent === owner-}--function activeSink(agent: Agent, controller: AbortController): NativeSink {- controller.signal.throwIfAborted()- const current = runtime.sinks.get(agent.id)- const exchange = runtime.exchanges.get(agent.id)- if (runtime.controllers.get(agent.id) !== controller || exchange?.state.input.agent !== agent || exchange.state.native !== current)- throw new Error('BRIDGE_NOTIFICATION_OUTSIDE_TURN: 原生内核在官方回合外或替换后输出。')- return exchange.state.native-}--function permissionOf(value: Session): NativePermission | undefined {- const state = getServerContext<HostContext>(server).sessionProjections.stateOf(value, 'permissions')- if (!state || (state.sandbox === null && state.approval === null))- return undefined- return { sandbox: state.sandbox ?? undefined, approval: state.approval ?? undefined }-}--function sameBinding(left: KernelBinding | null | undefined, right: KernelBinding): boolean {- return left?.backend === right.backend && left.nativeSessionId === right.nativeSessionId && left.sessionId === right.sessionId-}--function keyOf(binding: KernelBinding): string {- return `${binding.backend}:${binding.nativeSessionId}`-}diff --git a/packages/dsh-tauri-kernel/src/host/service/sink.test.ts b/packages/dsh-tauri-kernel/src/host/service/sink.test.tsdeleted file mode 100644index a74bc4ab..00000000--- a/packages/dsh-tauri-kernel/src/host/service/sink.test.ts+++ /dev/null@@ -1,650 +0,0 @@-import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent'-import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'-import type { UserMessage } from '@deepseek-ai/dsh-llm'-import type { SessionEvent } from '@deepseek-ai/dsh-session'-import type { PostToolDecision, ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'-import type { ApprovalRequest } from '@deepseek-ai/dsh-user-approval'-import type { AskUserQuestionRequest } from '@deepseek-ai/dsh-user-questions'-import type { NativeSession, NativeSink } from '../backends/types'-import type { HostContext, NativeExecution, PlatformLoader } from '../types'-import type { OfficialSink } from './sink.types'-import { createRequire } from 'node:module'-import process from 'node:process'-import { pathToFileURL } from 'node:url'-import { Context } from '@deepseek-ai/cordis'-import { AgentRegistry } from '@deepseek-ai/dsh-agent'-import { AgentLoop } from '@deepseek-ai/dsh-agent-loop'-import * as llmModule from '@deepseek-ai/dsh-llm'-import * as sessionModule from '@deepseek-ai/dsh-session'-import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'-import { ToolRuntime } from '@deepseek-ai/dsh-tools'-import { ApprovalService } from '@deepseek-ai/dsh-user-approval'-import { UserQuestionService } from '@deepseek-ai/dsh-user-questions'-import { getServerContext } from 'dsh-h3/utils'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import * as zodModule from 'zod'-import { apply } from '../apply'-import { BRIDGE_PROVIDER } from '../config/constants'-import { resetRuntime, runtime } from '../config/runtime'-import { server } from '../server'-import { identity } from './identity'-import { session as bridgeSession } from './session'-import { sink } from './sink'--const require = createRequire(import.meta.url)-const loopRequire = createRequire(require.resolve('@deepseek-ai/dsh-agent-loop'))-const promptModule: { SystemPrompt: new (ctx: Context, options: { includeHarnessIdentity: boolean, includeRuntimeContext: boolean }) => Context['systemPrompt'] } = await import(pathToFileURL(loopRequire.resolve('@deepseek-ai/dsh-system-prompt')).href)--let context: Context-let agents: AgentRegistry-let agent: Agent-let handle: AgentHandle-let connection: NativeSession & { submit: ReturnType<typeof vi.fn<NativeSession['submit']>>, dispose: ReturnType<typeof vi.fn<NativeSession['dispose']>> }-let events: SessionEvent[]-let errors: unknown[]-let results: { exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult> }[]-let timeline: string[]-let exchanges: OfficialSink[]-let releases: (() => void)[]-let background: Promise<unknown>[]-let nativeScript: (output: NativeSink, messages: readonly UserMessage[], signal: AbortSignal) => Promise<void>--function output(): NativeSink {- const exchange = runtime.exchanges.get(agent.id)- if (!exchange)- throw new Error('Test native boundary has no active official sink')- return exchange.state.native-}--function inheritedTool(name = 'shell_command') {- const body = vi.fn(async () => 'inherited DSH body must not run')- context.tools.register({- name,- description: 'inherited DSH test capability',- parameters: { type: 'object', additionalProperties: true },- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },- execute: body,- })- return body-}--function nativeCall(output: NativeSink, id: string, arguments_ = '{}', name = 'shell_command') {- output.assistant(`${id}:assistant`, [{ type: 'tool-call', id, name, arguments: arguments_ }])- output.toolStart(id, name, arguments_)-}--async function exchange(): Promise<OfficialSink> {- agent.session.append('turn/start', { turn: 1 })- agent.session.append('step/start', { turn: 1, step: 1 })- const input: NativeExecution = {- agent,- turn: 1,- step: 1,- messages: [],- signal: new AbortController().signal,- dispatched: true,- binding: identity.resolve(agent),- }- const current = await sink.create(input)- exchanges.push(current)- return current-}--function runTurn(): Promise<void> {- agent.followup(llmModule.createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'native task' }] }))- const idle = agent.whenIdle()- background.push(idle)- return idle-}--function execute(id: string, signal: AbortSignal, arguments_: unknown = {}, name = 'shell_command') {- const task = context.tools.execute({ agent, callId: llmModule.ToolCallId(id), name, arguments: arguments_, signal })- background.push(task)- return task-}--function toolResults() {- return events.filter((event): event is Extract<SessionEvent, { type: 'tool/result' }> => event.type === 'tool/result')-}--function assistants() {- return events.filter((event): event is Extract<SessionEvent, { type: 'assistant/message' }> => event.type === 'assistant/message')-}--beforeEach(async () => {- await resetRuntime()- runtime.lifetime = new AbortController()- context = new Context()- agents = new AgentRegistry(context)- const services = [- new sessionModule.SessionStore(context),- new SessionProjectionRegistry(context),- new llmModule.LlmRuntime(context),- new promptModule.SystemPrompt(context, { includeHarnessIdentity: false, includeRuntimeContext: false }),- new ToolRuntime(context, { mode: 'native' }),- new ApprovalService(context, { policy: 'ask' }),- new UserQuestionService(context),- ]- expect(services).toHaveLength(7)- events = []- errors = []- results = []- timeline = []- exchanges = []- releases = []- background = []- context.on('session/event', (value, event) => {- if (value === agent?.session) {- events.push(event)- if (event.type === 'tool/result')- timeline.push(`commit:${event.data.message.toolCallId}`)- }- })- context.on('agent/error', ({ error }) => {- errors.push(error)- })- context.on('tools/result', (exec, result) => {- results.push({ exec, result })- timeline.push(`result:${exec.callId}`)- return undefined- })- const routes = new Map<string, WebRoute>()- context.provide('webServer', {- register(route: WebRoute) {- routes.set(route.path, route)- return () => {- routes.delete(route.path)- }- },- } as unknown as HostContext['webServer'])- const loader: PlatformLoader = {- async import(id) {- if (id === 'zod')- return zodModule- if (id === '@deepseek-ai/dsh-llm')- return llmModule- if (id === '@deepseek-ai/dsh-session')- return sessionModule- throw new Error(`Unexpected public runtime import: ${id}`)- },- unwrapExports: value => value,- }- context.provide('loader', loader as HostContext['loader'])- context.provide('agentPresets', { inspectCompositions: () => [] } as unknown as HostContext['agentPresets'])- const loop = context.plugin(AgentLoop, { agents: [] })- await loop.await()- context.plugin((ctx) => {- apply(ctx as HostContext)- })- await vi.waitFor(() => expect(runtime.ready).toBe(true))- expect(getServerContext<HostContext>(server).root).toBe(context.root)- expect([...routes.keys()].sort()).toEqual(['/api/tauri/bridge/backends', '/api/tauri/bridge/models', '/api/tauri/bridge/sessions'])- handle = await agents.create({- sessionId: sessionModule.SessionId('sink-contract-session'),- meta: { cwd: process.cwd() },- agentOptions: { provider: BRIDGE_PROVIDER, model: 'codex' },- async setup(_agentCtx, owner) {- await identity.append(owner, { backend: 'codex', nativeSessionId: 'native-sink-session', sessionId: owner.id })- owner.session.append('request/header', { header: { config: { provider: BRIDGE_PROVIDER, model: 'codex' } }, reason: 'initial' })- },- })- agent = handle.agent- nativeScript = async (native) => {- native.assistant('final', [{ type: 'text', text: 'native done' }])- }- connection = {- id: 'native-sink-session',- submit: vi.fn<NativeSession['submit']>(async (messages, signal) => nativeScript(output(), messages, signal)),- dispose: vi.fn<NativeSession['dispose']>().mockResolvedValue(undefined),- }- runtime.sessions.set(agent.id, { agent, binding: identity.resolve(agent), session: connection, controller: new AbortController() })-})--afterEach(async () => {- for (const release of releases)- release()- for (const current of exchanges)- current.settle(new Error('TEST_TURN_CLOSED'))- await bridgeSession.dispose()- await Promise.allSettled(background)- await handle?.dispose()- await context.fiber.dispose()- await resetRuntime()- vi.restoreAllMocks()-})--describe('real official cross-step native sink', () => {- it('settles a full terminal queue with done, one wake, and a retained overflow failure', async () => {- const current = await exchange()- const native = current.state.native- for (let index = 0; index < 8_190; index++)- native.text('full', 'x')- native.assistant('full', [{ type: 'text', text: 'x'.repeat(8_190) }])- expect(current.state.queue).toHaveLength(8_192)- const wake = vi.fn()- current.state.wake = wake- expect(() => current.settle()).not.toThrow()- expect(current.state.done).toBe(true)- expect(current.state.active).toBe(false)- expect(current.state.failure).toMatchObject({ message: 'BRIDGE_STREAM_OVERFLOW: 原生输出超过缓冲限制。' })- expect(current.state.queue.filter(chunk => chunk.type === 'finish')).toEqual([])- expect(wake).toHaveBeenCalledOnce()- expect(current.state.wake).toBeUndefined()- current.settle()- expect(wake).toHaveBeenCalledOnce()- })-- it('wakes the real official stream with overflow instead of leaving its idle future hanging', async () => {- nativeScript = async (native) => {- native.text('overflow', 'x'.repeat(8 * 1_024 * 1_024))- }- await runTurn()- expect(connection.submit).toHaveBeenCalledOnce()- expect(errors).toHaveLength(1)- expect(errors[0]).toMatchObject({ message: 'BRIDGE_STREAM_OVERFLOW: 原生输出超过缓冲限制。' })- expect(events.filter(event => event.type === 'turn/end')).toHaveLength(1)- expect(runtime.exchanges.size).toBe(0)- expect(agent.status).toBe('idle')- }, 10_000)-- it('queues 32 early native results across real official steps without invoking an inherited DSH body', async () => {- const inherited = inheritedTool()- nativeScript = async (native) => {- for (let index = 0; index < 32; index++)- nativeCall(native, `native-${index}`, JSON.stringify({ command: `inspect-${index}` }))- for (let index = 31; index >= 0; index--)- native.toolEnd(`native-${index}`, `native output ${index}`)- native.assistant('final', [{ type: 'text', text: 'all native tools settled' }])- }- await runTurn()- expect(errors).toEqual([])- expect(connection.submit).toHaveBeenCalledOnce()- expect(inherited).not.toHaveBeenCalled()- expect(assistants().map(event => event.data.step)).toEqual(Array.from({ length: 33 }, (_, index) => index + 1))- expect(assistants().slice(0, 32).map(event => event.data.message.content)).toEqual(Array.from({ length: 32 }, (_, index) => [{ type: 'tool-call', id: `native-${index}`, name: 'shell_command', arguments: JSON.stringify({ command: `inspect-${index}` }) }]))- expect(assistants()[32]!.data.message.content).toEqual([{ type: 'text', text: 'all native tools settled' }])- expect(toolResults().map(event => ({ id: event.data.message.toolCallId, step: event.data.step, content: event.data.message.content }))).toEqual(Array.from({ length: 32 }, (_, index) => ({ id: `native-${index}`, step: index + 1, content: [{ type: 'text', text: `native output ${index}` }] })))- expect(toolResults().map(event => event.data.message.isError)).toEqual(Array.from({ length: 32 }).fill(false))- expect(results.map(({ result }) => result)).toEqual(Array.from({ length: 32 }, (_, index) => ({ isError: false, value: `native output ${index}`, content: [{ type: 'text', text: `native output ${index}` }] })))- expect(results.every(({ exec, result }) => exec.agent === agent && Object.isFrozen(exec) && Object.isFrozen(result))).toBe(true)- expect(timeline).toEqual(Array.from({ length: 32 }, (_, index) => [`result:native-${index}`, `commit:native-${index}`]).flat())- expect(context.tools.get('shell_command', agent)?.execute).toBe(inherited)- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it('keeps a native command turn alive when DSH replaces a committed long result in model history', async () => {- const full = `${'H'.repeat(4_096)}${'M'.repeat(4_096)}${'T'.repeat(1_024)}`- const pruned = `${'H'.repeat(4_096)}\n\n[... tool result middle pruned ...]\n\n${'T'.repeat(1_024)}`- let current!: OfficialSink- context.on('agent/pre-step', async (payload, next) => {- if (payload.agent === agent && payload.step === 2) {- current = runtime.exchanges.get(agent.id)!- const original = toolResults()[0]!- agent.session.append('tool/result', {- ...original.data,- message: { ...original.data.message, content: [{ type: 'text', text: pruned }] },- }, {- surfaceOp: { op: 'replace', startSeq: original.seq, endSeq: original.seq },- sourceEventSeqs: [original.seq],- })- }- return next()- })- nativeScript = async (native) => {- nativeCall(native, 'long-command', '{}', 'commandExecution')- native.toolEnd('long-command', full)- native.assistant('final', [{ type: 'text', text: 'continued after history pruning' }])- }- await runTurn()- expect(errors).toEqual([])- expect(current.state.failure).toBeUndefined()- expect(current.state.tools.get('long-command')!.committed).toBe(true)- const [original, replacement] = toolResults()- expect(original!.surfaceOp).toBe('append')- expect(original!.data.message.content).toEqual([{ type: 'text', text: full }])- expect(replacement).toMatchObject({ surfaceOp: { op: 'replace', startSeq: original!.seq, endSeq: original!.seq }, sourceEventSeqs: [original!.seq], data: { turn: 1, step: 1, message: { toolCallId: 'long-command', content: [{ type: 'text', text: pruned }] } } })- expect(agent.session.deriveMessages().filter(message => message.role === 'tool').map(message => message.content)).toEqual([[{ type: 'text', text: pruned }]])- expect(assistants().map(event => event.data.step)).toEqual([1, 2])- expect(assistants()[1]!.data.message.content).toEqual([{ type: 'text', text: 'continued after history pruning' }])- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it.each(['content', 'isError', 'meta'] as const)('rejects a first official native result append with changed %s', async (field) => {- const current = await exchange()- nativeCall(current.state.native, 'first-append')- current.state.native.toolEnd('first-append', 'complete native output')- await execute('first-append', current.state.signal)- current.state.tools.get('first-append')!.step = 1- const message = llmModule.createToolResultMessage({ callId: llmModule.ToolCallId('first-append'), isError: field === 'isError', content: [{ type: 'text', text: field === 'content' ? 'pruned output' : 'complete native output' }] })- agent.session.append('tool/result', { turn: 1, step: 1, message, ...(field === 'meta' ? { meta: { rewritten: true } } : {}) }, { surfaceOp: 'append' })- expect(current.state.tools.get('first-append')!.committed).toBe(false)- expect(current.state.signal.aborted).toBe(true)- expect(current.state.failure).toMatchObject({ message: 'BRIDGE_TOOL_RESULT_REJECTED: 官方日志没有完整保留原生工具结果。' })- })-- it.each(['identical', 'changed'] as const)('rejects a genuinely duplicated official native result append with %s content', async (duplicate) => {- const current = await exchange()- nativeCall(current.state.native, 'duplicate-append')- current.state.native.toolEnd('duplicate-append', 'complete native output')- await execute('duplicate-append', current.state.signal)- current.state.tools.get('duplicate-append')!.step = 1- const message = llmModule.createToolResultMessage({ callId: llmModule.ToolCallId('duplicate-append'), isError: false, content: [{ type: 'text', text: 'complete native output' }] })- agent.session.append('tool/result', { turn: 1, step: 1, message }, { surfaceOp: 'append' })- expect(current.state.tools.get('duplicate-append')!.committed).toBe(true)- expect(current.state.signal.aborted).toBe(false)- agent.session.append('tool/result', { turn: 1, step: 1, message: { ...message, content: [{ type: 'text', text: duplicate === 'identical' ? 'complete native output' : 'changed output' }] } }, { surfaceOp: 'append' })- expect(current.state.signal.aborted).toBe(true)- expect(current.state.failure).toMatchObject({ message: 'BRIDGE_TOOL_RESULT_REJECTED: 官方日志没有完整保留原生工具结果。' })- })-- it('identifies only unsettled native tools without exposing their arguments or inventing results', async () => {- nativeScript = async (native) => {- nativeCall(native, 'finished-native', '{}', 'commandExecution')- native.toolEnd('finished-native', 'native result')- nativeCall(native, 'missing-native', '{"code":"private user input"}', 'mcp::node_repl/js')- native.assistant('final', [{ type: 'text', text: 'native done' }])- }- await runTurn()- expect(errors).toHaveLength(1)- expect(errors[0]).toMatchObject({ message: 'BRIDGE_TOOL_UNSETTLED: 原生内核没有确认全部工具结果。未确认工具:[{"id":"missing-native","name":"mcp::node_repl/js"}]' })- expect(toolResults().some(event => event.data.message.toolCallId === 'missing-native')).toBe(false)- expect(agent.status).toBe('idle')- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it('preserves native error text through the real tool pipeline and official result log', async () => {- const inherited = inheritedTool()- nativeScript = async (native) => {- nativeCall(native, 'failed-native')- native.toolEnd('failed-native', 'native stderr without a synthetic Error prefix', true)- native.assistant('final', [{ type: 'text', text: 'native recovery completed' }])- }- await runTurn()- expect(errors).toEqual([])- expect(inherited).not.toHaveBeenCalled()- expect(results).toHaveLength(1)- expect(results[0]!.result).toEqual({ isError: true, error: { message: 'native stderr without a synthetic Error prefix', info: { name: 'NativeToolError', code: 'BRIDGE_NATIVE_TOOL_ERROR' } }, content: [{ type: 'text', text: 'native stderr without a synthetic Error prefix' }] })- expect(toolResults()).toHaveLength(1)- expect(toolResults()[0]!.data).toMatchObject({ turn: 1, step: 1, message: { role: 'tool', toolCallId: 'failed-native', isError: true, content: [{ type: 'text', text: 'native stderr without a synthetic Error prefix' }] }, error: { name: 'NativeToolError', code: 'BRIDGE_NATIVE_TOOL_ERROR' } })- expect(assistants().map(event => event.data.step)).toEqual([1, 2])- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it('preserves a native failure when the host loader uses a distinct HarnessError module instance', async () => {- const reloaded = await import(`${pathToFileURL(require.resolve('@deepseek-ai/dsh-llm')).href}?native-error-reload`) as typeof llmModule- expect(new reloaded.HarnessError('probe', 'PROBE')).not.toBeInstanceOf(llmModule.HarnessError)- const originalImport = context.loader.import.bind(context.loader)- vi.spyOn(context.loader, 'import').mockImplementation(async id => id === '@deepseek-ai/dsh-llm' ? { ...llmModule, HarnessError: reloaded.HarnessError } : originalImport(id))- const stderr = 'Failed to create unified exec process: helper_unknown_error: setup refresh had errors'- nativeScript = async (native) => {- nativeCall(native, 'sandbox-refresh-failure', '{"command":"Get-Content -LiteralPath \'C:/fixture/skills/openai-docs/SKILL.md\'","cwd":"C:/fixture/workspace"}', 'commandExecution')- native.toolEnd('sandbox-refresh-failure', stderr, true)- native.assistant('final', [{ type: 'text', text: 'native failure acknowledged' }])- }- await runTurn()- expect(errors).toEqual([])- expect(results.map(({ result }) => result)).toEqual([{ isError: true, error: { message: stderr, info: { name: 'NativeToolError', code: 'BRIDGE_NATIVE_TOOL_ERROR' } }, content: [{ type: 'text', text: stderr }] }])- expect(toolResults().map(event => event.data.message)).toMatchObject([{ toolCallId: 'sandbox-refresh-failure', isError: true, content: [{ type: 'text', text: stderr }] }])- expect(assistants().map(event => event.data.step)).toEqual([1, 2])- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it('accepts semantically identical content properties at the final-result boundary', async () => {- const current = await exchange()- nativeCall(current.state.native, 'reordered')- current.state.native.toolEnd('reordered', 'canonical native output')- const result = await execute('reordered', current.state.signal)- expect(result).toEqual({ isError: false, value: 'canonical native output', content: [{ type: 'text', text: 'canonical native output' }] })- expect(sink.acceptTool(results[0]!.exec, { ...result, content: [{ text: 'canonical native output', type: 'text' }] })).toBeUndefined()- expect(current.state.tools.get('reordered')!.accepted).toBe(true)- expect(current.state.signal.aborted).toBe(false)- })-- it.each([false, true])('rejects changed native isError=%s content at the final-result boundary', async (isError) => {- const current = await exchange()- nativeCall(current.state.native, 'rewritten-error')- current.state.native.toolEnd('rewritten-error', 'canonical native output', isError)- const result = await execute('rewritten-error', current.state.signal)- expect(result.isError).toBe(isError)- expect(sink.acceptTool(results[0]!.exec, { ...result, content: [{ type: 'text', text: 'rewritten native error' }] })).toBeUndefined()- expect(current.state.signal.aborted).toBe(true)- expect(current.state.failure).toMatchObject({ message: expect.stringContaining('BRIDGE_TOOL_RESULT_REJECTED') })- })-- it('replays native results without duplicate DSH pre, around, or post policies while preserving core guards', async () => {- const inherited = inheritedTool()- const pre = vi.fn(async () => ({ kind: 'deny' as const, reason: 'DSH policy must not gate native replay' }))- const guard = vi.fn(() => undefined)- const around = vi.fn(async () => ({ isError: false as const, value: 'DSH replacement', content: [{ type: 'text' as const, text: 'DSH replacement' }] }))- const post = vi.fn(async (): Promise<PostToolDecision> => ({ kind: 'block', feedback: [{ type: 'text', text: 'DSH spill or repeat replacement' }] }))- context.on('tools/pre-execute', pre, { global: true })- context.tools.guard(guard)- agent.ctx.on('tools/execute', around)- agent.ctx.on('tools/post-execute', post)- nativeScript = async (native) => {- nativeCall(native, 'native-policy-isolation')- native.toolEnd('native-policy-isolation', 'canonical native output')- native.assistant('final', [{ type: 'text', text: 'native done' }])- }- await runTurn()- expect(errors).toEqual([])- expect(pre).not.toHaveBeenCalled()- expect(guard).toHaveBeenCalledOnce()- expect(around).not.toHaveBeenCalled()- expect(post).not.toHaveBeenCalled()- expect(inherited).not.toHaveBeenCalled()- expect(toolResults().map(event => event.data.message)).toMatchObject([{ toolCallId: 'native-policy-isolation', isError: false, content: [{ type: 'text', text: 'canonical native output' }] }])- expect(assistants().map(event => event.data.step)).toEqual([1, 2])- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it.each(['global', 'scoped'] as const)('retains a %s monotonic guard denial rather than silently force-allowing native replay', async (scope) => {- const inherited = inheritedTool()- const guard = vi.fn(() => 'composition guard denied replay')- ;(scope === 'global' ? context.tools : agent.ctx.tools).guard(guard)- nativeScript = async (native) => {- nativeCall(native, 'native-guard')- native.toolEnd('native-guard', 'canonical native output')- native.assistant('final', [{ type: 'text', text: 'must not override guard' }])- }- await runTurn()- expect(guard).toHaveBeenCalledOnce()- expect(inherited).not.toHaveBeenCalled()- expect(errors).toHaveLength(1)- expect(errors[0]).toMatchObject({ message: expect.stringContaining('BRIDGE_TOOL_RESULT_REJECTED') })- expect(results.map(({ result }) => result)).toMatchObject([{ isError: true, error: { message: 'composition guard denied replay' }, content: [{ type: 'text', text: 'Error: composition guard denied replay' }] }])- expect(assistants()).toHaveLength(1)- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it('leaves ordinary DSH policies active outside a native exchange', async () => {- const body = inheritedTool('ordinary_dsh_tool')- const pre = vi.fn(async (_exec: ToolExecution, next: () => Promise<import('@deepseek-ai/dsh-tools').PreToolDecision>) => next())- const guard = vi.fn(() => undefined)- const around = vi.fn(async (_exec: ToolExecution, next: () => Promise<ToolExecutionResult>) => next())- const post = vi.fn(async (): Promise<PostToolDecision> => ({ kind: 'accept', content: [{ type: 'text', text: 'ordinary DSH post policy' }] }))- agent.ctx.on('tools/pre-execute', pre)- agent.ctx.tools.guard(guard)- agent.ctx.on('tools/execute', around)- agent.ctx.on('tools/post-execute', post)- const result = await execute('ordinary', new AbortController().signal, {}, 'ordinary_dsh_tool')- expect(pre).toHaveBeenCalledOnce()- expect(guard).toHaveBeenCalledOnce()- expect(around).toHaveBeenCalledOnce()- expect(post).toHaveBeenCalledOnce()- expect(body).toHaveBeenCalledOnce()- expect(result).toEqual({ isError: false, value: 'inherited DSH body must not run', content: [{ type: 'text', text: 'ordinary DSH post policy' }] })- })-- it('keeps a native turn alive when DSH injects a mid-turn approval-policy notice', async () => {- context.on('tools/result', (exec) => {- if (exec.callId === 'policy-notice')- agent.inject(llmModule.createUserMessage({ source: { kind: 'user-approval' }, content: [{ type: 'text', text: 'Approval prompts are disabled in this session.' }] }))- return undefined- })- nativeScript = async (native) => {- nativeCall(native, 'policy-notice')- native.toolEnd('policy-notice', 'native output')- native.assistant('final', [{ type: 'text', text: 'continued after the policy switch' }])- }- await runTurn()- expect(errors).toEqual([])- expect(connection.submit).toHaveBeenCalledOnce()- expect(connection.submit.mock.calls[0]![0]).toMatchObject([{ content: [{ type: 'text', text: 'native task' }] }])- expect(assistants().map(event => event.data.step)).toEqual([1, 2])- expect(toolResults().map(event => event.data.message.toolCallId)).toEqual(['policy-notice'])- expect(events.filter((event): event is Extract<SessionEvent, { type: 'agent/inbox/spliced' }> => event.type === 'agent/inbox/spliced' && event.data.target === 'next-step').flatMap(event => event.data.inserted).map(message => message.source.kind)).toEqual(['user-approval'])- expect(events.filter(event => event.type === 'user/message').map(event => event.data.source.kind)).toEqual(['user', 'user-approval'])- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it('preserves an empty native error without adding fallback text to its content', async () => {- nativeScript = async (native) => {- nativeCall(native, 'empty-error')- native.toolEnd('empty-error', '', true)- native.assistant('final', [{ type: 'text', text: 'native done' }])- }- await runTurn()- expect(errors).toEqual([])- expect(results.map(({ result }) => result)).toEqual([{ isError: true, error: { message: 'Native tool failed', info: { name: 'NativeToolError', code: 'BRIDGE_NATIVE_TOOL_ERROR' } }, content: [{ type: 'text', text: '' }] }])- expect(toolResults().map(event => event.data.message.content)).toEqual([[{ type: 'text', text: '' }]])- expect(assistants().map(event => event.data.step)).toEqual([1, 2])- }, 10_000)-- it.each(['block', 'value', 'content', 'context'] as const)('keeps native output unchanged instead of applying duplicate post-execute %s policy', async (policy) => {- const inherited = inheritedTool()- const additional = llmModule.createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'extra policy context' }] })- const rewrite = vi.fn(async (): Promise<PostToolDecision> => {- if (policy === 'block')- return { kind: 'block', feedback: [{ type: 'text', text: 'policy denied native output' }] }- if (policy === 'value')- return { kind: 'accept', value: 'rewritten native value' }- if (policy === 'content')- return { kind: 'accept', content: [{ type: 'text', text: 'rewritten native content' }] }- return { kind: 'accept', additionalContexts: [additional] }- })- agent.ctx.on('tools/post-execute', rewrite)- nativeScript = async (native) => {- nativeCall(native, 'native-policy')- native.toolEnd('native-policy', 'canonical native output')- native.assistant('final', [{ type: 'text', text: 'native done' }])- }- await runTurn()- expect(connection.submit).toHaveBeenCalledOnce()- expect(inherited).not.toHaveBeenCalled()- expect(rewrite).not.toHaveBeenCalled()- expect(errors).toEqual([])- expect(toolResults().map(event => event.data.message)).toMatchObject([{ toolCallId: 'native-policy', isError: false, content: [{ type: 'text', text: 'canonical native output' }] }])- expect(assistants().map(event => event.data.step)).toEqual([1, 2])- expect(events.filter(event => event.type === 'user/message').map(event => event.data.id)).not.toContain(additional.id)- expect(runtime.exchanges.size).toBe(0)- }, 10_000)-- it('rejects an authored concludesTurn at the public final-result acceptance boundary', async () => {- const inherited = inheritedTool()- const current = await exchange()- nativeCall(current.state.native, 'concluding')- current.state.native.toolEnd('concluding', 'canonical native output')- const result = await execute('concluding', current.state.signal)- expect(result).toEqual({ isError: false, value: 'canonical native output', content: [{ type: 'text', text: 'canonical native output' }] })- expect(inherited).not.toHaveBeenCalled()- expect(current.state.signal.aborted).toBe(false)- if (result.isError)- throw new Error('The independent canonical success fixture unexpectedly failed')- expect(sink.acceptTool(results[0]!.exec, { ...result, concludesTurn: true })).toBeUndefined()- expect(current.state.signal.aborted).toBe(true)- expect(current.state.failure).toMatchObject({ message: expect.stringContaining('BRIDGE_TOOL_RESULT_REJECTED') })- })-- it.each(['allowed-once', 'rejected', 'cancelled', 'unavailable'] as const)('audits approval before any call is presented and grants only %s', async (outcome) => {- const current = await exchange()- const answerer = vi.fn(async (_request: ApprovalRequest) => outcome)- agent.ctx.on('approval/request', answerer)- expect(await current.state.native.approval('not-yet-presented', { kind: 'command', title: 'native command', details: 'native permission reason' })).toBe(outcome === 'allowed-once')- expect(current.state.tools.size).toBe(0)- expect(answerer).toHaveBeenCalledOnce()- const request = answerer.mock.calls[0]![0]- expect(request.agent).toBe(agent)- expect({ toolName: request.toolName, reason: request.reason }).toEqual({ toolName: 'native command', reason: 'native permission reason' })- expect(Object.hasOwn(request, 'callId')).toBe(false)- const audit = events.filter(event => event.type === 'approval/asked' || event.type === 'approval/decided')- expect(audit).toHaveLength(2)- expect(audit[0]).toMatchObject({ type: 'approval/asked', data: { toolName: 'native command', reason: 'native permission reason' } })- expect(audit[1]).toMatchObject({ type: 'approval/decided', data: { id: audit[0]!.data.id, outcome } })- })-- it('preserves multi-selection and custom answers through the real user-questions service', async () => {- const current = await exchange()- const questions = [{ id: 'multi', question: 'Select native targets', options: [{ label: 'red' }, { label: 'blue' }], multiSelect: true }, { id: 'single', question: 'Choose one', options: [{ label: 'one' }] }]- const answerer = vi.fn(async (_request: AskUserQuestionRequest) => ({ answers: [{ id: 'multi', selected: ['red', 'blue'], custom: 'custom, literal' }, { id: 'single', selected: ['one'] }] }))- agent.ctx.on('user-questions/request', answerer)- expect(await current.state.native.questions('native-question-call', questions)).toEqual({ multi: ['red', 'blue', 'custom, literal'], single: 'one' })- expect(answerer).toHaveBeenCalledOnce()- const request = answerer.mock.calls[0]![0]- expect(request.agent).toBe(agent)- expect(request.questions).toEqual(questions)- expect(request.wait).toEqual({ callId: 'native-question-call' })- expect(current.state.tools.size).toBe(0)- })-- it('rejects an incomplete question answer instead of dropping unanswered identities', async () => {- const current = await exchange()- agent.ctx.on('user-questions/request', async () => ({ answers: [{ id: 'first', selected: ['yes'] }] }))- await expect(current.state.native.questions('question-call', [{ id: 'first', question: 'First?' }, { id: 'second', question: 'Second?' }])).rejects.toThrow('BRIDGE_QUESTION_ANSWER_MISSING')- })-- it('refuses late callbacks after cancellation without adding queued chunks', async () => {- const current = await exchange()- const failure = new Error('native turn cancelled')- current.state.controller.abort(failure)- expect(() => current.state.native.text('late', 'forbidden')).toThrow(failure)- expect(current.state.queue).toEqual([])- current.settle()- expect(current.state.done).toBe(true)- expect(current.state.failure).toBe(failure)- expect(() => current.state.native.assistant('late-final', [{ type: 'text', text: 'forbidden' }])).toThrow('BRIDGE_NOTIFICATION_OUTSIDE_TURN')- expect(current.state.queue).toEqual([])- })-- it('deduplicates identical assistant and tool outcomes but refuses conflicting duplicates', async () => {- const current = await exchange()- const native = current.state.native- native.assistant('text', [{ type: 'text', text: 'authoritative text' }])- const initial = [...current.state.queue]- native.assistant('text', [{ type: 'text', text: 'authoritative text' }])- expect(current.state.queue).toEqual(initial)- expect(() => native.assistant('text', [{ type: 'text', text: 'changed text' }])).toThrow('BRIDGE_ASSISTANT_CONFLICT')- nativeCall(native, 'duplicate-native')- native.toolEnd('duplicate-native', 'canonical output')- native.toolEnd('duplicate-native', 'canonical output')- expect(current.state.tools.get('duplicate-native')!.result).toEqual({ output: 'canonical output', isError: false })- expect(() => native.toolEnd('duplicate-native', 'changed output')).toThrow('BRIDGE_TOOL_RESULT_CONFLICT')- expect(() => native.assistant('foreign-assistant', [{ type: 'tool-call', id: 'duplicate-native', name: 'shell_command', arguments: '{}' }])).toThrow('BRIDGE_TOOL_CONFLICT')- })-- it('does not dispatch an inherited tool body for an unpresented native call', async () => {- const inherited = inheritedTool()- const current = await exchange()- const result = await execute('never-presented', current.state.signal)- expect(inherited).not.toHaveBeenCalled()- expect(result).toMatchObject({ isError: true, content: [{ type: 'text', text: expect.stringContaining('BRIDGE_TOOL_NOT_PRESENTED') }] })- expect(current.state.signal.aborted).toBe(true)- expect(current.state.failure).toMatchObject({ message: expect.stringContaining('BRIDGE_TOOL_NOT_PRESENTED') })- })-- it('keeps pre-dispatch cancellation attributed by the real ToolRuntime instead of accepting a native result', async () => {- const inherited = inheritedTool()- const current = await exchange()- nativeCall(current.state.native, 'cancelled-before-dispatch')- current.state.native.toolEnd('cancelled-before-dispatch', 'native already finished')- const cancellation = new AbortController()- cancellation.abort(new Error('caller cancelled before official dispatch'))- const result = await execute('cancelled-before-dispatch', cancellation.signal)- expect(result).toMatchObject({ isError: true, error: { info: { code: 'ABORTED_BEFORE_DISPATCH' } } })- expect(inherited).not.toHaveBeenCalled()- expect(current.state.tools.get('cancelled-before-dispatch')!.dispatched).toBe(false)- expect(current.state.tools.get('cancelled-before-dispatch')!.accepted).toBe(false)- expect(current.state.signal.aborted).toBe(true)- expect(current.state.failure).toMatchObject({ message: expect.stringContaining('BRIDGE_TOOL_RESULT_REJECTED') })- })-})diff --git a/packages/dsh-tauri-kernel/src/host/service/sink.ts b/packages/dsh-tauri-kernel/src/host/service/sink.tsdeleted file mode 100644index 896192b2..00000000--- a/packages/dsh-tauri-kernel/src/host/service/sink.ts+++ /dev/null@@ -1,420 +0,0 @@-import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'-import type { PostToolDecision, PreToolDecision, ToolDispatchExecution, ToolExecution, ToolExecutionResult, ToolRunContext } from '@deepseek-ai/dsh-tools'-import type { HostContext, NativeExecution } from '../types'-import type { NativeToolResult, OfficialSink, SinkState, StreamTrack, ToolTrack } from './sink.types'-import { Buffer } from 'node:buffer'-import { isDeepStrictEqual } from 'node:util'-import { getServerContext } from 'dsh-h3/utils'-import { defineService } from 'dsh-tauri'-import { runtime } from '../config/runtime'-import { server } from '../server'-import { loadRuntimeModules } from '../utils/runtime-modules'--const MAX_QUEUED_CHUNKS = 8_192-const MAX_QUEUED_BYTES = 8 * 1_024 * 1_024-const MAX_TURN_BYTES = 64 * 1_024 * 1_024-const MAX_TURN_TOOLS = 1_024--export const sink = defineService({- async create(input: NativeExecution): Promise<OfficialSink> {- const ctx = getServerContext<HostContext>(server)- const modules = await loadRuntimeModules(ctx.loader)- const { agent, signal } = input- signal.throwIfAborted()- runtime.lifetime.signal.throwIfAborted()- if (runtime.exchanges.has(agent.id))- throw new Error('BRIDGE_BUSY: 此会话已有原生回合。')- const controller = new AbortController()- const state: SinkState = {- input,- controller,- signal: AbortSignal.any([signal, controller.signal, runtime.lifetime.signal]),- streams: new Map(),- assistants: new Map(),- tools: new Map(),- registrations: new Map(),- restoreMode: agent.ctx.tools.presentAs('native'),- queue: [],- queuedBytes: 0,- outputBytes: 0,- segment: 0,- nextIndex: 0,- lastStep: input.step,- active: true,- done: false,- finalConsumed: false,- native: {- text(id, text): void { delta(id, 'text', text) },- thinking(id, text): void { delta(id, 'reasoning', text) },- assistant(id, content): void {- assertActive()- const encoded = JSON.stringify(content)- const committed = state.assistants.get(id)- if (committed !== undefined) {- if (committed !== encoded)- throw new Error('BRIDGE_ASSISTANT_CONFLICT: 原生消息的重复提交不一致。')- return- }- const current = track(id)- const used = new Set<number>()- const calls: { index: number, call: Extract<typeof content[number], { type: 'tool-call' }> }[] = []- for (const block of content) {- if (block.type === 'tool-call') {- if (state.tools.has(block.id) || state.tools.size >= MAX_TURN_TOOLS)- throw new Error('BRIDGE_TOOL_CONFLICT: 原生工具身份重复或超过回合限制。')- const name = toolName(block.name)- const tool = createTool(name, block.arguments)- state.tools.set(block.id, tool)- register(name)- calls.push({ index: state.nextIndex++, call: { ...block, name } })- continue- }- const type = block.type === 'thinking' ? 'reasoning' : 'text'- let index = current.blocks.find(candidate => candidate.type === type && !used.has(candidate.index))?.index- if (index === undefined) {- index = startBlock(current, type)- push({ type: type === 'text' ? 'text-delta' : 'reasoning-delta', index, text: block.text })- }- used.add(index)- push({ type: 'block-end', index, block: { type, text: block.text } })- }- for (const block of current.blocks) {- if (!used.has(block.index))- push({ type: 'block-end', index: block.index, block: { type: block.type, text: '' } })- }- current.content = content- state.assistants.set(id, encoded)- account(encoded)- if (calls.length > 0) {- if ([...state.streams.values()].some(value => value.segment === state.segment && value.content === undefined))- throw new Error('BRIDGE_ASSISTANT_UNSETTLED: 原生工具边界前仍有未确认消息。')- for (const { index, call } of calls) {- const block = { ...call, id: modules.ToolCallId(call.id) }- push({ type: 'block-start', index, blockType: 'tool-call' })- push({ type: 'tool-call-delta', index, id: block.id, name: block.name, argumentsDelta: block.arguments })- push({ type: 'block-end', index, block })- }- push({ type: 'finish', reason: { kind: 'tool-calls' } })- state.segment++- state.nextIndex = 0- }- },- toolStart(id, name, arguments_): void {- assertActive()- const current = state.tools.get(id)- if (!current || current.name !== toolName(name) || current.arguments !== arguments_)- throw new Error('BRIDGE_TOOL_NOT_PRESENTED: 工具开始前没有对应的官方工具消息。')- current.started = true- },- toolEnd(id, output, isError = false): void {- assertActive()- const current = state.tools.get(id)- if (!current?.started)- throw new Error('BRIDGE_TOOL_NOT_STARTED: 原生工具结果没有对应调用。')- if (current.result !== undefined) {- if (current.result.output !== output || current.result.isError !== isError)- throw new Error('BRIDGE_TOOL_RESULT_CONFLICT: 原生工具的重复结果不一致。')- return- }- account(output)- current.result = { output, isError }- current.resolve(current.result)- },- async approval(id, request, requestSignal): Promise<boolean> {- assertActive()- const current = state.tools.get(id)- const outcome = await getServerContext<HostContext>(server).approval.request({- agent,- toolName: current?.name ?? request.title,- ...(current === undefined ? {} : { callId: modules.ToolCallId(id) }),- reason: request.details,- signal: requestSignal === undefined ? state.signal : AbortSignal.any([state.signal, requestSignal]),- })- assertActive()- requestSignal?.throwIfAborted()- return outcome === 'allowed-once'- },- async questions(id, questions, requestSignal): Promise<Record<string, string | string[]>> {- assertActive()- const answer = await getServerContext<HostContext>(server).userQuestions.ask({- agent,- questions,- wait: { callId: modules.ToolCallId(id) },- signal: requestSignal === undefined ? state.signal : AbortSignal.any([state.signal, requestSignal]),- })- assertActive()- requestSignal?.throwIfAborted()- const result: Record<string, string | string[]> = {}- for (const question of questions) {- const item = answer.answers.find(candidate => candidate.id === question.id)- if (!item)- throw new Error('BRIDGE_QUESTION_ANSWER_MISSING: 问题未得到完整回答。')- const values = [...item.selected, ...(item.custom === undefined ? [] : [item.custom])]- result[question.id] = question.multiSelect ? values : values.join(', ')- }- return result- },- },- }-- function assertActive(): void {- const host = getServerContext<HostContext>(server)- if (!state.active || host.agents.get(agent.id) !== agent || host.sessions.get(agent.id) !== agent.session)- throw new Error('BRIDGE_NOTIFICATION_OUTSIDE_TURN: 原生内核在回合结束后继续输出。')- state.signal.throwIfAborted()- }-- function account(text: string): number {- const bytes = Buffer.byteLength(text)- state.outputBytes += bytes- if (state.outputBytes > MAX_TURN_BYTES)- throw new Error('BRIDGE_STREAM_OVERFLOW: 原生回合超过输出限制。')- return bytes- }-- function push(chunk: SinkState['queue'][number]): void {- state.signal.throwIfAborted()- const bytes = account(JSON.stringify(chunk))- if (state.queue.length >= MAX_QUEUED_CHUNKS || state.queuedBytes + bytes > MAX_QUEUED_BYTES)- throw new Error('BRIDGE_STREAM_OVERFLOW: 原生输出超过缓冲限制。')- state.queue.push(chunk)- state.queuedBytes += bytes- state.wake?.()- state.wake = undefined- }-- function track(id: string): StreamTrack {- assertActive()- let current = state.streams.get(id)- if (!current) {- current = { blocks: [], deltaSlots: new Map(), segment: state.segment }- state.streams.set(id, current)- }- if (current.content !== undefined || current.segment !== state.segment)- throw new Error('BRIDGE_ASSISTANT_ALREADY_SETTLED: 原生消息已提交或跨越工具边界。')- return current- }-- function startBlock(current: StreamTrack, type: 'text' | 'reasoning'): number {- const index = state.nextIndex++- current.blocks.push({ index, type })- push({ type: 'block-start', index, blockType: type })- return index- }-- function delta(id: string, type: 'text' | 'reasoning', text: string): void {- const current = track(id)- let index = current.deltaSlots.get(type)- if (index === undefined) {- index = startBlock(current, type)- current.deltaSlots.set(type, index)- }- push({ type: type === 'text' ? 'text-delta' : 'reasoning-delta', index, text })- }-- function register(name: string): void {- if (state.registrations.has(name))- return- const dispose = agent.ctx.tools.register({- name,- description: '等待本机内核已经发起的工具结果;不执行 DSH 工具。',- parameters: { type: 'object', additionalProperties: true },- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },- isConcurrencySafe: () => true,- async execute(): Promise<never> {- throw new Error('BRIDGE_TOOL_ROUTE_UNAVAILABLE: 原生调用未经过官方工具检查。')- },- })- state.registrations.set(name, dispose)- }-- const official: OfficialSink = {- state,- settle(error): void {- if (!state.active)- return- if (error === undefined && !state.signal.aborted) {- if ([...state.streams.values()].some(current => current.content === undefined)) {- error = new Error('BRIDGE_ASSISTANT_UNSETTLED: 原生内核没有确认最终消息。')- }- else {- const pending = [...state.tools].filter(([, tool]) => tool.result === undefined).map(([id, tool]) => ({ id, name: tool.name }))- if (pending.length > 0)- error = new Error(`BRIDGE_TOOL_UNSETTLED: 原生内核没有确认全部工具结果。未确认工具:${JSON.stringify(pending)}`)- }- }- state.failure = error ?? (state.signal.aborted ? state.signal.reason : undefined)- state.active = false- try {- if (state.failure === undefined)- push({ type: 'finish', reason: { kind: 'stop' } })- }- catch (failure) {- state.failure = failure- }- finally {- if (state.failure !== undefined) {- for (const tool of state.tools.values())- tool.reject(state.failure)- }- state.done = true- state.wake?.()- state.wake = undefined- }- },- async dispose(): Promise<void> {- if (state.disposal)- return state.disposal- state.active = false- controller.abort(new Error('BRIDGE_TURN_CLOSED'))- for (const tool of state.tools.values())- tool.reject(state.failure ?? controller.signal.reason)- state.disposal = (async () => {- const outcomes = await Promise.allSettled([...state.registrations.values()].map(dispose => Promise.resolve().then(dispose)))- state.registrations.clear()- const mode = await Promise.allSettled([Promise.resolve().then(state.restoreMode)])- if (runtime.exchanges.get(agent.id) === official)- runtime.exchanges.delete(agent.id)- const failures = [...outcomes, ...mode].filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')- if (failures.length > 0)- throw new AggregateError(failures.map(failure => failure.reason), 'BRIDGE_TOOLS_DISPOSE_FAILED')- })()- return state.disposal- },- }- runtime.exchanges.set(agent.id, official)- return official- },-- async admitTool(exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision> {- const official = exec.agent === undefined ? undefined : runtime.exchanges.get(exec.agent.id)- if (!official)- return next()- try {- expectedTool(official.state, exec)- official.state.signal.throwIfAborted()- exec.signal.throwIfAborted()- // ponytail: 核心单调 guard 仍生效;上游公开原生结果回放接口后再消除这层差异。- return { kind: 'allow' }- }- catch (error) {- official.state.controller.abort(error)- await official.state.task- throw error- }- },-- async executeTool(exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> {- const official = exec.agent === undefined ? undefined : runtime.exchanges.get(exec.agent.id)- if (!official)- return next()- const state = official.state- const abort = (): void => state.controller.abort(exec.signal.reason)- try {- const tool = expectedTool(state, exec)- if (tool.dispatched)- throw new Error('BRIDGE_TOOL_ALREADY_DISPATCHED: 不能重复派发原生工具调用。')- tool.dispatched = true- exec.signal.addEventListener('abort', abort, { once: true })- if (exec.signal.aborted)- abort()- state.signal.throwIfAborted()- const result = await tool.wait- exec.signal.throwIfAborted()- state.signal.throwIfAborted()- const content = [{ type: 'text' as const, text: result.output }]- return result.isError- ? { isError: true, error: { message: result.output || 'Native tool failed', info: { name: 'NativeToolError', code: 'BRIDGE_NATIVE_TOOL_ERROR' } }, content }- : { isError: false, value: result.output, content }- }- catch (error) {- state.controller.abort(error)- await state.task- throw error- }- finally {- exec.signal.removeEventListener('abort', abort)- }- },-- async finishTool(exec: ToolExecution, _result: Readonly<ToolExecutionResult>, next: () => Promise<PostToolDecision>): Promise<PostToolDecision> {- const official = exec.agent === undefined ? undefined : runtime.exchanges.get(exec.agent.id)- if (!official)- return next()- try {- expectedTool(official.state, exec)- return { kind: 'accept' }- }- catch (error) {- official.state.controller.abort(error)- await official.state.task- throw error- }- },-- commitTool(value: Session, event: SessionEvent): void {- if (event.type !== 'tool/result' || event.surfaceOp !== 'append')- return- const official = runtime.exchanges.get(value.id)- if (!official || official.state.input.agent.session !== value || official.state.input.turn !== event.data.turn)- return- const state = official.state- const tool = state.tools.get(event.data.message.toolCallId)- if (!tool || tool.step !== event.data.step || !tool.accepted || tool.committed || !tool.result || tool.result.isError !== (event.data.message.isError === true) || !isDeepStrictEqual(event.data.message.content, [{ type: 'text', text: tool.result.output }]) || (tool.result.isError && event.data.error?.code !== 'BRIDGE_NATIVE_TOOL_ERROR') || event.data.meta !== undefined) {- state.failure = new Error('BRIDGE_TOOL_RESULT_REJECTED: 官方日志没有完整保留原生工具结果。')- state.controller.abort(state.failure)- return- }- tool.committed = true- },-- acceptTool(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): undefined {- const official = exec.agent === undefined ? undefined : runtime.exchanges.get(exec.agent.id)- if (!official)- return undefined- try {- const tool = expectedTool(official.state, exec)- if (!tool.dispatched || !tool.result || result.isError !== tool.result.isError || result.additionalContexts?.length || result.concludesTurn || !isDeepStrictEqual(result.content, [{ type: 'text', text: tool.result.output }]) || (!result.isError && result.value !== tool.result.output) || (result.isError && result.error.info?.code !== 'BRIDGE_NATIVE_TOOL_ERROR'))- throw new Error('BRIDGE_TOOL_RESULT_REJECTED: 官方工具结果与原生结果不一致,不能继续原生回合。')- tool.accepted = true- }- catch (error) {- official.state.failure = error- official.state.controller.abort(error)- }- return undefined- },-})--function createTool(name: string, arguments_: string): ToolTrack {- let resolve!: (result: NativeToolResult) => void- let reject!: (error: unknown) => void- const wait = new Promise<NativeToolResult>((accept, fail) => {- resolve = accept- reject = fail- })- void wait.catch(() => undefined)- return { name, arguments: arguments_, started: false, dispatched: false, accepted: false, committed: false, wait, resolve, reject }-}--function expectedTool(state: SinkState, exec: Readonly<ToolExecution> | ToolRunContext | ToolDispatchExecution): ToolTrack {- const tool = state.tools.get(exec.callId)- if (state.input.agent !== exec.agent || !tool || exec.parent !== undefined || tool.name !== exec.name || !sameArguments(tool.arguments, exec.arguments))- throw new Error('BRIDGE_TOOL_NOT_PRESENTED: 没有对应的原生工具调用。')- return tool-}--function sameArguments(raw: string, value: unknown): boolean {- try {- return isDeepStrictEqual(raw === '' ? {} : JSON.parse(raw), value)- }- catch {- return raw === value- }-}--function toolName(name: string): string {- if (name === 'AskUserQuestion')- return 'ask_user_question'- return name === 'run_code' ? 'native_run_code' : name-}diff --git a/packages/dsh-tauri-kernel/src/host/service/sink.types.ts b/packages/dsh-tauri-kernel/src/host/service/sink.types.tsdeleted file mode 100644index e3b62dfe..00000000--- a/packages/dsh-tauri-kernel/src/host/service/sink.types.ts+++ /dev/null@@ -1,60 +0,0 @@-import type { StreamChunk } from '@deepseek-ai/dsh-llm'-import type { NativeContent, NativeSink } from '../backends/types'-import type { NativeExecution } from '../types'--export interface StreamTrack {- blocks: { index: number, type: 'text' | 'reasoning' }[]- deltaSlots: Map<'text' | 'reasoning', number>- segment: number- content?: readonly NativeContent[]-}--export interface NativeToolResult {- output: string- isError: boolean-}--export interface ToolTrack {- name: string- arguments: string- started: boolean- dispatched: boolean- step?: number- accepted: boolean- committed: boolean- result?: NativeToolResult- wait: Promise<NativeToolResult>- resolve: (result: NativeToolResult) => void- reject: (error: unknown) => void-}--export interface SinkState {- input: NativeExecution- native: NativeSink- controller: AbortController- signal: AbortSignal- streams: Map<string, StreamTrack>- assistants: Map<string, string>- tools: Map<string, ToolTrack>- registrations: Map<string, () => void | Promise<void>>- restoreMode: () => void | Promise<void>- queue: StreamChunk[]- queuedBytes: number- outputBytes: number- segment: number- nextIndex: number- lastStep: number- active: boolean- done: boolean- finalConsumed: boolean- failure?: unknown- wake?: () => void- task?: Promise<void>- disposal?: Promise<void>-}--export interface OfficialSink {- state: SinkState- settle: (error?: unknown) => void- dispose: () => Promise<void>-}diff --git a/packages/dsh-tauri-kernel/src/host/types/index.ts b/packages/dsh-tauri-kernel/src/host/types/index.tsdeleted file mode 100644index 3611aee1..00000000--- a/packages/dsh-tauri-kernel/src/host/types/index.ts+++ /dev/null@@ -1,93 +0,0 @@-import type { Agent } from '@deepseek-ai/dsh-agent'-import type {} from '@deepseek-ai/dsh-agent-preset-registry'-import type {} from '@deepseek-ai/dsh-api-session-controller'-import type { GenerateOptions, UserMessage } from '@deepseek-ai/dsh-llm'-import type * as LlmRuntime from '@deepseek-ai/dsh-llm'-import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'-import type {} from '@deepseek-ai/dsh-session-persistence'-import type {} from '@deepseek-ai/dsh-session-projection'-import type {} from '@deepseek-ai/dsh-user-approval'-import type {} from '@deepseek-ai/dsh-user-questions'-import type {} from '@deepseek-ai/dsh-workspace'-import type { HostContext as DesktopHostContext } from 'dsh-tauri'-import type { NativeTurnOptions } from '../../shared/native-model'-import type { KernelBinding } from '../../shared/types'-import type { NativeSession } from '../backends/types'-import type { KERNEL_RECORD_TYPE, MODEL_RECORD_TYPE } from '../config/constants'--export interface PlatformLoader {- import: (id: string) => Promise<unknown>- unwrapExports: (value: unknown) => unknown-}--export interface RuntimeModules {- ToolCallId: typeof LlmRuntime.ToolCallId- LlmAdapter: typeof LlmRuntime.LlmAdapter- isAgentLoopRequest: typeof LlmRuntime.isAgentLoopRequest- appendPluginRecord?: (session: Session, type: 'plugin:dsh-tauri-kernel/kernel' | 'plugin:dsh-tauri-kernel/model', data: KernelBinding | NativeTurnOptions) => number- pluginRecordOf?: (event: SessionEvent) => { type: string, data: unknown } | undefined-}--export interface AdmittedStep {- agent: Agent- turn: number- step: number- messages: readonly UserMessage[]- signal: AbortSignal- request?: GenerateOptions- dispatched: boolean-}--export interface NativeExecution extends AdmittedStep {- binding: KernelBinding- options?: NativeTurnOptions-}--export type HostContext = DesktopHostContext & {- loader: DesktopHostContext['loader'] & PlatformLoader-}--export type BridgeRecordType = typeof KERNEL_RECORD_TYPE | typeof MODEL_RECORD_TYPE--export interface RecordWatermark {- readonly type: BridgeRecordType- readonly seq: number- readonly encodedData: string-}--export interface BridgeCheckpointState {- readonly ownerSessionId: string- readonly inheritedEventCount: number- readonly binding: RecordWatermark | null- readonly model: RecordWatermark | null-}--declare module '@deepseek-ai/dsh-session-projection/types' {- interface SessionProjectionStateMap {- bridgeCheckpoint: BridgeCheckpointState- }-}--export interface NativePending {- agent: Agent- controller: AbortController- task: Promise<NativeEntry>-}--export interface NativeEntry {- agent: Agent- binding: KernelBinding- session: NativeSession- controller: AbortController-}--export interface ModelBody extends NativeTurnOptions {- sessionId: string-}--export interface CreateBody {- backend: 'codex' | 'claude'- workspaceId?: string- cwd?: string- agentPreset?: string-}diff --git a/packages/dsh-tauri-kernel/src/host/utils/abort.ts b/packages/dsh-tauri-kernel/src/host/utils/abort.tsdeleted file mode 100644index 2f791a48..00000000--- a/packages/dsh-tauri-kernel/src/host/utils/abort.ts+++ /dev/null@@ -1,17 +0,0 @@-export async function waitFor<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {- if (signal.aborted) {- void pending.catch(() => undefined)- signal.throwIfAborted()- }- let cancel!: () => void- const aborted = new Promise<never>((_, reject) => {- cancel = () => reject(signal.reason)- signal.addEventListener('abort', cancel, { once: true })- })- try {- return await Promise.race([pending, aborted])- }- finally {- signal.removeEventListener('abort', cancel)- }-}diff --git a/packages/dsh-tauri-kernel/src/host/utils/detection.test.ts b/packages/dsh-tauri-kernel/src/host/utils/detection.test.tsdeleted file mode 100644index 255ab2e0..00000000--- a/packages/dsh-tauri-kernel/src/host/utils/detection.test.ts+++ /dev/null@@ -1,559 +0,0 @@-import type { ChildProcess } from 'node:child_process'-import type { DetectionOptions } from './detection'-import { spawn } from 'node:child_process'-import { EventEmitter } from 'node:events'-import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'-import { tmpdir } from 'node:os'-import { basename, dirname, isAbsolute, join, resolve } from 'node:path'-import process from 'node:process'-import { PassThrough } from 'node:stream'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { detectBackend, nativeEnvironment, resolveNativeCommand } from './detection'--vi.mock('node:child_process', () => ({ spawn: vi.fn() }))--interface ProbePlan {- stdout?: string- stderr?: string- code?: number | null- error?: Error- hold?: boolean- closeOnKill?: boolean- killReturn?: boolean- killError?: Error-}--class ProbeFixture extends EventEmitter {- readonly stdout = new PassThrough()- readonly stderr = new PassThrough()- private closed = false- readonly kill = vi.fn(() => {- if (this.plan.killError)- throw this.plan.killError- if (this.plan.closeOnKill !== false)- this.finish(null)- return this.plan.killReturn ?? true- })-- constructor(private readonly plan: ProbePlan) {- super()- }-- get child(): ChildProcess {- return this as unknown as ChildProcess- }-- run(): void {- if (this.plan.error) {- this.emit('error', this.plan.error)- return- }- if (this.plan.stdout)- this.stdout.write(this.plan.stdout)- if (!this.closed && this.plan.stderr)- this.stderr.write(this.plan.stderr)- if (!this.closed && !this.plan.hold)- this.finish(this.plan.code ?? 0)- }-- finish(code: number | null): void {- if (this.closed)- return- this.closed = true- this.stdout.end()- this.stderr.end()- this.emit('close', code, null)- }-}--const spawnMock = vi.mocked(spawn)-let root: string-let plans: ProbePlan[]-let probes: ProbeFixture[]-let waiters: { index: number, resolve: (probe: ProbeFixture) => void }[]--function nextProbe(index = 0): Promise<ProbeFixture> {- if (probes[index])- return Promise.resolve(probes[index])- return new Promise(resolveProbe => waiters.push({ index, resolve: resolveProbe }))-}--async function file(relativePath: string, content = ''): Promise<string> {- const path = join(root, relativePath)- await mkdir(dirname(path), { recursive: true })- await writeFile(path, content, { mode: 0o755 })- return path-}--function options(path = root, rest: DetectionOptions = {}): DetectionOptions {- return { platform: 'win32', arch: 'x64', env: { Path: path, HOME: root, USERPROFILE: root }, ...rest }-}--async function codexPackage(nativeLocation: 'optional' | 'vendor' = 'optional', target = 'x86_64-pc-windows-msvc'): Promise<{ entry: string, native: string }> {- const packageRoot = 'node_modules/@openai/codex'- const entry = await file(`${packageRoot}/bin/codex.js`, '#!/usr/bin/env node\n')- await file(`${packageRoot}/package.json`, JSON.stringify({ name: '@openai/codex', version: '0.147.0' }))- const vendor = nativeLocation === 'optional' ? `${packageRoot}/node_modules/@openai/codex-win32-x64/vendor` : `${packageRoot}/vendor`- if (nativeLocation === 'optional')- await file(`${packageRoot}/node_modules/@openai/codex-win32-x64/package.json`, JSON.stringify({ name: '@openai/codex', version: '0.147.0-win32-x64' }))- const native = await file(`${vendor}/${target}/bin/${target.includes('windows') ? 'codex.exe' : 'codex'}`)- return { entry, native }-}--async function claudePackage(): Promise<string> {- const entry = await file('node_modules/@anthropic-ai/claude-code/cli.js', '#!/usr/bin/env node\n')- await file('node_modules/@anthropic-ai/claude-code/package.json', JSON.stringify({ name: '@anthropic-ai/claude-code', version: '2.1.287' }))- return entry-}--function healthyCodex(auth: ProbePlan = { stderr: 'Logged in using ChatGPT', code: 0 }): void {- plans = [{ stdout: 'codex-cli 0.147.0\n' }, { stdout: 'Usage: codex app-server [OPTIONS]\n' }, auth]-}--function healthyClaude(auth: ProbePlan = { stdout: '{"loggedIn":true}', code: 0 }): void {- plans = [{ stdout: '2.1.287 (Claude Code)\n' }, { stdout: '--input-format stream-json --output-format stream-json\n' }, auth]-}--beforeEach(async () => {- root = await mkdtemp(join(tmpdir(), 'dsh-bridge-detection-test-'))- plans = []- probes = []- waiters = []- spawnMock.mockReset()- spawnMock.mockImplementation((_file, _args) => {- const plan = plans.shift()- if (!plan)- throw new Error('Unexpected native probe without a protocol fixture')- const probe = new ProbeFixture(plan)- const index = probes.push(probe) - 1- for (const waiter of waiters.filter(waiter => waiter.index === index)) {- waiters.splice(waiters.indexOf(waiter), 1)- waiter.resolve(probe)- }- queueMicrotask(() => probe.run())- return probe.child- })-})--afterEach(async () => {- for (const probe of probes)- probe.finish(null)- vi.clearAllTimers()- vi.useRealTimers()- vi.restoreAllMocks()- spawnMock.mockReset()- const target = resolve(root)- if (!isAbsolute(target) || dirname(target) !== resolve(tmpdir()) || !basename(target).startsWith('dsh-bridge-detection-test-'))- throw new Error('Refusing to remove a directory outside the owned detection fixture')- await rm(target, { recursive: true, force: true })-})--describe('native command resolution', () => {- it('prefers an explicit executable over every PATH candidate', async () => {- const explicit = await file('chosen/codex.exe')- await file('path/codex.exe')- const result = await resolveNativeCommand('codex', explicit, options(join(root, 'path')))- expect(result).toEqual({ file: await realpath(explicit), args: [], env: { Path: join(root, 'path'), HOME: root, USERPROFILE: root } })- expect(spawnMock).not.toHaveBeenCalled()- })-- it.each(['', ' ', 'relative/codex.exe'])('refuses invalid explicit path %j without falling back to PATH', async (override) => {- await file('codex.exe')- const result = await detectBackend('codex', override, options())- expect(result).toEqual({ detection: { id: 'codex', installed: false, auth: 'unknown', version: null, drift: false, hint: 'BRIDGE_EXECUTABLE_PATH: 请配置本机 CLI 的绝对路径。' } })- expect(spawnMock).not.toHaveBeenCalled()- })-- it('refuses a missing explicit executable despite a working PATH installation', async () => {- await file('codex.exe')- const result = await detectBackend('codex', join(root, 'missing.exe'), options())- expect(result.detection.hint).toBe('BRIDGE_EXECUTABLE_MISSING: 配置的 CLI 不存在或不可执行。')- expect(result).not.toHaveProperty('command')- expect(spawnMock).not.toHaveBeenCalled()- })-- it('prefers the first absolute PATH directory over later native executables', async () => {- const installation = await codexPackage()- await file('codex.ps1', '& "$basedir/node_modules/@openai/codex/bin/codex.js" $args')- await file('later/codex.exe')- const result = await resolveNativeCommand('codex', undefined, options(`${root};${join(root, 'later')}`))- expect(result.file).toBe(await realpath(installation.native))- expect(result.args).toEqual([])- })-- it('prefers exe over npm wrappers in the same Windows PATH directory', async () => {- const native = await file('codex.exe')- await file('codex.cmd', 'unrecognized wrapper')- await file('codex.ps1', 'unrecognized wrapper')- expect((await resolveNativeCommand('codex', undefined, options())).file).toBe(await realpath(native))- })-- it('ignores relative and empty PATH segments instead of searching the process directory', async () => {- const native = await file('absolute/claude.exe')- const result = await resolveNativeCommand('claude', undefined, options(`;relative;${join(root, 'absolute')};;`))- expect(result.file).toBe(await realpath(native))- })-- it('skips directories named like executables', async () => {- await mkdir(join(root, 'codex.exe'))- const native = await file('codex')- expect((await resolveNativeCommand('codex', undefined, options())).file).toBe(await realpath(native))- })-- it.each(['codex', 'claude'] as const)('reports absent %s without spawning a fallback engine', async (backend) => {- const result = await detectBackend(backend, undefined, options())- expect(result.detection).toEqual({ id: backend, installed: false, auth: 'unknown', version: null, drift: false, hint: `BRIDGE_EXECUTABLE_MISSING: 本机未安装 ${backend === 'codex' ? 'Codex' : 'Claude'} CLI,或其不在 PATH 中。` })- expect(result).not.toHaveProperty('command')- expect(spawnMock).not.toHaveBeenCalled()- })-- it.each(['cmd', 'ps1'])('unwraps the official Codex npm %s shim into its optional native platform package', async (extension) => {- const installation = await codexPackage()- const shim = await file(`codex.${extension}`, '@ECHO off\n"%~dp0\\node_modules\\@openai\\codex\\bin\\codex.js" %*')- const result = await resolveNativeCommand('codex', shim, options())- expect(result).toEqual({ file: await realpath(installation.native), args: [], env: { Path: root, HOME: root, USERPROFILE: root } })- expect(spawnMock).not.toHaveBeenCalled()- })-- it('uses the official embedded Codex vendor layout when no optional platform package exists', async () => {- const installation = await codexPackage('vendor')- expect((await resolveNativeCommand('codex', installation.entry, options())).file).toBe(await realpath(installation.native))- })-- it.each(['cmd', 'ps1'])('unwraps the official Claude npm %s shim to Node plus its validated entrypoint', async (extension) => {- const entry = await claudePackage()- const shim = await file(`claude.${extension}`, 'node "%~dp0/node_modules/@anthropic-ai/claude-code/cli.js" %*')- const result = await resolveNativeCommand('claude', shim, options())- expect(result).toEqual({ file: process.execPath, args: [await realpath(entry)], env: { Path: root, HOME: root, USERPROFILE: root } })- })-- it.each(['cmd', 'ps1'])('resolves the official Claude native npm %s entrypoint without invoking a shell', async (extension) => {- const native = await file('node_modules/@anthropic-ai/claude-code/bin/claude.exe')- await file('node_modules/@anthropic-ai/claude-code/package.json', JSON.stringify({ name: '@anthropic-ai/claude-code', version: '2.1.295', bin: { claude: 'bin/claude.exe' } }))- const shim = await file(`claude.${extension}`, '"%dp0%\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe" %*')- const result = await resolveNativeCommand('claude', shim, options())- expect(result).toEqual({ file: await realpath(native), args: [], env: { Path: root, HOME: root, USERPROFILE: root } })- expect(spawnMock).not.toHaveBeenCalled()- })-- it('rejects an impersonated native Claude package before using its executable', async () => {- await file('node_modules/@anthropic-ai/claude-code/bin/claude.exe')- await file('node_modules/@anthropic-ai/claude-code/package.json', '{"name":"not-anthropic"}')- const shim = await file('claude.cmd', '"%dp0%\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe" %*')- await expect(resolveNativeCommand('claude', shim, options())).rejects.toThrow('BRIDGE_PACKAGE_MISMATCH: CLI 包装器不是所选内核的官方安装。')- expect(spawnMock).not.toHaveBeenCalled()- })-- it('refuses an unrecognized wrapper instead of falling back to another PATH installation', async () => {- const shim = await file('chosen/codex.cmd', '@ECHO off\ncustom-command %*')- await file('codex.exe')- await expect(resolveNativeCommand('codex', shim, options())).rejects.toThrow('BRIDGE_SHIM_UNSUPPORTED: 此命令包装器无法安全解析,请配置原生可执行文件路径。')- expect(spawnMock).not.toHaveBeenCalled()- })-- it('rejects a package impersonating the selected official CLI', async () => {- const entry = await file('node_modules/@anthropic-ai/claude-code/cli.js')- await file('node_modules/@anthropic-ai/claude-code/package.json', '{"name":"not-the-official-package"}')- await expect(resolveNativeCommand('claude', entry, options())).rejects.toThrow('BRIDGE_PACKAGE_MISMATCH: CLI 包装器不是所选内核的官方安装。')- })-- it('rejects an oversized wrapper before attempting a native probe', async () => {- const shim = await file('claude.cmd', 'x'.repeat(128 * 1024 + 1))- const result = await detectBackend('claude', shim, options())- expect(result.detection.hint).toBe('BRIDGE_SHIM_TOO_LARGE: CLI 包装器文件异常。')- expect(spawnMock).not.toHaveBeenCalled()- })-- it('fails closed when an official Codex installation lacks its native binary', async () => {- const entry = await file('node_modules/@openai/codex/bin/codex.js')- await file('node_modules/@openai/codex/package.json', '{"name":"@openai/codex"}')- await expect(resolveNativeCommand('codex', entry, options())).rejects.toThrow('BRIDGE_EXECUTABLE_MISSING: 官方 CLI 安装缺少原生可执行文件,请重新安装。')- })-- it.each([- ['win32', 'arm64', 'aarch64-pc-windows-msvc'],- ['darwin', 'x64', 'x86_64-apple-darwin'],- ['darwin', 'arm64', 'aarch64-apple-darwin'],- ['linux', 'x64', 'x86_64-unknown-linux-musl'],- ['linux', 'arm64', 'aarch64-unknown-linux-musl'],- ] as const)('resolves the official %s %s target triple without running a shim', async (platform, arch, target) => {- const installation = await codexPackage('vendor', target)- expect((await resolveNativeCommand('codex', installation.entry, options(root, { platform, arch }))).file).toBe(await realpath(installation.native))- })-- it('refuses unsupported Codex architectures without substituting another native binary', async () => {- const installation = await codexPackage('vendor')- await expect(resolveNativeCommand('codex', installation.entry, options(root, { arch: 'riscv64' }))).rejects.toThrow('BRIDGE_PLATFORM_UNSUPPORTED: 此平台没有可用的本机 Codex CLI。')- })-})--describe('native environment isolation', () => {- it('removes case-insensitive DSH and nested-runtime markers while retaining native credentials', () => {- const input = Object.freeze({ Path: root, DSH_HOME: 'outer-home', dsh_api_token: 'outer-token', Dsh_Foo: 'outer', CLAUDECODE: '1', claude_code_entrypoint: 'sdk', CODEX_THREAD_ID: 'outer-thread', codex_internal_originator_override: 'outer', node_options: '--inspect', OPENAI_API_KEY: 'native-test-key', ANTHROPIC_API_KEY: 'native-test-key', HTTPS_PROXY: 'http://native-proxy' })- expect(nativeEnvironment(input)).toEqual({ Path: root, OPENAI_API_KEY: 'native-test-key', ANTHROPIC_API_KEY: 'native-test-key', HTTPS_PROXY: 'http://native-proxy' })- expect(input.DSH_HOME).toBe('outer-home')- expect(input.node_options).toBe('--inspect')- })-- it('passes a full scrubbed environment and direct argv without shell execution to every probe', async () => {- const entry = await claudePackage()- healthyClaude()- const result = await detectBackend('claude', entry, options(root, { env: { Path: root, HOME: root, DSH_TOKEN: 'outer', CLAUDECODE: '1', NODE_OPTIONS: '--inspect', ANTHROPIC_API_KEY: 'native-test-key' } }))- expect(result.detection.auth).toBe('ok')- expect(spawnMock.mock.calls).toEqual([- [process.execPath, [await realpath(entry), '--version'], { env: { Path: root, HOME: root, ANTHROPIC_API_KEY: 'native-test-key' }, windowsHide: true, shell: false, stdio: ['ignore', 'pipe', 'pipe'] }],- [process.execPath, [await realpath(entry), '--help'], { env: { Path: root, HOME: root, ANTHROPIC_API_KEY: 'native-test-key' }, windowsHide: true, shell: false, stdio: ['ignore', 'pipe', 'pipe'] }],- [process.execPath, [await realpath(entry), 'auth', 'status', '--json'], { env: { Path: root, HOME: root, ANTHROPIC_API_KEY: 'native-test-key' }, windowsHide: true, shell: false, stdio: ['ignore', 'pipe', 'pipe'] }],- ])- })-})--describe('backend detection capability probes', () => {- it('returns Codex installation, version, authentication and the exact native command', async () => {- const native = await file('codex.exe')- healthyCodex()- const result = await detectBackend('codex', undefined, options())- expect(result).toEqual({ detection: { id: 'codex', installed: true, auth: 'ok', version: '0.147.0', drift: false, hint: null }, command: { file: await realpath(native), args: [], env: { Path: root, HOME: root, USERPROFILE: root } } })- expect(spawnMock.mock.calls.map(([, args]) => args)).toEqual([['--version'], ['app-server', '--help'], ['login', 'status']])- })-- it.each(['0.0.1', '99.9.9-preview.7'])('does not impose a hard version gate on an advertised capable CLI %s', async (version) => {- await file('codex.exe')- healthyCodex()- plans[0] = { stdout: `codex-cli ${version}\n` }- const result = await detectBackend('codex', undefined, options())- expect(result.detection).toEqual({ id: 'codex', installed: true, auth: 'ok', version, drift: false, hint: null })- })-- it('rejects a failed version probe without trying another installed executable', async () => {- await file('chosen/codex.exe')- await file('later/codex.exe')- plans = [{ stderr: 'native installation is broken', code: 2 }]- const result = await detectBackend('codex', undefined, options(`${join(root, 'chosen')};${join(root, 'later')}`))- expect(result.detection).toEqual({ id: 'codex', installed: false, auth: 'unknown', version: null, drift: false, hint: 'BRIDGE_PROBE_FAILED: CLI 版本探测失败,请在终端检查该安装。' })- expect(result).not.toHaveProperty('command')- expect(spawnMock).toHaveBeenCalledTimes(1)- })-- it('rejects unrecognizable version output before capability or authentication probes', async () => {- await file('codex.exe')- plans = [{ stdout: 'codex-cli development build\n' }]- const result = await detectBackend('codex', undefined, options())- expect(result.detection.hint).toBe('BRIDGE_VERSION_UNRECOGNIZED: CLI 未返回可识别版本。')- expect(result.detection.version).toBeNull()- expect(spawnMock).toHaveBeenCalledTimes(1)- })-- it('marks unsupported Codex app-server as drift without returning an executable capability', async () => {- await file('codex.exe')- plans = [{ stdout: 'codex-cli 0.147.0' }, { stderr: 'unknown subcommand app-server', code: 2 }]- const result = await detectBackend('codex', undefined, options())- expect(result.detection).toEqual({ id: 'codex', installed: false, auth: 'unknown', version: '0.147.0', drift: true, hint: 'BRIDGE_PROTOCOL_UNAVAILABLE: 本机 CLI 不支持所需桥接协议,请更新 CLI。' })- expect(result).not.toHaveProperty('command')- expect(spawnMock).toHaveBeenCalledTimes(2)- })-- it('rejects Claude help missing stream-json despite a successful help exit', async () => {- await file('claude.exe')- plans = [{ stdout: '2.1.287 (Claude Code)' }, { stdout: '--output-format text\n' }]- const result = await detectBackend('claude', undefined, options())- expect(result.detection.installed).toBe(false)- expect(result.detection.drift).toBe(true)- expect(result.detection.hint).toBe('BRIDGE_PROTOCOL_UNAVAILABLE: 本机 CLI 不支持所需桥接协议,请更新 CLI。')- expect(result).not.toHaveProperty('command')- expect(spawnMock).toHaveBeenCalledTimes(2)- })-- it.each([- [{ stderr: 'Not logged in', code: 1 }, 'unknown', '无法确认 Codex 认证状态;请检查原生 CLI 的 provider 配置和认证方式。'],- [{ stderr: 'Native authentication backend unavailable', code: 2 }, 'unknown', '无法确认 Codex 认证状态;请检查原生 CLI 的 provider 配置和认证方式。'],- ] as const)('keeps Codex login status informational for custom providers %j', async (auth, status, hint) => {- await file('codex.exe')- healthyCodex(auth)- const result = await detectBackend('codex', undefined, options())- expect(result.detection).toEqual({ id: 'codex', installed: true, auth: status, version: '0.147.0', drift: false, hint })- expect(result.command?.args).toEqual([])- })-- it.each([- ['{"loggedIn":true}', 'ok', null],- ['{"loggedIn":false}', 'missing', '请先在终端运行 claude auth login。'],- ['{"loggedIn":"true"}', 'unknown', '无法确认登录状态;原生 CLI 会在连接时检查认证。'],- ['not JSON', 'unknown', '无法确认登录状态;原生 CLI 会在连接时检查认证。'],- ] as const)('interprets Claude status payload %s without inventing an authenticated session', async (stdout, status, hint) => {- await file('claude.exe')- healthyClaude({ stdout, code: 0 })- const result = await detectBackend('claude', undefined, options())- expect(result.detection).toEqual({ id: 'claude', installed: true, auth: status, version: '2.1.287', drift: false, hint })- expect(result.command?.args).toEqual([])- })-- it('refuses a successful Claude authentication claim from a failed status command', async () => {- await file('claude.exe')- healthyClaude({ stdout: '{"loggedIn":true}', code: 2 })- const result = await detectBackend('claude', undefined, options())- expect(result.detection).toEqual({ id: 'claude', installed: true, auth: 'unknown', version: '2.1.287', drift: false, hint: '无法确认登录状态;原生 CLI 会在连接时检查认证。' })- expect(result.command?.args).toEqual([])- })-- it('keeps a proven installation when only the authentication probe emits a process error', async () => {- await file('codex.exe')- healthyCodex({ error: new Error('auth executable error') })- const result = await detectBackend('codex', undefined, options())- expect(result.detection).toEqual({ id: 'codex', installed: true, auth: 'unknown', version: '0.147.0', drift: false, hint: '无法确认 Codex 认证状态;请检查原生 CLI 的 provider 配置和认证方式。' })- expect(result.command?.args).toEqual([])- })-- it('fails closed when the native version child emits an error', async () => {- await file('codex.exe')- plans = [{ error: new Error('EACCES') }]- const result = await detectBackend('codex', undefined, options())- expect(result.detection).toEqual({ id: 'codex', installed: false, auth: 'unknown', version: null, drift: false, hint: 'BRIDGE_PROBE_FAILED: 无法探测本机 CLI,请检查配置路径和安装。' })- expect(result).not.toHaveProperty('command')- expect(spawnMock).toHaveBeenCalledTimes(1)- })-})--describe('bounded native probes', () => {- it.each([- [0, 100],- [undefined, 5_000],- [100_000, 30_000],- ] as const)('enforces timeout %j at the bounded deadline %i without starting another engine', async (timeoutMs, deadline) => {- vi.useFakeTimers()- await file('codex.exe')- plans = [{ hold: true }]- let settled = 0- const pending = detectBackend('codex', undefined, options(root, { timeoutMs })).then((result) => {- settled++- return result- })- const child = await nextProbe()- await vi.advanceTimersByTimeAsync(deadline - 1)- expect(settled).toBe(0)- expect(child.kill).not.toHaveBeenCalled()- await vi.advanceTimersByTimeAsync(1)- expect((await pending).detection.hint).toBe('BRIDGE_PROBE_TIMEOUT: 本机 CLI 探测超时。')- expect(child.kill).toHaveBeenCalledTimes(1)- expect(spawnMock).toHaveBeenCalledTimes(1)- expect(vi.getTimerCount()).toBe(0)- })-- it('settles a timed-out probe even when child.kill fails and close never arrives', async () => {- vi.useFakeTimers()- await file('codex.exe')- plans = [{ hold: true, closeOnKill: false, killReturn: false }]- let result: Awaited<ReturnType<typeof detectBackend>> | undefined- const pending = detectBackend('codex', undefined, options(root, { timeoutMs: 100 })).then(value => result = value)- const child = await nextProbe()- await vi.advanceTimersByTimeAsync(100)- expect(child.kill).toHaveBeenCalledTimes(1)- expect(result?.detection.hint).toBe('BRIDGE_PROBE_TIMEOUT: 本机 CLI 探测超时。')- expect(spawnMock).toHaveBeenCalledTimes(1)- child.finish(null)- await pending- })-- it('settles timeout rejection when native kill throws without retaining owned output listeners', async () => {- vi.useFakeTimers()- await file('codex.exe')- plans = [{ hold: true, killError: new Error('EPERM') }]- const pending = detectBackend('codex', undefined, options(root, { timeoutMs: 100 }))- const child = await nextProbe()- await vi.advanceTimersByTimeAsync(100)- expect((await pending).detection.hint).toBe('BRIDGE_PROBE_TIMEOUT: 本机 CLI 探测超时。')- expect(child.kill).toHaveBeenCalledTimes(1)- expect(child.stdout.listenerCount('data')).toBe(0)- expect(child.stderr.listenerCount('data')).toBe(0)- expect(child.listenerCount('close')).toBe(0)- expect(() => child.emit('error', new Error('late EPERM'))).not.toThrow()- child.stdout.write('late untrusted output')- child.stderr.write('late stderr')- expect(child.kill).toHaveBeenCalledTimes(1)- expect(vi.getTimerCount()).toBe(0)- })-- it('accepts exactly 128 KiB of ASCII stdout and stderr', async () => {- await file('codex.exe')- const prefix = 'codex-cli 0.147.0\n'- plans = [{ stdout: prefix + ' '.repeat(64 * 1024 - prefix.length), stderr: ' '.repeat(64 * 1024) }, { stdout: 'Usage: codex app-server' }, { stderr: 'Logged in using ChatGPT' }]- const result = await detectBackend('codex', undefined, options())- expect(result.detection).toEqual({ id: 'codex', installed: true, auth: 'ok', version: '0.147.0', drift: false, hint: null })- expect(probes[0].kill).not.toHaveBeenCalled()- })-- it('rejects combined ASCII stdout and stderr one byte beyond the probe limit', async () => {- await file('codex.exe')- plans = [{ stdout: 'x'.repeat(64 * 1024), stderr: 'x'.repeat(64 * 1024 + 1) }]- const result = await detectBackend('codex', undefined, options())- expect(result.detection.hint).toBe('BRIDGE_PROBE_OUTPUT_LIMIT: CLI 探测输出异常。')- expect(result.detection.installed).toBe(false)- expect(probes[0].kill).toHaveBeenCalledTimes(1)- expect(spawnMock).toHaveBeenCalledTimes(1)- })-- it('bounds multibyte UTF-8 output by bytes rather than by decoded character count', async () => {- await file('codex.exe')- plans = [{ stdout: '你'.repeat(43_691) }]- const result = await detectBackend('codex', undefined, options())- expect(result.detection.hint).toBe('BRIDGE_PROBE_OUTPUT_LIMIT: CLI 探测输出异常。')- expect(result.detection.installed).toBe(false)- expect(probes[0].kill).toHaveBeenCalledTimes(1)- expect(spawnMock).toHaveBeenCalledTimes(1)- })-- it('settles an over-limit probe without waiting for an uncooperative child close', async () => {- vi.useFakeTimers()- await file('codex.exe')- plans = [{ hold: true, closeOnKill: false, killReturn: false }]- let result: Awaited<ReturnType<typeof detectBackend>> | undefined- const pending = detectBackend('codex', undefined, options()).then(value => result = value)- const child = await nextProbe()- child.stdout.write('x'.repeat(128 * 1024 + 1))- await vi.advanceTimersByTimeAsync(0)- expect(child.kill).toHaveBeenCalledTimes(1)- expect(result?.detection.hint).toBe('BRIDGE_PROBE_OUTPUT_LIMIT: CLI 探测输出异常。')- child.finish(null)- await pending- })-- it('stops consuming late output after the limit instead of repeatedly killing and accumulating it', async () => {- await file('codex.exe')- plans = [{ hold: true, closeOnKill: false }]- const pending = detectBackend('codex', undefined, options())- const child = await nextProbe()- child.stdout.write('x'.repeat(128 * 1024 + 1))- child.stderr.write('late output'.repeat(1000))- expect(child.kill).toHaveBeenCalledTimes(1)- expect(child.stdout.listenerCount('data')).toBe(0)- expect(child.stderr.listenerCount('data')).toBe(0)- expect(child.listenerCount('close')).toBe(0)- expect(() => child.emit('error', new Error('late output error'))).not.toThrow()- expect(child.kill).toHaveBeenCalledTimes(1)- child.finish(null)- expect((await pending).detection.hint).toBe('BRIDGE_PROBE_OUTPUT_LIMIT: CLI 探测输出异常。')- })-- it('keeps auth unknown when its bounded status probe times out', async () => {- vi.useFakeTimers()- await file('claude.exe')- healthyClaude({ hold: true })- const pending = detectBackend('claude', undefined, options(root, { timeoutMs: 100 }))- const child = await nextProbe(2)- await vi.advanceTimersByTimeAsync(100)- const result = await pending- expect(result.detection).toEqual({ id: 'claude', installed: true, auth: 'unknown', version: '2.1.287', drift: false, hint: '无法确认登录状态;原生 CLI 会在连接时检查认证。' })- expect(child.kill).toHaveBeenCalledTimes(1)- expect(result.command?.args).toEqual([])- expect(vi.getTimerCount()).toBe(0)- })-- it('clears all probe deadlines after a successful detection', async () => {- vi.useFakeTimers()- await file('codex.exe')- healthyCodex()- expect((await detectBackend('codex', undefined, options())).detection.auth).toBe('ok')- expect(vi.getTimerCount()).toBe(0)- expect(probes.every(probe => probe.kill.mock.calls.length === 0)).toBe(true)- })-})diff --git a/packages/dsh-tauri-kernel/src/host/utils/detection.ts b/packages/dsh-tauri-kernel/src/host/utils/detection.tsdeleted file mode 100644index 663267ed..00000000--- a/packages/dsh-tauri-kernel/src/host/utils/detection.ts+++ /dev/null@@ -1,216 +0,0 @@-import type { Buffer } from 'node:buffer'-import type { BackendDetection } from '../../shared/types'-import type { NativeCommand } from '../backends/types'-import { spawn } from 'node:child_process'-import { constants } from 'node:fs'-import { access, readFile, realpath, stat } from 'node:fs/promises'-import { createRequire } from 'node:module'-import { delimiter, dirname, extname, isAbsolute, join } from 'node:path'-import process from 'node:process'--export interface DetectionOptions {- platform?: NodeJS.Platform- arch?: string- env?: NodeJS.ProcessEnv- timeoutMs?: number-}--export interface DetectedCommand {- detection: BackendDetection- command?: NativeCommand-}--export function nativeEnvironment(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {- const clean = { ...env }- for (const key of Object.keys(clean)) {- if (/^(?:DSH_.*|CLAUDECODE|CLAUDE_CODE_ENTRYPOINT|CODEX_THREAD_ID|CODEX_INTERNAL_ORIGINATOR_OVERRIDE|NODE_OPTIONS)$/i.test(key))- delete clean[key]- }- return clean-}--export async function resolveNativeCommand(backend: 'codex' | 'claude', override: string | undefined, options: DetectionOptions = {}): Promise<NativeCommand> {- const platform = options.platform ?? process.platform- const env = nativeEnvironment(options.env)- const extensions = platform === 'win32' ? ['.exe', '.cmd', '.ps1', ''] : ['']- let entry: string | undefined- if (override !== undefined) {- if (!override.trim() || !isAbsolute(override))- throw new Error('BRIDGE_EXECUTABLE_PATH: 请配置本机 CLI 的绝对路径。')- if (!await executable(override, platform))- throw new Error('BRIDGE_EXECUTABLE_MISSING: 配置的 CLI 不存在或不可执行。')- entry = override- }- else {- const pathValue = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] ?? ''- for (const directory of pathValue.split(platform === 'win32' ? ';' : delimiter)) {- if (!directory || !isAbsolute(directory))- continue- for (const extension of extensions) {- const candidate = join(directory, `${backend}${extension}`)- if (await executable(candidate, platform)) {- entry = candidate- break- }- }- if (entry)- break- }- if (!entry)- throw new Error(`BRIDGE_EXECUTABLE_MISSING: 本机未安装 ${backend === 'codex' ? 'Codex' : 'Claude'} CLI,或其不在 PATH 中。`)- }- let packageRoot: string | undefined- const suffix = extname(entry).toLowerCase()- if (suffix === '.cmd' || suffix === '.ps1') {- const text = await boundedRead(entry)- const packagePath = backend === 'codex' ? '@openai[/\\\\]codex[/\\\\]bin[/\\\\]codex\\.js' : '@anthropic-ai[/\\\\]claude-code[/\\\\](?:cli\\.js|bin[/\\\\]claude(?:\\.exe)?)'- const match = new RegExp(`(?:node_modules[/\\\\]${packagePath})`, 'i').exec(text)- if (!match)- throw new Error('BRIDGE_SHIM_UNSUPPORTED: 此命令包装器无法安全解析,请配置原生可执行文件路径。')- entry = join(dirname(entry), match[0].replace(/[\\/]/g, '/'))- packageRoot = backend === 'claude' && /\.js$/i.test(entry) ? dirname(entry) : dirname(dirname(entry))- }- entry = await realpath(entry)- const script = /\.[cm]?js$/i.test(entry)- if (packageRoot !== undefined || script) {- const root = packageRoot ?? (backend === 'codex' ? dirname(dirname(entry)) : dirname(entry))- const metadata = JSON.parse(await boundedRead(join(root, 'package.json'))) as { name?: string }- const expected = backend === 'codex' ? '@openai/codex' : '@anthropic-ai/claude-code'- if (metadata.name !== expected)- throw new Error('BRIDGE_PACKAGE_MISMATCH: CLI 包装器不是所选内核的官方安装。')- }- if (script) {- const root = backend === 'codex' ? dirname(dirname(entry)) : dirname(entry)- if (backend === 'claude')- return { file: process.execPath, args: [entry], env }- const target = codexTarget(platform, options.arch ?? process.arch)- const platformPackage = `@openai/codex-${platform === 'win32' ? 'win32' : platform}-${options.arch ?? process.arch}`- let vendor = join(root, 'vendor')- try {- vendor = join(dirname(createRequire(join(root, 'package.json')).resolve(`${platformPackage}/package.json`)), 'vendor')- }- catch {}- entry = join(vendor, target, 'bin', platform === 'win32' ? 'codex.exe' : 'codex')- }- if (!await executable(entry, platform))- throw new Error('BRIDGE_EXECUTABLE_MISSING: 官方 CLI 安装缺少原生可执行文件,请重新安装。')- return { file: await realpath(entry), args: [], env }-}--export async function detectBackend(backend: 'codex' | 'claude', override?: string, options: DetectionOptions = {}): Promise<DetectedCommand> {- const detection: BackendDetection = { id: backend, installed: false, auth: 'unknown', version: null, drift: false, hint: null }- try {- const command = await resolveNativeCommand(backend, override, options)- const timeout = options.timeoutMs ?? 5_000- const version = await probe(command, ['--version'], timeout)- if (version.code !== 0)- throw new Error('BRIDGE_PROBE_FAILED: CLI 版本探测失败,请在终端检查该安装。')- detection.version = /\b\d+\.\d+\.\d+(?:[-+][\w.-]+)?\b/.exec(version.output)?.[0] ?? null- if (!detection.version)- throw new Error('BRIDGE_VERSION_UNRECOGNIZED: CLI 未返回可识别版本。')- const help = await probe(command, backend === 'codex' ? ['app-server', '--help'] : ['--help'], timeout)- if (help.code !== 0 || (backend === 'claude' && !/stream-json/.test(help.output))) {- detection.drift = true- throw new Error('BRIDGE_PROTOCOL_UNAVAILABLE: 本机 CLI 不支持所需桥接协议,请更新 CLI。')- }- detection.installed = true- const auth = await probe(command, backend === 'codex' ? ['login', 'status'] : ['auth', 'status', '--json'], timeout).catch(() => undefined)- if (auth) {- if (backend === 'codex') {- detection.auth = auth.code === 0 ? 'ok' : 'unknown'- }- else {- try {- const status = JSON.parse(auth.output) as { loggedIn?: boolean }- detection.auth = status.loggedIn === false ? 'missing' : auth.code === 0 && status.loggedIn === true ? 'ok' : 'unknown'- }- catch {}- }- }- detection.hint = detection.auth === 'missing'- ? '请先在终端运行 claude auth login。'- : detection.auth === 'unknown'- ? backend === 'codex' ? '无法确认 Codex 认证状态;请检查原生 CLI 的 provider 配置和认证方式。' : '无法确认登录状态;原生 CLI 会在连接时检查认证。'- : null- return { detection, command }- }- catch (error) {- detection.hint = error instanceof Error && error.message.startsWith('BRIDGE_') ? error.message : 'BRIDGE_PROBE_FAILED: 无法探测本机 CLI,请检查配置路径和安装。'- return { detection }- }-}--async function executable(file: string, platform: NodeJS.Platform): Promise<boolean> {- try {- if (!(await stat(file)).isFile())- return false- await access(file, platform === 'win32' || /\.(?:cmd|ps1)$/i.test(file) ? constants.F_OK : constants.X_OK)- return true- }- catch {- return false- }-}--async function boundedRead(file: string): Promise<string> {- if ((await stat(file)).size > 128 * 1024)- throw new Error('BRIDGE_SHIM_TOO_LARGE: CLI 包装器文件异常。')- return readFile(file, 'utf8')-}--function codexTarget(platform: NodeJS.Platform, arch: string): string {- const cpu = arch === 'x64' ? 'x86_64' : arch === 'arm64' ? 'aarch64' : undefined- const os = platform === 'win32' ? 'pc-windows-msvc' : platform === 'darwin' ? 'apple-darwin' : platform === 'linux' ? 'unknown-linux-musl' : undefined- if (!cpu || !os)- throw new Error('BRIDGE_PLATFORM_UNSUPPORTED: 此平台没有可用的本机 Codex CLI。')- return `${cpu}-${os}`-}--async function probe(command: NativeCommand, args: string[], timeoutMs: number): Promise<{ code: number | null, output: string }> {- return new Promise((resolveProbe, reject) => {- const child = spawn(command.file, [...command.args, ...args], { env: command.env, windowsHide: true, shell: false, stdio: ['ignore', 'pipe', 'pipe'] })- let output = ''- let bytes = 0- let settled = false- const timer = setTimeout(() => fail(new Error('BRIDGE_PROBE_TIMEOUT: 本机 CLI 探测超时。')), Math.min(30_000, Math.max(100, timeoutMs)))- function cleanup(): void {- clearTimeout(timer)- child.stdout.off('data', collect)- child.stderr.off('data', collect)- child.off('close', close)- }- function fail(error: Error): void {- if (settled)- return- settled = true- cleanup()- reject(error)- child.stdout.resume()- child.stderr.resume()- try {- child.kill()- }- catch {}- }- function collect(chunk: Buffer): void {- bytes += chunk.byteLength- if (bytes > 128 * 1024) {- fail(new Error('BRIDGE_PROBE_OUTPUT_LIMIT: CLI 探测输出异常。'))- return- }- output += chunk.toString('utf8')- }- function close(code: number | null): void {- if (settled)- return- settled = true- cleanup()- child.off('error', fail)- resolveProbe({ code, output })- }- child.stdout.on('data', collect)- child.stderr.on('data', collect)- child.on('error', fail)- child.once('close', close)- })-}diff --git a/packages/dsh-tauri-kernel/src/host/utils/runtime-modules.test.ts b/packages/dsh-tauri-kernel/src/host/utils/runtime-modules.test.tsdeleted file mode 100644index c389d4dd..00000000--- a/packages/dsh-tauri-kernel/src/host/utils/runtime-modules.test.ts+++ /dev/null@@ -1,51 +0,0 @@-import type { PlatformLoader } from '../types'-import { Loader } from '@deepseek-ai/cordis-plugin-loader'-import { afterEach, describe, expect, it, vi } from 'vitest'-import * as zodModule from 'zod'-import { loadRuntimeZod } from './runtime-modules'--afterEach(() => vi.restoreAllMocks())--describe('official runtime Zod resolution', () => {- it.each([- ['ESM named exports', zodModule],- ['CommonJS default exports', { default: zodModule }],- ['transpiled nested default exports', { default: { __esModule: true, default: zodModule } }],- ])('returns the host Zod instance from %s using the real official export normalizer', async (_, namespace) => {- const loader: PlatformLoader = {- import: vi.fn(async () => namespace),- unwrapExports: value => Loader.prototype.unwrapExports(value),- }- expect(await loadRuntimeZod(loader)).toBe(zodModule.z)- expect(loader.import).toHaveBeenCalledExactlyOnceWith('zod')- })-- it('prefers the named Zod namespace rather than treating its default object as a plugin', async () => {- const loader: PlatformLoader = {- import: vi.fn(async () => ({ z: zodModule.z, default: {} })),- unwrapExports: vi.fn(() => { throw new Error('named Zod should not be unwrapped') }),- }- expect(await loadRuntimeZod(loader)).toBe(zodModule.z)- expect(loader.unwrapExports).not.toHaveBeenCalled()- })-- it.each([undefined, null, {}, { z: {} }, { default: { z: { object: () => {} } } }])('rejects incomplete host exports without silently importing a local copy: %j', async (namespace) => {- const loader: PlatformLoader = {- import: vi.fn(async () => namespace),- unwrapExports: value => Loader.prototype.unwrapExports(value),- }- await expect(loadRuntimeZod(loader)).rejects.toThrow('BRIDGE_RUNTIME_EXPORT_MISSING: zod.z')- expect(loader.import).toHaveBeenCalledExactlyOnceWith('zod')- })-- it('preserves a loader rejection without caching it or falling back to a bundled module', async () => {- const failure = new Error('official Zod import refused')- const loader: PlatformLoader = {- import: vi.fn().mockRejectedValueOnce(failure).mockResolvedValueOnce(zodModule),- unwrapExports: value => Loader.prototype.unwrapExports(value),- }- await expect(loadRuntimeZod(loader)).rejects.toBe(failure)- expect(await loadRuntimeZod(loader)).toBe(zodModule.z)- expect(vi.mocked(loader.import).mock.calls).toEqual([['zod'], ['zod']])- })-})diff --git a/packages/dsh-tauri-kernel/src/host/utils/runtime-modules.ts b/packages/dsh-tauri-kernel/src/host/utils/runtime-modules.tsdeleted file mode 100644index 2a219411..00000000--- a/packages/dsh-tauri-kernel/src/host/utils/runtime-modules.ts+++ /dev/null@@ -1,37 +0,0 @@-import type { z } from 'zod'-import type { PlatformLoader, RuntimeModules } from '../types'--export async function loadRuntimeZod(loader: PlatformLoader): Promise<typeof z> {- const value = await loader.import('zod')- const direct = (value as { z?: typeof z } | null)?.z- const resolved = direct ?? (loader.unwrapExports(value) as { z?: typeof z } | null)?.z- if (typeof resolved?.object !== 'function' || typeof resolved.string !== 'function' || typeof resolved.enum !== 'function' || typeof resolved.number !== 'function' || typeof resolved.array !== 'function')- throw new TypeError('BRIDGE_RUNTIME_EXPORT_MISSING: zod.z')- return resolved-}--export async function loadRuntimeModules(loader: PlatformLoader): Promise<RuntimeModules> {- const [llm, session] = await Promise.all([loader.import('@deepseek-ai/dsh-llm'), loader.import('@deepseek-ai/dsh-session')])- return {- ToolCallId: resolveExport(loader, llm, 'ToolCallId'),- LlmAdapter: resolveExport(loader, llm, 'LlmAdapter'),- isAgentLoopRequest: resolveExport(loader, llm, 'isAgentLoopRequest'),- appendPluginRecord: optionalExport(loader, session, 'appendPluginRecord'),- pluginRecordOf: optionalExport(loader, session, 'pluginRecordOf'),- }-}--function optionalExport<K extends keyof RuntimeModules>(loader: PlatformLoader, value: unknown, key: K): RuntimeModules[K] | undefined {- const direct = (value as Partial<RuntimeModules> | null)?.[key]- if (typeof direct === 'function')- return direct as RuntimeModules[K]- const fallback = (loader.unwrapExports(value) as Partial<RuntimeModules> | null)?.[key]- return typeof fallback === 'function' ? fallback as RuntimeModules[K] : undefined-}--function resolveExport<K extends keyof RuntimeModules>(loader: PlatformLoader, value: unknown, key: K): NonNullable<RuntimeModules[K]> {- const value_ = optionalExport(loader, value, key)- if (value_ === undefined)- throw new TypeError(`BRIDGE_RUNTIME_EXPORT_MISSING: ${key}`)- return value_ as NonNullable<RuntimeModules[K]>-}diff --git a/packages/dsh-tauri-kernel/src/host/utils/runtime-version.test.ts b/packages/dsh-tauri-kernel/src/host/utils/runtime-version.test.tsdeleted file mode 100644index 523775f5..00000000--- a/packages/dsh-tauri-kernel/src/host/utils/runtime-version.test.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { PlatformLoader } from '../types'-import { describe, expect, it, vi } from 'vitest'-import { runtimeVersion } from './runtime-version'--function loader(value: (id: string) => unknown, unwrap: PlatformLoader['unwrapExports'] = exports => exports): PlatformLoader {- return { import: vi.fn(async (id: string) => value(id)), unwrapExports: unwrap }-}--describe('host runtime version probe', () => {- it('reads the official runtime version through the loader', async () => {- const runtime = vi.fn(() => '0.2.1-rc.1')- expect(await runtimeVersion(loader(() => ({ getDshRuntimeVersion: runtime })))).toBe('0.2.1-rc.1')- expect(runtime).toHaveBeenCalledOnce()- })-- it('accepts a loader whose module namespace needs unwrapping', async () => {- expect(await runtimeVersion(loader(() => ({ default: {} }), () => ({ getDshRuntimeVersion: () => '0.2.1-rc.1' })))).toBe('0.2.1-rc.1')- })-- it.each([- ['a missing export', () => ({})],- ['a failed import', () => { throw new Error('runtime package not installed') }],- ['a non-string version', () => ({ getDshRuntimeVersion: () => 2 })],- ['an empty version', () => ({ getDshRuntimeVersion: () => ' ' })],- ])('reports no runtime version for %s', async (_label, value) => {- expect(await runtimeVersion(loader(value as (id: string) => unknown))).toBeNull()- })-})diff --git a/packages/dsh-tauri-kernel/src/host/utils/runtime-version.ts b/packages/dsh-tauri-kernel/src/host/utils/runtime-version.tsdeleted file mode 100644index 228cf38d..00000000--- a/packages/dsh-tauri-kernel/src/host/utils/runtime-version.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { PlatformLoader } from '../types'--const RUNTIME_PACKAGE = '@deepseek-ai/dsh-app-boot'--function runtimeExport(loader: PlatformLoader, value: unknown, key: string): unknown {- const direct = (value as Record<string, unknown> | null)?.[key]- if (direct !== undefined)- return direct- return (loader.unwrapExports(value) as Record<string, unknown> | null)?.[key]-}--export async function runtimeVersion(loader: PlatformLoader): Promise<string | null> {- try {- const version = runtimeExport(loader, await loader.import(RUNTIME_PACKAGE), 'getDshRuntimeVersion')- if (typeof version !== 'function')- return null- const value = (version as () => unknown)()- return typeof value === 'string' && value.trim() !== '' ? value : null- }- catch {- return null- }-}diff --git a/packages/dsh-tauri-kernel/src/index.ts b/packages/dsh-tauri-kernel/src/index.tsdeleted file mode 100644index 944d25dd..00000000--- a/packages/dsh-tauri-kernel/src/index.ts+++ /dev/null@@ -1,6 +0,0 @@-import { PLUGIN_ID } from './shared/constants'--export const name = PLUGIN_ID-export const inject = ['webServer', 'connection', 'llm', 'agents', 'sessions', 'sessionProjections', 'workspaceRegistry', 'agentPresets', 'loader', 'approval', 'userQuestions']-export { apply } from './host/apply'-export type { Config } from './host/config/options'diff --git a/packages/dsh-tauri-kernel/src/shared/constants.ts b/packages/dsh-tauri-kernel/src/shared/constants.tsdeleted file mode 100644index d26e4789..00000000--- a/packages/dsh-tauri-kernel/src/shared/constants.ts+++ /dev/null@@ -1 +0,0 @@-export const PLUGIN_ID = 'dsh-tauri-kernel'diff --git a/packages/dsh-tauri-kernel/src/shared/native-model.ts b/packages/dsh-tauri-kernel/src/shared/native-model.tsdeleted file mode 100644index dacae7ec..00000000--- a/packages/dsh-tauri-kernel/src/shared/native-model.ts+++ /dev/null@@ -1,25 +0,0 @@-export interface NativeTurnOptions {- model: string | null- reasoningEffort: string | null-}--export interface NativeModelInfo {- id: string- name: string- description?: string- reasoning?: {- efforts: { id: string, name: string, description?: string }[]- defaultEffort?: string- }-}--export interface NativeModelCatalog {- models: NativeModelInfo[]- defaultModel?: string- defaultReasoningEffort?: string-}--export interface NativeModelDirectory extends NativeModelCatalog {- backend: 'codex' | 'claude'- current: NativeTurnOptions-}diff --git a/packages/dsh-tauri-kernel/src/shared/types.ts b/packages/dsh-tauri-kernel/src/shared/types.tsdeleted file mode 100644index b02a4f16..00000000--- a/packages/dsh-tauri-kernel/src/shared/types.ts+++ /dev/null@@ -1,45 +0,0 @@-import type { NativeTurnOptions } from './native-model'--export type BackendId = 'dsh' | 'codex' | 'claude'--export interface BackendDetection {- id: BackendId- installed: boolean- bridgeReady?: boolean- auth: 'ok' | 'missing' | 'unknown'- version: string | null- drift: boolean- hint: string | null-}--export interface KernelBinding {- backend: Exclude<BackendId, 'dsh'>- nativeSessionId: string- sessionId: string-}--export interface KernelProjectionState {- readonly ownerSessionId: string- readonly inheritedEventCount: number- readonly inheritedBinding: KernelBinding | null- readonly binding: KernelBinding | null-}--declare module '@deepseek-ai/dsh-session/types' {- interface PluginRecordMap {- 'plugin:dsh-tauri-kernel/kernel': KernelBinding- 'plugin:dsh-tauri-kernel/model': NativeTurnOptions- }-}--declare module '@deepseek-ai/dsh-session-projection/types' {- interface SessionProjectionMap {- bridgeModel: NativeTurnOptions- bridgeKernel: KernelBinding | null- }-- interface SessionProjectionStateMap {- bridgeModel: NativeTurnOptions- bridgeKernel: KernelProjectionState- }-}diff --git a/packages/dsh-tauri-kernel/tsdown.config.ts b/packages/dsh-tauri-kernel/tsdown.config.tsdeleted file mode 100644index d058ee99..00000000--- a/packages/dsh-tauri-kernel/tsdown.config.ts+++ /dev/null@@ -1,3 +0,0 @@-import { defineDshConfig } from '../dsh-tauri-tsdown/src/index.ts'--export default defineDshConfig({ client: { dts: true } })diff --git a/packages/dsh-tauri-ui/src/client/styles/index.ts b/packages/dsh-tauri-ui/src/client/styles/index.tsindex c91b5f21..2185e9f6 100644--- a/packages/dsh-tauri-ui/src/client/styles/index.ts+++ b/packages/dsh-tauri-ui/src/client/styles/index.ts@@ -600,9 +600,6 @@ const TAILWINDCSS_GENERATED = `.shrink-0 {flex-shrink: 0;}- .grow {- flex-grow: 1;- }.-translate-y-1\\/2 {--tw-translate-y: calc(calc(1/2 * 100%) * -1);translate: var(--tw-translate-x) var(--tw-translate-y);@@ -813,9 +810,6 @@ const TAILWINDCSS_GENERATED = `.rounded-md {border-radius: var(--dsw-radius-md);}- .rounded-none {- border-radius: 0;- }.rounded-sm {border-radius: var(--dsw-radius-sm);}@@ -1153,9 +1147,6 @@ const TAILWINDCSS_GENERATED = `.pt-\\[28px\\] {padding-top: 28px;}- .pr-0 {- padding-right: calc(var(--spacing) * 0);- }.pr-\\[4px\\] {padding-right: 4px;}@@ -1165,9 +1156,6 @@ const TAILWINDCSS_GENERATED = `.pr-\\[6px\\] {padding-right: 6px;}- .pr-\\[8px\\] {- padding-right: 8px;- }.pr-\\[10px\\] {padding-right: 10px;}@@ -1198,9 +1186,6 @@ const TAILWINDCSS_GENERATED = `.pl-\\[2px\\] {padding-left: 2px;}- .pl-\\[4px\\] {- padding-left: 4px;- }.pl-\\[8px\\] {padding-left: 8px;}@@ -1378,9 +1363,6 @@ const TAILWINDCSS_GENERATED = `.text-\\[var\\(--dsw-alias-label-primary-dimmed\\,var\\(--dsw-alias-label-dimmed\\)\\)\\] {color: var(--dsw-alias-label-primary-dimmed,var(--dsw-alias-label-dimmed));}- .text-\\[var\\(--dsw-alias-label-quaternary\\)\\] {- color: var(--dsw-alias-label-quaternary);- }.text-\\[var\\(--dsw-alias-label-secondary\\,var\\(--dsw-alias-label-primary\\)\\)\\] {color: var(--dsw-alias-label-secondary,var(--dsw-alias-label-primary));}@@ -1614,30 +1596,6 @@ const TAILWINDCSS_GENERATED = `.\\[transition\\:width_200ms_ease\\] {transition: width 200ms ease;}- .group-hover\\:hidden {- &:is(:where(.group):hover *) {- @media (hover: hover) {- display: none;- }- }- }- .group-hover\\:inline-flex {- &:is(:where(.group):hover *) {- @media (hover: hover) {- display: inline-flex;- }- }- }- .group-focus-visible\\:hidden {- &:is(:where(.group):focus-visible *) {- display: none;- }- }- .group-focus-visible\\:inline-flex {- &:is(:where(.group):focus-visible *) {- display: inline-flex;- }- }.before\\:pointer-events-none {&::before {content: var(--tw-content);@@ -1967,15 +1925,6 @@ const TAILWINDCSS_GENERATED = `}}}- .hover\\:not-disabled\\:bg-transparent {- &:hover {- @media (hover: hover) {- &:not(*:disabled) {- background-color: transparent;- }- }- }- }.hover\\:not-disabled\\:text-error {&:hover {@media (hover: hover) {@@ -2740,21 +2689,6 @@ const TAILWINDCSS_GENERATED = `object-fit: fill;}}- .\\[\\&\\>span\\]\\:inline-flex {- &>span {- display: inline-flex;- }- }- .\\[\\&\\>span\\]\\:h-full {- &>span {- height: 100%;- }- }- .\\[\\&\\>span\\]\\:items-center {- &>span {- align-items: center;- }- }.\\[\\&\\>span\\:first-child\\]\\:text-tertiary {&>span:first-child {color: var(--dsw-alias-label-tertiary);diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.test.tsindex f77eab83..42c554e8 100644--- a/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts@@ -1,5 +1,4 @@-import type { Agent, AgentSetupCommit } from '@deepseek-ai/dsh-agent'-import type { NativeSessionBridge } from 'dsh-tauri'+import type { Agent } from '@deepseek-ai/dsh-agent'import { resolve } from 'node:path'import { Context } from '@deepseek-ai/cordis'import { MessageId } from '@deepseek-ai/dsh-llm'@@ -54,10 +53,7 @@ interface SetupOptions {presets?: unknownsourceContext?: unknowngetAgent?: (id: string) => unknown- bridge?: NativeSessionBridge- projections?: unknownworkspace?: unknown- storedSession?: unknown}function setup(options: SetupOptions = {}): { created: any[] } {@@ -72,9 +68,8 @@ function setup(options: SetupOptions = {}): { created: any[] } {return options.create?.(value)},},- get: (key: string) => key === 'agentPresets' ? options.presets : key === 'nativeSessionBridge' ? options.bridge : key === 'sessionProjections' ? options.projections : undefined,+ get: (key: string) => key === 'agentPresets' ? options.presets : undefined,workspaceRegistry: { resolveByPath: async () => options.workspace },- sessions: { get: (id: string) => id === 'session-source' ? options.storedSession : undefined, list: () => [] },logger: { warn: options.warn ?? (() => {}) },webServer: { register: () => () => {} },} as never))@@ -98,66 +93,6 @@ describe('handoff API', () => {})describe('handoff.inherit', () => {- it.each(['codex', 'claude'] as const)('preserves the official %s fork binding without injecting a desktop handoff message', async (backend) => {- const kernel = await import('@deepseek-ai/dsh-session')- const context = new Context()- try {- const sessions = new kernel.SessionStore(context)- const source = kernel.Session.create(kernel.SessionId('session-source'))- source.append('user/message', { id: MessageId('message-source'), role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'source human conversation' }] }, { surfaceOp: 'append' })- kernel.appendPluginRecord(source, 'plugin:dsh-tauri-kernel/kernel', { backend, nativeSessionId: `native-source-${backend}`, sessionId: 'session-source' })- const prefix = source.snapshotEvents()- const followup = vi.fn()- const commit = vi.fn()- const sourceOptions = { provider: 'dsh-tauri-kernel', model: backend }- let target: Agent | undefined- const bridge: NativeSessionBridge = {- create: vi.fn(async (_source, createChild) => createChild()),- prepare: vi.fn(async (forkSource, agent, signal) => {- expect(forkSource).toBe(source)- expect(agent.session.header).toMatchObject({ cwd: resolve('worktrees/w1'), parentSession: 'session-source', isSeeded: true })- expect(agent.session.inheritedEventCount).toBe(2)- expect(agent.options).toEqual({ provider: 'dsh-tauri-kernel', model: backend })- expect(signal.aborted).toBe(false)- expect(kernel.appendPluginRecord(agent.session, 'plugin:dsh-tauri-kernel/kernel', { backend, nativeSessionId: `native-child-${backend}`, sessionId: 'session-target' })).toBe(3)- return { commit }- }),- }- const { created } = setup({- getAgent: id => id === 'session-source' ? { session: source, ctx: {}, options: sourceOptions } : undefined,- bridge,- create: async (options) => {- const session = sessions.prepare(kernel.SessionId(options.sessionId), options)- target = { id: session.id, session, ctx: context, options: { ...options.agentOptions }, followup } as unknown as Agent- const prepared = await options.setup(context, target)- prepared.commit()- return { agent: target }- },- })-- expect(await handoff.inherit('session-source', 'session-target', resolve('worktrees/w1'))).toEqual({ ok: true, targetSessionId: 'session-target', seedLength: 2 })- expect(created).toHaveLength(1)- expect(created[0].seed).toEqual(prefix)- expect(created[0].agentOptions).toBe(sourceOptions)- expect(bridge.create).toHaveBeenCalledExactlyOnceWith(source, expect.any(Function))- expect(bridge.prepare).toHaveBeenCalledExactlyOnceWith(source, target, expect.any(AbortSignal))- expect(commit).toHaveBeenCalledTimes(1)- expect(target!.session.snapshotEvents().slice(2)).toEqual([- { seq: 2, time: expect.any(Number), type: 'session/end-seed', data: { inherited: true } },- { seq: 3, time: expect.any(Number), type: 'plugin:dsh-tauri-kernel/kernel', ignorable: true, data: { backend, nativeSessionId: `native-child-${backend}`, sessionId: 'session-target' } },- ])- expect(target!.session.deriveMessages().map(({ role, content }) => ({ role, content }))).toEqual([- { role: 'user', content: [{ type: 'text', text: 'source human conversation' }] },- ])- expect(source.snapshotEvents()).toEqual(prefix)- expect(followup).not.toHaveBeenCalled()- expect(pendingWorktreeTitles.size).toBe(0)- }- finally {- await context.fiber.dispose()- }- })-it('composes the source preset without returning its id as an agent setup commit', async () => {const sourceContext = { preset: 'source' }const targetContext = { preset: 'target' }@@ -167,7 +102,7 @@ describe('handoff.inherit', () => {sourceContext,presets: { composedPreset, composeFrom },create: async (options) => {- (await options.setup?.(targetContext, { ctx: targetContext }))?.commit()+ await options.setup?.(targetContext, { ctx: targetContext })},})@@ -187,372 +122,7 @@ describe('handoff.inherit', () => {expect(composeFrom).toHaveBeenCalledExactlyOnceWith(targetContext, sourceContext)})- it('awaits bridge preparation and returns its exact commit to the official factory before publication', async () => {- const targetContext = new Context()- try {- const sessions = new SessionStore(targetContext)- const source = Session.create(SessionId('session-source'))- source.append('user/message', { id: MessageId('message-source'), role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'source history' }] }, { surfaceOp: 'append' })- const sourceContext = { preset: 'source' }- const order: string[] = []- const entered = Promise.withResolvers<void>()- const ack = Promise.withResolvers<void>()- const commit: AgentSetupCommit = { commit: vi.fn(() => order.push('commit')) }- let target: Agent | undefined- let nativeSignal: AbortSignal | undefined- const create = vi.fn<NativeSessionBridge['create']>(async (_source, createChild) => {- order.push('lock')- const handle = await createChild()- order.push('unlock')- return handle- })- const prepare = vi.fn<NativeSessionBridge['prepare']>(async (forkSource, agent, signal) => {- expect(forkSource).toBe(source)- expect(agent.ctx).toBe(targetContext)- expect(agent.session.header).toMatchObject({ cwd: resolve('worktrees/w1'), parentSession: 'session-source', isSeeded: true })- expect(agent.session.inheritedEventCount).toBe(1)- nativeSignal = signal- order.push('prepare')- entered.resolve()- await ack.promise- signal.throwIfAborted()- order.push('ack')- return commit- })- const { created } = setup({- session: source,- sourceContext,- bridge: { create, prepare },- presets: { composedPreset: () => 'default', composeFrom: vi.fn(() => order.push('compose')) },- create: async (options) => {- const session = sessions.prepare(SessionId(options.sessionId), options)- target = { id: session.id, session, ctx: targetContext } as Agent- const returned = await options.setup(targetContext, target)- expect(returned).toBe(commit)- expect(commit.commit).not.toHaveBeenCalled()- returned.commit()- order.push('durable')- order.push('publish')- return { agent: target }- },- })- const pending = handoff.inherit('session-source', 'session-target', resolve('worktrees/w1'))- await Promise.race([entered.promise, pending.then((result) => {- throw new Error(`Bridge setup was bypassed: ${JSON.stringify(result)}`)- })])- expect(order).toEqual(['lock', 'compose', 'prepare'])- expect(commit.commit).not.toHaveBeenCalled()- expect(nativeSignal?.aborted).toBe(false)- expect(pendingWorktreeTitles.size).toBe(0)- ack.resolve()- expect(await pending).toEqual({ ok: true, targetSessionId: 'session-target', seedLength: 1 })- expect(created).toHaveLength(1)- expect(create).toHaveBeenCalledExactlyOnceWith(source, expect.any(Function))- expect(prepare).toHaveBeenCalledExactlyOnceWith(source, target, nativeSignal)- expect(order).toEqual(['lock', 'compose', 'prepare', 'ack', 'commit', 'durable', 'publish', 'unlock'])- expect(commit.commit).toHaveBeenCalledTimes(1)- }- finally {- await targetContext.fiber.dispose()- }- })-- it('forwards the exact bridge factory signal and prepares with the scoped cancellation signal', async () => {- const context = new Context()- try {- const sessions = new SessionStore(context)- const source = Session.create(SessionId('session-source'))- source.append('turn/start', { turn: 0 })- const lifetime = new AbortController()- const commit = vi.fn()- let preparingSignal: AbortSignal | undefined- const { created } = setup({- session: source,- bridge: {- create: async (_source, createChild) => createChild(lifetime.signal),- prepare: async (_source, _agent, signal) => {- preparingSignal = signal- return { commit }- },- },- create: async (options) => {- expect(options.signal).toBe(lifetime.signal)- const session = sessions.prepare(SessionId(options.sessionId), options)- const agent = { id: session.id, session, ctx: context } as Agent- const prepared = await options.setup(context, agent)- prepared.commit()- return { agent }- },- })- expect(await handoff.inherit('session-source', 'session-target', resolve('worktrees/w1'))).toEqual({ ok: true, targetSessionId: 'session-target', seedLength: 1 })- expect(created).toHaveLength(1)- expect(created[0].signal).toBe(lifetime.signal)- expect(preparingSignal).toBeInstanceOf(AbortSignal)- expect(preparingSignal).not.toBe(lifetime.signal)- expect(preparingSignal?.aborted).toBe(false)- expect(commit).toHaveBeenCalledTimes(1)- }- finally {- await context.fiber.dispose()- }- })-- it('rejects an already aborted bridge factory signal before reading or creating the child', async () => {- const source = Session.create(SessionId('session-source'))- source.append('turn/start', { turn: 0 })- const snapshot = vi.spyOn(source, 'snapshotEvents')- const lifetime = new AbortController()- lifetime.abort(new Error('BRIDGE_DISPOSED: The bridge creation lifetime ended'))- const prepare = vi.fn<NativeSessionBridge['prepare']>(async () => {})- const { created } = setup({- session: source,- bridge: { create: async (_source, createChild) => createChild(lifetime.signal), prepare },- })- expect(await handoff.inherit('session-source', 'session-target', 'C:/work')).toEqual({ ok: false, error: 'BRIDGE_DISPOSED: The bridge creation lifetime ended' })- expect(snapshot).not.toHaveBeenCalled()- expect(created).toHaveLength(0)- expect(prepare).not.toHaveBeenCalled()- expect(pendingWorktreeTitles.size).toBe(0)- })-- it('rejects a late native ACK after the captured bridge lifetime aborts without committing or publishing', async () => {- const context = new Context()- try {- const sessions = new SessionStore(context)- const source = Session.create(SessionId('session-source'))- source.append('turn/start', { turn: 0 })- const maintenance = new AbortController()- const lifetime = new AbortController()- const factorySignal = AbortSignal.any([maintenance.signal, lifetime.signal])- const entered = Promise.withResolvers<void>()- const ack = Promise.withResolvers<void>()- const commit = vi.fn()- const published = vi.fn()- const reason = new Error('BRIDGE_DISPOSED: The captured bridge was unloaded')- let preparingSignal: AbortSignal | undefined- const { created } = setup({- session: source,- bridge: {- create: async (_source, createChild) => createChild(factorySignal),- prepare: async (_source, _agent, signal) => {- preparingSignal = signal- entered.resolve()- await ack.promise- return { commit }- },- },- create: async (options) => {- expect(options.signal).toBe(factorySignal)- const session = sessions.prepare(SessionId(options.sessionId), options)- const agent = { id: session.id, session, ctx: context } as Agent- const prepared = await options.setup(context, agent)- prepared.commit()- published()- return { agent }- },- })- const pending = handoff.inherit('session-source', 'session-target', resolve('worktrees/w1'))- await Promise.race([entered.promise, pending.then((result) => {- throw new Error(`Native preparation was bypassed: ${JSON.stringify(result)}`)- })])- expect(preparingSignal?.aborted).toBe(false)- lifetime.abort(reason)- expect(factorySignal.aborted).toBe(true)- expect(preparingSignal?.aborted).toBe(true)- expect(preparingSignal?.reason).toBe(reason)- expect(() => context.fiber.assertActive()).not.toThrow()- ack.resolve()- expect(await pending).toEqual({ ok: false, error: reason.message })- expect(created).toHaveLength(1)- expect(created[0].signal).toBe(factorySignal)- expect(commit).not.toHaveBeenCalled()- expect(published).not.toHaveBeenCalled()- expect(pendingWorktreeTitles.size).toBe(0)- }- finally {- await context.fiber.dispose()- }- })-- it('captures the latest source prefix inside the bridge creation lock instead of using the offered snapshot', async () => {- const context = new Context()- try {- const sessions = new SessionStore(context)- const source = Session.create(SessionId('session-source'))- source.append('turn/start', { turn: 0 })- const snapshot = vi.spyOn(source, 'snapshotEvents')- const bridge: NativeSessionBridge = {- create: vi.fn(async (_source, createChild) => {- expect(snapshot).not.toHaveBeenCalled()- source.append('user/message', { id: MessageId('message-late'), role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'arrived before the fork lock' }] }, { surfaceOp: 'append' })- source.append('turn/end', { turn: 0, reason: { kind: 'completed' } })- return createChild()- }),- prepare: vi.fn(async () => {}),- }- const { created } = setup({- session: source,- bridge,- create: async (options) => {- const target = sessions.prepare(SessionId(options.sessionId), options)- const agent = { id: target.id, session: target, ctx: context } as Agent- const commit = await options.setup(context, agent)- commit?.commit()- return { agent }- },- })- expect(await handoff.inherit('session-source', 'session-target', resolve('worktrees/w1'))).toEqual({ ok: true, targetSessionId: 'session-target', seedLength: 3 })- expect(created).toHaveLength(1)- expect(snapshot).toHaveBeenCalledTimes(1)- expect(created[0].seed).toEqual(source.snapshotEvents())- expect(created[0].inheritedEventCount).toBe(3)- expect(pendingWorktreeTitles.size).toBe(0)- expect(bridge.create).toHaveBeenCalledExactlyOnceWith(source, expect.any(Function))- expect(bridge.prepare).toHaveBeenCalledTimes(1)- }- finally {- await context.fiber.dispose()- }- })-- it.each([- { ownerSessionId: 'session-source', inheritedEventCount: 0, inheritedBinding: null, binding: { backend: 'codex', nativeSessionId: 'native-source', sessionId: 'session-source' } },- { ownerSessionId: 'session-source', inheritedEventCount: 1, inheritedBinding: { backend: 'claude', nativeSessionId: 'native-parent', sessionId: 'session-parent' }, binding: null },- { backend: 'codex', nativeSessionId: 'native-source', sessionId: 'session-source' },- ])('rejects a native projection without a bridge capability before creating a child: %j', async (projected) => {- const stateOf = vi.fn(() => projected)- const { created } = setup({ projections: { stateOf } })- expect(await handoff.inherit('session-source', 'session-target', 'C:/work')).toEqual({ ok: false, error: 'BRIDGE_CORE_UNAVAILABLE: Native session inheritance requires the native session fork capability' })- expect(created).toHaveLength(0)- expect(stateOf).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ id: 'session-source' }), 'bridgeKernel')- expect(pendingWorktreeTitles.size).toBe(0)- })-- it('rejects a native request header after the bridge projection and capability were unloaded', async () => {- const session = { ...sessionOf(conversationEvents) as object, requestHeader: () => ({ config: { provider: 'dsh-tauri-kernel', model: 'claude' } }) }- const { created } = setup({ session })- expect(await handoff.inherit('session-source', 'session-target', 'C:/work')).toEqual({ ok: false, error: 'BRIDGE_CORE_UNAVAILABLE: Native session inheritance requires the native session fork capability' })- expect(created).toHaveLength(0)- expect(pendingWorktreeTitles.size).toBe(0)- })-- it('rejects a native source selected before any binding or request was committed when its bridge capability is absent', async () => {- const session = sessionOf(emptyEvents)- const { created } = setup({ getAgent: () => ({ session, ctx: {}, options: { provider: 'dsh-tauri-kernel', model: 'codex' } }) })- expect(await handoff.inherit('session-source', 'session-target', 'C:/work')).toEqual({ ok: false, error: 'BRIDGE_CORE_UNAVAILABLE: Native session inheritance requires the native session fork capability' })- expect(created).toHaveLength(0)- expect(pendingWorktreeTitles.size).toBe(0)- })-- it('rejects a cold native kernel marker after both the projection and capability were unloaded without reading its binding payload', async () => {- const payload = vi.fn(() => {- throw new Error('A capability guard must not parse a native identity from raw history')- })- const marker = {- type: 'plugin:dsh-tauri-kernel/kernel',- seq: 2,- time: 3,- ignorable: true,- get data() {- return payload()- },- }- const session = sessionOf([...conversationEvents, marker])- const { created } = setup({ getAgent: () => undefined, storedSession: session })- expect(await handoff.inherit('session-source', 'session-target', 'C:/work')).toEqual({ ok: false, error: 'BRIDGE_CORE_UNAVAILABLE: Native session inheritance requires the native session fork capability' })- expect(payload).not.toHaveBeenCalled()- expect(created).toHaveLength(0)- expect(pendingWorktreeTitles.size).toBe(0)- })-- it.each([- { type: 'plugin:dsh-tauri-kernel/kernel', seq: 2, time: 3, data: {} },- { type: 'plugin:another/kernel', seq: 2, time: 3, data: {}, ignorable: true },- ])('does not classify unrelated or non-ignorable records as a native capability marker: %j', async (marker) => {- const session = sessionOf([...conversationEvents, marker])- const { created } = setup({ session })- expect(await handoff.inherit('session-source', 'session-target', 'C:/work')).toEqual({ ok: true, targetSessionId: 'session-target', seedLength: 3 })- expect(created).toHaveLength(1)- expect(created[0].setup).toBeUndefined()- })-- it('reports a bridge preparation failure without committing or attaching the inherited child', async () => {- const context = new Context()- try {- const commit = vi.fn()- const attachSession = vi.fn()- const published = vi.fn()- const prepare = vi.fn<NativeSessionBridge['prepare']>(async () => {- throw new Error('BRIDGE_FORK_UNAVAILABLE: Native CLI cannot fork stored history')- })- setup({- session: sessionOf(emptyEvents),- bridge: { create: async (_source, createChild) => createChild(), prepare },- workspace: { attachSession },- create: async (options) => {- const agent = { session: { id: options.sessionId }, ctx: context } as Agent- const returned = await options.setup(context, agent)- returned?.commit()- commit()- published()- return { agent }- },- })- expect(await handoff.handback('session-source', 'C:/project')).toEqual({ ok: false, error: 'BRIDGE_FORK_UNAVAILABLE: Native CLI cannot fork stored history' })- expect(prepare).toHaveBeenCalledTimes(1)- expect(commit).not.toHaveBeenCalled()- expect(published).not.toHaveBeenCalled()- expect(attachSession).not.toHaveBeenCalled()- expect(pendingWorktreeTitles.size).toBe(0)- }- finally {- await context.fiber.dispose()- }- })-- it('aborts native preparation when the official child setup scope is disposed', async () => {- const context = new Context()- try {- const entered = Promise.withResolvers<void>()- const ack = Promise.withResolvers<void>()- const commit = vi.fn()- let signal: AbortSignal | undefined- setup({- session: sessionOf(emptyEvents),- bridge: {- create: async (_source, createChild) => createChild(),- prepare: async (_source, _agent, preparingSignal) => {- signal = preparingSignal- entered.resolve()- await ack.promise- return { commit }- },- },- create: async (options) => {- const agent = { session: { id: options.sessionId }, ctx: context } as Agent- const returned = await options.setup(context, agent)- returned?.commit()- return { agent }- },- })- const pending = handoff.inherit('session-source', 'session-target', 'C:/work')- await Promise.race([entered.promise, pending.then((result) => {- throw new Error(`Native preparation was bypassed: ${JSON.stringify(result)}`)- })])- expect(signal?.aborted).toBe(false)- await context.fiber.dispose()- expect(signal?.aborted).toBe(true)- ack.resolve()- expect(await pending).toEqual({ ok: false, error: 'BRIDGE_DISPOSED: The inherited agent setup was disposed' })- expect(commit).not.toHaveBeenCalled()- expect(pendingWorktreeTitles.size).toBe(0)- }- finally {- await context.fiber.dispose()- }- })-- it('replays the actual kernel history with seeded lineage and an end-seed marker', async () => {+ it('replays the actual session history with seeded lineage and an end-seed marker', async () => {const context = new Context()try {const sessions = new SessionStore(context)@@ -582,8 +152,7 @@ describe('handoff.inherit', () => {presets: { composedPreset: () => 'default', composeFrom: () => 'default' },create: async (options) => {const target = sessions.prepare(SessionId(options.sessionId), options)- const commit = await options.setup?.(context, { session: target })- commit?.commit()+ await options.setup?.(context, { session: target })targets.push(target)},})@@ -636,7 +205,7 @@ describe('handoff.inherit', () => {expect(created).toHaveLength(0)})- it('seeds the target session from the kernel snapshot log', async () => {+ it('seeds the target session from the snapshot log', async () => {const { created } = setup()const outcome = await handoff.inherit('session-source', 'session-target', 'C:/worktrees/w1')expect(outcome).toEqual({ ok: true, targetSessionId: 'session-target', seedLength: conversationEvents.length })@@ -725,61 +294,32 @@ describe('handoff.inherit', () => {})describe('handoff.checkout', () => {- it('rejects removal when native handback preparation fails without publishing or queuing desktop followup', async () => {- const context = new Context()- try {- const sessions = new SessionStore(context)- const source = Session.create(SessionId('session-source'))- source.append('turn/start', { turn: 0 })- const followup = vi.fn()- const attachSession = vi.fn()- const save = vi.spyOn(checkoutContext, 'save')- let published: Agent | undefined- setup({- session: source,- workspace: { attachSession },- bridge: {- create: async (_source, createChild) => createChild(),- prepare: async () => {- throw new Error('BRIDGE_FORK_UNAVAILABLE: The native CLI cannot fork')- },- },- create: async (options) => {- const session = sessions.prepare(SessionId(options.sessionId), options)- const agent = { id: session.id, session, ctx: context, followup } as unknown as Agent- const prepared = await options.setup(context, agent)- prepared.commit()- published = agent- return { agent }- },- })- const checkout = vi.spyOn(worktree, 'checkout').mockImplementation(async (_input, options) => {- const result = await options!.beforeRemove!({ branch: 'feature-child', projectPath: resolve('local-project'), worktreePath: resolve('worktrees/w1') })- expect(result).toEqual({ ok: false, error: 'BRIDGE_FORK_UNAVAILABLE: The native CLI cannot fork' })- return result.ok- ? { ok: true, branch: 'feature-child', projectPath: resolve('local-project'), worktreePath: resolve('worktrees/w1') }- : { ok: false, error: `Failed to create the local handback session; the worktree was preserved: ${result.error}` }- })+ it('keeps the worktree when handback creation fails', async () => {+ const save = vi.spyOn(checkoutContext, 'save')+ setup({+ session: sessionOf(emptyEvents),+ create: async () => {+ throw new Error('boom')+ },+ })+ const checkout = vi.spyOn(worktree, 'checkout').mockImplementation(async (_input, options) => {+ const result = await options!.beforeRemove!({ branch: 'feature-child', projectPath: resolve('local-project'), worktreePath: resolve('worktrees/w1') })+ expect(result).toEqual({ ok: false, error: 'boom' })+ return { ok: false, error: `Failed to create the local handback session; the worktree was preserved: ${result.error}` }+ })- expect(await handoff.checkout('session-source', 'hash/w1', 'feature-child', true)).toEqual({- ok: false,- error: 'Failed to create the local handback session; the worktree was preserved: BRIDGE_FORK_UNAVAILABLE: The native CLI cannot fork',- })- expect(checkout).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-source', worktree_hash_dirname: 'hash/w1', branch_name: 'feature-child' }, { carryStaged: true, beforeRemove: expect.any(Function) })- expect(published).toBeUndefined()- expect(attachSession).not.toHaveBeenCalled()- expect(save).not.toHaveBeenCalled()- expect(followup).not.toHaveBeenCalled()- expect(pendingWorktreeTitles.size).toBe(0)- }- finally {- await context.fiber.dispose()- }+ expect(await handoff.checkout('session-source', 'hash/w1', 'feature-child', true)).toEqual({+ ok: false,+ error: 'Failed to create the local handback session; the worktree was preserved: boom',+ })+ expect(checkout).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session-source', worktree_hash_dirname: 'hash/w1', branch_name: 'feature-child' }, { carryStaged: true, beforeRemove: expect.any(Function) })+ expect(save).not.toHaveBeenCalled()+ expect(pendingWorktreeTitles.size).toBe(0)})})describe('handoff.handback', () => {- it('publishes the prepared native child before attaching it and saving checkout context', async () => {+ it('publishes the inherited child before attaching it and saving checkout context', async () => {const context = new Context()try {const sessions = new SessionStore(context)@@ -787,7 +327,6 @@ describe('handoff.handback', () => {source.append('turn/start', { turn: 0 })source.append('turn/end', { turn: 0, reason: { kind: 'completed' } })const order: string[] = []- const commit = vi.fn(() => order.push('commit'))const attachSession = vi.fn(async () => {order.push('attach')})@@ -797,24 +336,9 @@ describe('handoff.handback', () => {setup({session: source,workspace: { attachSession },- bridge: {- create: async (_source, createChild) => {- order.push('lock')- const handle = await createChild()- order.push('unlock')- return handle- },- prepare: async (_source, agent) => {- expect(agent.session.header).toMatchObject({ cwd: resolve('local-project'), parentSession: source.id, isSeeded: true })- order.push('prepare')- return { commit }- },- },create: async (options) => {const session = sessions.prepare(SessionId(options.sessionId), options)const agent = { id: session.id, session, ctx: context } as Agent- const prepared = await options.setup(context, agent)- prepared.commit()order.push('publish')return { agent }},@@ -822,9 +346,8 @@ describe('handoff.handback', () => {const outcome = await handoff.handback(source.id, resolve('local-project'), { branch: 'feature-child', worktreePath: 'C:/worktrees/w1' })expect(outcome).toEqual({ ok: true, targetSessionId: expect.stringMatching(/^session-/) })if (!outcome.ok)- throw new Error(`The native handback failed: ${outcome.error}`)- expect(order).toEqual(['lock', 'prepare', 'commit', 'publish', 'unlock', 'attach', 'save'])- expect(commit).toHaveBeenCalledTimes(1)+ throw new Error(`The handback failed: ${outcome.error}`)+ expect(order).toEqual(['publish', 'attach', 'save'])expect(attachSession).toHaveBeenCalledExactlyOnceWith(outcome.targetSessionId)expect(save).toHaveBeenCalledExactlyOnceWith(outcome.targetSessionId, { projectPath: resolve('local-project'), branch: 'feature-child', worktreePath: 'C:/worktrees/w1', checkedOutAt: expect.any(String) })}diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.tsindex c82171b2..24d0232b 100644--- a/packages/dsh-tauri-worktree/src/host/service/handoff.ts+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.ts@@ -1,7 +1,5 @@import type { Context } from '@deepseek-ai/cordis'-import type { Agent, AgentHandle, AgentSetupCommit } from '@deepseek-ai/dsh-agent'-import type { Session } from '@deepseek-ai/dsh-session'-import type { NativeSessionBridge } from 'dsh-tauri'+import type { AgentHandle } from '@deepseek-ai/dsh-agent'import type { CheckoutInfo, HostContext, OperationResult } from '../types'import { randomUUID } from 'node:crypto'import { getServerContext } from 'dsh-h3/utils'@@ -132,60 +130,32 @@ async function createAgent(options: { parentSession?: string, requireEvents?: boolean } = {},): Promise<{ handle: AgentHandle, seed: readonly unknown[] }> {const ctx = getServerContext<HostContext>(server)- const bridge: NativeSessionBridge | undefined = ctx.get?.('nativeSessionBridge')- if (bridge && (typeof bridge.create !== 'function' || typeof bridge.prepare !== 'function'))- throw new Error('BRIDGE_CORE_UNAVAILABLE: The native session fork capability is unavailable')- let inheritedSeed: readonly unknown[] = []- const create = (signal?: AbortSignal): Promise<AgentHandle> => {- signal?.throwIfAborted()- inheritedSeed = sessionEvents(sourceSession)- if (options.requireEvents && inheritedSeed.length === 0)- throw new Error(`源会话没有可继承的事件:${sourceSession.id}`)- if (!bridge) {- const projected = ctx.get?.('sessionProjections')?.stateOf?.(sourceSession, 'bridgeKernel')- const hasNativeRecord = inheritedSeed.some((value) => {- const event = value as { type?: unknown, ignorable?: unknown }- return event?.type === 'plugin:dsh-tauri-kernel/kernel' && event.ignorable === true- })- if (hasNativeRecord || projected?.binding || projected?.inheritedBinding || projected?.nativeSessionId || sourceSession.requestHeader?.()?.config?.provider === 'dsh-tauri-kernel' || sourceAgent?.options?.provider === 'dsh-tauri-kernel')- throw new Error('BRIDGE_CORE_UNAVAILABLE: Native session inheritance requires the native session fork capability')- }- const presets = ctx.get?.('agentPresets')- const parentPreset = sourceAgent- ? (presets?.composedPreset(sourceAgent.ctx) ?? sourceSession.header?.agentPreset)- : sourceSession.header?.agentPreset- return ctx.agents.create({- sessionId: targetSessionId,- seed: inheritedSeed,- ...(signal ? { signal } : {}),- meta: {- cwd,- parentSession: options.parentSession ?? sourceSession.id,- isSeeded: true,- ...(parentPreset ? { agentPreset: parentPreset } : {}),- },- inheritedEventCount: inheritedSeed.length,- agentOptions: sourceAgent?.options ?? {},- ...(bridge || (sourceAgent && presets && parentPreset)- ? {- setup: async (agentCtx: Context, agent: Agent): Promise<AgentSetupCommit | void> => {- if (sourceAgent && presets && parentPreset)- presets.composeFrom(agentCtx, sourceAgent.ctx)- if (!bridge)- return- const controller = new AbortController()- agentCtx.effect(() => () => controller.abort(new Error('BRIDGE_DISPOSED: The inherited agent setup was disposed')))- const scoped = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal- scoped.throwIfAborted()- const commit = await bridge.prepare(sourceSession as Session, agent, scoped)- scoped.throwIfAborted()- return commit- },- }- : {}),- })- }- const handle = bridge ? await bridge.create(sourceSession as Session, create) : await create()+ const inheritedSeed = sessionEvents(sourceSession)+ if (options.requireEvents && inheritedSeed.length === 0)+ throw new Error(`源会话没有可继承的事件:${sourceSession.id}`)+ const presets = ctx.get?.('agentPresets')+ const parentPreset = sourceAgent+ ? (presets?.composedPreset(sourceAgent.ctx) ?? sourceSession.header?.agentPreset)+ : sourceSession.header?.agentPreset+ const handle = await ctx.agents.create({+ sessionId: targetSessionId,+ seed: inheritedSeed,+ meta: {+ cwd,+ parentSession: options.parentSession ?? sourceSession.id,+ isSeeded: true,+ ...(parentPreset ? { agentPreset: parentPreset } : {}),+ },+ inheritedEventCount: inheritedSeed.length,+ agentOptions: sourceAgent?.options ?? {},+ ...(sourceAgent && presets && parentPreset+ ? {+ setup: async (agentCtx: Context): Promise<void> => {+ presets.composeFrom(agentCtx, sourceAgent.ctx)+ },+ }+ : {}),+ })return { handle, seed: inheritedSeed }}diff --git a/packages/dsh-tauri/src/host/types/harness.ts b/packages/dsh-tauri/src/host/types/harness.tsindex fdd1ef96..31626755 100644--- a/packages/dsh-tauri/src/host/types/harness.ts+++ b/packages/dsh-tauri/src/host/types/harness.ts@@ -8,9 +8,8 @@* 并作为 dsh-tauri 宿主侧全部类型的统一出口。*/import type { Context } from '@deepseek-ai/cordis'-import type { Agent, AgentHandle, AgentSetupCommit } from '@deepseek-ai/dsh-agent'import type { WebRoute, WebServer } from '@deepseek-ai/dsh-host-webserver'-import type { Session, SessionStore } from '@deepseek-ai/dsh-session'+import type { SessionStore } from '@deepseek-ai/dsh-session'import type { IncomingMessage } from 'node:http'export type { Context } from '@deepseek-ai/cordis'@@ -35,16 +34,6 @@ export type {ToolRuntime,} from '@deepseek-ai/dsh-tools'export type { WorkspaceId, WorkspaceRegistry } from '@deepseek-ai/dsh-workspace'-export interface NativeSessionBridge {- create: (source: Session, create: (signal?: AbortSignal) => Promise<AgentHandle>) => Promise<AgentHandle>- prepare: (source: Session, agent: Agent, signal: AbortSignal) => Promise<AgentSetupCommit | void>-}--declare module '@deepseek-ai/cordis' {- interface Context {- nativeSessionBridge: NativeSessionBridge- }-}export interface ConnectionGate {requestRejection: (request: IncomingMessage) => 401 | 403 | undefineddiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b894c465..b9546bbb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1006,9 +1006,6 @@ importers:dsh-tauri-extension:specifier: workspace:*version: link:../dsh-tauri-extension- dsh-tauri-kernel:- specifier: workspace:*- version: link:../dsh-tauri-kerneldsh-tauri-mobile-ui:specifier: workspace:*version: link:../dsh-tauri-mobile-ui@@ -1120,28 +1117,6 @@ importers:specifier: catalog:cliversion: 0.17.4(@emnapi/[email protected])(@emnapi/[email protected])([email protected])([email protected])([email protected])([email protected])- packages/dsh-tauri-kernel:- dependencies:- dsh-h3:- specifier: 'catalog:'- version: 0.2.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@genapi/[email protected])([email protected])- dsh-tauri:- specifier: workspace:*- version: link:../dsh-tauri- h3:- specifier: 'catalog:'- version: 2.0.1- devDependencies:- dsh-tauri-tsdown:- specifier: workspace:*- version: link:../dsh-tauri-tsdown- dsh-tauri-ui:- specifier: workspace:*- version: link:../dsh-tauri-ui- tsdown:- specifier: catalog:cli- version: 0.17.4(@emnapi/[email protected])(@emnapi/[email protected])([email protected])([email protected])([email protected])([email protected])-packages/dsh-tauri-mobile-ui:dependencies:dsh-tauri:diff --git a/src-tauri/resources/manifest.jsonc b/src-tauri/resources/manifest.jsoncindex ca33f5e7..df3a834f 100644--- a/src-tauri/resources/manifest.jsonc+++ b/src-tauri/resources/manifest.jsonc@@ -75,7 +75,8 @@"dsh-tauri-turnrewind","dsh-tauri-connection","dsh-tauri-bridge",- "dsh-tauri-running-changes"+ "dsh-tauri-running-changes",+ "dsh-tauri-kernel"],"built-in": [{@@ -96,12 +97,6 @@"name": "DSH Tauri Mobile UI","repo": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-mobile-ui"},- {- "id": "dsh-tauri-kernel",- "spec": "dsh-tauri-kernel",- "name": "DSH Tauri Kernel",- "repo": "https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-kernel"- },{"id": "dsh-tauri-worktree","spec": "dsh-tauri-worktree",diff --git a/src-tauri/src/service/plugin/preset.rs b/src-tauri/src/service/plugin/preset.rsindex 8c0e53d0..92b6579f 100644--- a/src-tauri/src/service/plugin/preset.rs+++ b/src-tauri/src/service/plugin/preset.rs@@ -842,11 +842,20 @@ mod tests {#[test]fn deprecated_manifest_lists_the_renamed_bridge() {- // dsh-tauri-bridge 改名为 dsh-tauri-kernel:老档案里的 link: 依赖与 bundle 引用- // 只能靠弃用名单兜底卸载(残留 bundle 会导致无法进入软件页面)。+ // dsh-tauri-bridge 改名为 dsh-tauri-kernel(该功能已整体退役):老档案里的+ // link: 依赖与 bundle 引用只能靠弃用名单兜底卸载(残留 bundle 会导致无法进入+ // 软件页面)。assert!(shipped_deprecated_ids().contains("dsh-tauri-bridge"));}+ #[test]+ fn deprecated_manifest_lists_the_retired_kernel() {+ // dsh-tauri-kernel 因原生内核不稳定退役,并从内置清单移除了条目:升级用户的+ // link: 依赖与 bundle 引用只能靠弃用名单兜底卸载(残留 bundle 会导致无法进入+ // 软件页面)。+ assert!(shipped_deprecated_ids().contains("dsh-tauri-kernel"));+ }+#[test]fn deprecated_manifest_lists_absorbed_running_changes() {// dsh-tauri-running-changes 已并入 dsh-tauri-experimental,并从内置清单移除diff --git a/test/plugin-resource-closure.test.ts b/test/plugin-resource-closure.test.tsindex 004cedcb..edfa2d0a 100644--- a/test/plugin-resource-closure.test.ts+++ b/test/plugin-resource-closure.test.ts@@ -1,7 +1,6 @@import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'import { join } from 'node:path'import { fileURLToPath, pathToFileURL } from 'node:url'-import ts from 'typescript'import { describe, expect, it } from 'vitest'const BUNDLE_MANIFEST = new URL('../packages/dsh-tauri-bundle/package.json', import.meta.url)@@ -34,21 +33,6 @@ function packageJsonFiles(root: URL): string[] {return files}-describe('worktree handoff host dependency closure', () => {- it('keeps native fork runtime while erasing official types without static DSH imports', () => {- const source = readFileSync(new URL('../packages/dsh-tauri-worktree/src/host/service/handoff.ts', import.meta.url), 'utf8')- const { outputText } = ts.transpileModule(source, {- fileName: 'handoff.ts',- compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext, verbatimModuleSyntax: true },- })- expect(outputText).toContain('randomUUID()')- expect(outputText).toContain('bridge.create(sourceSession, create)')- expect(outputText).toContain('bridge.prepare(sourceSession, agent, scoped)')- expect(outputText).not.toContain('.agent.followup(')- expect(outputText).not.toMatch(DSH_STATIC_IMPORT)- })-})-describe.skipIf(!BUILT)('bundled plugin resource closure', () => {it('contains every bundled plugin with a valid entry', () => {for (const name of bundledPluginNames()) {diff --git a/test/plugin-version-baseline.test.ts b/test/plugin-version-baseline.test.tsindex e698be9e..6a68444b 100644--- a/test/plugin-version-baseline.test.ts+++ b/test/plugin-version-baseline.test.ts@@ -23,7 +23,6 @@ const expectedPlugins = ['dsh-tauri-archive','dsh-tauri-experimental','dsh-tauri-extension',- 'dsh-tauri-kernel','dsh-tauri-mobile-ui','dsh-tauri-model','dsh-tauri-notification',@@ -37,7 +36,7 @@ const expectedPlugins = []describe('运行插件最低内核声明', () => {- it('覆盖全部 15 个 dsh 插件而不包含聚合与构建包', () => {+ it('覆盖全部 14 个 dsh 插件而不包含聚合与构建包', () => {expect(plugins.map(({ directory }) => directory).sort()).toEqual(expectedPlugins)})diff --git a/test/session-projection-types.test.ts b/test/session-projection-types.test.tsindex ecdd9761..6d3aab1d 100644--- a/test/session-projection-types.test.ts+++ b/test/session-projection-types.test.ts@@ -1,17 +1,13 @@import type {} from '@deepseek-ai/dsh-agent-preset-registry/types'import type { SessionProjectionMap as ClientProjectionMap } from '@deepseek-ai/dsh-api-session-controller/client'import type { SessionProjectionMap } from '@deepseek-ai/dsh-session-projection/types'-import type { NativeTurnOptions } from '../packages/dsh-tauri-kernel/src/shared/native-model'-import type { KernelBinding } from '../packages/dsh-tauri-kernel/src/shared/types'import { describe, expect, expectTypeOf, it } from 'vitest'import { SESSION_SCHEDULE_ORIGIN_PROJECTION } from '../packages/dsh-tauri-scheduler/src/shared/constants'describe('session projection augmentation contracts', () => {- it('keeps scheduler, bridge and upstream projections identical through canonical and client exports', () => {+ it('keeps scheduler and upstream projections identical through canonical and client exports', () => {expect(SESSION_SCHEDULE_ORIGIN_PROJECTION).toBe('dsh-tauri-scheduler.origin')expectTypeOf<SessionProjectionMap[typeof SESSION_SCHEDULE_ORIGIN_PROJECTION]>().toEqualTypeOf<boolean>()- expectTypeOf<SessionProjectionMap['bridgeModel']>().toEqualTypeOf<NativeTurnOptions>()- expectTypeOf<SessionProjectionMap['bridgeKernel']>().toEqualTypeOf<KernelBinding | null>()expectTypeOf<SessionProjectionMap['agentPreset']>().toEqualTypeOf<string | null>()expectTypeOf<ClientProjectionMap>().toEqualTypeOf<SessionProjectionMap>()})