DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(bridge): 官方会话连接本机 Codex / Claude 内核 (#988)
Mao Mr79947d56a9d9
diff --git a/genapi.config.ts b/genapi.config.tsindex c1da3266..ede6dac8 100644--- a/genapi.config.ts+++ b/genapi.config.ts@@ -14,6 +14,7 @@ const plugins = ['dsh-tauri-notification','dsh-tauri-worktree','dsh-tauri-ssh',+ 'dsh-tauri-bridge',]export default defineConfig({@@ -36,7 +37,7 @@ export default defineConfig({),meta: { import: { http: 'dsh-tauri/client' } },transform: {- operation: name => name.replace(/ApiTauri(?:Extension|Scheduler|Rightclick|Archive|Experimental|Model|Ui|Notification|Worktree|Ssh)/, ''),+ operation: name => name.replace(/ApiTauri(?:Extension|Scheduler|Rightclick|Archive|Experimental|Model|Ui|Notification|Worktree|Ssh|Bridge)/, ''),},patch: { operations: { post: 'postWorktree', delete: 'deleteWorktree' } },servers: [diff --git a/package.json b/package.jsonindex 47f5e2e4..2eb5692d 100644--- a/package.json+++ b/package.json@@ -59,6 +59,7 @@"@deepseek-ai/cordis-plugin-loader": "catalog:dsh","@deepseek-ai/dsh-agent": "catalog:dsh","@deepseek-ai/dsh-agent-default-model": "catalog:dsh",+ "@deepseek-ai/dsh-agent-loop": "catalog:dsh","@deepseek-ai/dsh-agent-preset": "catalog:dsh","@deepseek-ai/dsh-agent-preset-registry": "catalog:dsh","@deepseek-ai/dsh-api-session-controller": "catalog:dsh",@@ -70,21 +71,28 @@"@deepseek-ai/dsh-client-ui-layout": "catalog:dsh","@deepseek-ai/dsh-client-ui-primitives": "catalog:dsh","@deepseek-ai/dsh-client-ui-renderer": "catalog:dsh",+ "@deepseek-ai/dsh-client-ui-session": "catalog:dsh","@deepseek-ai/dsh-client-ui-settings": "catalog:dsh","@deepseek-ai/dsh-client-ui-slots": "catalog:dsh","@deepseek-ai/dsh-client-ui-theme": "catalog:dsh",+ "@deepseek-ai/dsh-client-ui-workspace": "catalog:dsh","@deepseek-ai/dsh-host-webserver": "catalog:dsh","@deepseek-ai/dsh-llm": "catalog:dsh","@deepseek-ai/dsh-permission-presets": "catalog:dsh","@deepseek-ai/dsh-session": "catalog:dsh",+ "@deepseek-ai/dsh-session-persistence": "catalog:dsh",+ "@deepseek-ai/dsh-session-projection": "catalog:dsh","@deepseek-ai/dsh-skill-filesystem": "catalog:dsh","@deepseek-ai/dsh-tools": "catalog:dsh","@deepseek-ai/dsh-user-approval": "catalog:dsh",+ "@deepseek-ai/dsh-user-questions": "catalog:dsh",+ "@deepseek-ai/dsh-util-code-language": "catalog:dsh","@deepseek-ai/dsh-workspace": "catalog:dsh","@eslint-react/eslint-plugin": "catalog:lint","@genapi/core": "catalog:","@genapi/presets": "catalog:","@genapi/shared": "catalog:",+ "@shikijs/langs": "catalog:testing","@tailwindcss/postcss": "catalog:build","@tailwindcss/vite": "catalog:build","@tauri-apps/cli": "catalog:tauri",@@ -98,24 +106,32 @@"@vitejs/plugin-react": "catalog:build","@vitest/coverage-v8": "catalog:testing","@wdio/tauri-service": "catalog:testing",+ "anser": "catalog:testing","babel-plugin-react-compiler": "catalog:build","bumpp": "catalog:release","changelogithub": "catalog:release",+ "diff": "catalog:testing","dsh-h3": "catalog:",+ "dsh-session-current": "catalog:testing","eslint": "catalog:lint","eslint-plugin-react-refresh": "catalog:lint","h3": "catalog:",+ "immer": "catalog:testing","jsdom": "catalog:testing","pathe": "catalog:utils","playwright": "catalog:testing","postcss": "catalog:build","publint": "catalog:cli",+ "shiki": "catalog:testing",+ "simple-icons": "catalog:testing","ssh2": "catalog:utils","tailwindcss": "catalog:build","tsx": "catalog:build","typescript": "catalog:cli","vite": "catalog:build","vitest": "catalog:testing",- "webdriverio": "catalog:testing"+ "webdriverio": "catalog:testing",+ "zod": "catalog:utils",+ "zustand": "catalog:testing"}}diff --git a/packages/dsh-tauri-bridge/cordis.patch.yml b/packages/dsh-tauri-bridge/cordis.patch.ymlnew file mode 100644index 00000000..762668df--- /dev/null+++ b/packages/dsh-tauri-bridge/cordis.patch.yml@@ -0,0 +1,3 @@+- insert:+ - id: dsh-tauri-bridge+ name: dsh-tauri-bridgediff --git a/packages/dsh-tauri-bridge/package.json b/packages/dsh-tauri-bridge/package.jsonnew file mode 100644index 00000000..3a1e8f10--- /dev/null+++ b/packages/dsh-tauri-bridge/package.json@@ -0,0 +1,73 @@+{+ "name": "dsh-tauri-bridge",+ "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"],+ "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:",+ "zod": "catalog:utils"+ },+ "devDependencies": {+ "@deepseek-ai/cordis": "catalog:dsh",+ "@deepseek-ai/cordis-plugin-loader": "catalog:dsh",+ "@deepseek-ai/dsh-agent": "catalog:dsh",+ "@deepseek-ai/dsh-agent-preset-registry": "catalog:dsh",+ "@deepseek-ai/dsh-api-session-controller": "catalog:dsh",+ "@deepseek-ai/dsh-client-connection": "catalog:dsh",+ "@deepseek-ai/dsh-client-ui-conversation": "catalog:dsh",+ "@deepseek-ai/dsh-client-ui-session": "catalog:dsh",+ "@deepseek-ai/dsh-client-ui-slots": "catalog:dsh",+ "@deepseek-ai/dsh-client-ui-workspace": "catalog:dsh",+ "@deepseek-ai/dsh-llm": "catalog:dsh",+ "@deepseek-ai/dsh-session": "catalog:dsh",+ "@deepseek-ai/dsh-session-persistence": "catalog:dsh",+ "@deepseek-ai/dsh-session-projection": "catalog:dsh",+ "@deepseek-ai/dsh-user-approval": "catalog:dsh",+ "@deepseek-ai/dsh-user-questions": "catalog:dsh",+ "@deepseek-ai/dsh-workspace": "catalog:dsh",+ "dsh-tauri-tsdown": "workspace:*",+ "dsh-tauri-ui": "workspace:*",+ "tsdown": "catalog:cli"+ }+}diff --git a/packages/dsh-tauri-bridge/src/client/apis/index.ts b/packages/dsh-tauri-bridge/src/client/apis/index.tsnew file mode 100644index 00000000..99038e59--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/apis/index.ts@@ -0,0 +1,29 @@+/*+ * @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-bridge/src/client/apis/index.type.ts b/packages/dsh-tauri-bridge/src/client/apis/index.type.tsnew file mode 100644index 00000000..b5edbc99--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/apis/index.type.ts@@ -0,0 +1,20 @@+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-bridge/src/client/components/hero-kernel.tsx b/packages/dsh-tauri-bridge/src/client/components/hero-kernel.tsxnew file mode 100644index 00000000..cf298d17--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/components/hero-kernel.tsx@@ -0,0 +1,178 @@+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-bridge/src/client/components/kernel-icon.tsx b/packages/dsh-tauri-bridge/src/client/components/kernel-icon.tsxnew file mode 100644index 00000000..4c63f610--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/components/kernel-icon.tsx@@ -0,0 +1,14 @@+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-bridge/src/client/components/kernel.test.tsx b/packages/dsh-tauri-bridge/src/client/components/kernel.test.tsxnew file mode 100644index 00000000..b5e52a5d--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/components/kernel.test.tsx@@ -0,0 +1,366 @@+// @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-bridge/src/client/components/model-kernel.test.tsx b/packages/dsh-tauri-bridge/src/client/components/model-kernel.test.tsxnew file mode 100644index 00000000..1ebe5ea9--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/components/model-kernel.test.tsx@@ -0,0 +1,591 @@+// @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-bridge/src/client/components/model-kernel.tsx b/packages/dsh-tauri-bridge/src/client/components/model-kernel.tsxnew file mode 100644index 00000000..1d003b26--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/components/model-kernel.tsx@@ -0,0 +1,73 @@+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-bridge/src/client/components/session-kernel-hover.tsx b/packages/dsh-tauri-bridge/src/client/components/session-kernel-hover.tsxnew file mode 100644index 00000000..82f29314--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/components/session-kernel-hover.tsx@@ -0,0 +1,31 @@+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-bridge/src/client/components/session-kernel.tsx b/packages/dsh-tauri-bridge/src/client/components/session-kernel.tsxnew file mode 100644index 00000000..506d41e0--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/components/session-kernel.tsx@@ -0,0 +1,32 @@+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-bridge/src/client/components/slot-contract.ts b/packages/dsh-tauri-bridge/src/client/components/slot-contract.tsnew file mode 100644index 00000000..25bb862c--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/components/slot-contract.ts@@ -0,0 +1,21 @@+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-bridge/src/client/constants/index.ts b/packages/dsh-tauri-bridge/src/client/constants/index.tsnew file mode 100644index 00000000..9c6b3e0c--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/constants/index.ts@@ -0,0 +1,5 @@+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-bridge/src/client/index.ts b/packages/dsh-tauri-bridge/src/client/index.tsnew file mode 100644index 00000000..f8366cae--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/index.ts@@ -0,0 +1,12 @@+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-bridge/src/client/locales/index.ts b/packages/dsh-tauri-bridge/src/client/locales/index.tsnew file mode 100644index 00000000..a57f8929--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/locales/index.ts@@ -0,0 +1,49 @@+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-bridge/src/client/register/kernel-model.test.ts b/packages/dsh-tauri-bridge/src/client/register/kernel-model.test.tsnew file mode 100644index 00000000..d6a6de46--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/register/kernel-model.test.ts@@ -0,0 +1,401 @@+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-bridge/src/client/register/kernel-model.ts b/packages/dsh-tauri-bridge/src/client/register/kernel-model.tsnew file mode 100644index 00000000..4c7087a3--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/register/kernel-model.ts@@ -0,0 +1,127 @@+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-bridge/src/client/register/kernel.test.ts b/packages/dsh-tauri-bridge/src/client/register/kernel.test.tsnew file mode 100644index 00000000..9f707258--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/register/kernel.test.ts@@ -0,0 +1,475 @@+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 { 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: {} }+ 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: () => state, 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, 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-bridge:kernel', order: -10 },+ { name: 'sidebar.session.row.hover', id: 'dsh-tauri-bridge: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-bridge')+ 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).toHaveBeenCalledWith('[dsh-tauri-bridge] slot decoration unavailable; the official renderer capability is unverified', undefined)+ 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-bridge] 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-bridge] 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-bridge] 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 with no kernel key warns once 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).toHaveBeenCalledTimes(1)+ expect(console.warn).toHaveBeenCalledWith('[dsh-tauri-bridge] session kernel identity unavailable: archived-session', undefined)+ expect(feature.openSession).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-bridge] sessions.refreshProjections unavailable; session kernel identity is unknown', undefined)+ expect(feature.openSession).not.toHaveBeenCalled()+ })+})diff --git a/packages/dsh-tauri-bridge/src/client/register/kernel.ts b/packages/dsh-tauri-bridge/src/client/register/kernel.tsnew file mode 100644index 00000000..bb6895b6--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/register/kernel.ts@@ -0,0 +1,176 @@+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)+ 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 identity = sessions === undefined ? undefined : kernelFromList(sessions.list.getSnapshot(), sessionId as SessionId)+ if (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-bridge/src/client/service/kernel-identity.test.ts b/packages/dsh-tauri-bridge/src/client/service/kernel-identity.test.tsnew file mode 100644index 00000000..c1a5823f--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/service/kernel-identity.test.ts@@ -0,0 +1,63 @@+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-bridge/src/client/service/kernel-identity.ts b/packages/dsh-tauri-bridge/src/client/service/kernel-identity.tsnew file mode 100644index 00000000..5c8ecd84--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/service/kernel-identity.ts@@ -0,0 +1,31 @@+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-bridge/src/client/service/kernel-model.test.ts b/packages/dsh-tauri-bridge/src/client/service/kernel-model.test.tsnew file mode 100644index 00000000..0b26fb1a--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/service/kernel-model.test.ts@@ -0,0 +1,237 @@+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-bridge/src/client/service/kernel-model.ts b/packages/dsh-tauri-bridge/src/client/service/kernel-model.tsnew file mode 100644index 00000000..7abfca3c--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/service/kernel-model.ts@@ -0,0 +1,101 @@+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-bridge/src/client/service/kernel-model.utils.test.ts b/packages/dsh-tauri-bridge/src/client/service/kernel-model.utils.test.tsnew file mode 100644index 00000000..3ffb5cf8--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/service/kernel-model.utils.test.ts@@ -0,0 +1,191 @@+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-bridge/src/client/service/kernel-model.utils.ts b/packages/dsh-tauri-bridge/src/client/service/kernel-model.utils.tsnew file mode 100644index 00000000..48d494e3--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/service/kernel-model.utils.ts@@ -0,0 +1,65 @@+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-bridge/src/client/service/kernel-session.test.ts b/packages/dsh-tauri-bridge/src/client/service/kernel-session.test.tsnew file mode 100644index 00000000..b8526cb4--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/service/kernel-session.test.ts@@ -0,0 +1,190 @@+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-bridge/src/client/service/kernel-session.ts b/packages/dsh-tauri-bridge/src/client/service/kernel-session.tsnew file mode 100644index 00000000..87d1a6a7--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/service/kernel-session.ts@@ -0,0 +1,56 @@+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-bridge/src/client/service/kernel-version.test.ts b/packages/dsh-tauri-bridge/src/client/service/kernel-version.test.tsnew file mode 100644index 00000000..bdeb9c8b--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/service/kernel-version.test.ts@@ -0,0 +1,39 @@+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.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', 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-bridge/src/client/service/kernel-version.ts b/packages/dsh-tauri-bridge/src/client/service/kernel-version.tsnew file mode 100644index 00000000..44b0fc9d--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/service/kernel-version.ts@@ -0,0 +1,66 @@+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-bridge/src/client/store/modules/kernel-store.ts b/packages/dsh-tauri-bridge/src/client/store/modules/kernel-store.tsnew file mode 100644index 00000000..f71fa176--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/store/modules/kernel-store.ts@@ -0,0 +1,10 @@+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-bridge/src/client/store/modules/native-model.ts b/packages/dsh-tauri-bridge/src/client/store/modules/native-model.tsnew file mode 100644index 00000000..a17ff19d--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/store/modules/native-model.ts@@ -0,0 +1,23 @@+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-bridge/src/client/types/kernel-model.ts b/packages/dsh-tauri-bridge/src/client/types/kernel-model.tsnew file mode 100644index 00000000..ffc872bc--- /dev/null+++ b/packages/dsh-tauri-bridge/src/client/types/kernel-model.ts@@ -0,0 +1,53 @@+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-bridge/src/host/apply.test.ts b/packages/dsh-tauri-bridge/src/host/apply.test.tsnew file mode 100644index 00000000..1cbe5020--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/apply.test.ts@@ -0,0 +1,185 @@+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 { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'+import { getServerContext } from 'dsh-h3/utils'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { apply } from './apply'+import { resetRuntime, runtime } from './config/runtime'+import { server } from './server'++const packageId: string = 'dsh-session-current'+const sessionModule = await import(packageId) as typeof import('@deepseek-ai/dsh-session')++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 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'])+ const loader: PlatformLoader = {+ async import(id) {+ 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('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-bridge'])+ expect(registerAdapter.mock.calls[0]![1]).toBeInstanceOf(llmModule.LlmAdapter)+ expect(runtime.ready).toBe(true)+ await fiber.dispose()+ expect(unregisterAdapter).toHaveBeenCalledOnce()+ expect(runtime.ready).toBe(false)+ 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-bridge/src/host/apply.ts b/packages/dsh-tauri-bridge/src/host/apply.tsnew file mode 100644index 00000000..9dc7f9af--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/apply.ts@@ -0,0 +1,37 @@+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(function* () {+ runtime.lifetime = new AbortController()+ yield server(ctx, config)+ yield () => session.dispose()+ yield identity.register()+ yield model.register()+ yield 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/execute', sink.executeTool, { 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-bridge: native session disposal failed', error))+ }, { global: true })+ yield ctx.effect(async function* () {+ yield await adapter.register()+ yield () => session.dispose()+ }, `${PLUGIN_ID}: adapter lifetime`)+ }, `${PLUGIN_ID}: official native adapter`)+}diff --git a/packages/dsh-tauri-bridge/src/host/backends/claude.test.ts b/packages/dsh-tauri-bridge/src/host/backends/claude.test.tsnew file mode 100644index 00000000..fcb07fab--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/backends/claude.test.ts@@ -0,0 +1,947 @@+import type { Frame } from './process.fixture'+import type { 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) {+ const session = await createClaudeSession(command, 'C:/fixture/workspace', nativeId, sink, new AbortController().signal, options)+ sessions.push(session)+ return session+}++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',+ `--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 inherited model and effort flags before the first null selection after %s', async (mode) => {+ const fixture = claudeProcess({ useSystemInit: true, model: 'persisted-override' })+ const session = await open(mode === 'resume' ? storedId : null, createSink(), mode === 'fork' ? { forkFrom: storedId } : undefined)+ const input = fixture.next(frame => frame.type === 'user')+ const submitted = session.submit([user()], new AbortController().signal, { model: null, 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,+ { subtype: 'set_model', model: null },+ { subtype: 'apply_flag_settings', settings: { effortLevel: null } },+ ])+ expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(1)+ 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('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('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: '{"tool":"Bash","input":{"command":"git status"}}' }])+ result(fixture, session.id)+ await submitted+ })++ it('maps AskUserQuestion multi-selection back into native updatedInput answers', async () => {+ const fixture = claudeProcess()+ const sink = createSink()+ sink.questions.mockResolvedValue({ 'Which areas?': ['Events', 'Cancel'] })+ const session = await open(null, sink)+ const submitted = session.submit([user()], new AbortController().signal)+ 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('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-bridge/src/host/backends/claude.ts b/packages/dsh-tauri-bridge/src/host/backends/claude.tsnew file mode 100644index 00000000..02f9c1b0--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/backends/claude.ts@@ -0,0 +1,699 @@+import type { UserMessage } from '@deepseek-ai/dsh-llm'+import type { Deferred } from './transport'+import type { NativeCommand, NativeContent, NativeModelCatalog, NativeModelInfo, NativeQuestion, NativeSession, NativeSessionOpenOptions, NativeSink, NativeTurnOptions } from './types'+import { randomUUID } from 'node:crypto'+import { nativeEnvironment } from '../utils/detection'+import { abortError, deferred, errorFrom, INTERRUPT_TIMEOUT_MS, JsonLinesProcess, NativeBridgeError, PendingRequests, record, REQUEST_TIMEOUT_MS, stringField, textMessages } 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 }++ constructor(command: NativeCommand, cwd: string, storedId: string | null, private readonly sink: NativeSink, private readonly options?: NativeSessionOpenOptions) {+ this.nativeId = options?.forkFrom ? '' : storedId ?? randomUUID()+ this.defaultsPending = storedId !== null || options?.forkFrom !== 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',+ ...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> {+ 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+ }+ }++ async submit(messages: readonly UserMessage[], signal: AbortSignal, options?: NativeTurnOptions): 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 texts = textMessages(messages)+ if (texts.length === 0)+ throw new NativeBridgeError('BRIDGE_EMPTY_INPUT', 'Claude native run requires a user message')+ const selection = options ? { ...options } : undefined+ 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 (selection && (this.defaultsPending || selection.model !== this.appliedOptions.model || selection.reasoningEffort !== this.appliedOptions.reasoningEffort))+ await this.applyOptions(selection, signal)+ 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: texts.map(text => ({ type: 'text', text })) },+ })+ 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 {+ 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: JSON.stringify({ tool, input, ...typeof request.description === 'string' ? { description: request.description } : {} }),+ }, 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): 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)+ await session.open(signal)+ return session+}diff --git a/packages/dsh-tauri-bridge/src/host/backends/codex.test.ts b/packages/dsh-tauri-bridge/src/host/backends/codex.test.tsnew file mode 100644index 00000000..79925c7d--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/backends/codex.test.ts@@ -0,0 +1,963 @@+import type { Frame } from './process.fixture'+import type { 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) {+ const session = await createCodexSession(command, 'C:/fixture/workspace', storedId, sink, new AbortController().signal, options)+ sessions.push(session)+ return session+}++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' } })+ })++ 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 on the first null selection after %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 started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: null })+ const frame = await started+ completed(fixture)+ await submitted+ expect(frame.params).toMatchObject({ threadId: 'thread-1', model: 'cli-default', effort: 'low' })+ expect((await session.models!(new AbortController().signal)).defaultModel).toBe('cli-default')+ expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)+ expect(fixture.frames.some(frame => frame.method === 'thread/start')).toBe(false)+ expect(session.id).toBe('thread-1')+ })++ it('refuses an unknown resumed CLI default instead of using the persisted acknowledgement or catalog default', 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')+ expect((await session.models!(new AbortController().signal)).defaultModel).toBeUndefined()+ await expect(session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: null })).rejects.toMatchObject({ code: 'BRIDGE_DEFAULT_UNAVAILABLE' })+ expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)+ })++ it('refuses a 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')+ await expect(session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: null })).rejects.toMatchObject({ code: 'BRIDGE_DEFAULT_UNAVAILABLE' })+ expect(fixture.frames.some(frame => frame.method === 'turn/start')).toBe(false)+ 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('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(['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('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' } })+ 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: '{"threadId":"thread-1","turnId":"turn-1","itemId":"command-approval","command":"git status"}',+ }])+ 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('rejects 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-bridge/src/host/backends/codex.ts b/packages/dsh-tauri-bridge/src/host/backends/codex.tsnew file mode 100644index 00000000..935e7c03--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/backends/codex.ts@@ -0,0 +1,698 @@+import type { UserMessage } from '@deepseek-ai/dsh-llm'+import type { Deferred } from './transport'+import type { NativeCommand, NativeContent, NativeModelCatalog, NativeModelInfo, NativeQuestion, NativeSession, NativeSessionOpenOptions, NativeSink, NativeTurnOptions } from './types'+import { abortError, deferred, errorFrom, INTERRUPT_TIMEOUT_MS, JsonLinesProcess, NativeBridgeError, PendingRequests, record, REQUEST_TIMEOUT_MS, stringField, textMessages } from './transport'++const INITIALIZATION = {+ clientInfo: { name: 'dsh-tauri-bridge', 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>+}++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>()+ 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) {+ 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 response = record(await this.request(forkFrom ? 'thread/fork' : storedId === null ? 'thread/start' : 'thread/resume', {+ ...forkFrom ? { threadId: forkFrom } : storedId === null ? {} : { threadId: storedId },+ cwd,+ }, 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 && !modelChanged && !effortChanged)+ 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): 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 input = textMessages(messages).map(text => ({ type: 'text', text, text_elements: [] }))+ if (input.length === 0)+ throw new NativeBridgeError('BRIDGE_EMPTY_INPUT', 'Codex native turn requires a user message')+ const selection = options ? { ...options } : undefined+ 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) : {}+ 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 }))+ if (selection) {+ this.appliedOptions = selection+ 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': {+ 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': {+ 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')+ if (item.type === 'commandExecution') {+ turn.commandItems.add(id)+ this.commandItems.add(id)+ }+ 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 (item.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:+ throw new NativeBridgeError('BRIDGE_UNSUPPORTED_EVENT', `Unsupported Codex item type: ${String(item.type)}`)+ }+ turn.assistants.add(id)+ this.sink.assistant(id, content)+ }++ 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: JSON.stringify(params),+ }, signal)+ : false+ result = { decision: allowed && !signal.aborted ? 'accept' : 'decline' }+ }+ else if (method === 'item/permissions/requestApproval') {+ const allowed = belongs ? await this.sink.approval(itemId, { kind: 'tool', title: 'Codex additional permissions', details: JSON.stringify(params) }, 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): 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)+ await session.open(cwd, nativeSessionId, signal, options)+ return session+}diff --git a/packages/dsh-tauri-bridge/src/host/backends/process.fixture.ts b/packages/dsh-tauri-bridge/src/host/backends/process.fixture.tsnew file mode 100644index 00000000..8439bf6d--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/backends/process.fixture.ts@@ -0,0 +1,80 @@+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-bridge/src/host/backends/transport.test.ts b/packages/dsh-tauri-bridge/src/host/backends/transport.test.tsnew file mode 100644index 00000000..6e608c67--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/backends/transport.test.ts@@ -0,0 +1,182 @@+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-bridge/src/host/backends/transport.ts b/packages/dsh-tauri-bridge/src/host/backends/transport.tsnew file mode 100644index 00000000..5d2f3683--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/backends/transport.ts@@ -0,0 +1,287 @@+import type { UserMessage } from '@deepseek-ai/dsh-llm'+import type { ChildProcessWithoutNullStreams } from 'node:child_process'+import type { NativeCommand } 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]+}++export function textMessages(messages: readonly UserMessage[]): string[] {+ return messages.map(message => message.content.map((block) => {+ if (block.type !== 'text')+ throw new NativeBridgeError('BRIDGE_UNSUPPORTED_CONTENT', `Native bridge does not yet support user content: ${block.type}`)+ return block.text+ }).join(''))+}++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-bridge/src/host/backends/types.ts b/packages/dsh-tauri-bridge/src/host/backends/types.tsnew file mode 100644index 00000000..cfaf4403--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/backends/types.ts@@ -0,0 +1,47 @@+import type { 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 NativeSessionOpenOptions {+ forkFrom?: string+}++export interface NativeCommand {+ file: string+ args: string[]+ env?: Record<string, string | undefined>+}++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) => Promise<void>+ dispose: () => Promise<void>+}diff --git a/packages/dsh-tauri-bridge/src/host/config/constants.ts b/packages/dsh-tauri-bridge/src/host/config/constants.tsnew file mode 100644index 00000000..1d7b46bd--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/config/constants.ts@@ -0,0 +1,3 @@+export const BRIDGE_PROVIDER = 'dsh-tauri-bridge'+export const KERNEL_RECORD_TYPE = 'plugin:dsh-tauri-bridge/kernel'+export const MODEL_RECORD_TYPE = 'plugin:dsh-tauri-bridge/model'diff --git a/packages/dsh-tauri-bridge/src/host/config/options.ts b/packages/dsh-tauri-bridge/src/host/config/options.tsnew file mode 100644index 00000000..84eb206f--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/config/options.ts@@ -0,0 +1,5 @@+export interface Config {+ codexPath?: string+ claudePath?: string+ probeTimeoutMs?: number+}diff --git a/packages/dsh-tauri-bridge/src/host/config/runtime.ts b/packages/dsh-tauri-bridge/src/host/config/runtime.tsnew file mode 100644index 00000000..7158c08d--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/config/runtime.ts@@ -0,0 +1,62 @@+import type { Agent } from '@deepseek-ai/dsh-agent'+import type { BackendDetection } 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>(),+ coldRoutes: new Set<Agent>(),+ modelWrites: new Map<Agent, Promise<void>>(),+ checkpoints: new Map<Agent, Promise<void>>(),+ verified: new Map<Agent, Map<BridgeRecordType, RecordWatermark>>(),+ ready: false,+ lifetime: new AbortController(),+}++export async function resetRuntime(): Promise<void> {+ runtime.ready = false+ 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.coldRoutes.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-bridge/src/host/server/index.test.ts b/packages/dsh-tauri-bridge/src/host/server/index.test.tsnew file mode 100644index 00000000..0e0510a9--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/server/index.test.ts@@ -0,0 +1,552 @@+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, RuntimeModules } from '../types'+import { createServer } from 'node:http'+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 legacySessionModule 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 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 packageId: string = 'dsh-session-current'+const sessionModule = await import(packageId) as typeof legacySessionModule & Pick<RuntimeModules, 'appendPluginRecord' | 'pluginRecordOf'>+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: typeof legacySessionModule+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 === '@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-bridge/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.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-alpha.2' }+ 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-alpha.2' })+ })++ it('retains CLI installation status while marking the bridge unavailable when official record support is absent', async () => {+ runtimeSession = legacySessionModule+ 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-bridge/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-bridge/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-bridge/model', ignorable: true, data: { model: 'native/default', reasoningEffort: 'deep' } },+ { seq: cursor + 1, time: now, type: 'plugin:dsh-tauri-bridge/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-bridge', 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-bridge/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-bridge/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-bridge', 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-bridge/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-bridge/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-bridge/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-bridge/model')).toEqual(modelEvents(agent.session))+ expect(connection.submit).not.toHaveBeenCalled()+ expect(createCodexSession).toHaveBeenCalledOnce()+ }, 10_000)+})diff --git a/packages/dsh-tauri-bridge/src/host/server/index.ts b/packages/dsh-tauri-bridge/src/host/server/index.tsnew file mode 100644index 00000000..e42218ff--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/server/index.ts@@ -0,0 +1,15 @@+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-bridge/src/host/server/routes/backends/get.ts b/packages/dsh-tauri-bridge/src/host/server/routes/backends/get.tsnew file mode 100644index 00000000..e20eb521--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/server/routes/backends/get.ts@@ -0,0 +1,6 @@+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-bridge/src/host/server/routes/models/get.ts b/packages/dsh-tauri-bridge/src/host/server/routes/models/get.tsnew file mode 100644index 00000000..a642d8f4--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/server/routes/models/get.ts@@ -0,0 +1,11 @@+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-bridge/src/host/server/routes/models/post.ts b/packages/dsh-tauri-bridge/src/host/server/routes/models/post.tsnew file mode 100644index 00000000..dcb6f668--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/server/routes/models/post.ts@@ -0,0 +1,16 @@+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-bridge/src/host/server/routes/sessions/post.ts b/packages/dsh-tauri-bridge/src/host/server/routes/sessions/post.tsnew file mode 100644index 00000000..b428770b--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/server/routes/sessions/post.ts@@ -0,0 +1,17 @@+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 不能同时指定。' })+ return session.create(body.backend, body.workspaceId, body.cwd, body.agentPreset)+})diff --git a/packages/dsh-tauri-bridge/src/host/service/adapter.ts b/packages/dsh-tauri-bridge/src/host/service/adapter.tsnew file mode 100644index 00000000..289a153d--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/adapter.ts@@ -0,0 +1,256 @@+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 } 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'++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> {+ let 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)+ // Cold API activation supplies the global selection until the loop commits its first legal request header.+ const fallback = ctx.get('agentDefaultModel')?.currentSelection()+ if (runtime.coldRoutes.has(payload.agent) && payload.agent.session.requestHeader() === undefined && !payload.agent.session.snapshotEvents().some(event => event.type === 'model/selection') && fallback !== undefined && config.provider === fallback.provider && config.model === fallback.model && config.reasoningEffort === fallback.reasoningEffort && config.maxTokens === undefined && config.temperature === undefined && config.stop === undefined) {+ const { reasoningEffort: _effort, ...native } = config+ config = { ...native, provider: BRIDGE_PROVIDER, model: binding.backend }+ }+ if (config.provider !== BRIDGE_PROVIDER || config.model !== binding.backend || config.reasoningEffort !== undefined || config.maxTokens !== undefined || config.temperature !== undefined || config.stop !== undefined)+ throw new Error('BRIDGE_KERNEL_IMMUTABLE: 已绑定会话不能切换内核或由 DSH 覆写原生选项。')+ return config+ },++ async* capture(options: GenerateOptions, next: () => AsyncIterable<StreamChunk>): AsyncIterable<StreamChunk> {+ if (options.provider !== BRIDGE_PROVIDER) {+ 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> {+ 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> {+ runtime.coldRoutes.delete(agent)+ 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 {+ if (event.type === 'request/header' || event.type === 'model/selection') {+ const agent = getServerContext<HostContext>(server).agents.get(value.id)+ if (agent?.session === value)+ runtime.coldRoutes.delete(agent)+ }+ 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-bridge: native turn drainage failed', error))+ }+ }+ },+})++function nativeMessage(message: UserMessage): boolean {+ const source: string = message.source.kind+ return source !== 'runtime-context' && source !== 'time-context'+}++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-bridge/src/host/service/backend.ts b/packages/dsh-tauri-bridge/src/host/service/backend.tsnew file mode 100644index 00000000..51804259--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/backend.ts@@ -0,0 +1,41 @@+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-bridge/src/host/service/checkpoint.ts b/packages/dsh-tauri-bridge/src/host/service/checkpoint.tsnew file mode 100644index 00000000..e1744bb4--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/checkpoint.ts@@ -0,0 +1,139 @@+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 { z } from 'zod'+import { KERNEL_RECORD_TYPE, MODEL_RECORD_TYPE } from '../config/constants'+import { runtime } from '../config/runtime'+import { server } from '../server'+import { waitFor } from '../utils/abort'++const watermarkSchema = z.object({+ type: z.enum([KERNEL_RECORD_TYPE, MODEL_RECORD_TYPE]),+ seq: z.number().int().nonnegative(),+ encodedData: z.string(),+}).strict().readonly().nullable()++export const checkpoint = defineService({+ register(): () => void {+ const ctx = getServerContext<HostContext>(server)+ 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-bridge/src/host/service/identity-write.test.ts b/packages/dsh-tauri-bridge/src/host/service/identity-write.test.tsnew file mode 100644index 00000000..ce939eab--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/identity-write.test.ts@@ -0,0 +1,322 @@+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, RuntimeModules } from '../types'+import { Context } from '@deepseek-ai/cordis'+import * as llmModule from '@deepseek-ai/dsh-llm'+import { SessionLogOffset } 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 { loadRuntimeModules } from '../utils/runtime-modules'+import { identity } from './identity'++vi.mock('dsh-h3/utils', () => ({ getServerContext: vi.fn() }))+vi.mock('../server', () => ({ server: vi.fn() }))++const currentSessionPackage: string = 'dsh-session-current'+const sessionModule = await import(currentSessionPackage) as unknown as typeof import('@deepseek-ai/dsh-session') & Required<Pick<RuntimeModules, 'appendPluginRecord' | 'pluginRecordOf'>>+const { Session, SessionId, 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(() => {+ 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 === '@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()+ 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) => {+ identity.register()+ 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-bridge/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-bridge/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 () => {+ identity.register()+ 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 () => {+ identity.register()+ 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-bridge/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) => {+ identity.register()+ 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 () => {+ identity.register()+ 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 () => {+ identity.register()+ 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-bridge/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 () => {+ identity.register()+ 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 () => {+ identity.register()+ 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 () => {+ identity.register()+ 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 () => {+ identity.register()+ 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 () => {+ identity.register()+ 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 = identity.register()+ 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 () => {+ identity.register()+ 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 () => {+ identity.register()+ 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-bridge/src/host/service/identity.test.ts b/packages/dsh-tauri-bridge/src/host/service/identity.test.tsnew file mode 100644index 00000000..8a5a4c4e--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/identity.test.ts@@ -0,0 +1,344 @@+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 { 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-bridge/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(() => {+ context = new Context()+ projections = new SessionProjectionRegistry(context)+ loader = {+ import: vi.fn(async id => 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()+ vi.restoreAllMocks()+})++describe('official kernel identity projection', () => {+ it('registers a nullable complete wire value rather than inferring native identity from model routes', () => {+ identity.register()+ 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-bridge', 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', () => {+ identity.register()+ 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', () => {+ identity.register()+ 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', () => {+ identity.register()+ 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', () => {+ identity.register()+ 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', (value) => {+ identity.register()+ 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', () => {+ identity.register()+ 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', (different) => {+ identity.register()+ 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', () => {+ identity.register()+ 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', () => {+ identity.register()+ 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', () => {+ identity.register()+ 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', () => {+ identity.register()+ 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', () => {+ identity.register()+ 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', () => {+ identity.register()+ 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', () => {+ identity.register()+ 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', () => {+ const unregister = identity.register()+ 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('fails before any append when the actual alpha official module lacks the plugin record writer', async () => {+ identity.register()+ const session = Session.create(SessionId('session-a'))+ const append = vi.spyOn(session, 'append')+ const before = session.seq+ expect(Reflect.get(sessionModule, 'appendPluginRecord')).toBeUndefined()+ expect(Reflect.get(sessionModule, 'pluginRecordOf')).toBeUndefined()+ 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 () => {+ identity.register()+ 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 () => {+ identity.register()+ 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 () => {+ identity.register()+ 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-bridge/src/host/service/identity.ts b/packages/dsh-tauri-bridge/src/host/service/identity.tsnew file mode 100644index 00000000..884c2b93--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/identity.ts@@ -0,0 +1,185 @@+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 { z } from 'zod'+import { BRIDGE_PROVIDER, KERNEL_RECORD_TYPE } from '../config/constants'+import { runtime } from '../config/runtime'+import { server } from '../server'+import { loadRuntimeModules } from '../utils/runtime-modules'++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()++export const identity = defineService({+ register(): () => void {+ const ctx = getServerContext<HostContext>(server)+ 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,+ })+ 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)+ if (agent.session.requestHeader() === undefined && !agent.session.snapshotEvents().some(event => event.type === 'model/selection'))+ runtime.coldRoutes.add(agent)+ }+ else if (agent.options.provider === BRIDGE_PROVIDER && agent.options.model === binding.backend) {+ identity.hydrate(agent)+ }+ return undefined+ }, { global: true })+ return () => {+ dispose()+ unregister()+ runtime.coldRoutes.clear()+ }+ },++ 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 {+ const parsed = 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-bridge/src/host/service/model.test.ts b/packages/dsh-tauri-bridge/src/host/service/model.test.tsnew file mode 100644index 00000000..e56e2133--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/model.test.ts@@ -0,0 +1,853 @@+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, RuntimeModules } 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 { 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 { 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 packageId: string = 'dsh-session-current'+const sessionModule = await import(packageId) as typeof import('@deepseek-ai/dsh-session') & Pick<RuntimeModules, 'appendPluginRecord' | 'pluginRecordOf'>+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 === '@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-bridge/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-bridge', model: 'codex' })+ expect(agent.session.requestHeader()?.config).toEqual(started ? { provider: 'dsh-tauri-bridge', model: 'codex' } : undefined)+ expect(context.agentDefaultModel.currentSelection()).toEqual({ provider: 'global-provider', model: 'global-model', reasoningEffort: 'global-effort' })+}++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-bridge/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-bridge/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-bridge/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-bridge/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-bridge/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-bridge/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-bridge/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-bridge/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-bridge/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-bridge/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-bridge', 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-bridge/src/host/service/model.ts b/packages/dsh-tauri-bridge/src/host/service/model.tsnew file mode 100644index 00000000..75e5f694--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/model.ts@@ -0,0 +1,195 @@+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 { z } from 'zod'+import { MODEL_RECORD_TYPE } from '../config/constants'+import { runtime } from '../config/runtime'+import { server } from '../server'+import { waitFor } from '../utils/abort'+import { loadRuntimeModules } from '../utils/runtime-modules'+import { checkpoint } from './checkpoint'+import { identity } from './identity'+import { session } from './session'++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(),+})++export const model = defineService({+ register(): () => void {+ const ctx = getServerContext<HostContext>(server)+ return 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,+ })+ },++ 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 {+ const parsed = 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 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-bridge/src/host/service/session.test.ts b/packages/dsh-tauri-bridge/src/host/service/session.test.tsnew file mode 100644index 00000000..e4a40aca--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/session.test.ts@@ -0,0 +1,1716 @@+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, RuntimeModules } from '../types'+import type { DetectedCommand } from '../utils/detection'+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 { 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 { apply } from '../apply'+import { createClaudeSession } from '../backends/claude'+import { createCodexSession } from '../backends/codex'+import { BRIDGE_PROVIDER } 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 packageId: string = 'dsh-session-current'+const sessionModule = await import(packageId) as typeof import('@deepseek-ai/dsh-session') & Pick<RuntimeModules, 'appendPluginRecord' | 'pluginRecordOf'>+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 === '@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('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-bridge/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-bridge/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-bridge', 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-bridge/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-bridge/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-bridge/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(runtime.coldRoutes.has(restored)).toBe(true)+ 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(runtime.coldRoutes.has(restored)).toBe(false)+ 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.each([+ { provider: 'cloud-provider', model: 'global-default' },+ { provider: 'dsh-tauri-bridge', model: 'claude' },+ { provider: 'dsh-tauri-bridge', model: 'codex', reasoningEffort: llmModule.ReasoningEffortId('high') },+ ])('rejects an explicit cold model selection instead of restoring over it: %j', async (selected) => {+ 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+ controller.selectForNextRequest(found.agent, selected)+ await followup(found.agent, 'reject switching the bound native kernel')+ expect(errors).toEqual([expect.objectContaining({ message: 'BRIDGE_KERNEL_IMMUTABLE: 已绑定会话不能切换内核或由 DSH 覆写原生选项。' })])+ 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(runtime.coldRoutes.has(found.agent)).toBe(false)+ 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('BRIDGE_KERNEL_IMMUTABLE: 已绑定会话不能切换内核或由 DSH 覆写原生选项。')+ 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-bridge/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.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-bridge/kernel', data: binding }])+ expect(official.snapshotEvents().find(event => (event.type as string) === 'plugin:dsh-tauri-bridge/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 dispatched = 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)+ agent.ctx.on('tools/execute', async (exec, next) => {+ if (exec.callId === 'native-wait')+ dispatched.resolve()+ return next()+ })+ let idle = false+ const turn = followup(agent, 'read through the native kernel').then(() => {+ idle = true+ })+ background.push(turn)+ await dispatched.promise+ 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-bridge/src/host/service/session.ts b/packages/dsh-tauri-bridge/src/host/service/session.tsnew file mode 100644index 00000000..ac490d78--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/session.ts@@ -0,0 +1,508 @@+import type { Agent, AgentHandle, AgentSetupCommit } from '@deepseek-ai/dsh-agent'+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 { NativeSession, NativeSessionOpenOptions, NativeSink } from '../backends/types'+import type { HostContext, NativeEntry, NativeExecution } from '../types'+import type { OfficialSink } from './sink.types'+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 { BRIDGE_PROVIDER, KERNEL_RECORD_TYPE } 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 })+ }+ if (!isAbsolute(cwd) || !(await stat(cwd)).isDirectory())+ 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 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)+ 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-bridge: 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 native = await factory(resolved.command, agent.session.header.cwd!, storedId, nativeSink, signal, options)+ 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+ }+}++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 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-bridge/src/host/service/sink.test.ts b/packages/dsh-tauri-bridge/src/host/service/sink.test.tsnew file mode 100644index 00000000..a2e0f1db--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/sink.test.ts@@ -0,0 +1,427 @@+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, RuntimeModules } 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 { 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 { 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 currentPackage: string = 'dsh-session-current'+const sessionModule = await import(currentPackage) as unknown as typeof import('@deepseek-ai/dsh-session') & Required<Pick<RuntimeModules, 'appendPluginRecord' | 'pluginRecordOf'>>+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 === '@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('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.each(['block', 'value', 'content', 'context'] as const)('refuses continuation after real post-execute %s rewrites the native result', async (policy) => {+ const inherited = inheritedTool()+ const additional = llmModule.createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'extra policy context' }] })+ agent.ctx.on('tools/post-execute', 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] }+ })+ nativeScript = async (native) => {+ nativeCall(native, 'rewritten')+ native.toolEnd('rewritten', 'canonical native output')+ native.assistant('final', [{ type: 'text', text: 'must not enter another official step' }])+ }+ await runTurn()+ expect(connection.submit).toHaveBeenCalledOnce()+ expect(inherited).not.toHaveBeenCalled()+ expect(errors).toHaveLength(1)+ expect(errors[0]).toMatchObject({ message: expect.stringContaining('BRIDGE_TOOL_RESULT_REJECTED') })+ expect(assistants()).toHaveLength(1)+ expect(toolResults()).toHaveLength(1)+ expect(assistants()[0]!.data.step).toBe(1)+ expect(events.filter(event => event.type === 'step/start').map(event => event.data.step)).toEqual([1])+ 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-bridge/src/host/service/sink.ts b/packages/dsh-tauri-bridge/src/host/service/sink.tsnew file mode 100644index 00000000..a4f05ec3--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/sink.ts@@ -0,0 +1,394 @@+import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'+import type { 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 { 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(_args, exec): Promise<string> {+ const tool = expectedTool(state, exec)+ if (!tool.dispatched)+ throw new Error('BRIDGE_TOOL_ROUTE_UNAVAILABLE: 原生调用未经过官方工具检查。')+ const abort = (): void => controller.abort(exec.signal.reason)+ exec.signal.addEventListener('abort', abort, { once: true })+ if (exec.signal.aborted)+ abort()+ try {+ const result = await tool.wait+ exec.signal.throwIfAborted()+ if (result.isError) {+ const error = new modules.HarnessError(result.output || 'Native tool failed', 'BRIDGE_NATIVE_TOOL_ERROR')+ error.name = 'NativeToolError'+ throw error+ }+ return result.output+ }+ finally {+ exec.signal.removeEventListener('abort', abort)+ if (state.signal.aborted)+ await state.task+ }+ },+ projectContent(exec, result) {+ const tool = state.tools.get(exec.callId)+ if (tool?.result?.isError && result.isError && result.error.info?.code === 'BRIDGE_NATIVE_TOOL_ERROR')+ return [{ type: 'text', text: tool.result.output }]+ return undefined+ },+ })+ 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 if ([...state.tools.values()].some(tool => tool.result === undefined))+ error = new Error('BRIDGE_TOOL_UNSETTLED: 原生内核没有确认全部工具结果。')+ }+ 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 executeTool(exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> {+ const official = exec.agent === undefined ? undefined : runtime.exchanges.get(exec.agent.id)+ if (!official)+ return next()+ try {+ const tool = expectedTool(official.state, exec)+ if (tool.dispatched)+ throw new Error('BRIDGE_TOOL_ALREADY_DISPATCHED: 不能重复派发原生工具调用。')+ tool.dispatched = true+ return await next()+ }+ catch (error) {+ official.state.controller.abort(error)+ await official.state.task+ throw error+ }+ },++ commitTool(value: Session, event: SessionEvent): void {+ if (event.type !== 'tool/result')+ 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) || JSON.stringify(event.data.message.content) !== JSON.stringify([{ 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 || JSON.stringify(result.content) !== JSON.stringify([{ 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 JSON.stringify(raw === '' ? {} : JSON.parse(raw)) === JSON.stringify(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-bridge/src/host/service/sink.types.ts b/packages/dsh-tauri-bridge/src/host/service/sink.types.tsnew file mode 100644index 00000000..e3b62dfe--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/service/sink.types.ts@@ -0,0 +1,60 @@+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-bridge/src/host/types/index.ts b/packages/dsh-tauri-bridge/src/host/types/index.tsnew file mode 100644index 00000000..eaa9d738--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/types/index.ts@@ -0,0 +1,94 @@+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+ HarnessError: typeof LlmRuntime.HarnessError+ LlmAdapter: typeof LlmRuntime.LlmAdapter+ isAgentLoopRequest: typeof LlmRuntime.isAgentLoopRequest+ appendPluginRecord?: (session: Session, type: 'plugin:dsh-tauri-bridge/kernel' | 'plugin:dsh-tauri-bridge/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-bridge/src/host/utils/abort.ts b/packages/dsh-tauri-bridge/src/host/utils/abort.tsnew file mode 100644index 00000000..2f791a48--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/utils/abort.ts@@ -0,0 +1,17 @@+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-bridge/src/host/utils/detection.test.ts b/packages/dsh-tauri-bridge/src/host/utils/detection.test.tsnew file mode 100644index 00000000..255ab2e0--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/utils/detection.test.ts@@ -0,0 +1,559 @@+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-bridge/src/host/utils/detection.ts b/packages/dsh-tauri-bridge/src/host/utils/detection.tsnew file mode 100644index 00000000..663267ed--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/utils/detection.ts@@ -0,0 +1,216 @@+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-bridge/src/host/utils/runtime-modules.ts b/packages/dsh-tauri-bridge/src/host/utils/runtime-modules.tsnew file mode 100644index 00000000..b98dbbae--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/utils/runtime-modules.ts@@ -0,0 +1,28 @@+import type { PlatformLoader, RuntimeModules } from '../types'++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'),+ HarnessError: resolveExport(loader, llm, 'HarnessError'),+ 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-bridge/src/host/utils/runtime-version.test.ts b/packages/dsh-tauri-bridge/src/host/utils/runtime-version.test.tsnew file mode 100644index 00000000..1c65a609--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/utils/runtime-version.test.ts@@ -0,0 +1,28 @@+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-alpha.2')+ expect(await runtimeVersion(loader(() => ({ getDshRuntimeVersion: runtime })))).toBe('0.2.1-alpha.2')+ expect(runtime).toHaveBeenCalledOnce()+ })++ it('accepts a loader whose module namespace needs unwrapping', async () => {+ expect(await runtimeVersion(loader(() => ({ default: {} }), () => ({ getDshRuntimeVersion: () => '0.2.1-alpha.2' })))).toBe('0.2.1-alpha.2')+ })++ 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-bridge/src/host/utils/runtime-version.ts b/packages/dsh-tauri-bridge/src/host/utils/runtime-version.tsnew file mode 100644index 00000000..228cf38d--- /dev/null+++ b/packages/dsh-tauri-bridge/src/host/utils/runtime-version.ts@@ -0,0 +1,23 @@+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-bridge/src/index.ts b/packages/dsh-tauri-bridge/src/index.tsnew file mode 100644index 00000000..944d25dd--- /dev/null+++ b/packages/dsh-tauri-bridge/src/index.ts@@ -0,0 +1,6 @@+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-bridge/src/shared/constants.ts b/packages/dsh-tauri-bridge/src/shared/constants.tsnew file mode 100644index 00000000..b0efe8e3--- /dev/null+++ b/packages/dsh-tauri-bridge/src/shared/constants.ts@@ -0,0 +1 @@+export const PLUGIN_ID = 'dsh-tauri-bridge'diff --git a/packages/dsh-tauri-bridge/src/shared/native-model.ts b/packages/dsh-tauri-bridge/src/shared/native-model.tsnew file mode 100644index 00000000..dacae7ec--- /dev/null+++ b/packages/dsh-tauri-bridge/src/shared/native-model.ts@@ -0,0 +1,25 @@+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-bridge/src/shared/types.ts b/packages/dsh-tauri-bridge/src/shared/types.tsnew file mode 100644index 00000000..2d3d883f--- /dev/null+++ b/packages/dsh-tauri-bridge/src/shared/types.ts@@ -0,0 +1,38 @@+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-projection/types' {+ interface SessionProjectionMap {+ bridgeModel: NativeTurnOptions+ bridgeKernel: KernelBinding | null+ }++ interface SessionProjectionStateMap {+ bridgeModel: NativeTurnOptions+ bridgeKernel: KernelProjectionState+ }+}diff --git a/packages/dsh-tauri-bridge/tsdown.config.ts b/packages/dsh-tauri-bridge/tsdown.config.tsnew file mode 100644index 00000000..d058ee99--- /dev/null+++ b/packages/dsh-tauri-bridge/tsdown.config.ts@@ -0,0 +1,3 @@+import { defineDshConfig } from '../dsh-tauri-tsdown/src/index.ts'++export default defineDshConfig({ client: { dts: true } })diff --git a/packages/dsh-tauri-bundle/package.json b/packages/dsh-tauri-bundle/package.jsonindex 7657b524..a39342ac 100644--- a/packages/dsh-tauri-bundle/package.json+++ b/packages/dsh-tauri-bundle/package.json@@ -5,6 +5,7 @@"dependencies": {"dsh-tauri": "workspace:*","dsh-tauri-archive": "workspace:*",+ "dsh-tauri-bridge": "workspace:*","dsh-tauri-extension": "workspace:*","dsh-tauri-mobile-ui": "workspace:*","dsh-tauri-model": "workspace:*",diff --git a/packages/dsh-tauri-scheduler/src/shared/constants.ts b/packages/dsh-tauri-scheduler/src/shared/constants.tsindex 96cb8336..e7a2d1fb 100644--- a/packages/dsh-tauri-scheduler/src/shared/constants.ts+++ b/packages/dsh-tauri-scheduler/src/shared/constants.ts@@ -1,4 +1,4 @@-import type {} from '@deepseek-ai/dsh-api-session-controller/client'+import type {} from '@deepseek-ai/dsh-session-projection/types'/*** shared/constants.ts — 跨 host/client 的稳定协议常量(dsh-tauri-scheduler)。@@ -12,7 +12,7 @@ export const PLUGIN_ID = 'dsh-tauri-scheduler'export const SESSION_SCHEDULE_ORIGIN_PROJECTION = 'dsh-tauri-scheduler.origin'-declare module '@deepseek-ai/dsh-api-session-controller/client' {+declare module '@deepseek-ai/dsh-session-projection/types' {interface SessionProjectionMap {[SESSION_SCHEDULE_ORIGIN_PROJECTION]: boolean}diff --git a/packages/dsh-tauri-ui/THIRD_PARTY_NOTICES.md b/packages/dsh-tauri-ui/THIRD_PARTY_NOTICES.mdindex e1c593e4..50257504 100644--- a/packages/dsh-tauri-ui/THIRD_PARTY_NOTICES.md+++ b/packages/dsh-tauri-ui/THIRD_PARTY_NOTICES.md@@ -35,6 +35,38 @@ Derived (upstream → this package):- License: MIT — Copyright (c) 2026 dsh-chat-content-visibility-auto contributors- Not vendored, not installed: the external client plugin stays out of this repo's manifests. Its converged windowing rule — `content-visibility: auto` + `contain-intrinsic-size: auto 320px` on `[data-chat-flow] > [data-chat-anchor-key]` — is reimplemented on this repo's own `css-render` stack in `src/client/styles/global.cssr.ts`, keyed off the official chat DOM contract (`ChatView` column `[data-chat-flow]` → node rows `[data-chat-anchor-key]`).+## lobehub/lobe-icons++- Repository: <https://github.com/lobehub/lobe-icons>+- Revision: `c385b2b8d1f9e19aa86e628d4e23c91ee1111a47`+- Sources: `src/OpenAI/components/Mono.tsx`, `src/Claude/components/Mono.tsx`+- Derived: monochrome SVG paths adapted into `src/client/components/brand-icons.tsx`; no icon runtime is installed or bundled.+- License: MIT — Copyright (c) 2023 LobeHub++```text+MIT License++Copyright (c) 2023 LobeHub++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+```+## Compatibility `0.2.0-rc.2` → `0.2.1-alpha.1`- The official primitives re-exports receive the StateDot restart fix without a local fork. InlineEditor is additive; no existing primitive export used here is removed.diff --git a/packages/dsh-tauri-ui/package.json b/packages/dsh-tauri-ui/package.jsonindex ce775942..27d5ff1c 100644--- a/packages/dsh-tauri-ui/package.json+++ b/packages/dsh-tauri-ui/package.json@@ -31,6 +31,7 @@"module": "./dist/index.js","types": "./dist/index.d.ts","files": [+ "THIRD_PARTY_NOTICES.md","cordis.patch.yml","dist"],diff --git a/packages/dsh-tauri-ui/src/client/components/brand-icons.tsx b/packages/dsh-tauri-ui/src/client/components/brand-icons.tsxnew file mode 100644index 00000000..72ac6639--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/components/brand-icons.tsx@@ -0,0 +1,17 @@+import type { ComponentProps, ReactElement } from 'react'++export function GptIcon(props: ComponentProps<'svg'>): ReactElement {+ return (+ <svg width={16} height={16} viewBox="0 0 24 24" fill="currentColor" fillRule="evenodd" aria-hidden focusable="false" {...props}>+ <path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z" />+ </svg>+ )+}++export function ClaudeIcon(props: ComponentProps<'svg'>): ReactElement {+ return (+ <svg width={16} height={16} viewBox="0 0 24 24" fill="currentColor" fillRule="evenodd" aria-hidden focusable="false" {...props}>+ <path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" />+ </svg>+ )+}diff --git a/packages/dsh-tauri-ui/src/client/components/index.ts b/packages/dsh-tauri-ui/src/client/components/index.tsindex 1db7286e..3a45fcac 100644--- a/packages/dsh-tauri-ui/src/client/components/index.ts+++ b/packages/dsh-tauri-ui/src/client/components/index.ts@@ -1,4 +1,5 @@export * from './action'+export * from './brand-icons'export * from './button'export * from './card'export * from './checkbox'diff --git a/packages/dsh-tauri-ui/src/client/index.ts b/packages/dsh-tauri-ui/src/client/index.tsindex 26ff55bc..098b26f1 100644--- a/packages/dsh-tauri-ui/src/client/index.ts+++ b/packages/dsh-tauri-ui/src/client/index.ts@@ -19,6 +19,7 @@ export * from './components/panel'export * from './components/segmented-control'export * from './constants/theme'export * from './hooks/use-mount-style'+export * from './register/slot-decoration'export type * from './store/modules/sections.types'export type * from './store/modules/settings.types'export * from './types/remotes'diff --git a/packages/dsh-tauri-ui/src/client/register/slot-decoration.test.ts b/packages/dsh-tauri-ui/src/client/register/slot-decoration.test.tsnew file mode 100644index 00000000..81864c37--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/register/slot-decoration.test.ts@@ -0,0 +1,240 @@+import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'+import type { SlotRegistry, StoredEntry } from 'dsh-tauri/client'+import type { ComponentType } from 'react'+import { SlotCore } from '@deepseek-ai/dsh-client-ui-slots'+import { createElement, memo, useState } from 'react'+import { renderToStaticMarkup } from 'react-dom/server'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { registerSlotDecoration } from './slot-decoration'++const SLOT = 'conversation.hero.agentPreset'+const disposers: (() => void)[] = []++function fixture(declared = true, spec: object = { kind: 'single', scope: 'session-maybe' }, options: { wrap?: boolean, accept?: (entry: StoredEntry) => boolean } = {}) {+ const core = new SlotCore()+ const register = core.register.bind(core) as unknown as (options: Record<string, unknown>, component: ComponentType<Record<string, unknown>>) => () => void+ const declare = () => register({ name: 'root', children: { [SLOT]: spec } }, () => null)+ 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.bind(core)),+ inject(key: string, setup: () => 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)+ cleanups = [...setup()]+ }+ const unsubscribe = core.subscribeDeclaration(key, sync)+ sync()+ return () => {+ unsubscribe()+ clear()+ }+ },+ }+ const undeclare = declared ? declare() : undefined+ const warn = vi.fn()+ const dispose = registerSlotDecoration<typeof SLOT, { addition: string }>(slots as unknown as SlotRegistry, {+ slot: SLOT,+ scope: 'session-maybe',+ registrant: 'test-decoration',+ ...(options.wrap+ ? {+ mode: 'wrap',+ component: props => createElement(props.Original, { ...props, label: 'Locked' }),+ } as const+ : {+ component: props => createElement('button', {}, String(props.addition)),+ }),+ accept: options.accept,+ inject: () => ({ addition: 'Kernel' }),+ warn,+ })+ disposers.push(dispose)+ function add(priority = 0, extras: Record<string, unknown> = {}, component = memo((props: Record<string, unknown>) => {+ const [value] = useState('official state')+ return createElement('button', {}, `${String(props.label)}:${value}`)+ })) {+ return register({ name: SLOT, priority, locale: 'settings.agentPreset', ...extras }, component)+ }+ function winner(): StoredEntry {+ const entry = core.entriesOfSlot(SLOT)[0]+ if (entry === undefined)+ throw new Error('missing elected renderer')+ return entry+ }+ function render(props: Record<string, unknown> = { label: 'Preset', addition: 'Kernel' }): string {+ return renderToStaticMarkup(createElement(winner().component as ComponentType<Record<string, unknown>>, props))+ }+ return { core, slots, warn, declare, undeclare, dispose, add, winner, render }+}++afterEach(() => {+ for (const dispose of disposers.splice(0))+ dispose()+ vi.restoreAllMocks()+})++describe('official single-slot decoration', () => {+ it('renders the original hook-bearing component before the addition without calling it as a function', async () => {+ const feature = fixture()+ feature.add()+ await Promise.resolve()+ expect(feature.render()).toBe('<button>Preset:official state</button><button>Kernel</button>')+ expect(feature.slots.register).toHaveBeenCalledOnce()+ expect(feature.winner().options.priority).toBe(-1)+ })++ it('preserves locale and shared store and invokes the original inject with its original arguments', async () => {+ const feature = fixture()+ const store = { spec: {} }+ const inject = vi.fn((sessionId: string) => ({ label: `Preset ${sessionId}`, hooks: { preset: 'official-observable' } }))+ feature.add(-4, { store, inject })+ await Promise.resolve()+ const entry = feature.winner()+ expect(entry.locale).toBe('settings.agentPreset')+ expect(entry.store).toBe(store)+ expect(entry.options.priority).toBe(-5)+ const read = entry.inject as ((sessionId: string) => Record<string, unknown>) | undefined+ if (read === undefined)+ throw new Error('missing preserved inject')+ expect(read('session-a')).toEqual({ label: 'Preset session-a', hooks: { preset: 'official-observable' }, addition: 'Kernel' })+ expect(inject).toHaveBeenCalledExactlyOnceWith('session-a')+ })++ it('waits for the official declaration and never declares a private core slot', async () => {+ const feature = fixture(false)+ expect(feature.slots.register).not.toHaveBeenCalled()+ feature.declare()+ feature.add()+ await Promise.resolve()+ expect(feature.winner().registrant).toBe('test-decoration')+ expect(feature.core.snapshot()[0]?.children.map(item => item.name)).toEqual(['conversation.hero.agentPreset'])+ })++ it('replaces the decorator when the original registration changes without creating an update loop', async () => {+ const feature = fixture()+ const remove = feature.add()+ await Promise.resolve()+ const first = feature.winner()+ remove()+ feature.add(-2)+ await Promise.resolve()+ expect(feature.winner()).not.toBe(first)+ expect(feature.winner().options.priority).toBe(-3)+ await Promise.resolve()+ expect(feature.slots.register).toHaveBeenCalledTimes(2)+ })++ it('original unload prevents same-tick stale rendering and removes the decorator on notification', async () => {+ const feature = fixture()+ const remove = feature.add()+ await Promise.resolve()+ remove()+ expect(feature.render()).toBe('')+ await Promise.resolve()+ expect(feature.core.entries(SLOT)).toEqual([])+ })++ it('plugin unload restores only the original occupant and no later subscription recreates the decorator', async () => {+ const feature = fixture()+ feature.add()+ await Promise.resolve()+ feature.dispose()+ await Promise.resolve()+ expect(feature.render()).toBe('<button>Preset:official state</button>')+ expect(feature.core.entries(SLOT)).toHaveLength(1)+ expect(feature.slots.register).toHaveBeenCalledOnce()+ })++ it('declaration collapse disposes the old lifecycle and permits a clean later declaration', async () => {+ const feature = fixture()+ feature.add()+ await Promise.resolve()+ feature.undeclare?.()+ expect(feature.core.entries(SLOT)).toEqual([])+ feature.declare()+ feature.add()+ await Promise.resolve()+ expect(feature.render()).toBe('<button>Preset:official state</button><button>Kernel</button>')+ expect(feature.slots.register).toHaveBeenCalledTimes(2)+ })++ it('does not shadow an original component that declares child slots', async () => {+ const feature = fixture()+ feature.add(0, { children: { 'test.original.child': { kind: 'single', scope: 'session-maybe' } } })+ await Promise.resolve()+ expect(feature.slots.register).not.toHaveBeenCalled()+ expect(feature.warn).toHaveBeenCalledExactlyOnceWith('slot decoration unavailable; the official renderer cannot be safely composed')+ expect(feature.render()).toBe('<button>Preset:official state</button>')+ })++ it.each([{ kind: 'list', scope: 'session-maybe' }, { kind: 'single', scope: 'root' }])('contract %j disables the decorator before registration', (spec) => {+ const feature = fixture(true, spec)+ expect(feature.slots.register).not.toHaveBeenCalled()+ expect(feature.warn).toHaveBeenCalledExactlyOnceWith('slot decoration unavailable; the official slot contract differs')+ })++ it('a retired original keeps its surviving official fallback rather than being revived by a decorator', async () => {+ const feature = fixture()+ feature.add(-2)+ feature.add(1, {}, memo(() => createElement('button', {}, 'Survivor')))+ const entry = feature.core.entries(SLOT).find(item => item.options.priority === -2)+ if (entry === undefined)+ throw new Error('missing original renderer')+ feature.core.reportEntryError(SLOT, entry, new Error('official crashed'), { abdicate: true })+ await Promise.resolve()+ expect(feature.render()).toBe('<button>Survivor</button>')+ expect(feature.slots.register).not.toHaveBeenCalled()+ })++ it('a crashing decorator abdicates without automatic re-registration or loss of the original', async () => {+ const feature = fixture()+ feature.add()+ await Promise.resolve()+ const entry = feature.winner()+ feature.core.reportEntryError(SLOT, entry, new Error('addition crashed'), { abdicate: true })+ await Promise.resolve()+ expect(feature.render()).toBe('<button>Preset:official state</button>')+ expect(feature.slots.register).toHaveBeenCalledOnce()+ expect(feature.core.entries(SLOT)).toHaveLength(1)+ expect(feature.warn).toHaveBeenCalledWith('slot decoration disabled after renderer retirement; the official fallback is preserved')+ })++ it('wrap mode renders the original exactly once through a normal React component boundary', async () => {+ const feature = fixture(true, { kind: 'single', scope: 'session-maybe' }, { wrap: true })+ feature.add()+ await Promise.resolve()+ expect(feature.render()).toBe('<button>Locked:official state</button>')+ expect(feature.winner().options.priority).toBe(-1)+ feature.dispose()+ await Promise.resolve()+ expect(feature.render()).toBe('<button>Preset:official state</button>')+ })++ it('unverified original capabilities keep the original renderer unchanged', async () => {+ const accept = vi.fn(() => false)+ const feature = fixture(true, { kind: 'single', scope: 'session-maybe' }, { accept })+ feature.add()+ await Promise.resolve()+ expect(accept).toHaveBeenCalledOnce()+ expect(feature.slots.register).not.toHaveBeenCalled()+ expect(feature.render()).toBe('<button>Preset:official state</button>')+ expect(feature.warn).toHaveBeenCalledExactlyOnceWith('slot decoration unavailable; the official renderer capability is unverified')+ })++ it('missing public registration APIs do not claim the official slot', () => {+ const warn = vi.fn()+ const dispose = registerSlotDecoration(undefined, { slot: SLOT, scope: 'session-maybe', registrant: 'test', component: () => null, inject: () => ({}), warn })+ dispose()+ expect(warn).toHaveBeenCalledExactlyOnceWith('slot decoration unavailable; official registration APIs are missing')+ })+})diff --git a/packages/dsh-tauri-ui/src/client/register/slot-decoration.ts b/packages/dsh-tauri-ui/src/client/register/slot-decoration.tsnew file mode 100644index 00000000..5cfca602--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/register/slot-decoration.ts@@ -0,0 +1,121 @@+import type { PropsRuntime, SlotMap, SlotScope } from '@deepseek-ai/dsh-client-ui-slots'+import type { SlotRegistry, StoredEntry } from 'dsh-tauri/client'+import type { ComponentType } from 'react'+import { createElement, Fragment } from 'react'++export interface SlotDecorationOriginalProps {+ Original: ComponentType<Record<string, unknown>>+}++export type SlotDecorationOptions<K extends keyof SlotMap & string, I extends object> = {+ slot: K+ scope: SlotScope+ registrant: string+ accept?: (entry: StoredEntry) => boolean+ inject: () => I+ warn: (reason: string) => void+} & ({+ mode?: 'append'+ component: ComponentType<PropsRuntime<K> & I>+} | {+ mode: 'wrap'+ component: ComponentType<PropsRuntime<K> & I & SlotDecorationOriginalProps>+})++export function registerSlotDecoration<K extends keyof SlotMap & string, I extends object>(+ slots: SlotRegistry | undefined,+ options: SlotDecorationOptions<K, I>,+): () => void {+ if (typeof slots?.inject !== 'function' || typeof slots.spec !== 'function'+ || typeof slots.entries !== 'function' || typeof slots.entriesOfSlot !== 'function'+ || typeof slots.subscribe !== 'function' || typeof slots.register !== 'function'+ || typeof slots.onEntryError !== 'function') {+ options.warn('slot decoration unavailable; official registration APIs are missing')+ return () => {}+ }+ return slots.inject(options.slot, function* () {+ const spec = slots.spec(options.slot)+ if (spec?.kind !== 'single' || spec.scope !== options.scope) {+ options.warn('slot decoration unavailable; the official slot contract differs')+ return+ }+ let original: StoredEntry | undefined+ let wrapper: unknown+ let unregister: (() => void) | undefined+ let disposed = false++ function sync(): void {+ if (disposed)+ return+ const next = slots!.entries(options.slot).find(entry => entry.component !== wrapper)+ if (next === original)+ return+ unregister?.()+ unregister = undefined+ wrapper = undefined+ original = next+ if (next === undefined)+ return+ const priority = (next.options.priority ?? 0) - 1+ const component = next.component+ if (slots!.entriesOfSlot(options.slot)[0] !== next+ || Object.keys(next.children ?? {}).length > 0+ || !Number.isFinite(priority) || priority >= (next.options.priority ?? 0)+ || !(typeof component === 'function' || (typeof component === 'object' && component !== null && '$$typeof' in component))) {+ options.warn('slot decoration unavailable; the official renderer cannot be safely composed')+ return+ }+ if (options.accept !== undefined && !options.accept(next)) {+ options.warn('slot decoration unavailable; the official renderer capability is unverified')+ return+ }+ const source = next+ const Original = component as ComponentType<Record<string, unknown>>+ const Addition = options.component as ComponentType<Record<string, unknown>>+ function Decorated(props: Record<string, unknown>) {+ if (!slots!.entries(options.slot).includes(source))+ return null+ return options.mode === 'wrap'+ ? createElement(Addition, { ...props, Original })+ : createElement(Fragment, null, createElement(Original, props), createElement(Addition, props))+ }+ wrapper = Decorated+ const originalInject = next.inject as ((...args: unknown[]) => Record<string, unknown>) | undefined+ const register = slots!.register as unknown as (+ registration: Pick<StoredEntry, 'locale' | 'store'> & {+ name: K+ priority: number+ registrant: string+ inject: (...args: unknown[]) => Record<string, unknown>+ },+ renderer: ComponentType<Record<string, unknown>>,+ ) => () => void+ unregister = register.call(slots, {+ name: options.slot,+ priority,+ registrant: options.registrant,+ locale: next.locale,+ store: next.store,+ inject: (...args) => slots!.entries(options.slot).includes(source)+ ? { ...originalInject?.(...args), ...options.inject() }+ : {},+ }, Decorated)+ }++ yield () => {+ disposed = true+ unregister?.()+ }+ yield slots.subscribe(options.slot, sync)+ yield slots.onEntryError((key, entry, _error, info) => {+ if (!disposed && key === options.slot && info.abdicated+ && (entry === original || entry.component === wrapper)) {+ unregister?.()+ unregister = undefined+ wrapper = undefined+ options.warn('slot decoration disabled after renderer retirement; the official fallback is preserved')+ }+ })+ sync()+ })+}diff --git a/packages/dsh-tauri-ui/src/client/service/ungrouped-session.test.ts b/packages/dsh-tauri-ui/src/client/service/ungrouped-session.test.tsindex 698f3b23..d286f5ed 100644--- a/packages/dsh-tauri-ui/src/client/service/ungrouped-session.test.ts+++ b/packages/dsh-tauri-ui/src/client/service/ungrouped-session.test.ts@@ -62,6 +62,7 @@ function createCtx(options: CtxOptions = {}) {}afterEach(() => {+ vi.restoreAllMocks()vi.mocked(getUngrouped).mockImplementation(async () => ({ cwd: UNGROUPED_CWD }))})diff --git a/packages/dsh-tauri-ui/src/client/styles/index.ts b/packages/dsh-tauri-ui/src/client/styles/index.tsindex 8342ad3d..1b136dd1 100644--- a/packages/dsh-tauri-ui/src/client/styles/index.ts+++ b/packages/dsh-tauri-ui/src/client/styles/index.ts@@ -2,7 +2,7 @@ import { cssr } from '../utils/cssr'const TAILWINDCSS_GENERATED = `/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */-@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:""}}}@layer theme{:root,:host{--color-white:#fff;--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1)}}@layer base,components;@layer utilities{.collapse{visibility:collapse}.visible{visibility:visible}.sr-only{clip:rect(0,0,0,0);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.top-1\\/2{top:50%}.right-\\[8px\\]{right:8px}.isolate{isolation:isolate}.z-30{z-index:30}.z-\\[1\\]{z-index:1}.z-\\[2\\]{z-index:2}.z-\\[1000\\]{z-index:1000}.z-\\[1100\\]{z-index:1100}.order-\\[1\\]{order:1}.order-\\[3\\]{order:3}.col-span-3{grid-column:span 3/span 3}.col-span-4{grid-column:span 4/span 4}.col-span-5{grid-column:span 5/span 5}.col-span-6{grid-column:span 6/span 6}.col-span-8{grid-column:span 8/span 8}.col-span-12{grid-column:span 12/span 12}.col-span-full{grid-column:1/-1}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.m-0{margin:calc(var(--spacing)*0)}.m-1{margin:calc(var(--spacing)*1)}.m-2{margin:calc(var(--spacing)*2)}.-mx-\\[2px\\]{margin-inline:-2px}.mx-0{margin-inline:calc(var(--spacing)*0)}.mx-\\[-8px\\]{margin-inline:-8px}.mx-\\[4px\\]{margin-inline:4px}.mx-auto{margin-inline:auto}.my-0{margin-block:calc(var(--spacing)*0)}.my-\\[4px\\]{margin-block:4px}.my-\\[6px\\]{margin-block:6px}.my-\\[8px\\]{margin-block:8px}.mt-0{margin-top:calc(var(--spacing)*0)}.mt-\\[2px\\]{margin-top:2px}.mt-\\[4px\\]{margin-top:4px}.mt-\\[6px\\]{margin-top:6px}.mt-\\[8px\\]{margin-top:8px}.mt-\\[12px\\]{margin-top:12px}.mt-\\[20px\\]{margin-top:20px}.mt-\\[28px\\]{margin-top:28px}.mr-0{margin-right:calc(var(--spacing)*0)}.mr-\\[-8px\\]{margin-right:-8px}.mr-\\[calc\\(6px-var\\(--detail-gutter\\)\\)\\]{margin-right:calc(6px - var(--detail-gutter))}.mr-auto{margin-right:auto}.mb-0{margin-bottom:calc(var(--spacing)*0)}.mb-\\[-1px\\]{margin-bottom:-1px}.mb-\\[4px\\]{margin-bottom:4px}.mb-\\[8px\\]{margin-bottom:8px}.mb-\\[10px\\]{margin-bottom:10px}.mb-\\[12px\\]{margin-bottom:12px}.mb-\\[16px\\]{margin-bottom:16px}.mb-\\[20px\\]{margin-bottom:20px}.-ml-1{margin-left:calc(var(--spacing)*-1)}.ml-\\[-6px\\]{margin-left:-6px}.ml-\\[4px\\]{margin-left:4px}.ml-\\[8px\\]{margin-left:8px}.ml-\\[10px\\]{margin-left:10px}.ml-auto{margin-left:auto}.box-border{box-sizing:border-box}.line-clamp-1{-webkit-line-clamp:1;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-none{-webkit-line-clamp:unset;-webkit-box-orient:horizontal;display:block;overflow:visible}.block{display:block}.block\\!{display:block!important}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.\\[field-sizing\\:content\\]{field-sizing:content}.h-\\[0\\.5px\\]{height:.5px}.h-\\[4px\\]{height:4px}.h-\\[8px\\]{height:8px}.h-\\[10px\\]{height:10px}.h-\\[12px\\]{height:12px}.h-\\[14px\\]{height:14px}.h-\\[16px\\]{height:16px}.h-\\[18px\\]{height:18px}.h-\\[20px\\]{height:20px}.h-\\[22px\\]{height:22px}.h-\\[24px\\]{height:24px}.h-\\[26px\\]{height:26px}.h-\\[28px\\]{height:28px}.h-\\[32px\\]{height:32px}.h-\\[36px\\]{height:36px}.h-\\[37px\\]{height:37px}.h-\\[38px\\]{height:38px}.h-\\[40px\\]{height:40px}.h-\\[42px\\]{height:42px}.h-\\[44px\\]{height:44px}.h-\\[48px\\]{height:48px}.h-\\[56px\\]{height:56px}.h-\\[60px\\]{height:60px}.h-\\[calc\\(28px\\+var\\(--dsh-content-font-delta\\,0px\\)\\)\\]{height:calc(28px + var(--dsh-content-font-delta,0px))}.h-auto{height:auto}.h-full{height:100%}.max-h-\\[60vh\\]{max-height:60vh}.max-h-\\[160px\\]{max-height:160px}.max-h-\\[180px\\]{max-height:180px}.max-h-\\[216px\\]{max-height:216px}.max-h-\\[calc\\(100vh-160px\\)\\]\\!{max-height:calc(100vh - 160px)!important}.max-h-\\[min\\(400px\\,52vh\\)\\]{max-height:min(400px,52vh)}.max-h-\\[min\\(420px\\,calc\\(100dvh-48px\\)\\)\\]{max-height:min(420px,100dvh - 48px)}.min-h-0{min-height:calc(var(--spacing)*0)}.min-h-\\[20px\\]{min-height:20px}.min-h-\\[28px\\]{min-height:28px}.min-h-\\[32px\\]{min-height:32px}.min-h-\\[37px\\]{min-height:37px}.min-h-\\[44px\\]{min-height:44px}.min-h-\\[48px\\]{min-height:48px}.min-h-\\[64px\\]{min-height:64px}.min-h-\\[96px\\]{min-height:96px}.min-h-\\[112px\\]{min-height:112px}.min-h-\\[240px\\]{min-height:240px}.min-h-\\[260px\\]{min-height:260px}.min-h-\\[320px\\]{min-height:320px}.min-h-full{min-height:100%}.w-\\[8px\\]{width:8px}.w-\\[10px\\]{width:10px}.w-\\[12px\\]{width:12px}.w-\\[14px\\]{width:14px}.w-\\[16px\\]{width:16px}.w-\\[20px\\]{width:20px}.w-\\[22px\\]{width:22px}.w-\\[24px\\]{width:24px}.w-\\[26px\\]{width:26px}.w-\\[28px\\]{width:28px}.w-\\[32px\\]{width:32px}.w-\\[36px\\]{width:36px}.w-\\[44px\\]{width:44px}.w-\\[48px\\]{width:48px}.w-\\[52px\\]{width:52px}.w-\\[56px\\]{width:56px}.w-\\[200px\\]{width:200px}.w-\\[232px\\]{width:232px}.w-\\[336px\\]{width:336px}.w-\\[360px\\]{width:360px}.w-\\[calc\\(28px\\+var\\(--dsh-content-font-delta\\,0px\\)\\)\\]{width:calc(28px + var(--dsh-content-font-delta,0px))}.w-\\[calc\\(100\\%\\+4px\\)\\]{width:calc(100% + 4px)}.w-\\[calc\\(100\\%_-_2_\\*_var\\(--dsh-composer-side-clearance\\)_-_4_\\*_var\\(--dsh-composer-dock-inset\\)\\)\\]{width:calc(100% - 2*var(--dsh-composer-side-clearance) - 4*var(--dsh-composer-dock-inset))}.w-\\[min\\(680px\\,100\\%\\)\\]\\!{width:min(680px,100%)!important}.w-\\[min\\(760px\\,100\\%\\)\\]\\!{width:min(760px,100%)!important}.w-\\[min\\(calc\\(var\\(--dsh-composer-card-max-width\\)_\\+_2_\\*_var\\(--dsh-composer-side-clearance\\)\\)\\,100\\%\\)\\]{width:min(calc(var(--dsh-composer-card-max-width) + 2*var(--dsh-composer-side-clearance)),100%)}.w-\\[var\\(--dsh-settings-rail-width\\)\\]{width:var(--dsh-settings-rail-width)}.w-full{width:100%}.w-full\\!{width:100%!important}.max-w-\\[40\\%\\]{max-width:40%}.max-w-\\[200px\\]{max-width:200px}.max-w-\\[220px\\]{max-width:220px}.max-w-\\[280px\\]{max-width:280px}.max-w-\\[460px\\]{max-width:460px}.max-w-\\[520px\\]{max-width:520px}.max-w-\\[960px\\]{max-width:960px}.max-w-\\[calc\\(100vw-32px\\)\\]{max-width:calc(100vw - 32px)}.max-w-\\[calc\\(var\\(--dsh-composer-card-max-width\\)_-_4_\\*_var\\(--dsh-composer-dock-inset\\)\\)\\]{max-width:calc(var(--dsh-composer-card-max-width) - 4*var(--dsh-composer-dock-inset))}.max-w-\\[min\\(100\\%\\,240px\\)\\]{max-width:min(100%,240px)}.max-w-\\[min\\(100\\%\\,360px\\)\\]{max-width:min(100%,360px)}.max-w-full{max-width:100%}.min-w-0{min-width:calc(var(--spacing)*0)}.min-w-\\[72px\\]{min-width:72px}.min-w-\\[220px\\]{min-width:220px}.flex-1{flex:1}.flex-\\[0_0_47\\%\\]{flex:0 0 47%}.flex-\\[0_1_58\\%\\]{flex:0 58%}.flex-\\[0_1_280px\\]{flex:0 280px}.flex-\\[0_1_auto\\]{flex:0 auto}.flex-\\[1_1_100\\%\\]{flex:100%}.flex-\\[1_1_220px\\]{flex:220px}.flex-\\[1_1_auto\\],.flex-auto{flex:auto}.flex-none{flex:none}.shrink-0{flex-shrink:0}.-translate-y-1\\/2{--tw-translate-y:calc(calc(1/2*100%)*-1);translate:var(--tw-translate-x)var(--tw-translate-y)}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.cursor-\\[inherit\\]{cursor:inherit}.cursor-col-resize{cursor:col-resize}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-none{list-style-type:none}.grid-cols-7{grid-template-columns:repeat(7,minmax(0,1fr))}.grid-cols-\\[minmax\\(0\\,1fr\\)\\]{grid-template-columns:minmax(0,1fr)}.grid-cols-\\[repeat\\(2\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-\\[repeat\\(12\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(12,minmax(0,1fr))}.grid-rows-\\[0fr\\]{grid-template-rows:0fr}.grid-rows-\\[1fr\\]{grid-template-rows:1fr}.flex-col{flex-direction:column}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-0{gap:calc(var(--spacing)*0)}.gap-8{gap:calc(var(--spacing)*8)}.gap-\\[1px\\]{gap:1px}.gap-\\[2px\\]{gap:2px}.gap-\\[4px\\]{gap:4px}.gap-\\[5px\\]{gap:5px}.gap-\\[6px\\]{gap:6px}.gap-\\[7px\\]{gap:7px}.gap-\\[8px\\]{gap:8px}.gap-\\[10px\\]{gap:10px}.gap-\\[10px_12px\\]{gap:10px 12px}.gap-\\[12px\\]{gap:12px}.gap-\\[14px\\]{gap:14px}.gap-\\[16px\\]{gap:16px}.gap-\\[20px\\]{gap:20px}.gap-\\[24px\\]{gap:24px}.gap-\\[36px\\]{gap:36px}.self-center{align-self:center}.self-end{align-self:flex-end}.self-start{align-self:flex-start}.self-stretch{align-self:stretch}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overscroll-contain{overscroll-behavior:contain}.rounded{border-radius:.25rem}.rounded-\\[2px\\]{border-radius:2px}.rounded-\\[3px\\]{border-radius:3px}.rounded-\\[4px\\]{border-radius:4px}.rounded-\\[6px\\]{border-radius:6px}.rounded-\\[7px\\]{border-radius:7px}.rounded-\\[8px\\]{border-radius:8px}.rounded-\\[10px\\]{border-radius:10px}.rounded-\\[12px\\]{border-radius:12px}.rounded-\\[13px\\]{border-radius:13px}.rounded-\\[14px\\]{border-radius:14px}.rounded-\\[16px\\]{border-radius:16px}.rounded-\\[18px\\]{border-radius:18px}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--dsw-radius-lg)}.rounded-md{border-radius:var(--dsw-radius-md)}.rounded-sm{border-radius:var(--dsw-radius-sm)}.rounded-xl{border-radius:var(--dsw-radius-xl)}.rounded-xs{border-radius:var(--dsw-radius-xs)}.rounded-tl-\\[16px\\]{border-top-left-radius:16px}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-\\[0\\.5px\\]{border-style:var(--tw-border-style);border-width:.5px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-t-\\[0\\.5px\\]{border-top-style:var(--tw-border-style);border-top-width:.5px}.border-b-\\[0\\.5px\\]{border-bottom-style:var(--tw-border-style);border-bottom-width:.5px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-l-\\[0\\.5px\\]{border-left-style:var(--tw-border-style);border-left-width:.5px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-none{--tw-border-style:none;border-style:none}.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_35\\%\\,transparent\\)\\]{border-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_35\\%\\,transparent\\)\\]{border-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)35%,transparent)}}.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_30\\%\\,transparent\\)\\]{border-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_30\\%\\,transparent\\)\\]{border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary)30%,transparent)}}.border-\\[color\\:var\\(--dsw-alias-line-secondary\\,currentColor\\)\\]{border-color:var(--dsw-alias-line-secondary,currentColor)}.border-border-l2{border-color:var(--dsw-alias-border-l2)}.border-border-l3{border-color:var(--dsw-alias-border-l3)}.border-border-l4{border-color:var(--dsw-alias-border-l4)}.border-border-weak{border-color:var(--dsw-alias-border-weak,#7f7f7f33)}.border-brand{border-color:var(--dsw-alias-brand-primary)}.border-business\\/35{border-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.border-business\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-business-primary)35%,transparent)}}.border-current{border-color:currentColor}.border-error\\/35{border-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.border-error\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-error-primary)35%,transparent)}}.border-success\\/35{border-color:var(--dsw-alias-state-success-primary)}@supports (color:color-mix(in lab, red, red)){.border-success\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-success-primary)35%,transparent)}}.border-t-border-l2{border-top-color:var(--dsw-alias-border-l2)}.border-l-transparent{border-left-color:#0000}.bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_8\\%\\,transparent\\)\\]{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_8\\%\\,transparent\\)\\]{background-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)8%,transparent)}}.bg-\\[color\\:var\\(--swatch-color\\)\\]{background-color:var(--swatch-color)}.bg-\\[var\\(--dsw-alias-bg-base\\)\\]{background-color:var(--dsw-alias-bg-base)}.bg-\\[var\\(--dsw-alias-bg-base\\,var\\(--dsw-alias-bg-module-platform\\)\\)\\]{background-color:var(--dsw-alias-bg-base,var(--dsw-alias-bg-module-platform))}.bg-\\[var\\(--dsw-alias-border-l3\\)\\]{background-color:var(--dsw-alias-border-l3)}.bg-\\[var\\(--dsw-alias-button-elevated-fill\\)\\]{background-color:var(--dsw-alias-button-elevated-fill)}.bg-\\[var\\(--dsw-alias-surface-tinted\\)\\]{background-color:var(--dsw-alias-surface-tinted)}.bg-\\[var\\(--dsw-specific-menu\\)\\]{background-color:var(--dsw-specific-menu)}.bg-\\[var\\(--dsw-specific-sidebar-fill\\)\\]{background-color:var(--dsw-specific-sidebar-fill)}.bg-\\[var\\(--dsw-specific-sidebar-nav-item-active\\)\\]{background-color:var(--dsw-specific-sidebar-nav-item-active)}.bg-border-l2{background-color:var(--dsw-alias-border-l2)}.bg-brand{background-color:var(--dsw-alias-brand-primary)}.bg-business\\/8{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.bg-business\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-business-primary)8%,transparent)}}.bg-current{background-color:currentColor}.bg-error\\/8{background-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.bg-error\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-error-primary)8%,transparent)}}.bg-hover{background-color:var(--dsw-alias-interactive-bg-hover)}.bg-layer-1{background-color:var(--dsw-alias-bg-layer-1)}.bg-layer-3{background-color:var(--dsw-alias-bg-layer-3)}.bg-module-platform{background-color:var(--dsw-alias-bg-module-platform)}.bg-primary-fill{background-color:var(--dsw-alias-button-primary-fill)}.bg-success\\/8{background-color:var(--dsw-alias-state-success-primary)}@supports (color:color-mix(in lab, red, red)){.bg-success\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-success-primary)8%,transparent)}}.bg-transparent{background-color:#0000}.bg-\\[image\\:linear-gradient\\(to_top_right\\,transparent_calc\\(50\\%_-_1px\\)\\,var\\(--dsw-alias-label-tertiary\\)\\,transparent_calc\\(50\\%_\\+_1px\\)\\)\\]{background-image:linear-gradient(to top right,transparent calc(50% - 1px),var(--dsw-alias-label-tertiary),transparent calc(50% + 1px))}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing)*0)}.p-1{padding:calc(var(--spacing)*1)}.p-2{padding:calc(var(--spacing)*2)}.p-\\[2px\\]{padding:2px}.p-\\[3px\\]{padding:3px}.p-\\[6px\\]{padding:6px}.p-\\[8px\\]{padding:8px}.p-\\[10px\\]{padding:10px}.p-\\[12px\\]{padding:12px}.p-\\[24px\\]{padding:24px}.px-0{padding-inline:calc(var(--spacing)*0)}.px-\\[2px\\]{padding-inline:2px}.px-\\[4px\\]{padding-inline:4px}.px-\\[6px\\]{padding-inline:6px}.px-\\[7px\\]{padding-inline:7px}.px-\\[8px\\]{padding-inline:8px}.px-\\[10px\\]{padding-inline:10px}.px-\\[12px\\]{padding-inline:12px}.px-\\[14px\\]{padding-inline:14px}.px-\\[16px\\]{padding-inline:16px}.px-\\[24px\\]{padding-inline:24px}.px-\\[36px\\]{padding-inline:36px}.px-\\[clamp\\(24px\\,4vw\\,48px\\)\\]{padding-inline:clamp(24px,4vw,48px)}.px-\\[var\\(--detail-gutter\\)\\]{padding-inline:var(--detail-gutter)}.py-\\[1px\\]{padding-block:1px}.py-\\[2px\\]{padding-block:2px}.py-\\[4px\\]{padding-block:4px}.py-\\[5px\\]{padding-block:5px}.py-\\[6px\\]{padding-block:6px}.py-\\[7px\\]{padding-block:7px}.py-\\[8px\\]{padding-block:8px}.py-\\[9px\\]{padding-block:9px}.py-\\[10px\\]{padding-block:10px}.py-\\[12px\\]{padding-block:12px}.py-\\[14px\\]{padding-block:14px}.py-\\[16px\\]{padding-block:16px}.py-\\[20px\\]{padding-block:20px}.py-\\[24px\\]{padding-block:24px}.py-\\[28px\\]{padding-block:28px}.py-\\[32px\\]{padding-block:32px}.py-\\[40px\\]{padding-block:40px}.py-\\[48px\\]{padding-block:48px}.py-px{padding-block:1px}.pt-0{padding-top:calc(var(--spacing)*0)}.pt-\\[2px\\]{padding-top:2px}.pt-\\[12px\\]{padding-top:12px}.pt-\\[24px\\]{padding-top:24px}.pt-\\[28px\\]{padding-top:28px}.pr-\\[4px\\]{padding-right:4px}.pr-\\[5px\\]{padding-right:5px}.pr-\\[6px\\]{padding-right:6px}.pr-\\[10px\\]{padding-right:10px}.pb-\\[4px\\]{padding-bottom:4px}.pb-\\[6px\\]{padding-bottom:6px}.pb-\\[9px\\]{padding-bottom:9px}.pb-\\[16px\\]{padding-bottom:16px}.pb-\\[28px\\]{padding-bottom:28px}.pb-\\[48px\\]{padding-bottom:48px}.pb-px{padding-bottom:1px}.pl-\\[2px\\]{padding-left:2px}.pl-\\[8px\\]{padding-left:8px}.pl-\\[12px\\]{padding-left:12px}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.\\[font-family\\:cursive\\]{font-family:cursive}.\\[font-family\\:inherit\\]{font-family:inherit}.\\[font-family\\:monospace\\]{font-family:monospace}.\\[font-family\\:var\\(--ds-font-family-code\\)\\],.font-mono{font-family:var(--ds-font-family-code)}.font-sans{font-family:var(--dsw-font-family)}.text-\\[10px\\]{font-size:10px}.text-\\[11px\\]{font-size:11px}.text-\\[12px\\]{font-size:12px}.text-\\[13px\\]{font-size:13px}.text-\\[14px\\]{font-size:14px}.text-\\[16px\\]{font-size:16px}.text-\\[18px\\]{font-size:18px}.text-\\[20px\\]{font-size:20px}.text-\\[22px\\]{font-size:22px}.text-\\[24px\\]{font-size:24px}.text-\\[28px\\]{font-size:28px}.leading-\\[1\\.5\\]{--tw-leading:1.5;line-height:1.5}.leading-\\[1\\.6\\]{--tw-leading:1.6;line-height:1.6}.leading-\\[15px\\]{--tw-leading:15px;line-height:15px}.leading-\\[16px\\]{--tw-leading:16px;line-height:16px}.leading-\\[17px\\]{--tw-leading:17px;line-height:17px}.leading-\\[18px\\]{--tw-leading:18px;line-height:18px}.leading-\\[19px\\]{--tw-leading:19px;line-height:19px}.leading-\\[20px\\]{--tw-leading:20px;line-height:20px}.leading-\\[21px\\]{--tw-leading:21px;line-height:21px}.leading-\\[22px\\]{--tw-leading:22px;line-height:22px}.leading-\\[24px\\]{--tw-leading:24px;line-height:24px}.leading-\\[28px\\]{--tw-leading:28px;line-height:28px}.leading-\\[32px\\]{--tw-leading:32px;line-height:32px}.leading-none{--tw-leading:1;line-height:1}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.\\[overflow-wrap\\:anywhere\\]{overflow-wrap:anywhere}.break-words{overflow-wrap:break-word}.wrap-anywhere{overflow-wrap:anywhere}.break-all{word-break:break-all}.whitespace-normal{white-space:normal}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\\[\\#ADB2B8\\]{color:#adb2b8}.text-\\[\\#CFD3D6\\]{color:#cfd3d6}.text-\\[var\\(--dsw-alias-label-caption\\)\\]{color:var(--dsw-alias-label-caption)}.text-\\[var\\(--dsw-alias-label-primary\\)\\]{color:var(--dsw-alias-label-primary)}.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-secondary\\,var\\(--dsw-alias-label-primary\\)\\)\\]{color:var(--dsw-alias-label-secondary,var(--dsw-alias-label-primary))}.text-\\[var\\(--dsw-alias-state-warning-primary\\,\\#d48806\\)\\]{color:var(--dsw-alias-state-warning-primary,#d48806)}.text-\\[var\\(--dsw-alias-state-warning-primary\\,var\\(--dsw-alias-label-tertiary\\)\\)\\]{color:var(--dsw-alias-state-warning-primary,var(--dsw-alias-label-tertiary))}.text-brand{color:var(--dsw-alias-brand-primary)}.text-business{color:var(--dsw-alias-state-business-primary)}.text-dimmed{color:var(--dsw-alias-label-dimmed)}.text-error{color:var(--dsw-alias-state-error-primary)}.text-idle{color:var(--dsw-alias-state-idle-primary)}.text-inherit{color:inherit}.text-primary{color:var(--dsw-alias-label-primary)}.text-primary-fg{color:var(--dsw-alias-label-primary-foreground)}.text-secondary{color:var(--dsw-alias-label-secondary)}.text-success{color:var(--dsw-alias-state-success-primary)}.text-tertiary{color:var(--dsw-alias-label-tertiary)}.text-warn{color:var(--dsw-alias-state-warn-primary)}.text-white{color:var(--color-white)}.lowercase{text-transform:lowercase}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.no-underline{text-decoration-line:none}.underline{text-decoration-line:underline}.decoration-transparent{text-decoration-color:#0000}.underline-offset-\\[2px\\]{text-underline-offset:2px}.accent-\\[var\\(--dsw-alias-button-primary-fill\\)\\]{accent-color:var(--dsw-alias-button-primary-fill)}.accent-brand{accent-color:var(--dsw-alias-brand-primary)}.opacity-0{opacity:0}.opacity-55{opacity:.55}.opacity-60{opacity:.6}.opacity-100{opacity:1}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[inset_0_0_0_0\\.5px_var\\(--dsw-alias-border-l3\\)\\]{--tw-shadow:inset 0 0 0 .5px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[inset_0_0_0_1px_rgba\\(0\\,0\\,0\\,0\\.12\\)\\]{--tw-shadow:inset 0 0 0 1px var(--tw-shadow-color,#0000001f);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[var\\(--dsw-elevation-panel\\)\\]{--tw-shadow:var(--dsw-elevation-panel);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[var\\(--dsw-elevation-prominent\\)\\]{--tw-shadow:var(--dsw-elevation-prominent);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.outline-2{outline-style:var(--tw-outline-style);outline-width:2px}.outline-offset-2{outline-offset:2px}.outline-brand{outline-color:var(--dsw-alias-brand-primary)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.\\[backdrop-filter\\:var\\(--dsw-menu-backdrop-filter\\)\\]{-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter);backdrop-filter:var(--dsw-menu-backdrop-filter)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\\[text-decoration-color\\]{transition-property:text-decoration-color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-\\[120ms\\]{--tw-duration:.12s;transition-duration:.12s}.ease-\\[ease\\]{--tw-ease:ease;transition-timing-function:ease}.outline-none{--tw-outline-style:none;outline-style:none}.\\[--detail-gutter\\:24px\\]{--detail-gutter:24px}.\\[--dsh-chat-content-width\\:748px\\]{--dsh-chat-content-width:748px}.\\[--dsh-composer-card-max-width\\:calc\\(var\\(--dsh-chat-content-width\\)_\\+_32px\\)\\]{--dsh-composer-card-max-width:calc(var(--dsh-chat-content-width) + 32px)}.\\[--dsh-composer-side-clearance\\:16px\\]{--dsh-composer-side-clearance:16px}.\\[--dsh-scrollbar-thumb-border\\:2px\\]{--dsh-scrollbar-thumb-border:2px}.\\[--dsh-scrollbar-thumb-hover\\:var\\(--dsw-alias-scrollbar-hover-l2\\)\\]{--dsh-scrollbar-thumb-hover:var(--dsw-alias-scrollbar-hover-l2)}.\\[--dsh-scrollbar-thumb\\:var\\(--dsw-alias-scrollbar-bg-l2\\)\\]{--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2)}.\\[--dsh-scrollbar-track-margin\\:12px\\]{--dsh-scrollbar-track-margin:12px}.\\[--dsh-scrollbar-width\\:9px\\]{--dsh-scrollbar-width:9px}.\\[--dsw-alias-interactive-bg-hover\\:color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_8\\%\\,transparent\\)\\]{--dsw-alias-interactive-bg-hover:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.\\[--dsw-alias-interactive-bg-hover\\:color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_8\\%\\,transparent\\)\\]{--dsw-alias-interactive-bg-hover:color-mix(in srgb,var(--dsw-alias-state-error-primary)8%,transparent)}}.\\[--dsw-elevation-stroke-color\\:var\\(--dsw-alias-border-l1\\)\\]{--dsw-elevation-stroke-color:var(--dsw-alias-border-l1)}.\\[corner-shape\\:round\\]{corner-shape:round}.\\[scrollbar-gutter\\:stable\\]{scrollbar-gutter:stable}.\\[scrollbar-width\\:none\\]{scrollbar-width:none}.\\[transition\\:grid-template-rows_180ms_cubic-bezier\\(\\.16\\,1\\,\\.3\\,1\\)\\,opacity_140ms_ease\\]{transition:grid-template-rows .18s cubic-bezier(.16,1,.3,1),opacity .14s}.\\[transition\\:width_200ms_ease\\]{transition:width .2s}.before\\:pointer-events-none:before{content:var(--tw-content);pointer-events:none}.before\\:absolute:before{content:var(--tw-content);position:absolute}.before\\:inset-0:before{content:var(--tw-content);inset:calc(var(--spacing)*0)}.before\\:top-0:before{content:var(--tw-content);top:calc(var(--spacing)*0)}.before\\:left-\\[15\\.75px\\]:before{content:var(--tw-content);left:15.75px}.before\\:z-\\[-1\\]:before{content:var(--tw-content);z-index:-1}.before\\:h-\\[14px\\]:before{content:var(--tw-content);height:14px}.before\\:w-\\[0\\.5px\\]:before{content:var(--tw-content);width:.5px}.before\\:rounded-\\[inherit\\]:before{content:var(--tw-content);border-radius:inherit}.before\\:bg-\\[var\\(--dsw-alias-border-l3\\)\\]:before{content:var(--tw-content);background-color:var(--dsw-alias-border-l3)}.before\\:bg-\\[var\\(--dsw-specific-menu\\)\\]:before{content:var(--tw-content);background-color:var(--dsw-specific-menu)}.before\\:\\[backdrop-filter\\:var\\(--dsw-menu-backdrop-filter\\)\\]:before{content:var(--tw-content);-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter);backdrop-filter:var(--dsw-menu-backdrop-filter)}.before\\:content-\\[\\"\\"\\]:before,.before\\:content-\\[\\'\\'\\]:before{content:var(--tw-content);--tw-content:"";content:var(--tw-content)}.after\\:absolute:after{content:var(--tw-content);position:absolute}.after\\:inset-\\[20\\%\\]:after{content:var(--tw-content);inset:20%}.after\\:inset-\\[25\\%\\]:after{content:var(--tw-content);inset:25%}.after\\:inset-x-0:after{content:var(--tw-content);inset-inline:calc(var(--spacing)*0)}.after\\:top-\\[42px\\]:after{content:var(--tw-content);top:42px}.after\\:bottom-0:after{content:var(--tw-content);bottom:calc(var(--spacing)*0)}.after\\:bottom-\\[-1px\\]:after{content:var(--tw-content);bottom:-1px}.after\\:left-\\[15\\.75px\\]:after{content:var(--tw-content);left:15.75px}.after\\:h-\\[2px\\]:after{content:var(--tw-content);height:2px}.after\\:w-\\[0\\.5px\\]:after{content:var(--tw-content);width:.5px}.after\\:rounded-\\[2px\\]:after{content:var(--tw-content);border-radius:2px}.after\\:rounded-full:after{content:var(--tw-content);border-radius:3.40282e38px}.after\\:bg-\\[var\\(--dsw-alias-border-l3\\)\\]:after{content:var(--tw-content);background-color:var(--dsw-alias-border-l3)}.after\\:bg-business:after{content:var(--tw-content);background-color:var(--dsw-alias-state-business-primary)}.after\\:bg-current:after{content:var(--tw-content);background-color:currentColor}.after\\:content-\\[\\"\\"\\]:after,.after\\:content-\\[\\'\\'\\]:after{content:var(--tw-content);--tw-content:"";content:var(--tw-content)}.after\\:content-\\[\\\\\\'\\\\\\'\\]:after{content:var(--tw-content);--tw-content:\\'\\';content:var(--tw-content)}.after\\:\\[corner-shape\\:round\\]:after{content:var(--tw-content);corner-shape:round}.first\\:pt-0:first-child{padding-top:calc(var(--spacing)*0)}.first\\:before\\:hidden:first-child:before{content:var(--tw-content);display:none}.first\\:after\\:top-\\[28px\\]:first-child:after{content:var(--tw-content);top:28px}.last\\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.last\\:after\\:hidden:last-child:after{content:var(--tw-content);display:none}.focus-within\\:bg-hover:focus-within{background-color:var(--dsw-alias-interactive-bg-hover)}@media (hover:hover){.hover\\:border-border-l2:hover{border-color:var(--dsw-alias-border-l2)}.hover\\:border-border-l4:hover{border-color:var(--dsw-alias-border-l4)}.hover\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\]:hover{background-color:var(--dsw-alias-bg-layer-4)}.hover\\:bg-hover:hover{background-color:var(--dsw-alias-interactive-bg-hover)}.hover\\:text-secondary:hover{color:var(--dsw-alias-label-secondary)}.hover\\:no-underline:hover{text-decoration-line:none}.hover\\:shadow-\\[0_1px_var\\(--dsw-alias-border-l3\\)\\]:hover{--tw-shadow:0 1px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.hover\\:not-disabled\\:bg-\\[var\\(--dsw-alias-button-floating-hover\\)\\]:hover:not(:disabled){background-color:var(--dsw-alias-button-floating-hover)}.hover\\:not-disabled\\:bg-hover:hover:not(:disabled){background-color:var(--dsw-alias-interactive-bg-hover)}.hover\\:not-disabled\\:bg-layer-1:hover:not(:disabled){background-color:var(--dsw-alias-bg-layer-1)}.hover\\:not-disabled\\:bg-primary-hover:hover:not(:disabled){background-color:var(--dsw-alias-button-primary-hover)}.hover\\:not-disabled\\:text-primary:hover:not(:disabled){color:var(--dsw-alias-label-primary)}.hover\\:not-disabled\\:text-secondary:hover:not(:disabled){color:var(--dsw-alias-label-secondary)}.hover\\:not-disabled\\:underline:hover:not(:disabled){text-decoration-line:underline}.hover\\:not-disabled\\:decoration-current:hover:not(:disabled){text-decoration-color:currentColor}.hover\\:not-disabled\\:decoration-secondary:hover:not(:disabled){-webkit-text-decoration-color:var(--dsw-alias-label-secondary);-webkit-text-decoration-color:var(--dsw-alias-label-secondary);text-decoration-color:var(--dsw-alias-label-secondary)}.hover\\:not-disabled\\:underline-offset-2:hover:not(:disabled){text-underline-offset:2px}}.focus\\:border-business:focus{border-color:var(--dsw-alias-state-business-primary)}.focus\\:shadow-\\[0_1px_var\\(--dsw-alias-state-business-primary\\)\\]:focus{--tw-shadow:0 1px var(--tw-shadow-color,var(--dsw-alias-state-business-primary));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:border-business:focus-visible{border-color:var(--dsw-alias-state-business-primary)}.focus-visible\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\]:focus-visible{background-color:var(--dsw-alias-bg-layer-4)}.focus-visible\\:bg-hover:focus-visible{background-color:var(--dsw-alias-interactive-bg-hover)}.focus-visible\\:text-secondary:focus-visible{color:var(--dsw-alias-label-secondary)}.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-state-business-primary))}@supports (color:color-mix(in lab, red, red)){.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,color-mix(in srgb,var(--dsw-alias-state-business-primary)18%,transparent))}}.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:shadow-focus-ring:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:\\[outline\\:2px_solid_var\\(--dsw-focus-ring-color\\,var\\(--dsw-alias-state-business-primary\\)\\)\\]:focus-visible{outline:2px solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.focus-visible\\:\\[outline\\:var\\(--dsw-focus-ring-width\\,2px\\)_solid_var\\(--dsw-focus-ring-color\\,var\\(--dsw-alias-state-business-primary\\)\\)\\]:focus-visible{outline:var(--dsw-focus-ring-width,2px)solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.focus-visible\\:\\[outline-offset\\:-2px\\]:focus-visible{outline-offset:-2px}.focus-visible\\:\\[outline-offset\\:1px\\]:focus-visible{outline-offset:1px}.focus-visible\\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.active\\:not-disabled\\:bg-active:active:not(:disabled){background-color:var(--dsw-alias-interactive-bg-active)}.disabled\\:cursor-default:disabled{cursor:default}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:text-\\[var\\(--dsw-alias-label-quaternary\\)\\]:disabled{color:var(--dsw-alias-label-quaternary)}.disabled\\:text-dimmed:disabled{color:var(--dsw-alias-label-dimmed)}.disabled\\:text-tertiary:disabled{color:var(--dsw-alias-label-tertiary)}.disabled\\:opacity-40:disabled{opacity:.4}.disabled\\:opacity-50:disabled{opacity:.5}.disabled\\:opacity-60:disabled{opacity:.6}.has-\\[\\>input\\:disabled\\]\\:cursor-not-allowed:has(>input:disabled){cursor:not-allowed}.has-\\[\\>input\\:disabled\\]\\:opacity-50:has(>input:disabled){opacity:.5}.aria-expanded\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\][aria-expanded=true]{background-color:var(--dsw-alias-bg-layer-4)}.aria-expanded\\:bg-hover[aria-expanded=true]{background-color:var(--dsw-alias-interactive-bg-hover)}.aria-expanded\\:text-secondary[aria-expanded=true]{color:var(--dsw-alias-label-secondary)}.aria-selected\\:bg-\\[var\\(--dsw-alias-button-ghost-active-fill\\)\\][aria-selected=true]{background-color:var(--dsw-alias-button-ghost-active-fill)}.aria-selected\\:shadow-\\[inset_0_0_0_1px_var\\(--dsw-alias-button-ghost-active-border\\)\\][aria-selected=true]{--tw-shadow:inset 0 0 0 1px var(--tw-shadow-color,var(--dsw-alias-button-ghost-active-border));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.aria-\\[current\\=date\\]\\:shadow-\\[inset_0_0_0_0\\.5px_var\\(--dsw-alias-border-l3\\)\\][aria-current=date]{--tw-shadow:inset 0 0 0 .5px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\\[open\\=true\\]\\:rotate-180[data-open=true]{rotate:180deg}.data-\\[tone\\=danger\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_10\\%\\,transparent\\)\\][data-tone=danger]{background-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.data-\\[tone\\=danger\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_10\\%\\,transparent\\)\\][data-tone=danger]{background-color:color-mix(in srgb,var(--dsw-alias-state-error-primary)10%,transparent)}}.data-\\[tone\\=danger\\]\\:text-error[data-tone=danger]{color:var(--dsw-alias-state-error-primary)}.data-\\[tone\\=info\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_10\\%\\,transparent\\)\\][data-tone=info]{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.data-\\[tone\\=info\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_10\\%\\,transparent\\)\\][data-tone=info]{background-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)10%,transparent)}}.data-\\[tone\\=info\\]\\:text-business[data-tone=info]{color:var(--dsw-alias-state-business-primary)}.data-\\[tone\\=neutral\\]\\:bg-module-platform[data-tone=neutral]{background-color:var(--dsw-alias-bg-module-platform)}.data-\\[tone\\=neutral\\]\\:text-secondary[data-tone=neutral]{color:var(--dsw-alias-label-secondary)}.data-\\[tone\\=outline\\]\\:border-\\[0\\.5px\\][data-tone=outline]{border-style:var(--tw-border-style);border-width:.5px}.data-\\[tone\\=outline\\]\\:border-border-l4[data-tone=outline]{border-color:var(--dsw-alias-border-l4)}.data-\\[tone\\=outline\\]\\:text-tertiary[data-tone=outline]{color:var(--dsw-alias-label-tertiary)}@media not all and (min-width:1100px){.max-\\[1100px\\]\\:\\[--detail-gutter\\:20px\\]{--detail-gutter:20px}}@media not all and (min-width:760px){.max-\\[760px\\]\\:col-span-3{grid-column:span 3/span 3}.max-\\[760px\\]\\:col-span-6{grid-column:span 6/span 6}.max-\\[760px\\]\\:hidden{display:none}.max-\\[760px\\]\\:flex-1{flex:1}.max-\\[760px\\]\\:grid-cols-\\[repeat\\(6\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(6,minmax(0,1fr))}.max-\\[760px\\]\\:border-l-0{border-left-style:var(--tw-border-style);border-left-width:0}.max-\\[760px\\]\\:pt-\\[20px\\]{padding-top:20px}}@media not all and (min-width:680px){.max-\\[680px\\]\\:w-\\[140px\\]{width:140px}.max-\\[680px\\]\\:max-w-\\[160px\\]{max-width:160px}.max-\\[680px\\]\\:grid-cols-\\[minmax\\(0\\,1fr\\)\\]{grid-template-columns:minmax(0,1fr)}}@media not all and (min-width:520px){.max-\\[520px\\]\\:col-span-6\\!{grid-column:span 6/span 6!important}}@media not all and (min-width:400px){.max-\\[400px\\]\\:gap-0{gap:calc(var(--spacing)*0)}.max-\\[400px\\]\\:\\[--detail-gutter\\:16px\\]{--detail-gutter:16px}}@container not (min-width:460px){.\\@max-\\[460px\\]\\:hidden{display:none}}.\\[\\&_a\\]\\:text-business a{color:var(--dsw-alias-state-business-primary)}.\\[\\&_code\\]\\:rounded-\\[4px\\] code{border-radius:4px}.\\[\\&_code\\]\\:bg-layer-3 code{background-color:var(--dsw-alias-bg-layer-3)}.\\[\\&_code\\]\\:px-\\[5px\\] code{padding-inline:5px}.\\[\\&_code\\]\\:py-\\[1px\\] code{padding-block:1px}.\\[\\&_code\\]\\:\\[font-family\\:var\\(--ds-font-family-code\\)\\] code{font-family:var(--ds-font-family-code)}.\\[\\&_code\\]\\:text-\\[12px\\] code{font-size:12px}.\\[\\&_h1\\]\\:mt-\\[14px\\] h1{margin-top:14px}.\\[\\&_h1\\]\\:mb-\\[6px\\] h1{margin-bottom:6px}.\\[\\&_h1\\]\\:text-\\[18px\\] h1{font-size:18px}.\\[\\&_h1\\]\\:leading-\\[1\\.4\\] h1{--tw-leading:1.4;line-height:1.4}.\\[\\&_h1\\]\\:text-primary h1{color:var(--dsw-alias-label-primary)}.\\[\\&_h2\\]\\:mt-\\[14px\\] h2{margin-top:14px}.\\[\\&_h2\\]\\:mb-\\[6px\\] h2{margin-bottom:6px}.\\[\\&_h2\\]\\:text-\\[16px\\] h2{font-size:16px}.\\[\\&_h2\\]\\:leading-\\[1\\.4\\] h2{--tw-leading:1.4;line-height:1.4}.\\[\\&_h2\\]\\:text-primary h2{color:var(--dsw-alias-label-primary)}.\\[\\&_h3\\]\\:m-0 h3{margin:calc(var(--spacing)*0)}.\\[\\&_h3\\]\\:mt-\\[14px\\] h3{margin-top:14px}.\\[\\&_h3\\]\\:mb-\\[6px\\] h3{margin-bottom:6px}.\\[\\&_h3\\]\\:text-\\[13px\\] h3{font-size:13px}.\\[\\&_h3\\]\\:text-\\[14px\\] h3{font-size:14px}.\\[\\&_h3\\]\\:text-\\[16px\\] h3{font-size:16px}.\\[\\&_h3\\]\\:leading-\\[1\\.4\\] h3{--tw-leading:1.4;line-height:1.4}.\\[\\&_h3\\]\\:leading-\\[20px\\] h3{--tw-leading:20px;line-height:20px}.\\[\\&_h3\\]\\:leading-\\[24px\\] h3{--tw-leading:24px;line-height:24px}.\\[\\&_h3\\]\\:font-medium h3{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\\[\\&_h3\\]\\:font-semibold h3{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.\\[\\&_h3\\]\\:text-primary h3{color:var(--dsw-alias-label-primary)}.\\[\\&_h4\\]\\:mt-\\[14px\\] h4{margin-top:14px}.\\[\\&_h4\\]\\:mb-\\[6px\\] h4{margin-bottom:6px}.\\[\\&_h4\\]\\:text-\\[13px\\] h4{font-size:13px}.\\[\\&_h4\\]\\:leading-\\[1\\.4\\] h4{--tw-leading:1.4;line-height:1.4}.\\[\\&_h4\\]\\:text-primary h4{color:var(--dsw-alias-label-primary)}.\\[\\&_input\\]\\:m-0 input{margin:calc(var(--spacing)*0)}.\\[\\&_input\\]\\:h-\\[12px\\] input{height:12px}.\\[\\&_input\\]\\:w-\\[12px\\] input{width:12px}.\\[\\&_input\\]\\:accent-brand input{accent-color:var(--dsw-alias-brand-primary)}.\\[\\&_input\\:focus-visible\\]\\:shadow-focus-ring input:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.\\[\\&_ol\\]\\:my-\\[6px\\] ol{margin-block:6px}.\\[\\&_ol\\]\\:pl-\\[20px\\] ol{padding-left:20px}.\\[\\&_p\\]\\:m-0 p{margin:calc(var(--spacing)*0)}.\\[\\&_p\\]\\:my-\\[6px\\] p{margin-block:6px}.\\[\\&_p\\]\\:leading-\\[20px\\] p{--tw-leading:20px;line-height:20px}.\\[\\&_pre\\]\\:my-\\[8px\\] pre{margin-block:8px}.\\[\\&_pre\\]\\:overflow-x-auto pre{overflow-x:auto}.\\[\\&_pre\\]\\:rounded-\\[8px\\] pre{border-radius:8px}.\\[\\&_pre\\]\\:border pre{border-style:var(--tw-border-style);border-width:1px}.\\[\\&_pre\\]\\:border-border-l2 pre{border-color:var(--dsw-alias-border-l2)}.\\[\\&_pre\\]\\:bg-layer-3 pre{background-color:var(--dsw-alias-bg-layer-3)}.\\[\\&_pre\\]\\:px-\\[12px\\] pre{padding-inline:12px}.\\[\\&_pre\\]\\:py-\\[10px\\] pre{padding-block:10px}.\\[\\&_svg\\]\\:h-\\[11px\\] svg{height:11px}.\\[\\&_svg\\]\\:h-\\[14px\\] svg{height:14px}.\\[\\&_svg\\]\\:w-\\[11px\\] svg{width:11px}.\\[\\&_svg\\]\\:w-\\[14px\\] svg{width:14px}.\\[\\&_ul\\]\\:my-\\[6px\\] ul{margin-block:6px}.\\[\\&_ul\\]\\:pl-\\[20px\\] ul{padding-left:20px}.\\[\\&\\+\\&\\]\\:border-t+.\\[\\&\\+\\&\\]\\:border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.\\[\\&\\+\\&\\]\\:border-border-weak+.\\[\\&\\+\\&\\]\\:border-border-weak{border-color:var(--dsw-alias-border-weak,#7f7f7f33)}.\\[\\&\\+\\&\\]\\:border-t-border-l2+.\\[\\&\\+\\&\\]\\:border-t-border-l2{border-top-color:var(--dsw-alias-border-l2)}.\\[\\&\\:\\:-webkit-scrollbar\\]\\:hidden::-webkit-scrollbar{display:none}.\\[\\&\\:has\\(input\\:disabled\\)\\]\\:cursor-default:has(input:disabled){cursor:default}.\\[\\&\\:has\\(input\\:disabled\\)\\]\\:opacity-60:has(input:disabled){opacity:.6}.\\[\\&\\>\\*\\]\\:w-full>*{width:100%}.\\[\\&\\>\\*\\]\\:max-w-\\[960px\\]>*{max-width:960px}.\\[\\&\\>button\\]\\:h-\\[32px\\]>button{height:32px}.\\[\\&\\>button\\]\\:text-\\[13px\\]>button{font-size:13px}.\\[\\&\\>button\\:last-child\\]\\:mr-\\[-8px\\]>button:last-child{margin-right:-8px}.\\[\\&\\>img\\]\\:absolute>img{position:absolute}.\\[\\&\\>img\\]\\:top-0>img{top:calc(var(--spacing)*0)}.\\[\\&\\>img\\]\\:left-0>img{left:calc(var(--spacing)*0)}.\\[\\&\\>img\\]\\:block>img{display:block}.\\[\\&\\>img\\]\\:h-\\[1100\\%\\]>img{height:1100%}.\\[\\&\\>img\\]\\:h-full>img{height:100%}.\\[\\&\\>img\\]\\:w-\\[800\\%\\]>img{width:800%}.\\[\\&\\>img\\]\\:w-full>img{width:100%}.\\[\\&\\>img\\]\\:max-w-none>img{max-width:none}.\\[\\&\\>img\\]\\:object-fill>img{object-fit:fill}.\\[\\&\\>span\\:first-child\\]\\:text-tertiary>span:first-child{color:var(--dsw-alias-label-tertiary)}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-content{syntax:"*";inherits:false;initial-value:""}+@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:""}}}@layer theme{:root,:host{--color-white:#fff;--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1)}}@layer base,components;@layer utilities{.collapse{visibility:collapse}.visible{visibility:visible}.sr-only{clip:rect(0,0,0,0);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.top-1\\/2{top:50%}.right-\\[8px\\]{right:8px}.isolate{isolation:isolate}.z-30{z-index:30}.z-\\[1\\]{z-index:1}.z-\\[2\\]{z-index:2}.z-\\[1000\\]{z-index:1000}.z-\\[1100\\]{z-index:1100}.order-\\[1\\]{order:1}.order-\\[3\\]{order:3}.col-span-3{grid-column:span 3/span 3}.col-span-4{grid-column:span 4/span 4}.col-span-5{grid-column:span 5/span 5}.col-span-6{grid-column:span 6/span 6}.col-span-8{grid-column:span 8/span 8}.col-span-12{grid-column:span 12/span 12}.col-span-full{grid-column:1/-1}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.m-0{margin:calc(var(--spacing)*0)}.m-1{margin:calc(var(--spacing)*1)}.m-2{margin:calc(var(--spacing)*2)}.-mx-\\[2px\\]{margin-inline:-2px}.mx-0{margin-inline:calc(var(--spacing)*0)}.mx-\\[-8px\\]{margin-inline:-8px}.mx-\\[4px\\]{margin-inline:4px}.mx-auto{margin-inline:auto}.my-0{margin-block:calc(var(--spacing)*0)}.my-\\[4px\\]{margin-block:4px}.my-\\[6px\\]{margin-block:6px}.my-\\[8px\\]{margin-block:8px}.mt-0{margin-top:calc(var(--spacing)*0)}.mt-\\[2px\\]{margin-top:2px}.mt-\\[4px\\]{margin-top:4px}.mt-\\[6px\\]{margin-top:6px}.mt-\\[8px\\]{margin-top:8px}.mt-\\[12px\\]{margin-top:12px}.mt-\\[20px\\]{margin-top:20px}.mt-\\[28px\\]{margin-top:28px}.mr-0{margin-right:calc(var(--spacing)*0)}.mr-\\[-8px\\]{margin-right:-8px}.mr-\\[calc\\(6px-var\\(--detail-gutter\\)\\)\\]{margin-right:calc(6px - var(--detail-gutter))}.mr-auto{margin-right:auto}.mb-0{margin-bottom:calc(var(--spacing)*0)}.mb-\\[-1px\\]{margin-bottom:-1px}.mb-\\[4px\\]{margin-bottom:4px}.mb-\\[8px\\]{margin-bottom:8px}.mb-\\[10px\\]{margin-bottom:10px}.mb-\\[12px\\]{margin-bottom:12px}.mb-\\[16px\\]{margin-bottom:16px}.mb-\\[20px\\]{margin-bottom:20px}.-ml-1{margin-left:calc(var(--spacing)*-1)}.ml-\\[-6px\\]{margin-left:-6px}.ml-\\[4px\\]{margin-left:4px}.ml-\\[8px\\]{margin-left:8px}.ml-\\[10px\\]{margin-left:10px}.ml-auto{margin-left:auto}.box-border{box-sizing:border-box}.line-clamp-1{-webkit-line-clamp:1;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-none{-webkit-line-clamp:unset;-webkit-box-orient:horizontal;display:block;overflow:visible}.block{display:block}.block\\!{display:block!important}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.\\[field-sizing\\:content\\]{field-sizing:content}.h-\\[0\\.5px\\]{height:.5px}.h-\\[4px\\]{height:4px}.h-\\[8px\\]{height:8px}.h-\\[10px\\]{height:10px}.h-\\[12px\\]{height:12px}.h-\\[14px\\]{height:14px}.h-\\[16px\\]{height:16px}.h-\\[18px\\]{height:18px}.h-\\[20px\\]{height:20px}.h-\\[22px\\]{height:22px}.h-\\[24px\\]{height:24px}.h-\\[26px\\]{height:26px}.h-\\[28px\\]{height:28px}.h-\\[32px\\]{height:32px}.h-\\[36px\\]{height:36px}.h-\\[37px\\]{height:37px}.h-\\[38px\\]{height:38px}.h-\\[40px\\]{height:40px}.h-\\[42px\\]{height:42px}.h-\\[44px\\]{height:44px}.h-\\[48px\\]{height:48px}.h-\\[56px\\]{height:56px}.h-\\[60px\\]{height:60px}.h-\\[calc\\(28px\\+var\\(--dsh-content-font-delta\\,0px\\)\\)\\]{height:calc(28px + var(--dsh-content-font-delta,0px))}.h-auto{height:auto}.h-full{height:100%}.max-h-\\[60vh\\]{max-height:60vh}.max-h-\\[160px\\]{max-height:160px}.max-h-\\[180px\\]{max-height:180px}.max-h-\\[216px\\]{max-height:216px}.max-h-\\[calc\\(100vh-160px\\)\\]\\!{max-height:calc(100vh - 160px)!important}.max-h-\\[min\\(400px\\,52vh\\)\\]{max-height:min(400px,52vh)}.max-h-\\[min\\(420px\\,calc\\(100dvh-48px\\)\\)\\]{max-height:min(420px,100dvh - 48px)}.min-h-0{min-height:calc(var(--spacing)*0)}.min-h-\\[20px\\]{min-height:20px}.min-h-\\[28px\\]{min-height:28px}.min-h-\\[32px\\]{min-height:32px}.min-h-\\[37px\\]{min-height:37px}.min-h-\\[44px\\]{min-height:44px}.min-h-\\[48px\\]{min-height:48px}.min-h-\\[64px\\]{min-height:64px}.min-h-\\[96px\\]{min-height:96px}.min-h-\\[112px\\]{min-height:112px}.min-h-\\[240px\\]{min-height:240px}.min-h-\\[260px\\]{min-height:260px}.min-h-\\[320px\\]{min-height:320px}.min-h-full{min-height:100%}.w-\\[8px\\]{width:8px}.w-\\[10px\\]{width:10px}.w-\\[12px\\]{width:12px}.w-\\[14px\\]{width:14px}.w-\\[16px\\]{width:16px}.w-\\[20px\\]{width:20px}.w-\\[22px\\]{width:22px}.w-\\[24px\\]{width:24px}.w-\\[26px\\]{width:26px}.w-\\[28px\\]{width:28px}.w-\\[32px\\]{width:32px}.w-\\[36px\\]{width:36px}.w-\\[44px\\]{width:44px}.w-\\[48px\\]{width:48px}.w-\\[52px\\]{width:52px}.w-\\[56px\\]{width:56px}.w-\\[200px\\]{width:200px}.w-\\[232px\\]{width:232px}.w-\\[336px\\]{width:336px}.w-\\[360px\\]{width:360px}.w-\\[calc\\(28px\\+var\\(--dsh-content-font-delta\\,0px\\)\\)\\]{width:calc(28px + var(--dsh-content-font-delta,0px))}.w-\\[calc\\(100\\%\\+4px\\)\\]{width:calc(100% + 4px)}.w-\\[calc\\(100\\%_-_2_\\*_var\\(--dsh-composer-side-clearance\\)_-_4_\\*_var\\(--dsh-composer-dock-inset\\)\\)\\]{width:calc(100% - 2*var(--dsh-composer-side-clearance) - 4*var(--dsh-composer-dock-inset))}.w-\\[min\\(680px\\,100\\%\\)\\]\\!{width:min(680px,100%)!important}.w-\\[min\\(760px\\,100\\%\\)\\]\\!{width:min(760px,100%)!important}.w-\\[min\\(calc\\(var\\(--dsh-composer-card-max-width\\)_\\+_2_\\*_var\\(--dsh-composer-side-clearance\\)\\)\\,100\\%\\)\\]{width:min(calc(var(--dsh-composer-card-max-width) + 2*var(--dsh-composer-side-clearance)),100%)}.w-\\[var\\(--dsh-settings-rail-width\\)\\]{width:var(--dsh-settings-rail-width)}.w-full{width:100%}.w-full\\!{width:100%!important}.max-w-\\[40\\%\\]{max-width:40%}.max-w-\\[200px\\]{max-width:200px}.max-w-\\[220px\\]{max-width:220px}.max-w-\\[280px\\]{max-width:280px}.max-w-\\[460px\\]{max-width:460px}.max-w-\\[520px\\]{max-width:520px}.max-w-\\[960px\\]{max-width:960px}.max-w-\\[calc\\(100vw-32px\\)\\]{max-width:calc(100vw - 32px)}.max-w-\\[calc\\(var\\(--dsh-composer-card-max-width\\)_-_4_\\*_var\\(--dsh-composer-dock-inset\\)\\)\\]{max-width:calc(var(--dsh-composer-card-max-width) - 4*var(--dsh-composer-dock-inset))}.max-w-\\[min\\(100\\%\\,240px\\)\\]{max-width:min(100%,240px)}.max-w-\\[min\\(100\\%\\,360px\\)\\]{max-width:min(100%,360px)}.max-w-full{max-width:100%}.min-w-0{min-width:calc(var(--spacing)*0)}.min-w-\\[72px\\]{min-width:72px}.min-w-\\[220px\\]{min-width:220px}.flex-1{flex:1}.flex-\\[0_0_47\\%\\]{flex:0 0 47%}.flex-\\[0_1_58\\%\\]{flex:0 58%}.flex-\\[0_1_280px\\]{flex:0 280px}.flex-\\[0_1_auto\\]{flex:0 auto}.flex-\\[1_1_100\\%\\]{flex:100%}.flex-\\[1_1_220px\\]{flex:220px}.flex-\\[1_1_auto\\],.flex-auto{flex:auto}.flex-none{flex:none}.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)}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.cursor-\\[inherit\\]{cursor:inherit}.cursor-col-resize{cursor:col-resize}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-none{list-style-type:none}.grid-cols-7{grid-template-columns:repeat(7,minmax(0,1fr))}.grid-cols-\\[minmax\\(0\\,1fr\\)\\]{grid-template-columns:minmax(0,1fr)}.grid-cols-\\[repeat\\(2\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-\\[repeat\\(12\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(12,minmax(0,1fr))}.grid-rows-\\[0fr\\]{grid-template-rows:0fr}.grid-rows-\\[1fr\\]{grid-template-rows:1fr}.flex-col{flex-direction:column}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-0{gap:calc(var(--spacing)*0)}.gap-8{gap:calc(var(--spacing)*8)}.gap-\\[1px\\]{gap:1px}.gap-\\[2px\\]{gap:2px}.gap-\\[4px\\]{gap:4px}.gap-\\[5px\\]{gap:5px}.gap-\\[6px\\]{gap:6px}.gap-\\[7px\\]{gap:7px}.gap-\\[8px\\]{gap:8px}.gap-\\[10px\\]{gap:10px}.gap-\\[10px_12px\\]{gap:10px 12px}.gap-\\[12px\\]{gap:12px}.gap-\\[14px\\]{gap:14px}.gap-\\[16px\\]{gap:16px}.gap-\\[20px\\]{gap:20px}.gap-\\[24px\\]{gap:24px}.gap-\\[36px\\]{gap:36px}.self-center{align-self:center}.self-end{align-self:flex-end}.self-start{align-self:flex-start}.self-stretch{align-self:stretch}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overscroll-contain{overscroll-behavior:contain}.rounded{border-radius:.25rem}.rounded-\\[2px\\]{border-radius:2px}.rounded-\\[3px\\]{border-radius:3px}.rounded-\\[4px\\]{border-radius:4px}.rounded-\\[6px\\]{border-radius:6px}.rounded-\\[7px\\]{border-radius:7px}.rounded-\\[8px\\]{border-radius:8px}.rounded-\\[10px\\]{border-radius:10px}.rounded-\\[12px\\]{border-radius:12px}.rounded-\\[13px\\]{border-radius:13px}.rounded-\\[14px\\]{border-radius:14px}.rounded-\\[16px\\]{border-radius:16px}.rounded-\\[18px\\]{border-radius:18px}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--dsw-radius-lg)}.rounded-md{border-radius:var(--dsw-radius-md)}.rounded-none{border-radius:0}.rounded-sm{border-radius:var(--dsw-radius-sm)}.rounded-xl{border-radius:var(--dsw-radius-xl)}.rounded-xs{border-radius:var(--dsw-radius-xs)}.rounded-tl-\\[16px\\]{border-top-left-radius:16px}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-\\[0\\.5px\\]{border-style:var(--tw-border-style);border-width:.5px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-t-\\[0\\.5px\\]{border-top-style:var(--tw-border-style);border-top-width:.5px}.border-b-\\[0\\.5px\\]{border-bottom-style:var(--tw-border-style);border-bottom-width:.5px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-l-\\[0\\.5px\\]{border-left-style:var(--tw-border-style);border-left-width:.5px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-none{--tw-border-style:none;border-style:none}.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_35\\%\\,transparent\\)\\]{border-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_35\\%\\,transparent\\)\\]{border-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)35%,transparent)}}.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_30\\%\\,transparent\\)\\]{border-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_30\\%\\,transparent\\)\\]{border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary)30%,transparent)}}.border-\\[color\\:var\\(--dsw-alias-line-secondary\\,currentColor\\)\\]{border-color:var(--dsw-alias-line-secondary,currentColor)}.border-border-l2{border-color:var(--dsw-alias-border-l2)}.border-border-l3{border-color:var(--dsw-alias-border-l3)}.border-border-l4{border-color:var(--dsw-alias-border-l4)}.border-border-weak{border-color:var(--dsw-alias-border-weak,#7f7f7f33)}.border-brand{border-color:var(--dsw-alias-brand-primary)}.border-business\\/35{border-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.border-business\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-business-primary)35%,transparent)}}.border-current{border-color:currentColor}.border-error\\/35{border-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.border-error\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-error-primary)35%,transparent)}}.border-success\\/35{border-color:var(--dsw-alias-state-success-primary)}@supports (color:color-mix(in lab, red, red)){.border-success\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-success-primary)35%,transparent)}}.border-t-border-l2{border-top-color:var(--dsw-alias-border-l2)}.border-l-transparent{border-left-color:#0000}.bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_8\\%\\,transparent\\)\\]{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_8\\%\\,transparent\\)\\]{background-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)8%,transparent)}}.bg-\\[color\\:var\\(--swatch-color\\)\\]{background-color:var(--swatch-color)}.bg-\\[var\\(--dsw-alias-bg-base\\)\\]{background-color:var(--dsw-alias-bg-base)}.bg-\\[var\\(--dsw-alias-bg-base\\,var\\(--dsw-alias-bg-module-platform\\)\\)\\]{background-color:var(--dsw-alias-bg-base,var(--dsw-alias-bg-module-platform))}.bg-\\[var\\(--dsw-alias-border-l3\\)\\]{background-color:var(--dsw-alias-border-l3)}.bg-\\[var\\(--dsw-alias-button-elevated-fill\\)\\]{background-color:var(--dsw-alias-button-elevated-fill)}.bg-\\[var\\(--dsw-alias-surface-tinted\\)\\]{background-color:var(--dsw-alias-surface-tinted)}.bg-\\[var\\(--dsw-specific-menu\\)\\]{background-color:var(--dsw-specific-menu)}.bg-\\[var\\(--dsw-specific-sidebar-fill\\)\\]{background-color:var(--dsw-specific-sidebar-fill)}.bg-\\[var\\(--dsw-specific-sidebar-nav-item-active\\)\\]{background-color:var(--dsw-specific-sidebar-nav-item-active)}.bg-border-l2{background-color:var(--dsw-alias-border-l2)}.bg-brand{background-color:var(--dsw-alias-brand-primary)}.bg-business\\/8{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.bg-business\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-business-primary)8%,transparent)}}.bg-current{background-color:currentColor}.bg-error\\/8{background-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.bg-error\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-error-primary)8%,transparent)}}.bg-hover{background-color:var(--dsw-alias-interactive-bg-hover)}.bg-layer-1{background-color:var(--dsw-alias-bg-layer-1)}.bg-layer-3{background-color:var(--dsw-alias-bg-layer-3)}.bg-module-platform{background-color:var(--dsw-alias-bg-module-platform)}.bg-primary-fill{background-color:var(--dsw-alias-button-primary-fill)}.bg-success\\/8{background-color:var(--dsw-alias-state-success-primary)}@supports (color:color-mix(in lab, red, red)){.bg-success\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-success-primary)8%,transparent)}}.bg-transparent{background-color:#0000}.bg-\\[image\\:linear-gradient\\(to_top_right\\,transparent_calc\\(50\\%_-_1px\\)\\,var\\(--dsw-alias-label-tertiary\\)\\,transparent_calc\\(50\\%_\\+_1px\\)\\)\\]{background-image:linear-gradient(to top right,transparent calc(50% - 1px),var(--dsw-alias-label-tertiary),transparent calc(50% + 1px))}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing)*0)}.p-1{padding:calc(var(--spacing)*1)}.p-2{padding:calc(var(--spacing)*2)}.p-\\[2px\\]{padding:2px}.p-\\[3px\\]{padding:3px}.p-\\[6px\\]{padding:6px}.p-\\[8px\\]{padding:8px}.p-\\[10px\\]{padding:10px}.p-\\[12px\\]{padding:12px}.p-\\[24px\\]{padding:24px}.px-0{padding-inline:calc(var(--spacing)*0)}.px-\\[2px\\]{padding-inline:2px}.px-\\[4px\\]{padding-inline:4px}.px-\\[6px\\]{padding-inline:6px}.px-\\[7px\\]{padding-inline:7px}.px-\\[8px\\]{padding-inline:8px}.px-\\[10px\\]{padding-inline:10px}.px-\\[12px\\]{padding-inline:12px}.px-\\[14px\\]{padding-inline:14px}.px-\\[16px\\]{padding-inline:16px}.px-\\[24px\\]{padding-inline:24px}.px-\\[36px\\]{padding-inline:36px}.px-\\[clamp\\(24px\\,4vw\\,48px\\)\\]{padding-inline:clamp(24px,4vw,48px)}.px-\\[var\\(--detail-gutter\\)\\]{padding-inline:var(--detail-gutter)}.py-\\[1px\\]{padding-block:1px}.py-\\[2px\\]{padding-block:2px}.py-\\[4px\\]{padding-block:4px}.py-\\[5px\\]{padding-block:5px}.py-\\[6px\\]{padding-block:6px}.py-\\[7px\\]{padding-block:7px}.py-\\[8px\\]{padding-block:8px}.py-\\[9px\\]{padding-block:9px}.py-\\[10px\\]{padding-block:10px}.py-\\[12px\\]{padding-block:12px}.py-\\[14px\\]{padding-block:14px}.py-\\[16px\\]{padding-block:16px}.py-\\[20px\\]{padding-block:20px}.py-\\[24px\\]{padding-block:24px}.py-\\[28px\\]{padding-block:28px}.py-\\[32px\\]{padding-block:32px}.py-\\[40px\\]{padding-block:40px}.py-\\[48px\\]{padding-block:48px}.py-px{padding-block:1px}.pt-0{padding-top:calc(var(--spacing)*0)}.pt-\\[2px\\]{padding-top:2px}.pt-\\[12px\\]{padding-top:12px}.pt-\\[24px\\]{padding-top:24px}.pt-\\[28px\\]{padding-top:28px}.pr-0{padding-right:calc(var(--spacing)*0)}.pr-\\[4px\\]{padding-right:4px}.pr-\\[5px\\]{padding-right:5px}.pr-\\[6px\\]{padding-right:6px}.pr-\\[8px\\]{padding-right:8px}.pr-\\[10px\\]{padding-right:10px}.pb-\\[4px\\]{padding-bottom:4px}.pb-\\[6px\\]{padding-bottom:6px}.pb-\\[9px\\]{padding-bottom:9px}.pb-\\[16px\\]{padding-bottom:16px}.pb-\\[28px\\]{padding-bottom:28px}.pb-\\[48px\\]{padding-bottom:48px}.pb-px{padding-bottom:1px}.pl-\\[2px\\]{padding-left:2px}.pl-\\[4px\\]{padding-left:4px}.pl-\\[8px\\]{padding-left:8px}.pl-\\[12px\\]{padding-left:12px}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.\\[font-family\\:cursive\\]{font-family:cursive}.\\[font-family\\:inherit\\]{font-family:inherit}.\\[font-family\\:monospace\\]{font-family:monospace}.\\[font-family\\:var\\(--ds-font-family-code\\)\\],.font-mono{font-family:var(--ds-font-family-code)}.font-sans{font-family:var(--dsw-font-family)}.text-\\[10px\\]{font-size:10px}.text-\\[11px\\]{font-size:11px}.text-\\[12px\\]{font-size:12px}.text-\\[13px\\]{font-size:13px}.text-\\[14px\\]{font-size:14px}.text-\\[16px\\]{font-size:16px}.text-\\[18px\\]{font-size:18px}.text-\\[20px\\]{font-size:20px}.text-\\[22px\\]{font-size:22px}.text-\\[24px\\]{font-size:24px}.text-\\[28px\\]{font-size:28px}.leading-\\[1\\.5\\]{--tw-leading:1.5;line-height:1.5}.leading-\\[1\\.6\\]{--tw-leading:1.6;line-height:1.6}.leading-\\[15px\\]{--tw-leading:15px;line-height:15px}.leading-\\[16px\\]{--tw-leading:16px;line-height:16px}.leading-\\[17px\\]{--tw-leading:17px;line-height:17px}.leading-\\[18px\\]{--tw-leading:18px;line-height:18px}.leading-\\[19px\\]{--tw-leading:19px;line-height:19px}.leading-\\[20px\\]{--tw-leading:20px;line-height:20px}.leading-\\[21px\\]{--tw-leading:21px;line-height:21px}.leading-\\[22px\\]{--tw-leading:22px;line-height:22px}.leading-\\[24px\\]{--tw-leading:24px;line-height:24px}.leading-\\[28px\\]{--tw-leading:28px;line-height:28px}.leading-\\[32px\\]{--tw-leading:32px;line-height:32px}.leading-none{--tw-leading:1;line-height:1}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.\\[overflow-wrap\\:anywhere\\]{overflow-wrap:anywhere}.break-words{overflow-wrap:break-word}.wrap-anywhere{overflow-wrap:anywhere}.break-all{word-break:break-all}.whitespace-normal{white-space:normal}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\\[\\#ADB2B8\\]{color:#adb2b8}.text-\\[\\#CFD3D6\\]{color:#cfd3d6}.text-\\[var\\(--dsw-alias-label-caption\\)\\]{color:var(--dsw-alias-label-caption)}.text-\\[var\\(--dsw-alias-label-primary\\)\\]{color:var(--dsw-alias-label-primary)}.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))}.text-\\[var\\(--dsw-alias-state-warning-primary\\,\\#d48806\\)\\]{color:var(--dsw-alias-state-warning-primary,#d48806)}.text-\\[var\\(--dsw-alias-state-warning-primary\\,var\\(--dsw-alias-label-tertiary\\)\\)\\]{color:var(--dsw-alias-state-warning-primary,var(--dsw-alias-label-tertiary))}.text-brand{color:var(--dsw-alias-brand-primary)}.text-business{color:var(--dsw-alias-state-business-primary)}.text-dimmed{color:var(--dsw-alias-label-dimmed)}.text-error{color:var(--dsw-alias-state-error-primary)}.text-idle{color:var(--dsw-alias-state-idle-primary)}.text-inherit{color:inherit}.text-primary{color:var(--dsw-alias-label-primary)}.text-primary-fg{color:var(--dsw-alias-label-primary-foreground)}.text-secondary{color:var(--dsw-alias-label-secondary)}.text-success{color:var(--dsw-alias-state-success-primary)}.text-tertiary{color:var(--dsw-alias-label-tertiary)}.text-warn{color:var(--dsw-alias-state-warn-primary)}.text-white{color:var(--color-white)}.lowercase{text-transform:lowercase}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.no-underline{text-decoration-line:none}.underline{text-decoration-line:underline}.decoration-transparent{text-decoration-color:#0000}.underline-offset-\\[2px\\]{text-underline-offset:2px}.accent-\\[var\\(--dsw-alias-button-primary-fill\\)\\]{accent-color:var(--dsw-alias-button-primary-fill)}.accent-brand{accent-color:var(--dsw-alias-brand-primary)}.opacity-0{opacity:0}.opacity-55{opacity:.55}.opacity-60{opacity:.6}.opacity-100{opacity:1}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[inset_0_0_0_0\\.5px_var\\(--dsw-alias-border-l3\\)\\]{--tw-shadow:inset 0 0 0 .5px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[inset_0_0_0_1px_rgba\\(0\\,0\\,0\\,0\\.12\\)\\]{--tw-shadow:inset 0 0 0 1px var(--tw-shadow-color,#0000001f);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[var\\(--dsw-elevation-panel\\)\\]{--tw-shadow:var(--dsw-elevation-panel);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[var\\(--dsw-elevation-prominent\\)\\]{--tw-shadow:var(--dsw-elevation-prominent);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.outline-2{outline-style:var(--tw-outline-style);outline-width:2px}.outline-offset-2{outline-offset:2px}.outline-brand{outline-color:var(--dsw-alias-brand-primary)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.\\[backdrop-filter\\:var\\(--dsw-menu-backdrop-filter\\)\\]{-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter);backdrop-filter:var(--dsw-menu-backdrop-filter)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\\[text-decoration-color\\]{transition-property:text-decoration-color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-\\[120ms\\]{--tw-duration:.12s;transition-duration:.12s}.ease-\\[ease\\]{--tw-ease:ease;transition-timing-function:ease}.outline-none{--tw-outline-style:none;outline-style:none}.\\[--detail-gutter\\:24px\\]{--detail-gutter:24px}.\\[--dsh-chat-content-width\\:748px\\]{--dsh-chat-content-width:748px}.\\[--dsh-composer-card-max-width\\:calc\\(var\\(--dsh-chat-content-width\\)_\\+_32px\\)\\]{--dsh-composer-card-max-width:calc(var(--dsh-chat-content-width) + 32px)}.\\[--dsh-composer-side-clearance\\:16px\\]{--dsh-composer-side-clearance:16px}.\\[--dsh-scrollbar-thumb-border\\:2px\\]{--dsh-scrollbar-thumb-border:2px}.\\[--dsh-scrollbar-thumb-hover\\:var\\(--dsw-alias-scrollbar-hover-l2\\)\\]{--dsh-scrollbar-thumb-hover:var(--dsw-alias-scrollbar-hover-l2)}.\\[--dsh-scrollbar-thumb\\:var\\(--dsw-alias-scrollbar-bg-l2\\)\\]{--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2)}.\\[--dsh-scrollbar-track-margin\\:12px\\]{--dsh-scrollbar-track-margin:12px}.\\[--dsh-scrollbar-width\\:9px\\]{--dsh-scrollbar-width:9px}.\\[--dsw-alias-interactive-bg-hover\\:color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_8\\%\\,transparent\\)\\]{--dsw-alias-interactive-bg-hover:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.\\[--dsw-alias-interactive-bg-hover\\:color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_8\\%\\,transparent\\)\\]{--dsw-alias-interactive-bg-hover:color-mix(in srgb,var(--dsw-alias-state-error-primary)8%,transparent)}}.\\[--dsw-elevation-stroke-color\\:var\\(--dsw-alias-border-l1\\)\\]{--dsw-elevation-stroke-color:var(--dsw-alias-border-l1)}.\\[corner-shape\\:round\\]{corner-shape:round}.\\[scrollbar-gutter\\:stable\\]{scrollbar-gutter:stable}.\\[scrollbar-width\\:none\\]{scrollbar-width:none}.\\[transition\\:grid-template-rows_180ms_cubic-bezier\\(\\.16\\,1\\,\\.3\\,1\\)\\,opacity_140ms_ease\\]{transition:grid-template-rows .18s cubic-bezier(.16,1,.3,1),opacity .14s}.\\[transition\\:width_200ms_ease\\]{transition:width .2s}@media (hover:hover){.group-hover\\:hidden:is(:where(.group):hover *){display:none}.group-hover\\:inline-flex:is(:where(.group):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);pointer-events:none}.before\\:absolute:before{content:var(--tw-content);position:absolute}.before\\:inset-0:before{content:var(--tw-content);inset:calc(var(--spacing)*0)}.before\\:top-0:before{content:var(--tw-content);top:calc(var(--spacing)*0)}.before\\:left-\\[15\\.75px\\]:before{content:var(--tw-content);left:15.75px}.before\\:z-\\[-1\\]:before{content:var(--tw-content);z-index:-1}.before\\:h-\\[14px\\]:before{content:var(--tw-content);height:14px}.before\\:w-\\[0\\.5px\\]:before{content:var(--tw-content);width:.5px}.before\\:rounded-\\[inherit\\]:before{content:var(--tw-content);border-radius:inherit}.before\\:bg-\\[var\\(--dsw-alias-border-l3\\)\\]:before{content:var(--tw-content);background-color:var(--dsw-alias-border-l3)}.before\\:bg-\\[var\\(--dsw-specific-menu\\)\\]:before{content:var(--tw-content);background-color:var(--dsw-specific-menu)}.before\\:\\[backdrop-filter\\:var\\(--dsw-menu-backdrop-filter\\)\\]:before{content:var(--tw-content);-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter);backdrop-filter:var(--dsw-menu-backdrop-filter)}.before\\:content-\\[\\"\\"\\]:before,.before\\:content-\\[\\'\\'\\]:before{content:var(--tw-content);--tw-content:"";content:var(--tw-content)}.after\\:absolute:after{content:var(--tw-content);position:absolute}.after\\:inset-\\[20\\%\\]:after{content:var(--tw-content);inset:20%}.after\\:inset-\\[25\\%\\]:after{content:var(--tw-content);inset:25%}.after\\:inset-x-0:after{content:var(--tw-content);inset-inline:calc(var(--spacing)*0)}.after\\:top-\\[42px\\]:after{content:var(--tw-content);top:42px}.after\\:bottom-0:after{content:var(--tw-content);bottom:calc(var(--spacing)*0)}.after\\:bottom-\\[-1px\\]:after{content:var(--tw-content);bottom:-1px}.after\\:left-\\[15\\.75px\\]:after{content:var(--tw-content);left:15.75px}.after\\:h-\\[2px\\]:after{content:var(--tw-content);height:2px}.after\\:w-\\[0\\.5px\\]:after{content:var(--tw-content);width:.5px}.after\\:rounded-\\[2px\\]:after{content:var(--tw-content);border-radius:2px}.after\\:rounded-full:after{content:var(--tw-content);border-radius:3.40282e38px}.after\\:bg-\\[var\\(--dsw-alias-border-l3\\)\\]:after{content:var(--tw-content);background-color:var(--dsw-alias-border-l3)}.after\\:bg-business:after{content:var(--tw-content);background-color:var(--dsw-alias-state-business-primary)}.after\\:bg-current:after{content:var(--tw-content);background-color:currentColor}.after\\:content-\\[\\"\\"\\]:after,.after\\:content-\\[\\'\\'\\]:after{content:var(--tw-content);--tw-content:"";content:var(--tw-content)}.after\\:content-\\[\\\\\\'\\\\\\'\\]:after{content:var(--tw-content);--tw-content:\\'\\';content:var(--tw-content)}.after\\:\\[corner-shape\\:round\\]:after{content:var(--tw-content);corner-shape:round}.first\\:pt-0:first-child{padding-top:calc(var(--spacing)*0)}.first\\:before\\:hidden:first-child:before{content:var(--tw-content);display:none}.first\\:after\\:top-\\[28px\\]:first-child:after{content:var(--tw-content);top:28px}.last\\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.last\\:after\\:hidden:last-child:after{content:var(--tw-content);display:none}.focus-within\\:bg-hover:focus-within{background-color:var(--dsw-alias-interactive-bg-hover)}@media (hover:hover){.hover\\:border-border-l2:hover{border-color:var(--dsw-alias-border-l2)}.hover\\:border-border-l4:hover{border-color:var(--dsw-alias-border-l4)}.hover\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\]:hover{background-color:var(--dsw-alias-bg-layer-4)}.hover\\:bg-hover:hover{background-color:var(--dsw-alias-interactive-bg-hover)}.hover\\:text-secondary:hover{color:var(--dsw-alias-label-secondary)}.hover\\:no-underline:hover{text-decoration-line:none}.hover\\:shadow-\\[0_1px_var\\(--dsw-alias-border-l3\\)\\]:hover{--tw-shadow:0 1px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.hover\\:not-disabled\\:bg-\\[var\\(--dsw-alias-button-floating-hover\\)\\]:hover:not(:disabled){background-color:var(--dsw-alias-button-floating-hover)}.hover\\:not-disabled\\:bg-hover:hover:not(:disabled){background-color:var(--dsw-alias-interactive-bg-hover)}.hover\\:not-disabled\\:bg-layer-1:hover:not(:disabled){background-color:var(--dsw-alias-bg-layer-1)}.hover\\:not-disabled\\:bg-primary-hover:hover:not(:disabled){background-color:var(--dsw-alias-button-primary-hover)}.hover\\:not-disabled\\:bg-transparent:hover:not(:disabled){background-color:#0000}.hover\\:not-disabled\\:text-primary:hover:not(:disabled){color:var(--dsw-alias-label-primary)}.hover\\:not-disabled\\:text-secondary:hover:not(:disabled){color:var(--dsw-alias-label-secondary)}.hover\\:not-disabled\\:underline:hover:not(:disabled){text-decoration-line:underline}.hover\\:not-disabled\\:decoration-current:hover:not(:disabled){text-decoration-color:currentColor}.hover\\:not-disabled\\:decoration-secondary:hover:not(:disabled){-webkit-text-decoration-color:var(--dsw-alias-label-secondary);-webkit-text-decoration-color:var(--dsw-alias-label-secondary);text-decoration-color:var(--dsw-alias-label-secondary)}.hover\\:not-disabled\\:underline-offset-2:hover:not(:disabled){text-underline-offset:2px}}.focus\\:border-business:focus{border-color:var(--dsw-alias-state-business-primary)}.focus\\:shadow-\\[0_1px_var\\(--dsw-alias-state-business-primary\\)\\]:focus{--tw-shadow:0 1px var(--tw-shadow-color,var(--dsw-alias-state-business-primary));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:border-business:focus-visible{border-color:var(--dsw-alias-state-business-primary)}.focus-visible\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\]:focus-visible{background-color:var(--dsw-alias-bg-layer-4)}.focus-visible\\:bg-hover:focus-visible{background-color:var(--dsw-alias-interactive-bg-hover)}.focus-visible\\:text-secondary:focus-visible{color:var(--dsw-alias-label-secondary)}.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-state-business-primary))}@supports (color:color-mix(in lab, red, red)){.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,color-mix(in srgb,var(--dsw-alias-state-business-primary)18%,transparent))}}.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:shadow-focus-ring:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:\\[outline\\:2px_solid_var\\(--dsw-focus-ring-color\\,var\\(--dsw-alias-state-business-primary\\)\\)\\]:focus-visible{outline:2px solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.focus-visible\\:\\[outline\\:var\\(--dsw-focus-ring-width\\,2px\\)_solid_var\\(--dsw-focus-ring-color\\,var\\(--dsw-alias-state-business-primary\\)\\)\\]:focus-visible{outline:var(--dsw-focus-ring-width,2px)solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.focus-visible\\:\\[outline-offset\\:-2px\\]:focus-visible{outline-offset:-2px}.focus-visible\\:\\[outline-offset\\:1px\\]:focus-visible{outline-offset:1px}.focus-visible\\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.active\\:not-disabled\\:bg-active:active:not(:disabled){background-color:var(--dsw-alias-interactive-bg-active)}.disabled\\:cursor-default:disabled{cursor:default}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:text-\\[var\\(--dsw-alias-label-quaternary\\)\\]:disabled{color:var(--dsw-alias-label-quaternary)}.disabled\\:text-dimmed:disabled{color:var(--dsw-alias-label-dimmed)}.disabled\\:text-tertiary:disabled{color:var(--dsw-alias-label-tertiary)}.disabled\\:opacity-40:disabled{opacity:.4}.disabled\\:opacity-50:disabled{opacity:.5}.disabled\\:opacity-60:disabled{opacity:.6}.has-\\[\\>input\\:disabled\\]\\:cursor-not-allowed:has(>input:disabled){cursor:not-allowed}.has-\\[\\>input\\:disabled\\]\\:opacity-50:has(>input:disabled){opacity:.5}.aria-expanded\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\][aria-expanded=true]{background-color:var(--dsw-alias-bg-layer-4)}.aria-expanded\\:bg-hover[aria-expanded=true]{background-color:var(--dsw-alias-interactive-bg-hover)}.aria-expanded\\:text-secondary[aria-expanded=true]{color:var(--dsw-alias-label-secondary)}.aria-selected\\:bg-\\[var\\(--dsw-alias-button-ghost-active-fill\\)\\][aria-selected=true]{background-color:var(--dsw-alias-button-ghost-active-fill)}.aria-selected\\:shadow-\\[inset_0_0_0_1px_var\\(--dsw-alias-button-ghost-active-border\\)\\][aria-selected=true]{--tw-shadow:inset 0 0 0 1px var(--tw-shadow-color,var(--dsw-alias-button-ghost-active-border));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.aria-\\[current\\=date\\]\\:shadow-\\[inset_0_0_0_0\\.5px_var\\(--dsw-alias-border-l3\\)\\][aria-current=date]{--tw-shadow:inset 0 0 0 .5px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\\[open\\=true\\]\\:rotate-180[data-open=true]{rotate:180deg}.data-\\[tone\\=danger\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_10\\%\\,transparent\\)\\][data-tone=danger]{background-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.data-\\[tone\\=danger\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_10\\%\\,transparent\\)\\][data-tone=danger]{background-color:color-mix(in srgb,var(--dsw-alias-state-error-primary)10%,transparent)}}.data-\\[tone\\=danger\\]\\:text-error[data-tone=danger]{color:var(--dsw-alias-state-error-primary)}.data-\\[tone\\=info\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_10\\%\\,transparent\\)\\][data-tone=info]{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.data-\\[tone\\=info\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_10\\%\\,transparent\\)\\][data-tone=info]{background-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)10%,transparent)}}.data-\\[tone\\=info\\]\\:text-business[data-tone=info]{color:var(--dsw-alias-state-business-primary)}.data-\\[tone\\=neutral\\]\\:bg-module-platform[data-tone=neutral]{background-color:var(--dsw-alias-bg-module-platform)}.data-\\[tone\\=neutral\\]\\:text-secondary[data-tone=neutral]{color:var(--dsw-alias-label-secondary)}.data-\\[tone\\=outline\\]\\:border-\\[0\\.5px\\][data-tone=outline]{border-style:var(--tw-border-style);border-width:.5px}.data-\\[tone\\=outline\\]\\:border-border-l4[data-tone=outline]{border-color:var(--dsw-alias-border-l4)}.data-\\[tone\\=outline\\]\\:text-tertiary[data-tone=outline]{color:var(--dsw-alias-label-tertiary)}@media not all and (min-width:1100px){.max-\\[1100px\\]\\:\\[--detail-gutter\\:20px\\]{--detail-gutter:20px}}@media not all and (min-width:760px){.max-\\[760px\\]\\:col-span-3{grid-column:span 3/span 3}.max-\\[760px\\]\\:col-span-6{grid-column:span 6/span 6}.max-\\[760px\\]\\:hidden{display:none}.max-\\[760px\\]\\:flex-1{flex:1}.max-\\[760px\\]\\:grid-cols-\\[repeat\\(6\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(6,minmax(0,1fr))}.max-\\[760px\\]\\:border-l-0{border-left-style:var(--tw-border-style);border-left-width:0}.max-\\[760px\\]\\:pt-\\[20px\\]{padding-top:20px}}@media not all and (min-width:680px){.max-\\[680px\\]\\:w-\\[140px\\]{width:140px}.max-\\[680px\\]\\:max-w-\\[160px\\]{max-width:160px}.max-\\[680px\\]\\:grid-cols-\\[minmax\\(0\\,1fr\\)\\]{grid-template-columns:minmax(0,1fr)}}@media not all and (min-width:520px){.max-\\[520px\\]\\:col-span-6\\!{grid-column:span 6/span 6!important}}@media not all and (min-width:400px){.max-\\[400px\\]\\:gap-0{gap:calc(var(--spacing)*0)}.max-\\[400px\\]\\:\\[--detail-gutter\\:16px\\]{--detail-gutter:16px}}@container not (min-width:460px){.\\@max-\\[460px\\]\\:hidden{display:none}}.\\[\\&_a\\]\\:text-business a{color:var(--dsw-alias-state-business-primary)}.\\[\\&_code\\]\\:rounded-\\[4px\\] code{border-radius:4px}.\\[\\&_code\\]\\:bg-layer-3 code{background-color:var(--dsw-alias-bg-layer-3)}.\\[\\&_code\\]\\:px-\\[5px\\] code{padding-inline:5px}.\\[\\&_code\\]\\:py-\\[1px\\] code{padding-block:1px}.\\[\\&_code\\]\\:\\[font-family\\:var\\(--ds-font-family-code\\)\\] code{font-family:var(--ds-font-family-code)}.\\[\\&_code\\]\\:text-\\[12px\\] code{font-size:12px}.\\[\\&_h1\\]\\:mt-\\[14px\\] h1{margin-top:14px}.\\[\\&_h1\\]\\:mb-\\[6px\\] h1{margin-bottom:6px}.\\[\\&_h1\\]\\:text-\\[18px\\] h1{font-size:18px}.\\[\\&_h1\\]\\:leading-\\[1\\.4\\] h1{--tw-leading:1.4;line-height:1.4}.\\[\\&_h1\\]\\:text-primary h1{color:var(--dsw-alias-label-primary)}.\\[\\&_h2\\]\\:mt-\\[14px\\] h2{margin-top:14px}.\\[\\&_h2\\]\\:mb-\\[6px\\] h2{margin-bottom:6px}.\\[\\&_h2\\]\\:text-\\[16px\\] h2{font-size:16px}.\\[\\&_h2\\]\\:leading-\\[1\\.4\\] h2{--tw-leading:1.4;line-height:1.4}.\\[\\&_h2\\]\\:text-primary h2{color:var(--dsw-alias-label-primary)}.\\[\\&_h3\\]\\:m-0 h3{margin:calc(var(--spacing)*0)}.\\[\\&_h3\\]\\:mt-\\[14px\\] h3{margin-top:14px}.\\[\\&_h3\\]\\:mb-\\[6px\\] h3{margin-bottom:6px}.\\[\\&_h3\\]\\:text-\\[13px\\] h3{font-size:13px}.\\[\\&_h3\\]\\:text-\\[14px\\] h3{font-size:14px}.\\[\\&_h3\\]\\:text-\\[16px\\] h3{font-size:16px}.\\[\\&_h3\\]\\:leading-\\[1\\.4\\] h3{--tw-leading:1.4;line-height:1.4}.\\[\\&_h3\\]\\:leading-\\[20px\\] h3{--tw-leading:20px;line-height:20px}.\\[\\&_h3\\]\\:leading-\\[24px\\] h3{--tw-leading:24px;line-height:24px}.\\[\\&_h3\\]\\:font-medium h3{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\\[\\&_h3\\]\\:font-semibold h3{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.\\[\\&_h3\\]\\:text-primary h3{color:var(--dsw-alias-label-primary)}.\\[\\&_h4\\]\\:mt-\\[14px\\] h4{margin-top:14px}.\\[\\&_h4\\]\\:mb-\\[6px\\] h4{margin-bottom:6px}.\\[\\&_h4\\]\\:text-\\[13px\\] h4{font-size:13px}.\\[\\&_h4\\]\\:leading-\\[1\\.4\\] h4{--tw-leading:1.4;line-height:1.4}.\\[\\&_h4\\]\\:text-primary h4{color:var(--dsw-alias-label-primary)}.\\[\\&_input\\]\\:m-0 input{margin:calc(var(--spacing)*0)}.\\[\\&_input\\]\\:h-\\[12px\\] input{height:12px}.\\[\\&_input\\]\\:w-\\[12px\\] input{width:12px}.\\[\\&_input\\]\\:accent-brand input{accent-color:var(--dsw-alias-brand-primary)}.\\[\\&_input\\:focus-visible\\]\\:shadow-focus-ring input:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.\\[\\&_ol\\]\\:my-\\[6px\\] ol{margin-block:6px}.\\[\\&_ol\\]\\:pl-\\[20px\\] ol{padding-left:20px}.\\[\\&_p\\]\\:m-0 p{margin:calc(var(--spacing)*0)}.\\[\\&_p\\]\\:my-\\[6px\\] p{margin-block:6px}.\\[\\&_p\\]\\:leading-\\[20px\\] p{--tw-leading:20px;line-height:20px}.\\[\\&_pre\\]\\:my-\\[8px\\] pre{margin-block:8px}.\\[\\&_pre\\]\\:overflow-x-auto pre{overflow-x:auto}.\\[\\&_pre\\]\\:rounded-\\[8px\\] pre{border-radius:8px}.\\[\\&_pre\\]\\:border pre{border-style:var(--tw-border-style);border-width:1px}.\\[\\&_pre\\]\\:border-border-l2 pre{border-color:var(--dsw-alias-border-l2)}.\\[\\&_pre\\]\\:bg-layer-3 pre{background-color:var(--dsw-alias-bg-layer-3)}.\\[\\&_pre\\]\\:px-\\[12px\\] pre{padding-inline:12px}.\\[\\&_pre\\]\\:py-\\[10px\\] pre{padding-block:10px}.\\[\\&_svg\\]\\:h-\\[11px\\] svg{height:11px}.\\[\\&_svg\\]\\:h-\\[14px\\] svg{height:14px}.\\[\\&_svg\\]\\:w-\\[11px\\] svg{width:11px}.\\[\\&_svg\\]\\:w-\\[14px\\] svg{width:14px}.\\[\\&_ul\\]\\:my-\\[6px\\] ul{margin-block:6px}.\\[\\&_ul\\]\\:pl-\\[20px\\] ul{padding-left:20px}.\\[\\&\\+\\&\\]\\:border-t+.\\[\\&\\+\\&\\]\\:border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.\\[\\&\\+\\&\\]\\:border-border-weak+.\\[\\&\\+\\&\\]\\:border-border-weak{border-color:var(--dsw-alias-border-weak,#7f7f7f33)}.\\[\\&\\+\\&\\]\\:border-t-border-l2+.\\[\\&\\+\\&\\]\\:border-t-border-l2{border-top-color:var(--dsw-alias-border-l2)}.\\[\\&\\:\\:-webkit-scrollbar\\]\\:hidden::-webkit-scrollbar{display:none}.\\[\\&\\:has\\(input\\:disabled\\)\\]\\:cursor-default:has(input:disabled){cursor:default}.\\[\\&\\:has\\(input\\:disabled\\)\\]\\:opacity-60:has(input:disabled){opacity:.6}.\\[\\&\\>\\*\\]\\:w-full>*{width:100%}.\\[\\&\\>\\*\\]\\:max-w-\\[960px\\]>*{max-width:960px}.\\[\\&\\>button\\]\\:h-\\[32px\\]>button{height:32px}.\\[\\&\\>button\\]\\:text-\\[13px\\]>button{font-size:13px}.\\[\\&\\>button\\:last-child\\]\\:mr-\\[-8px\\]>button:last-child{margin-right:-8px}.\\[\\&\\>img\\]\\:absolute>img{position:absolute}.\\[\\&\\>img\\]\\:top-0>img{top:calc(var(--spacing)*0)}.\\[\\&\\>img\\]\\:left-0>img{left:calc(var(--spacing)*0)}.\\[\\&\\>img\\]\\:block>img{display:block}.\\[\\&\\>img\\]\\:h-\\[1100\\%\\]>img{height:1100%}.\\[\\&\\>img\\]\\:h-full>img{height:100%}.\\[\\&\\>img\\]\\:w-\\[800\\%\\]>img{width:800%}.\\[\\&\\>img\\]\\:w-full>img{width:100%}.\\[\\&\\>img\\]\\:max-w-none>img{max-width:none}.\\[\\&\\>img\\]\\:object-fill>img{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)}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-content{syntax:"*";inherits:false;initial-value:""}`const tailwindcss = cssr.c([TAILWINDCSS_GENERATED])diff --git a/packages/dsh-tauri-ui/src/host/service/ungrouped.ts b/packages/dsh-tauri-ui/src/host/service/ungrouped.tsindex d48cafb0..5dc551f6 100644--- a/packages/dsh-tauri-ui/src/host/service/ungrouped.ts+++ b/packages/dsh-tauri-ui/src/host/service/ungrouped.ts@@ -1,5 +1,4 @@-import { defineService } from 'dsh-tauri'-import { resolveUngroupedSessionPath } from '../utils/paths'+import { defineService, resolveUngroupedSessionPath } from 'dsh-tauri'export const ungrouped = defineService({resolve(): string {diff --git a/packages/dsh-tauri-ui/src/host/utils/paths.test.ts b/packages/dsh-tauri-ui/src/host/utils/paths.test.tsdeleted file mode 100644index d83b4895..00000000--- a/packages/dsh-tauri-ui/src/host/utils/paths.test.ts+++ /dev/null@@ -1,16 +0,0 @@-import { homedir } from 'node:os'-import { join, resolve } from 'node:path'-import { describe, expect, it } from 'vitest'-import { resolveUngroupedSessionPath } from './paths'--describe('resolveUngroupedSessionPath', () => {- it('resolves to the ungrouped directory inside DSH_HOME, not the core install dir', () => {- expect(resolveUngroupedSessionPath({ DSH_HOME: 'D:\\harness' } as NodeJS.ProcessEnv))- .toBe(resolve('D:\\harness', 'ungrouped'))- })-- it('defaults to ~/.dsh/ungrouped when DSH_HOME is unset', () => {- expect(resolveUngroupedSessionPath({} as NodeJS.ProcessEnv))- .toBe(join(homedir(), '.dsh', 'ungrouped'))- })-})diff --git a/packages/dsh-tauri-ui/src/host/utils/paths.ts b/packages/dsh-tauri-ui/src/host/utils/paths.tsdeleted file mode 100644index 063a2e9f..00000000--- a/packages/dsh-tauri-ui/src/host/utils/paths.ts+++ /dev/null@@ -1,23 +0,0 @@-import { homedir } from 'node:os'-import { join, resolve } from 'node:path'-import process from 'node:process'--function expandHome(path: string): string {- if (path === '~')- return homedir()- if (path.startsWith('~/') || path.startsWith('~\\'))- return join(homedir(), path.slice(2))- return path-}--function resolveDshHome(env: NodeJS.ProcessEnv): string {- const configured = env.DSH_HOME- const home = configured !== undefined && configured.trim().length > 0- ? expandHome(configured)- : join(homedir(), '.dsh')- return resolve(home)-}--export function resolveUngroupedSessionPath(env: NodeJS.ProcessEnv = process.env): string {- return join(resolveDshHome(env), 'ungrouped')-}diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.test.tsindex e1bff27a..c4fea2bb 100644--- a/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts@@ -1,3 +1,5 @@+import type { Agent, AgentSetupCommit } from '@deepseek-ai/dsh-agent'+import type { NativeSessionBridge } from 'dsh-tauri'import { resolve } from 'node:path'import { Context } from '@deepseek-ai/cordis'import { MessageId } from '@deepseek-ai/dsh-llm'@@ -5,7 +7,9 @@ import { Session, SessionId, SessionStore } from '@deepseek-ai/dsh-session'import { afterEach, describe, expect, it, vi } from 'vitest'import { pendingWorktreeTitles, resetRuntime } from '../config/runtime'import { server } from '../server'+import { checkoutContext } from './checkout-context'import { handoff } from './handoff'+import { worktree } from './worktree'const disposers: Array<() => void> = []@@ -50,6 +54,10 @@ interface SetupOptions {presets?: unknownsourceContext?: unknowngetAgent?: (id: string) => unknown+ bridge?: NativeSessionBridge+ projections?: unknown+ workspace?: unknown+ storedSession?: unknown}function setup(options: SetupOptions = {}): { created: any[] } {@@ -64,8 +72,9 @@ function setup(options: SetupOptions = {}): { created: any[] } {return options.create?.(value)},},- get: () => options.presets,- workspaceRegistry: { resolveByPath: async () => undefined },+ get: (key: string) => key === 'agentPresets' ? options.presets : key === 'nativeSessionBridge' ? options.bridge : key === 'sessionProjections' ? options.projections : 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))@@ -82,7 +91,76 @@ afterEach(() => {vi.restoreAllMocks()})+describe('handoff API', () => {+ it('exposes only inheritance and checkout services after desktop agent tools are removed', () => {+ expect(Object.keys(handoff).sort()).toEqual(['checkout', 'handback', 'inherit'])+ })+})+describe('handoff.inherit', () => {+ it.each(['codex', 'claude'] as const)('preserves the official %s fork binding without injecting a desktop handoff message', async (backend) => {+ const packageId: string = 'dsh-session-current'+ const kernel = await import(packageId) as typeof import('@deepseek-ai/dsh-session') & {+ appendPluginRecord: (value: Session, type: 'plugin:dsh-tauri-bridge/kernel', data: { backend: 'codex' | 'claude', nativeSessionId: string, sessionId: string }) => number+ }+ 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-bridge/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-bridge', 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-bridge', model: backend })+ expect(signal.aborted).toBe(false)+ expect(kernel.appendPluginRecord(agent.session, 'plugin:dsh-tauri-bridge/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-bridge/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' }@@ -112,6 +190,371 @@ 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-bridge', 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-bridge', 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-bridge/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-bridge/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 () => {const context = new Context()try {@@ -288,3 +731,113 @@ describe('handoff.inherit', () => {expect(warn).toHaveBeenCalledWith(expect.stringContaining('session-target'))})})++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}` }+ })++ 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()+ }+ })+})++describe('handoff.handback', () => {+ it('publishes the prepared native child before attaching it and saving checkout context', async () => {+ const context = new Context()+ try {+ const sessions = new SessionStore(context)+ const source = Session.create(SessionId('session-source'))+ 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')+ })+ const save = vi.spyOn(checkoutContext, 'save').mockImplementation(async () => {+ order.push('save')+ })+ 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 }+ },+ })+ 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)+ 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) })+ }+ finally {+ await context.fiber.dispose()+ }+ })+})diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.tsindex a60eeccb..60e7e700 100644--- a/packages/dsh-tauri-worktree/src/host/service/handoff.ts+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.ts@@ -1,3 +1,7 @@+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 { CheckoutInfo, HostContext, OperationResult } from '../types'import { randomUUID } from 'node:crypto'import { getServerContext } from 'dsh-h3/utils'@@ -105,19 +109,15 @@ async function createInherited(const { cwd, attach = false } = optionsconst targetSessionId = options.targetSessionId ?? `session-${randomUUID()}`try {- const seed = sessionEvents(sourceSession)- if (seed.length === 0)- return { ok: false, error: `源会话没有可继承的事件:${sourceSessionId}` }-- await createAgent(sourceSession, agent, targetSessionId, cwd, seed, options.parentSession)- if (!hasInheritedConversation(seed))+ const inherited = await createAgent(sourceSession, agent, targetSessionId, cwd, { parentSession: options.parentSession, requireEvents: true })+ if (!hasInheritedConversation(inherited.seed))pendingWorktreeTitles.add(targetSessionId)if (attach) {const workspace = await ctx.workspaceRegistry.resolveByPath(cwd)if (workspace)await workspace.attachSession(targetSessionId)}- return { ok: true, targetSessionId, seedLength: seed.length }+ return { ok: true, targetSessionId, seedLength: inherited.seed.length }}catch (error) {return { ok: false, error: get(error, 'message', String(error)) }@@ -129,33 +129,64 @@ async function createAgent(sourceAgent: any,targetSessionId: string,cwd: string,- seed: readonly unknown[],- parentSession = sourceSession.id,-): Promise<any> {+ options: { parentSession?: string, requireEvents?: boolean } = {},+): Promise<{ handle: AgentHandle, seed: readonly unknown[] }> {const ctx = getServerContext<HostContext>(server)- 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,- meta: {- cwd,- parentSession,- isSeeded: true,- ...(parentPreset ? { agentPreset: parentPreset } : {}),- },- inheritedEventCount: seed.length,- agentOptions: sourceAgent?.options ?? {},- ...(sourceAgent && presets && parentPreset- ? {- setup: (agentCtx: any): void => {- presets.composeFrom(agentCtx, sourceAgent.ctx)- },- }- : {}),- })+ 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-bridge/kernel' && event.ignorable === true+ })+ if (hasNativeRecord || projected?.binding || projected?.inheritedBinding || projected?.nativeSessionId || sourceSession.requestHeader?.()?.config?.provider === 'dsh-tauri-bridge' || sourceAgent?.options?.provider === 'dsh-tauri-bridge')+ 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()+ return { handle, seed: inheritedSeed }}/** 内核 0.1.2-rc.1 移除 events,旧版本以 log/events 兼容。 */diff --git a/packages/dsh-tauri/package.json b/packages/dsh-tauri/package.jsonindex e1283766..a5f50663 100644--- a/packages/dsh-tauri/package.json+++ b/packages/dsh-tauri/package.json@@ -71,6 +71,7 @@"date-fns": "catalog:utils","dsh-tauri-tsdown": "workspace:*","lodash-es": "catalog:utils",+ "react-if-lite": "catalog:runtime","tailwind-variants": "catalog:runtime","tsdown": "catalog:cli","valtio": "catalog:",diff --git a/packages/dsh-tauri/src/client/modules/reause.ts b/packages/dsh-tauri/src/client/modules/reause.tsindex 97a3562c..28c174b7 100644--- a/packages/dsh-tauri/src/client/modules/reause.ts+++ b/packages/dsh-tauri/src/client/modules/reause.ts@@ -13,4 +13,5 @@* 具名清单只保留真正被消耗的 hook,其余被 tree-shake(941KB → 70KB)。* 新增 hook 在此登记即可(dts 同步收窄,漏登记时插件侧直接类型报错)。*/-export { noop, useEventListener, useMount, useResizeObserver, useTimeoutPoll, useUnmount, useWatchImmediate } from '@reause/core'+export { noop, useAsyncState, useEventListener, useMount, useResizeObserver, useTimeoutPoll, useUnmount, useWatchImmediate } from '@reause/core'+export { If } from 'react-if-lite'diff --git a/packages/dsh-tauri/src/client/register/index.adapter.test.ts b/packages/dsh-tauri/src/client/register/index.adapter.test.tsindex 25d499a2..8d5ff937 100644--- a/packages/dsh-tauri/src/client/register/index.adapter.test.ts+++ b/packages/dsh-tauri/src/client/register/index.adapter.test.ts@@ -685,6 +685,46 @@ describe('defineAdapter — 0.1.6-alpha.2 会话面投影', () => {})})+describe('defineAdapter — official session APIs', () => {+ it('create and catalog refresh capabilities bind only existing official methods', async () => {+ const owner = {+ create: vi.fn(function (this: object, input?: unknown) {+ expect(this).toBe(owner)+ expect(input).toEqual({ cwd: '/project' })+ return Promise.resolve('official-session')+ }),+ refresh: vi.fn(function (this: object) {+ expect(this).toBe(owner)+ return Promise.resolve()+ }),+ }+ const adapter = defineAdapter(makeContext({ sessions: owner }))+ expect(adapter.has('sessions.create')).toBe(true)+ expect(adapter.has('sessions.refresh')).toBe(true)+ await expect(adapter.sessions.create?.({ cwd: '/project' })).resolves.toBe('official-session')+ await adapter.sessions.refresh?.()+ expect(owner.refresh).toHaveBeenCalledOnce()+ const unavailable = defineAdapter(makeContext({ sessions: {} }))+ expect(unavailable.has('sessions.create')).toBe(false)+ expect(unavailable.has('sessions.refresh')).toBe(false)+ })++ it('projection refresh capability binds only the official existing method', async () => {+ const owner = {+ refreshProjections: vi.fn(function (this: object, id: string) {+ expect(this).toBe(owner)+ expect(id).toBe('session-a')+ return Promise.resolve()+ }),+ }+ const adapter = defineAdapter(makeContext({ sessions: owner }))+ expect(adapter.has('sessions.refreshProjections')).toBe(true)+ await adapter.sessions.refreshProjections?.('session-a')+ expect(owner.refreshProjections).toHaveBeenCalledOnce()+ expect(defineAdapter(makeContext({ sessions: {} })).has('sessions.refreshProjections')).toBe(false)+ })+})+describe('defineAdapter — sessionList 投影', () => {it('sessionList:过滤非字符串 id、只带字符串 current,subscribe 转发到核心列表', () => {const list = makeLiveList<{ ids: unknown[], current?: unknown }>({ ids: ['s1', 7, 's2', null], current: 's2' })diff --git a/packages/dsh-tauri/src/client/register/index.adapter.ts b/packages/dsh-tauri/src/client/register/index.adapter.tsindex 702a898a..e19b5954 100644--- a/packages/dsh-tauri/src/client/register/index.adapter.ts+++ b/packages/dsh-tauri/src/client/register/index.adapter.ts@@ -835,6 +835,9 @@ export function defineAdapter(ctx: unknown, options: DefineAdapterOptions = {}):const capabilityChecks: Record<AdapterCapability, () => boolean> = {'sessions.list': () => typeof sessions.list?.getSnapshot === 'function','sessions.provideInfo': () => typeof sessions.provideInfo === 'function',+ 'sessions.create': () => typeof sessions.create === 'function',+ 'sessions.refresh': () => typeof sessions.refresh === 'function',+ 'sessions.refreshProjections': () => typeof sessions.refreshProjections === 'function','workspaces.list': () => typeof workspaces.list?.getSnapshot === 'function','workspaces.create': () => typeof workspaces.create === 'function','navigation.startSession': () => surfaceStartSession(surface) !== undefined,diff --git a/packages/dsh-tauri/src/client/request/index.test.ts b/packages/dsh-tauri/src/client/request/index.test.tsindex 421ba2b1..36a45571 100644--- a/packages/dsh-tauri/src/client/request/index.test.ts+++ b/packages/dsh-tauri/src/client/request/index.test.ts@@ -25,6 +25,11 @@ beforeAll(async () => {res.writeHead(500, { 'content-type': 'text/plain' })res.end('oops')}+ else if (req.url?.startsWith('/status/')) {+ const status = Number(req.url.slice('/status/'.length))+ res.writeHead(status, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ error: `failure-${status}` }))+ }else if (req.url === '/echo' && req.method === 'POST') {res.writeHead(200, { 'content-type': 'application/json' })res.end(JSON.stringify({ got: body }))@@ -59,6 +64,21 @@ describe('dsh-tauri fetch', () => {await expect(fetch(`${base}/oops`)).rejects.toThrow('请求失败 (500): oops')})+ it.each([401, 403, 404, 500])('retains HTTP status %s without changing readable errors', async (status) => {+ await expect(fetch(`${base}/status/${status}`)).rejects.toMatchObject({+ status,+ message: `请求失败 (${status}): failure-${status}`,+ })+ })++ it('does not invent an HTTP status for errors without a response', async () => {+ const reason = new Error('offline 404')+ await expect(fetch(`${base}/ok`, { onRequest: () => {+ throw reason+ } })).rejects.toBe(reason)+ expect(reason).not.toHaveProperty('status')+ })+it('posts JSON objects with content-type handled by ofetch', async () => {const result = await fetch<{ got: string }>(`${base}/echo`, { method: 'POST', body: { a: 1 } })expect(JSON.parse(result.got)).toEqual({ a: 1 })diff --git a/packages/dsh-tauri/src/client/request/index.ts b/packages/dsh-tauri/src/client/request/index.tsindex b6448286..64f16285 100644--- a/packages/dsh-tauri/src/client/request/index.ts+++ b/packages/dsh-tauri/src/client/request/index.ts@@ -20,7 +20,7 @@ export const fetch = createFetch({retry: 0,parseResponse: parseJsonResponse,onResponseError: ({ response }) => {- throw new Error(defaultErrorMessage(response.status, response._data))+ throw Object.assign(new Error(defaultErrorMessage(response.status, response._data)), { status: response.status })},},})diff --git a/packages/dsh-tauri/src/client/types/adapter.ts b/packages/dsh-tauri/src/client/types/adapter.tsindex b62ca2b0..b280a6eb 100644--- a/packages/dsh-tauri/src/client/types/adapter.ts+++ b/packages/dsh-tauri/src/client/types/adapter.ts@@ -34,6 +34,12 @@ export interface AdapterListProjection<TSnapshot = unknown> {getSnapshot: () => TSnapshot}+export interface AdapterSessionCreateOptions {+ workspaceId?: AdapterWorkspaceId+ cwd?: string+ sessionId?: AdapterSessionId+}+/** 已适配的 `ctx.sessions` 面;成员按能力可选,缺失即视为不可用。 */export interface AdapterSessions extends AdapterRuntimeObject {/** `useSessions` 标准 feed(跨版本同形)。 */@@ -46,6 +52,8 @@ export interface AdapterSessions extends AdapterRuntimeObject {provideInfo?: (sessionId: AdapterSessionId) => unknown/** 稳定会话 binding(legacy 的 `provideInfo` 兼容投影依赖它)。 */binding?: (sessionId: AdapterSessionId) => unknown+ create?: (options?: AdapterSessionCreateOptions) => Promise<AdapterSessionId>+ refreshProjections?: (sessionId: AdapterSessionId) => Promise<void>refresh?: () => unknownopen?: (sessionId: AdapterSessionId) => unknownfork?: (...args: unknown[]) => unknown@@ -150,6 +158,9 @@ export interface AdapterMigrationFailure {export type AdapterCapability= | 'sessions.list'| 'sessions.provideInfo'+ | 'sessions.create'+ | 'sessions.refresh'+ | 'sessions.refreshProjections'| 'workspaces.list'| 'workspaces.create'| 'navigation.startSession'diff --git a/packages/dsh-tauri/src/client/types/harness.ts b/packages/dsh-tauri/src/client/types/harness.tsindex 96d43aa8..7bc8f0d7 100644--- a/packages/dsh-tauri/src/client/types/harness.ts+++ b/packages/dsh-tauri/src/client/types/harness.ts@@ -24,7 +24,10 @@ export type {ISessions,SessionBinding,SessionListState,+ SessionProjectionMap,+ SessionProjectionSnapshot,SessionSummary,+ UseProjection,} from '@deepseek-ai/dsh-api-session-controller/client'export type {IWorkspaces,diff --git a/packages/dsh-tauri/src/host/types/harness.ts b/packages/dsh-tauri/src/host/types/harness.tsindex 9b8cdbd3..feaf0ee5 100644--- a/packages/dsh-tauri/src/host/types/harness.ts+++ b/packages/dsh-tauri/src/host/types/harness.ts@@ -10,8 +10,9 @@* 【基准】@deepseek-ai/* 0.2.1-alpha.1(版本由 pnpm-workspace.yaml 的 `dsh` catalog 钉住)。*/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 { SessionStore } from '@deepseek-ai/dsh-session'+import type { Session, SessionStore } from '@deepseek-ai/dsh-session'import type { IncomingMessage } from 'node:http'export type { Context } from '@deepseek-ai/cordis'@@ -36,6 +37,17 @@ 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 | undefined}diff --git a/packages/dsh-tauri/src/host/utils/paths.test.ts b/packages/dsh-tauri/src/host/utils/paths.test.tsnew file mode 100644index 00000000..4842c2f3--- /dev/null+++ b/packages/dsh-tauri/src/host/utils/paths.test.ts@@ -0,0 +1,22 @@+import { homedir } from 'node:os'+import { join, resolve } from 'node:path'+import { describe, expect, it } from 'vitest'+import { resolveUngroupedSessionPath } from './paths'++describe('resolveUngroupedSessionPath', () => {+ it('uses DSH_HOME instead of the core installation directory', () => {+ expect(resolveUngroupedSessionPath({ DSH_HOME: 'D:\\harness' }))+ .toBe(resolve('D:\\harness', 'ungrouped'))+ })++ it('defaults to ~/.dsh/ungrouped without a configured home', () => {+ expect(resolveUngroupedSessionPath({})).toBe(join(homedir(), '.dsh', 'ungrouped'))+ expect(resolveUngroupedSessionPath({ DSH_HOME: ' ' })).toBe(join(homedir(), '.dsh', 'ungrouped'))+ })++ it('expands both home-relative spellings', () => {+ expect(resolveUngroupedSessionPath({ DSH_HOME: '~/harness' })).toBe(join(homedir(), 'harness', 'ungrouped'))+ expect(resolveUngroupedSessionPath({ DSH_HOME: '~\\harness' })).toBe(join(homedir(), 'harness', 'ungrouped'))+ expect(resolveUngroupedSessionPath({ DSH_HOME: '~' })).toBe(join(homedir(), 'ungrouped'))+ })+})diff --git a/packages/dsh-tauri/src/host/utils/paths.ts b/packages/dsh-tauri/src/host/utils/paths.tsnew file mode 100644index 00000000..2530c41b--- /dev/null+++ b/packages/dsh-tauri/src/host/utils/paths.ts@@ -0,0 +1,15 @@+import { homedir } from 'node:os'+import { join, resolve } from 'node:path'+import process from 'node:process'++export function resolveUngroupedSessionPath(env: NodeJS.ProcessEnv = process.env): string {+ const configured = env.DSH_HOME?.trim()+ const home = configured+ ? configured === '~'+ ? homedir()+ : /^~[\\/]/.test(configured)+ ? join(homedir(), configured.slice(2))+ : configured+ : join(homedir(), '.dsh')+ return join(resolve(home), 'ungrouped')+}diff --git a/packages/dsh-tauri/src/index.ts b/packages/dsh-tauri/src/index.tsindex 742be64e..c46b32ad 100644--- a/packages/dsh-tauri/src/index.ts+++ b/packages/dsh-tauri/src/index.ts@@ -13,5 +13,6 @@ export * from './host/types/harness'export * from './host/utils/atomic'export * from './host/utils/driver'export * from './host/utils/open'+export * from './host/utils/paths'export * from './host/utils/spawn'export * from './host/utils/url'diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3c1b1c76..8d7a4ae0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -90,6 +90,9 @@ catalogs:'@deepseek-ai/dsh-agent-default-model':specifier: 0.2.1-alpha.1version: 0.2.1-alpha.1+ '@deepseek-ai/dsh-agent-loop':+ specifier: 0.2.1-alpha.1+ version: 0.2.1-alpha.1'@deepseek-ai/dsh-agent-preset':specifier: 0.2.1-alpha.1version: 0.2.1-alpha.1@@ -123,6 +126,9 @@ catalogs:'@deepseek-ai/dsh-client-ui-renderer':specifier: 0.2.1-alpha.1version: 0.2.1-alpha.1+ '@deepseek-ai/dsh-client-ui-session':+ specifier: 0.2.1-alpha.1+ version: 0.2.1-alpha.1'@deepseek-ai/dsh-client-ui-settings':specifier: 0.2.1-alpha.1version: 0.2.1-alpha.1@@ -132,6 +138,9 @@ catalogs:'@deepseek-ai/dsh-client-ui-theme':specifier: 0.2.1-alpha.1version: 0.2.1-alpha.1+ '@deepseek-ai/dsh-client-ui-workspace':+ specifier: 0.2.1-alpha.1+ version: 0.2.1-alpha.1'@deepseek-ai/dsh-host-webserver':specifier: 0.2.1-alpha.1version: 0.2.1-alpha.1@@ -144,6 +153,12 @@ catalogs:'@deepseek-ai/dsh-session':specifier: 0.2.1-alpha.1version: 0.2.1-alpha.1+ '@deepseek-ai/dsh-session-persistence':+ specifier: 0.2.1-alpha.1+ version: 0.2.1-alpha.1+ '@deepseek-ai/dsh-session-projection':+ specifier: 0.2.1-alpha.1+ version: 0.2.1-alpha.1'@deepseek-ai/dsh-skill-filesystem':specifier: 0.2.1-alpha.1version: 0.2.1-alpha.1@@ -153,6 +168,12 @@ catalogs:'@deepseek-ai/dsh-user-approval':specifier: 0.2.1-alpha.1version: 0.2.1-alpha.1+ '@deepseek-ai/dsh-user-questions':+ specifier: 0.2.1-alpha.1+ version: 0.2.1-alpha.1+ '@deepseek-ai/dsh-util-code-language':+ specifier: 0.2.1-alpha.1+ version: 0.2.1-alpha.1'@deepseek-ai/dsh-util-values':specifier: 0.2.1-alpha.1version: 0.2.1-alpha.1@@ -236,6 +257,9 @@ catalogs:specifier: ^2.6.0version: 2.6.0testing:+ '@shikijs/langs':+ specifier: 4.3.1+ version: 4.3.1'@testing-library/dom':specifier: ^10.4.0version: 10.4.2@@ -248,12 +272,30 @@ catalogs:'@wdio/tauri-service':specifier: ^1.4.0version: 1.4.0+ anser:+ specifier: 2.3.5+ version: 2.3.5+ diff:+ specifier: 9.0.0+ version: 9.0.0+ dsh-session-current:+ specifier: npm:@deepseek-ai/[email protected]+ version: 0.2.1-alpha.2+ immer:+ specifier: 10.1.1+ version: 10.1.1jsdom:specifier: ^26.1.0version: 26.1.0playwright:specifier: ^1.63.0version: 1.63.0+ shiki:+ specifier: 4.3.1+ version: 4.3.1+ simple-icons:+ specifier: 16.31.0+ version: 16.31.0vitest:specifier: ^4.1.11version: 4.1.11@@ -263,6 +305,9 @@ catalogs:yaml:specifier: ^2.9.0version: 2.9.0+ zustand:+ specifier: 4.4.7+ version: 4.4.7types:'@types/lodash-es':specifier: ^4.17.12@@ -326,6 +371,9 @@ catalogs:unstorage:specifier: ^1.17.5version: 1.17.5+ zod:+ specifier: ^4.4.3+ version: 4.4.3patchedDependencies:'@tauri-apps/[email protected]': 6bbec7f8a8e969a867d222e8b2b542d2dbd639ffbaf2184a4df47f330b6ad431@@ -423,6 +471,9 @@ importers:'@deepseek-ai/dsh-agent-default-model':specifier: catalog:dshversion: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](bc8e1a234d16d0329e7a818df1caf030))(@deepseek-ai/[email protected](@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected]))(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-agent-loop':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(e1828a76db60a945ed06863233e61b8e)'@deepseek-ai/dsh-agent-preset':specifier: catalog:dshversion: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](54d3464f7955532d08907e94aa6ef05e))@@ -456,6 +507,9 @@ importers:'@deepseek-ai/dsh-client-ui-renderer':specifier: catalog:dshversion: 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-client-ui-session':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])'@deepseek-ai/dsh-client-ui-settings':specifier: catalog:dshversion: 0.2.1-alpha.1(@deepseek-ai/[email protected])@@ -465,6 +519,9 @@ importers:'@deepseek-ai/dsh-client-ui-theme':specifier: catalog:dshversion: 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-client-ui-workspace':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])'@deepseek-ai/dsh-host-webserver':specifier: catalog:dshversion: 0.2.1-alpha.1(@deepseek-ai/[email protected])@@ -477,6 +534,12 @@ importers:'@deepseek-ai/dsh-session':specifier: catalog:dshversion: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-session-persistence':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-session-projection':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))'@deepseek-ai/dsh-skill-filesystem':specifier: catalog:dshversion: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))@@ -486,6 +549,12 @@ importers:'@deepseek-ai/dsh-user-approval':specifier: catalog:dshversion: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](bc8e1a234d16d0329e7a818df1caf030))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))+ '@deepseek-ai/dsh-user-questions':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](bc8e1a234d16d0329e7a818df1caf030))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-util-code-language':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])'@deepseek-ai/dsh-workspace':specifier: catalog:dshversion: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))@@ -501,6 +570,9 @@ importers:'@genapi/shared':specifier: 'catalog:'version: 4.1.4+ '@shikijs/langs':+ specifier: catalog:testing+ version: 4.3.1'@tailwindcss/postcss':specifier: catalog:buildversion: 4.1.11@@ -540,6 +612,9 @@ importers:'@wdio/tauri-service':specifier: catalog:testing+ anser:+ specifier: catalog:testing+ version: 2.3.5babel-plugin-react-compiler:specifier: catalog:buildversion: 1.0.0@@ -549,9 +624,15 @@ importers:changelogithub:specifier: catalog:releaseversion: 15.0.5+ diff:+ specifier: catalog:testing+ version: 9.0.0dsh-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-session-current:+ specifier: catalog:testing+ version: '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))'eslint:specifier: catalog:lintversion: 10.8.1([email protected])@@ -561,6 +642,9 @@ importers:h3:specifier: 'catalog:'version: 2.0.1+ immer:+ specifier: catalog:testing+ version: 10.1.1jsdom:specifier: catalog:testingversion: 26.1.0@@ -576,6 +660,12 @@ importers:publint:specifier: catalog:cliversion: 0.3.24+ shiki:+ specifier: catalog:testing+ version: 4.3.1+ simple-icons:+ specifier: catalog:testing+ version: 16.31.0ssh2:specifier: catalog:utilsversion: 1.17.0@@ -597,6 +687,12 @@ importers:webdriverio:specifier: catalog:testingversion: 9.31.9+ zod:+ specifier: catalog:utils+ version: 4.4.3+ zustand:+ specifier: catalog:testingpackages/dsh-tauri:dependencies:@@ -646,6 +742,9 @@ importers:lodash-es:specifier: catalog:utilsversion: 4.18.1+ react-if-lite:+ specifier: catalog:runtime+ version: 0.1.0([email protected])tailwind-variants:specifier: catalog:runtimeversion: 3.3.1([email protected])([email protected])@@ -687,6 +786,82 @@ importers:specifier: catalog:cliversion: 0.17.4(@emnapi/[email protected])(@emnapi/[email protected])([email protected])([email protected])([email protected])([email protected])+ packages/dsh-tauri-bridge:+ 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+ zod:+ specifier: catalog:utils+ version: 4.4.3+ devDependencies:+ '@deepseek-ai/cordis':+ specifier: catalog:dsh+ version: 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/cordis-plugin-loader':+ specifier: catalog:dsh+ version: 1.0.6-alpha.1(@deepseek-ai/[email protected])([email protected])+ '@deepseek-ai/dsh-agent':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(bc8e1a234d16d0329e7a818df1caf030)+ '@deepseek-ai/dsh-agent-preset-registry':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(54d3464f7955532d08907e94aa6ef05e)+ '@deepseek-ai/dsh-api-session-controller':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(a79f88b2459a2ea67d90459500724f45)+ '@deepseek-ai/dsh-client-connection':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-client-ui-conversation':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-client-ui-session':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-client-ui-slots':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-client-ui-workspace':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-llm':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-session':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-session-persistence':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-session-projection':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))+ '@deepseek-ai/dsh-user-approval':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](bc8e1a234d16d0329e7a818df1caf030))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))+ '@deepseek-ai/dsh-user-questions':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](bc8e1a234d16d0329e7a818df1caf030))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-workspace':+ specifier: catalog:dsh+ version: 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ 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-bundle:dependencies:dsh-tauri:@@ -695,6 +870,9 @@ importers:dsh-tauri-archive:specifier: workspace:*version: link:../dsh-tauri-archive+ dsh-tauri-bridge:+ specifier: workspace:*+ version: link:../dsh-tauri-bridgedsh-tauri-extension:specifier: workspace:*version: link:../dsh-tauri-extension@@ -1487,6 +1665,19 @@ packages:'@deepseek-ai/dsh-agent': 0.2.1-alpha.1'@deepseek-ai/dsh-llm': 0.2.1-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-Tg1iniB25uzDWEb7M/22BovzleV12OqzL4PgPYxThWGe7HbzL47pK0f+vooew2ZEXvFbJ8dlwZLETD0wmLH34w==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/dsh-agent': 0.2.1-alpha.1+ '@deepseek-ai/dsh-llm': 0.2.1-alpha.1+ '@deepseek-ai/dsh-scope': 0.2.1-alpha.1+ '@deepseek-ai/dsh-session': 0.2.1-alpha.1+ '@deepseek-ai/dsh-session-persistence': 0.2.1-alpha.1+ '@deepseek-ai/dsh-session-projection': 0.2.1-alpha.1+ '@deepseek-ai/dsh-system-prompt': 0.2.1-alpha.1+ '@deepseek-ai/dsh-tools': 0.2.1-alpha.1+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-jHD5M0POCDvh3IpjLCUPQxDrIONHa24jnnA75EocyAhTTrVRvprBNNrVoIStmKAhjML2t9Iy6V2Zk/GycpYcbA==}peerDependencies:@@ -1611,6 +1802,11 @@ packages:peerDependencies:'@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-2cpJzyu0IbyRXwZMBSEy+tWxj1OvhgiQwSTY1GlhEcPi+VF0nvT2pJIa/i43kH+0hs48r4tFX/v/tczK6d//Hg==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-j8k2SUn4D0LOxgQnPPHCOqphLe/YdHIQuRrLdXX4o6oNynrOSQSWYsbvHqQxhjbRdDFHqcOXZf2u5/tMcrWYKA==}peerDependencies:@@ -1657,6 +1853,11 @@ packages:peerDependencies:'@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-+vZbJ5tevvomurukmI3i9eWOcLvo/yfhV218HBFdd/yEbFxcI5XQeJIcpQrHUgn+5VHV7ZaGO+Hz0tTehYbl2Q==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-tSGa/ljVo5ip1YIOEXl3MkQ9WfTGighPc06AxyGzxMe3NrFO9fgoTUer4FZJ0TAoSoG9XIRzIc4+OpmT1kmcfQ==}peerDependencies:@@ -1672,6 +1873,11 @@ packages:peerDependencies:'@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-b/kGOoLg60FTphriytOt8yEbIgmySUarpEZBVNWS0n9dHsBm6CaLlWbnhoFAMZYs3Stz06PTh7goCI68RNPhIw==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-Zple4rDiwd4SU7uVqfOHNkDQlR4JjdxdCBhfQWLer9yPMgpPAQszQNOIUscDV2uqp4D5lwqBgPvzLydz8sQv4g==}peerDependencies:@@ -1768,6 +1974,11 @@ packages:peerDependencies:'@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-+pUKWsWBZorW3nQLGAC2qEQudFOscKINR0njoPhhFhJsVPuAqLUYF3bf6G4evbMKUF1+Uw901CFHOfwLluljNQ==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-cmfuE0mrtMyGQRm5s9UYyJOO1X5cLYtDiG45ryzaEH9u2UxFywYzvQ5MBW9XRSRZFtWOCE7Uw5nt4/Dq5SNQPw==}peerDependencies:@@ -1900,6 +2111,12 @@ packages:'@deepseek-ai/cordis': ~4.0.5-alpha.1'@deepseek-ai/dsh-scope': 0.2.1-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-xINgQ8XFC40aLxPLBMxAMl3ZkY8NlkasVVrnIio94hZYX+dqw7N63y53vqLU69WKTPEFJ11GdCJq4Yx5Tr2HFA==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/dsh-scope': 0.2.1-alpha.2+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-KjiH3Cnr3hxsuVOX+j3r8cPWbhQOcxq2sIg8icRWdOMKN9vdhsKLpId56lezXF1tKIlAHVcLkQyO4ac9Bjp6WA==}peerDependencies:@@ -2007,6 +2224,11 @@ packages:peerDependencies:'@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-hgII55C+B2MWnMwP8Nv1BTCh+RbNP14EhzwMfOiwBWK08PdVHi2gdB7ZtbRprps5s2fO2gVXaclgXpnLX05hgw==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-gjDpn7aLmZZRWMaOHOhjZu8wchSeWxDSIlCsMh79HXYBSgdZsu7ExJeYm61TSfG4wqUevOH7TrjVhVXsimcSIw==}peerDependencies:@@ -2035,6 +2257,11 @@ packages:peerDependencies:'@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-L/f22tnjV9LXFOf8CaX5XmEyKXR18oRKP2X3qb/I7NrAxk5uwKZcLHCFU/LXECVXrkm/Q0MPp5iNiREG1rLfzQ==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-CK9Nxgh7xQpOOohMb100qHM5Vu6XgffH+5FdaQ8sPqAaAivjZWZXOVPXrUaZK8Fces/BooPY9PUyV7DN/JhpOw==}peerDependencies:@@ -2051,11 +2278,32 @@ packages:'@deepseek-ai/dsh-session': 0.2.1-alpha.1'@deepseek-ai/dsh-system-prompt': 0.2.1-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-1Gmlxo62T5Nk8EFWD+aGaIDQAnUS5AFaqayyWl3GTedhtw+v5/HX6lMO622wUQHOhGGsQXOyps4NIqJbPPPVEA==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/dsh-agent': 0.2.1-alpha.1+ '@deepseek-ai/dsh-llm': 0.2.1-alpha.1+ '@deepseek-ai/dsh-scope': 0.2.1-alpha.1+ '@deepseek-ai/dsh-session': 0.2.1-alpha.1+ '@deepseek-ai/dsh-session-projection': 0.2.1-alpha.1+ '@deepseek-ai/dsh-typert-protocol': 0.2.1-alpha.1++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-nrbjxZGnsQFdCGsP9Cv57gOlx6HOpWbtCGVGw4pGg3NZufqZN70y3bym8mOBtmV+IJmd0u41H47IS6mkD0vhoA==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-uZhfu30VShru7GxknldvvKdPfiXIJJewm0KwJgrtwZbOMoWTH8lzTvDFgK8YvhG8rCRmFySNqQdgdzsMRLiZVQ==}peerDependencies:'@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-Hrm2c1H5ZOGBfviHPSEfPOg+FqagqH7PwGLoB/PVWZztQ2otw31NarPgrzSXO4cVY5fUmuoK8lsMRmgnQzs0FA==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-fdVI4yWqGTMEgYeWbJy5X9mhmdfBLgt95pi0A5lTvyrxIAFc58t3LzDEerVhnKsU1/9SYTNLmlOvJnaQRX7t+w==}peerDependencies:@@ -2066,6 +2314,11 @@ packages:peerDependencies:'@deepseek-ai/cordis': ~4.0.5-alpha.1+ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-0MoZ0C8rXC+2PyxJER6ZSRfkU21/HbX4Z5oCcdC3b151epcBYQVlP/o8vjqePQAJCZwTrWAEknnJHRMWbVlh0A==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.0.5-alpha.1+'@deepseek-ai/[email protected]':resolution: {integrity: sha512-N1nU1FdJ3JXXZoUWoL+y1A9SH7FxQrNRBn2/RKMDKPrp4nrEhtd+Jdih8iPmA5rjzVJIkN4Rc3FDA2GxEDVTHg==}peerDependencies:@@ -3219,6 +3472,37 @@ packages:cpu: [x64]os: [win32]+ '@shikijs/[email protected]':+ resolution: {integrity: sha512-ANMDxuaPsNMdDC1m4vfvhlDmJweMwkE5XitTwrq2rWHx5jM+dlm4MmHt2PP6t0uejfR77SuhrhJ0zEijIF/uhA==}+ engines: {node: '>=20'}++ '@shikijs/[email protected]':+ resolution: {integrity: sha512-JBItcnPuYq7jVJdZo/vMj94r+szT7XEjHFX+mvFDGSEIbVAXAGyHAHzhbWzpGOwYidCZrErJLLgn2PVeiokHnQ==}+ engines: {node: '>=20'}++ '@shikijs/[email protected]':+ resolution: {integrity: sha512-OXyNMzg0pews+msMj4cHeqT4xiYKKvbnn6VbdAXxfoFl3SSx4fJTc8FadECuc5/H9p3BzhNAoAUXKwAu9rWYhg==}+ engines: {node: '>=20'}++ '@shikijs/[email protected]':+ resolution: {integrity: sha512-m0l9nsDqgBHvbZbk7A0/kXz/impK3uB/c6rAn6Gpg/uPtdZRQ+alsN/17MU5thb68XTj/4DxkZAotrM0GGSpDQ==}+ engines: {node: '>=20'}++ '@shikijs/[email protected]':+ resolution: {integrity: sha512-CXQRQOYy1leqQ8ceTeJdmXv/bsUY++6QyLpXJ94LZAAYj5X2SKRdc5ipguv4NPyGVKItB2PPwUpRNe0Sjh5S1A==}+ engines: {node: '>=20'}++ '@shikijs/[email protected]':+ resolution: {integrity: sha512-dgpoJ4WqNi2yTmizQHBJ5zcX6j2lE6icN/0yt4l1kkf16jrY/pwPLoTb1ETsWMz0OBLf9ZNvwmxft+cH+N9qSA==}+ engines: {node: '>=20'}++ '@shikijs/[email protected]':+ resolution: {integrity: sha512-CHFxE0jztBIZRHH6gxXE7DXUCFXjReEGxZ/j0rfSLGKZuwp2xBYycEP14875DSa9KLL/6700oxIq6oO6ef9K2g==}+ engines: {node: '>=20'}++ '@shikijs/[email protected]':+ resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==}+'@sinclair/[email protected]':resolution: {integrity: sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==}@@ -3639,6 +3923,9 @@ packages:resolution: {integrity: sha512-fkv8dHRDqfGtTHuJeebdrQ7cX6Ad4WAS00rgHh9UGvMycF1mjBfsxry1XsLIFhWZ6Judlh6UdzK+TYlbpCXgnA==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+ '@ungap/[email protected]':+ resolution: {integrity: sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==}+'@vitejs/[email protected]':resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==}engines: {node: ^14.18.0 || >=16.0.0}@@ -3811,6 +4098,9 @@ packages:resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}+ resolution: {integrity: sha512-vcZjxvvVoxTeR5XBNJB38oTu/7eDCZlwdz32N1eNgpyPF7j/Z7Idf+CUwQOkKKpJ7RJyjxgLHCM7vdIK0iCNMQ==}+resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}engines: {node: '>=8'}@@ -4076,6 +4366,12 @@ packages:engines: {node: ^22.19.0 || ^24.11.0 || >=26.0.0}hasBin: true+ resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}++ resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==}+resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==}@@ -4137,6 +4433,9 @@ packages:resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==}+ resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}+resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==}engines: {node: '>= 12'}@@ -4366,6 +4665,10 @@ packages:resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==}engines: {node: '>=0.3.1'}+ resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==}+ engines: {node: '>=0.3.1'}+resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}@@ -4972,6 +5275,12 @@ packages:resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}engines: {node: '>=8'}+ resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==}++ resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}+resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==}@@ -4991,6 +5300,9 @@ packages:resolution: {integrity: sha512-0zHsZJrK7S3K2aucXWL6ycoYJ/iNtIcFHC/nYQgFklPtrv5LpJctIiSCroWZWeuoXvuyFdzp6KzjJQ+OT5MfFw==}+ resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}+resolution: {integrity: sha512-xWROBw9+MEGwxpotll0h672KCaLrKKiCYzsyN8ZgL9cQbVumFnyvsk2JqiB9ELAV1GLj1GG/jxZUjV9OZZi/yQ==}@@ -5038,6 +5350,9 @@ packages:resolution: {integrity: sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==}+ resolution: {integrity: sha512-s2MPrmjovJcoMaHtx6K11Ra7oD05NT97w1IC5zpMkT6Atjr7H8LjaDd81iIxUYpMKSRRNMJE703M1Fhr/TctHw==}+resolution: {integrity: sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==}@@ -5450,6 +5765,9 @@ packages:resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}+ resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==}+resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==}@@ -5760,6 +6078,12 @@ packages:resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}+ resolution: {integrity: sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==}++ resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==}+resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}engines: {node: '>=18'}@@ -5941,6 +6265,9 @@ packages:resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}+ resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==}+resolution: {integrity: sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==}engines: {node: '>= 14'}@@ -6076,6 +6403,15 @@ packages:resolution: {integrity: sha512-J8rn6v4DBb2nnFqkqwy6/NnTYMcgLA+sLr0iIO41qpv0n+ngb7ksag2tMRl0inb1bbO/esUwzW1vbJi7K0sI0g==}engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0}+ resolution: {integrity: sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==}++ resolution: {integrity: sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==}++ resolution: {integrity: sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==}+resolution: {integrity: sha512-sZuz1dYW/ZsfG17WSAG7eS85r5a0dDsvg+7BiiYR5o6lKCAtUrEwdmRmaGF6rwVj3LcmAeYkOWKEPlbPzN3Y3A==}engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0}@@ -6220,6 +6556,10 @@ packages:resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}engines: {node: '>=8'}+ resolution: {integrity: sha512-oR+qDVi2OjX1tmDpyv+3KviX01KzO6Af+0NNnKnsp9491UEGz2YpxTuJboS/6VhYpTdqzmuJBuiTlrAWWJAssw==}+ engines: {node: '>=20'}+resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}@@ -6227,6 +6567,10 @@ packages:resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}engines: {node: '>=14'}+ resolution: {integrity: sha512-dDEqvQrmxL7ZnqQtGHGjCNW6CfiwzAif+83Hol9JXAnAB6wh2zsZD7Sc1kWT0O/RRAKt7xfG8W6UZhYBPD+GAA==}+ engines: {node: '>=0.12.18'}+resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}@@ -6258,6 +6602,9 @@ packages:resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==}+resolution: {integrity: sha512-lLYsktklSRKprreOm7NXReW8YiX2VBjbgmXYEziOoGf/qsJqAEACaDvoTtUOycwjpaSh+bT8eu0KrJn7UNxiCg==}@@ -6316,6 +6663,9 @@ packages:resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}+ resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}+resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}engines: {node: '>=8'}@@ -6447,6 +6797,9 @@ packages:resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}hasBin: true+ resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}+resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==}engines: {node: '>=18.12'}@@ -6546,6 +6899,9 @@ packages:resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==}+ resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}+resolution: {integrity: sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==}@@ -6646,6 +7002,11 @@ packages:resolution: {integrity: sha512-IGjKp/o0NL3Bso1PymYURCJxMPNAf/ILOpendP9f5B6e1rTJgdgiOvgfoT8VxCAdY+Wisb9uhGaJJf3yZ2V9nw==}+ resolution: {integrity: sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0+resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}peerDependencies:@@ -6698,6 +7059,12 @@ packages:resolution: {integrity: sha512-sXMwN6DMHeouPfCxkxWkKAmxphWKEenHYY5H1nIBzU3PmDsmJp6kBXJdshjVdpMZuWCmL9SH7KFRx29AylpP6g==}engines: {node: '>=18.12.0'}+ resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==}++ resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}+resolution: {integrity: sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==}engines: {node: ^20.19.0 || >=22.12.0}@@ -6928,6 +7295,21 @@ packages:resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}+ resolution: {integrity: sha512-QFJWJMdlETcI69paJwhSMJz7PPWjVP8Sjhclxmxmxv/RYI7ZOvR5BHX+ktH0we9gTWQMxcne8q1OY8xxz604gw==}+ engines: {node: '>=12.7.0'}+ peerDependencies:+ '@types/react': '>=16.8'+ immer: '>=9.0'+ react: '>=16.8'+ peerDependenciesMeta:+ '@types/react':+ optional: true+ immer:+ optional: true+ react:+ optional: true+resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}@@ -7232,6 +7614,22 @@ snapshots:- '@deepseek-ai/dsh-app-boot'- '@deepseek-ai/dsh-hmr'+ '@deepseek-ai/[email protected](e1828a76db60a945ed06863233e61b8e)':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-agent': 0.2.1-alpha.1(bc8e1a234d16d0329e7a818df1caf030)+ '@deepseek-ai/dsh-brand': 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-llm': 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-scope': 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-session': 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-session-persistence': 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-session-projection': 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))+ '@deepseek-ai/dsh-system-prompt': 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-tools': 0.2.1-alpha.1(6990646b5580becf37a10a1fe3d5469e)+ '@deepseek-ai/dsh-util-values': 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/schemastery': 3.18.5-alpha.1+ zod: 4.4.3+'@deepseek-ai/[email protected](54d3464f7955532d08907e94aa6ef05e)':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])@@ -7371,6 +7769,10 @@ snapshots:dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+'@deepseek-ai/[email protected](@deepseek-ai/[email protected])':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])@@ -7417,6 +7819,10 @@ snapshots:dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+'@deepseek-ai/[email protected](@deepseek-ai/[email protected])':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])@@ -7431,6 +7837,10 @@ snapshots:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])'@deepseek-ai/schemastery': 3.18.5-alpha.1+ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+'@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](bc8e1a234d16d0329e7a818df1caf030))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])@@ -7529,6 +7939,17 @@ snapshots:'@deepseek-ai/schemastery': 3.18.5-alpha.1zod: 4.4.3+ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-brand': 0.2.1-alpha.2(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-timeout': 0.2.1-alpha.2(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-typert-protocol': 0.2.1-alpha.2(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-util-crypto': 0.2.1-alpha.2(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-util-values': 0.2.1-alpha.2(@deepseek-ai/[email protected])+ '@deepseek-ai/schemastery': 3.18.5-alpha.1+ zod: 4.4.3+'@deepseek-ai/[email protected](@deepseek-ai/[email protected])':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])@@ -7675,6 +8096,14 @@ snapshots:'@deepseek-ai/dsh-scope': 0.2.1-alpha.1(@deepseek-ai/[email protected])'@deepseek-ai/dsh-util-values': 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-brand': 0.2.1-alpha.2(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-llm': 0.2.1-alpha.2(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-scope': 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-util-values': 0.2.1-alpha.2(@deepseek-ai/[email protected])+'@deepseek-ai/[email protected](7bb39d3a398590d9618f8116f6a0da69)':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])@@ -7772,6 +8201,10 @@ snapshots:dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+'@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](bc8e1a234d16d0329e7a818df1caf030))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](6990646b5580becf37a10a1fe3d5469e))':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])@@ -7803,6 +8236,11 @@ snapshots:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])'@deepseek-ai/dsh-brand': 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-brand': 0.2.1-alpha.2(@deepseek-ai/[email protected])+'@deepseek-ai/[email protected](@deepseek-ai/[email protected])':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])@@ -7819,10 +8257,30 @@ snapshots:'@deepseek-ai/dsh-system-prompt': 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))'@deepseek-ai/schemastery': 3.18.5-alpha.1+ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](bc8e1a234d16d0329e7a818df1caf030))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))))(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-agent': 0.2.1-alpha.1(bc8e1a234d16d0329e7a818df1caf030)+ '@deepseek-ai/dsh-llm': 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-scope': 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-session': 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))+ '@deepseek-ai/dsh-session-projection': 0.2.1-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected])))+ '@deepseek-ai/dsh-typert-protocol': 0.2.1-alpha.1(@deepseek-ai/[email protected])+ '@deepseek-ai/schemastery': 3.18.5-alpha.1+ zod: 4.4.3++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+'@deepseek-ai/[email protected](@deepseek-ai/[email protected])':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+'@deepseek-ai/[email protected](@deepseek-ai/[email protected])':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])@@ -7831,6 +8289,10 @@ snapshots:dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+'@deepseek-ai/[email protected](@deepseek-ai/[email protected])':dependencies:'@deepseek-ai/cordis': 4.0.5-alpha.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])@@ -8820,6 +9282,46 @@ snapshots:'@rollup/[email protected]':optional: true+ '@shikijs/[email protected]':+ dependencies:+ '@shikijs/primitive': 4.3.1+ '@shikijs/types': 4.3.1+ '@shikijs/vscode-textmate': 10.0.2+ '@types/hast': 3.0.5+ hast-util-to-html: 9.0.5++ '@shikijs/[email protected]':+ dependencies:+ '@shikijs/types': 4.3.1+ '@shikijs/vscode-textmate': 10.0.2+ oniguruma-to-es: 4.3.6++ '@shikijs/[email protected]':+ dependencies:+ '@shikijs/types': 4.3.1+ '@shikijs/vscode-textmate': 10.0.2++ '@shikijs/[email protected]':+ dependencies:+ '@shikijs/types': 4.3.1++ '@shikijs/[email protected]':+ dependencies:+ '@shikijs/types': 4.3.1+ '@shikijs/vscode-textmate': 10.0.2+ '@types/hast': 3.0.5++ '@shikijs/[email protected]':+ dependencies:+ '@shikijs/types': 4.3.1++ '@shikijs/[email protected]':+ dependencies:+ '@shikijs/vscode-textmate': 10.0.2+ '@types/hast': 3.0.5++ '@shikijs/[email protected]': {}+'@sinclair/[email protected]': {}'@sindresorhus/[email protected]': {}@@ -9243,6 +9745,8 @@ snapshots:'@typescript-eslint/types': 8.67.0eslint-visitor-keys: 5.0.1+ '@ungap/[email protected]': {}+'@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@babel/core': 7.29.7@@ -9511,6 +10015,8 @@ snapshots:json-schema-traverse: 1.0.0require-from-string: 2.0.2+ [email protected]: {}+@@ -9786,6 +10292,10 @@ snapshots:transitivePeerDependencies:- magicast+ [email protected]: {}++ [email protected]: {}+@@ -9860,6 +10370,8 @@ snapshots:+ [email protected]: {}+@@ -10049,6 +10561,8 @@ snapshots:+ [email protected]: {}+@@ -10817,6 +11331,24 @@ snapshots:+ dependencies:+ '@types/hast': 3.0.5+ '@types/unist': 3.0.3+ ccount: 2.0.1+ comma-separated-tokens: 2.0.3+ hast-util-whitespace: 3.0.0+ html-void-elements: 3.0.0+ mdast-util-to-hast: 13.2.1+ property-information: 7.2.0+ space-separated-tokens: 2.0.2+ stringify-entities: 4.0.4+ zwitch: 2.0.4++ dependencies:+ '@types/hast': 3.0.5+@@ -10831,6 +11363,8 @@ snapshots:+ [email protected]: {}+@@ -10876,6 +11410,8 @@ snapshots:+ [email protected]: {}+@@ -11344,6 +11880,18 @@ snapshots:'@types/mdast': 4.0.4unist-util-is: 6.0.1+ dependencies:+ '@types/hast': 3.0.5+ '@types/mdast': 4.0.4+ '@ungap/structured-clone': 1.4.0+ devlop: 1.1.0+ micromark-util-sanitize-uri: 2.0.1+ trim-lines: 3.0.1+ unist-util-position: 5.0.0+ unist-util-visit: 5.1.0+ vfile: 6.0.3+dependencies:'@types/mdast': 4.0.4@@ -11750,6 +12298,14 @@ snapshots:dependencies:wrappy: 1.0.2+ [email protected]: {}++ dependencies:+ oniguruma-parser: 0.12.2+ regex: 6.1.0+ regex-recursion: 6.0.2+dependencies:default-browser: 5.5.1@@ -11952,6 +12508,8 @@ snapshots:object-assign: 4.1.1react-is: 16.13.1+ [email protected]: {}+dependencies:agent-base: 7.1.4@@ -12112,6 +12670,16 @@ snapshots:dependencies:'@eslint-community/regexpp': 4.12.2+ dependencies:+ regex-utilities: 2.3.0++ [email protected]: {}++ dependencies:+ regex-utilities: 2.3.0+dependencies:'@eslint-community/regexpp': 4.12.2@@ -12288,10 +12856,23 @@ snapshots:+ dependencies:+ '@shikijs/core': 4.3.1+ '@shikijs/engine-javascript': 4.3.1+ '@shikijs/engine-oniguruma': 4.3.1+ '@shikijs/langs': 4.3.1+ '@shikijs/themes': 4.3.1+ '@shikijs/types': 4.3.1+ '@shikijs/vscode-textmate': 10.0.2+ '@types/hast': 3.0.5++ [email protected]: {}+@@ -12318,6 +12899,8 @@ snapshots:optional: true+ [email protected]: {}+@@ -12382,6 +12965,11 @@ snapshots:dependencies:safe-buffer: 5.2.1+ dependencies:+ character-entities-html4: 2.1.0+ character-entities-legacy: 3.0.0+dependencies:ansi-regex: 5.0.1@@ -12522,6 +13110,8 @@ snapshots:+ [email protected]: {}+dependencies:typescript: 5.8.3@@ -12610,6 +13200,10 @@ snapshots:dependencies:'@types/unist': 3.0.3+ dependencies:+ '@types/unist': 3.0.3+dependencies:'@types/unist': 3.0.3@@ -12663,6 +13257,10 @@ snapshots:+ dependencies:+ react: 19.2.8+dependencies:react: 19.2.8@@ -12706,6 +13304,16 @@ snapshots:+ dependencies:+ '@types/unist': 3.0.3+ unist-util-stringify-position: 4.0.0++ dependencies:+ '@types/unist': 3.0.3+ vfile-message: 4.0.3+[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:esbuild: 0.28.2@@ -12933,4 +13541,12 @@ snapshots:+ dependencies:+ use-sync-external-store: 1.2.0([email protected])+ optionalDependencies:+ '@types/react': 19.2.18+ immer: 10.1.1+ react: 19.2.8+diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex efd84a25..7c349d9f 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -22,11 +22,12 @@ minimumReleaseAgeExclude:- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'+ - '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- - '@deepseek-ai/[email protected]'+ - '@deepseek-ai/[email protected] || 0.2.1-alpha.2'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'@@ -35,26 +36,29 @@ minimumReleaseAgeExclude:- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'+ - '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'+ - '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- - '@deepseek-ai/[email protected]'+ - '@deepseek-ai/[email protected] || 0.2.1-alpha.2'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- - '@deepseek-ai/[email protected]'+ - '@deepseek-ai/[email protected] || 0.2.1-alpha.2'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- - '@deepseek-ai/[email protected]'+ - '@deepseek-ai/[email protected] || 0.2.1-alpha.2'- '@deepseek-ai/[email protected]'- - '@deepseek-ai/[email protected]'+ - '@deepseek-ai/[email protected] || 0.2.1-alpha.2'- '@deepseek-ai/[email protected]'- - '@deepseek-ai/[email protected]'- - '@deepseek-ai/[email protected]'+ - '@deepseek-ai/[email protected]'+ - '@deepseek-ai/[email protected] || 0.2.1-alpha.2'+ - '@deepseek-ai/[email protected] || 0.2.1-alpha.2'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'- '@deepseek-ai/[email protected]'@@ -139,6 +143,7 @@ catalogs:'@deepseek-ai/cordis-plugin-loader': 1.0.6-alpha.1'@deepseek-ai/dsh-agent': 0.2.1-alpha.1'@deepseek-ai/dsh-agent-default-model': 0.2.1-alpha.1+ '@deepseek-ai/dsh-agent-loop': 0.2.1-alpha.1'@deepseek-ai/dsh-agent-preset': 0.2.1-alpha.1'@deepseek-ai/dsh-agent-preset-registry': 0.2.1-alpha.1'@deepseek-ai/dsh-api-session-controller': 0.2.1-alpha.1@@ -150,16 +155,22 @@ catalogs:'@deepseek-ai/dsh-client-ui-layout': 0.2.1-alpha.1'@deepseek-ai/dsh-client-ui-primitives': 0.2.1-alpha.1'@deepseek-ai/dsh-client-ui-renderer': 0.2.1-alpha.1+ '@deepseek-ai/dsh-client-ui-session': 0.2.1-alpha.1'@deepseek-ai/dsh-client-ui-settings': 0.2.1-alpha.1'@deepseek-ai/dsh-client-ui-slots': 0.2.1-alpha.1'@deepseek-ai/dsh-client-ui-theme': 0.2.1-alpha.1+ '@deepseek-ai/dsh-client-ui-workspace': 0.2.1-alpha.1'@deepseek-ai/dsh-host-webserver': 0.2.1-alpha.1'@deepseek-ai/dsh-llm': 0.2.1-alpha.1'@deepseek-ai/dsh-permission-presets': 0.2.1-alpha.1'@deepseek-ai/dsh-session': 0.2.1-alpha.1+ '@deepseek-ai/dsh-session-persistence': 0.2.1-alpha.1+ '@deepseek-ai/dsh-session-projection': 0.2.1-alpha.1'@deepseek-ai/dsh-skill-filesystem': 0.2.1-alpha.1'@deepseek-ai/dsh-tools': 0.2.1-alpha.1'@deepseek-ai/dsh-user-approval': 0.2.1-alpha.1+ '@deepseek-ai/dsh-user-questions': 0.2.1-alpha.1+ '@deepseek-ai/dsh-util-code-language': 0.2.1-alpha.1'@deepseek-ai/dsh-util-values': 0.2.1-alpha.1'@deepseek-ai/dsh-workspace': 0.2.1-alpha.1lint:@@ -191,15 +202,23 @@ catalogs:'@tauri-apps/cli': ^2.11.4'@tauri-apps/plugin-http': ^2.6.0testing:+ '@shikijs/langs': 4.3.1'@testing-library/dom': ^10.4.0'@testing-library/react': ^16.3.0'@vitest/coverage-v8': ^4.1.11'@wdio/tauri-service': ^1.4.0+ anser: 2.3.5+ diff: 9.0.0+ dsh-session-current: npm:@deepseek-ai/[email protected]+ immer: 10.1.1jsdom: ^26.1.0playwright: ^1.63.0+ shiki: 4.3.1+ simple-icons: 16.31.0vitest: ^4.1.11webdriverio: ^9.31.9yaml: ^2.9.0+ zustand: 4.4.7types:'@types/lodash-es': ^4.17.12'@types/node': ^22.10.0@@ -224,4 +243,5 @@ catalogs:ssh2: ^1.17.0unstorage: ^1.17.5+ zod: ^4.4.3trustPolicyIgnoreAfter: 525600diff --git a/src-tauri/resources/manifest.jsonc b/src-tauri/resources/manifest.jsoncindex e44e3956..38a27592 100644--- a/src-tauri/resources/manifest.jsonc+++ b/src-tauri/resources/manifest.jsonc@@ -94,6 +94,12 @@"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-bridge",+ "spec": "dsh-tauri-bridge",+ "name": "DSH Tauri Bridge",+ "repo": "https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-bridge"+ },{"id": "dsh-tauri-worktree","spec": "dsh-tauri-worktree",diff --git a/src-tauri/src/service/cli/shim/build.rs b/src-tauri/src/service/cli/shim/build.rsindex b32398a3..c1002786 100644--- a/src-tauri/src/service/cli/shim/build.rs+++ b/src-tauri/src/service/cli/shim/build.rs@@ -219,12 +219,7 @@ if "%DSH_PREFER_BUNDLED_PNPM%"=="1" (if exist "%PNPM_BIN%" goto :after_user)-rem Re-entry guard: DSH_PNPM, or the first pnpm found on PATH, may itself be a shim-rem that resolves back through PATH into this file; forwarding twice would exec the-rem two shims into each other forever and the installer child would never exit.-rem Armed once here, before either forward, and checked on entry: a re-entered shim-rem goes straight to the bundled pnpm.-if "%DSH_PNPM_SHIM_GUARD%"=="1" goto :after_user+if "%DSH_PNPM_SHIM_GUARD%"=="1" if exist "%PNPM_BIN%" goto :after_userset "DSH_PNPM_SHIM_GUARD=1"rem Use the exact user pnpm discovered by the desktop app.@@ -266,13 +261,33 @@ rem target keeps arguments byte-identical. A batch target transfers control, sorem exit code is ours; a `.exe`/`.com` target returns, and `exit /b %ERRORLEVEL%`rem still forwards its code (issue #130).:use_selected+if exist "%PNPM_BIN%" goto :forward_selected+if defined DSH_PNPM_SHIM_CHAIN goto :append_selected+set "DSH_PNPM_SHIM_CHAIN=1"+goto :forward_selected+:append_selected+if not "%DSH_PNPM_SHIM_CHAIN:~15,1%"=="" goto :reentry_limit+set "DSH_PNPM_SHIM_CHAIN=%DSH_PNPM_SHIM_CHAIN%1"+:forward_selected"%DSH_PNPM%" %*exit /b %ERRORLEVEL%:use_user+if exist "%PNPM_BIN%" goto :forward_user+if defined DSH_PNPM_SHIM_CHAIN goto :append_user+set "DSH_PNPM_SHIM_CHAIN=1"+goto :forward_user+:append_user+if not "%DSH_PNPM_SHIM_CHAIN:~15,1%"=="" goto :reentry_limit+set "DSH_PNPM_SHIM_CHAIN=%DSH_PNPM_SHIM_CHAIN%1"+:forward_user"%USER_PNPM%" %*exit /b %ERRORLEVEL%+:reentry_limit+1>&2 echo [pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls.+exit /b 1+:after_user{node_resolve}:launch@@ -322,17 +337,33 @@ if (-not $systemGitWorks -and $gitDir -and (Test-Path -LiteralPath (Join-Path $g$env:PATH = $gitDir + ';' + $env:PATH}}-$useBundled = $env:DSH_PREFER_BUNDLED_PNPM -eq '1' -and (Test-Path -LiteralPath $pnpmBin -PathType Leaf)+$hasBundled = Test-Path -LiteralPath $pnpmBin -PathType Leaf+$useBundled = $env:DSH_PREFER_BUNDLED_PNPM -eq '1' -and $hasBundled++if (-not $useBundled -and -not ($hasBundled -and $env:DSH_PNPM_SHIM_GUARD -eq '1')) {{+ # The guard must not outlive this call: `$env:` writes are process-wide, so a+ # forwarded pnpm would leave DSH_PNPM_SHIM_GUARD set in the caller's shell and+ # send every later pnpm call straight to the bundled one. The cmd shim is+ # immune through `setlocal`; PowerShell has no equivalent.+ $guardBefore = $env:DSH_PNPM_SHIM_GUARD+ $chainBefore = $env:DSH_PNPM_SHIM_CHAIN-# Re-entry guard: DSH_PNPM, or the first pnpm found on PATH, may itself be a shim-# that resolves back through PATH into this file; forwarding twice would exec the-# two shims into each other forever and the installer child would never exit.-# Once forwarded, skip user resolution and use the bundled pnpm.-if (-not $useBundled -and $env:DSH_PNPM_SHIM_GUARD -ne '1') {{# Use the exact user pnpm discovered by the desktop app.if ($env:DSH_PNPM -and (Test-Path -LiteralPath $env:DSH_PNPM -PathType Leaf)) {{- $env:DSH_PNPM_SHIM_GUARD = '1'- & $env:DSH_PNPM @args+ try {{+ if (-not $hasBundled) {{+ if ($chainBefore.Length -ge 16) {{+ [Console]::Error.WriteLine('[pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls.')+ exit 1+ }}+ $env:DSH_PNPM_SHIM_CHAIN = $chainBefore + '1'+ }}+ $env:DSH_PNPM_SHIM_GUARD = '1'+ & $env:DSH_PNPM @args+ }} finally {{+ $env:DSH_PNPM_SHIM_GUARD = $guardBefore+ $env:DSH_PNPM_SHIM_CHAIN = $chainBefore+ }}exit $LASTEXITCODE}}@@ -342,8 +373,20 @@ if (-not $useBundled -and $env:DSH_PNPM_SHIM_GUARD -ne '1') {{Where-Object {{ $_.Source -and -not $_.Source.StartsWith($selfDir, [System.StringComparison]::OrdinalIgnoreCase) }} |Select-Object -First 1if ($userPnpm) {{- $env:DSH_PNPM_SHIM_GUARD = '1'- & $userPnpm.Source @args+ try {{+ if (-not $hasBundled) {{+ if ($chainBefore.Length -ge 16) {{+ [Console]::Error.WriteLine('[pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls.')+ exit 1+ }}+ $env:DSH_PNPM_SHIM_CHAIN = $chainBefore + '1'+ }}+ $env:DSH_PNPM_SHIM_GUARD = '1'+ & $userPnpm.Source @args+ }} finally {{+ $env:DSH_PNPM_SHIM_GUARD = $guardBefore+ $env:DSH_PNPM_SHIM_CHAIN = $chainBefore+ }}exit $LASTEXITCODE}}}}@@ -385,14 +428,17 @@ if [ "$DSH_PREFER_BUNDLED_PNPM" = "1" ] && [ -f "$PNPM_BIN" ]; thenUSE_BUNDLED=1fi-# Re-entry guard: DSH_PNPM, or the first pnpm found on PATH, may itself be a shim-# that resolves back through PATH into this file (mise shims exec whatever `pnpm`-# PATH resolves to). Forwarding twice would then exec the two shims into each-# other forever, so the installer child never exits and the app hangs with no-# output at all. Once forwarded, skip user resolution and use the bundled pnpm.-if [ -z "$USE_BUNDLED" ] && [ "$DSH_PNPM_SHIM_GUARD" != "1" ]; then+if [ -z "$USE_BUNDLED" ] && ! {{ [ "$DSH_PNPM_SHIM_GUARD" = "1" ] && [ -f "$PNPM_BIN" ]; }}; then# Use the exact user pnpm discovered by the desktop app unless bundled was requested.if [ -n "$DSH_PNPM" ] && [ -x "$DSH_PNPM" ]; then+ if [ ! -f "$PNPM_BIN" ]; then+ if [ "${{#DSH_PNPM_SHIM_CHAIN}}" -ge 16 ]; then+ echo "[pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls." >&2+ exit 1+ fi+ DSH_PNPM_SHIM_CHAIN="${{DSH_PNPM_SHIM_CHAIN}}1"+ export DSH_PNPM_SHIM_CHAIN+ fiDSH_PNPM_SHIM_GUARD=1export DSH_PNPM_SHIM_GUARDexec "$DSH_PNPM" "$@"@@ -406,6 +452,14 @@ if [ -z "$USE_BUNDLED" ] && [ "$DSH_PNPM_SHIM_GUARD" != "1" ]; thencontinuefiif [ -x "$dir/pnpm" ]; then+ if [ ! -f "$PNPM_BIN" ]; then+ if [ "${{#DSH_PNPM_SHIM_CHAIN}}" -ge 16 ]; then+ echo "[pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls." >&2+ exit 1+ fi+ DSH_PNPM_SHIM_CHAIN="${{DSH_PNPM_SHIM_CHAIN}}1"+ export DSH_PNPM_SHIM_CHAIN+ fiDSH_PNPM_SHIM_GUARD=1export DSH_PNPM_SHIM_GUARDexec "$dir/pnpm" "$@"@@ -603,10 +657,10 @@ mod tests {// 应用内部安装可经 DSH_PREFER_BUNDLED_PNPM=1 强制捆绑版(须在用户搜索前生效)assert!(content.contains("DSH_PREFER_BUNDLED_PNPM"));let env_at = content.find("DSH_PREFER_BUNDLED_PNPM").unwrap();- let exact_at = content.find("if defined DSH_PNPM").unwrap();+ let exact_at = content.find("if defined DSH_PNPM (").unwrap();let user_at = content.find("where pnpm").unwrap();assert!(env_at < exact_at && exact_at < user_at);- assert_eq!(content.matches("if defined DSH_PNPM").count(), 1);+ assert_eq!(content.matches("if defined DSH_PNPM (").count(), 1);}/// issue #130:真实执行生成的 cmd shim,确保用户 pnpm 的失败码不会因 cmd@@ -687,6 +741,47 @@ mod tests {let _ = std::fs::remove_dir_all(dir);}+ /// 回归:脚本内嵌套的 pnpm(`pnpm run` 再调 pnpm)会继承上一跳置位的重入+ /// 保护变量。捆绑版缺失时保护无法终止转发链,只有回退用户 pnpm 才对——+ /// 否则 `pnpm dev:desktop` 里的 `pnpm dev:plugins` 直接报 pnpm not found。+ #[cfg(windows)]+ #[test]+ fn pnpm_cmd_shim_keeps_user_fallback_when_guard_set_without_bundle() {+ let dir = temp_dir("pnpm-guard-no-bundle");+ let selected = dir.join("selected pnpm.cmd");+ std::fs::write(+ &selected,+ "@echo off\r\necho SELECTED_PNPM %*\r\nexit /b 37\r\n",+ )+ .unwrap();+ let selected = dunce::canonicalize(&selected).unwrap();+ let shim = dir.join("pnpm.cmd");+ std::fs::write(+ &shim,+ build_pnpm_cmd_shim(&shim_paths_for(&dir.join("app"))),+ )+ .unwrap();+ let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());+ let system32 = PathBuf::from(&system_root).join("System32");+ let output = std::process::Command::new(system32.join("cmd.exe"))+ .args(["/d", "/c"])+ .arg(&shim)+ .arg("probe-guard")+ .env("PATH", &system32)+ .env("SystemRoot", system_root)+ .env("DSH_PNPM", &selected)+ .env("DSH_PNPM_SHIM_GUARD", "1")+ .output()+ .unwrap();+ assert_eq!(output.status.code(), Some(37));+ assert!(+ String::from_utf8_lossy(&output.stdout).contains("SELECTED_PNPM probe-guard"),+ "unexpected stdout: {}",+ String::from_utf8_lossy(&output.stdout)+ );+ let _ = std::fs::remove_dir_all(dir);+ }+/// 两个变量同时存在且捆绑文件可用时,显式的捆绑策略必须优先。#[cfg(windows)]#[test]@@ -811,6 +906,82 @@ mod tests {let _ = std::fs::remove_dir_all(dir);}+ /// 回归:ps1 侧同样禁止在捆绑版缺失时按重入保护直落捆绑版。+ #[cfg(windows)]+ #[test]+ fn pnpm_ps1_shim_keeps_user_fallback_when_guard_set_without_bundle() {+ let dir = temp_dir("pnpm-ps1-guard-no-bundle");+ let selected = dir.join("selected pnpm.cmd");+ std::fs::write(&selected, "@echo off\r\necho SELECTED:%*\r\nexit /b 37\r\n").unwrap();+ let shim = dir.join("pnpm.ps1");+ std::fs::write(+ &shim,+ build_pnpm_ps1_shim(&shim_paths_for(&dir.join("app"))),+ )+ .unwrap();+ let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());+ let powershell =+ PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");+ let output = std::process::Command::new(powershell)+ .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])+ .arg(&shim)+ .arg("probe-guard")+ .env("DSH_PNPM", &selected)+ .env("DSH_PNPM_SHIM_GUARD", "1")+ .output()+ .unwrap();+ assert_eq!(output.status.code(), Some(37));+ assert!(+ String::from_utf8_lossy(&output.stdout).contains("SELECTED:probe-guard"),+ "unexpected stdout: {}",+ String::from_utf8_lossy(&output.stdout)+ );+ let _ = std::fs::remove_dir_all(dir);+ }++ /// 回归:`$env:` 写入是进程级的,转发后必须还原重入保护——否则同一次+ /// PowerShell 会话里后续每个 pnpm 都直落捆绑版,捆绑缺失时误报未安装。+ #[cfg(windows)]+ #[test]+ fn pnpm_ps1_shim_restores_reentry_guard_after_forwarding() {+ let dir = temp_dir("pnpm-ps1-guard-restore");+ let target = dir.join("target.cmd");+ std::fs::write(&target, "@echo off\r\nexit /b 0\r\n").unwrap();+ let shim = dir.join("pnpm.ps1");+ std::fs::write(+ &shim,+ build_pnpm_ps1_shim(&shim_paths_for(&dir.join("app"))),+ )+ .unwrap();+ let driver = dir.join("driver.ps1");+ std::fs::write(+ &driver,+ format!(+ "& '{}' probe\n'GUARD=[' + $env:DSH_PNPM_SHIM_GUARD + ']'\nexit 0\n",+ shim.display()+ ),+ )+ .unwrap();+ let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());+ let powershell =+ PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");+ let run = |guard: Option<&str>| {+ let mut command = std::process::Command::new(&powershell);+ command+ .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])+ .arg(&driver)+ .env("DSH_PNPM", &target)+ .env_remove("DSH_PNPM_SHIM_GUARD");+ if let Some(guard) = guard {+ command.env("DSH_PNPM_SHIM_GUARD", guard);+ }+ String::from_utf8_lossy(&command.output().unwrap().stdout).into_owned()+ };+ assert!(run(None).contains("GUARD=[]"), "guard not dropped");+ assert!(run(Some("0")).contains("GUARD=[0]"), "guard not restored");+ let _ = std::fs::remove_dir_all(dir);+ }+#[test]fn pnpm_sh_shim_contains_user_precedence() {let paths = sample_shim_paths();diff --git a/test/plugin-resource-closure.test.ts b/test/plugin-resource-closure.test.tsindex e26a8c83..607fcaad 100644--- a/test/plugin-resource-closure.test.ts+++ b/test/plugin-resource-closure.test.ts@@ -1,6 +1,7 @@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)@@ -40,6 +41,21 @@ 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/pnpm-shim-chain.test.ts b/test/pnpm-shim-chain.test.tsnew file mode 100644index 00000000..b179755d--- /dev/null+++ b/test/pnpm-shim-chain.test.ts@@ -0,0 +1,373 @@+import type { ChildProcess } from 'node:child_process'+import { spawn, spawnSync } from 'node:child_process'+import { accessSync, chmodSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { basename, dirname, join } from 'node:path'+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++type ShellKind = 'cmd' | 'ps1' | 'sh'+type Forwarding = 'selected' | 'path'++interface Fixture {+ shell: ShellKind+ shim: string+ user: string+ node: string+ bundle: string+ home: string+ env: NodeJS.ProcessEnv+}++interface ShellResult {+ code: number | null+ signal: NodeJS.Signals | null+ stdout: string+ stderr: string+}++const systemRoot = process.env.SystemRoot ?? 'C:\\Windows'+const system32 = join(systemRoot, 'System32')+const powershellRoot = join(system32, 'WindowsPowerShell', 'v1.0')+const programs: Record<ShellKind, string> = {+ cmd: join(system32, 'cmd.exe'),+ ps1: join(powershellRoot, 'powershell.exe'),+ sh: process.platform === 'win32' ? 'C:\\Program Files\\Git\\bin\\sh.exe' : '/bin/sh',+}+const shells: ShellKind[] = process.platform === 'win32' ? ['cmd', 'ps1', 'sh'] : ['sh']+const generatorSource = readFileSync(new URL('../src-tauri/src/service/cli/shim/build.rs', import.meta.url), 'utf8')+const fragmentSource = readFileSync(new URL('../src-tauri/src/service/cli/shim/templates.rs', import.meta.url), 'utf8')+const tempBase = realpathSync(tmpdir())+const owned = new Map<number, ChildProcess>()+let root: string+let runIndex = 0++function shellPath(shell: ShellKind, path: string): string {+ if (shell !== 'sh' || process.platform !== 'win32')+ return path+ return path.replace(/\\/g, '/').replace(/^([a-z]):/i, (_, drive: string) => `/${drive.toLowerCase()}`)+}++function quoteLiteral(shell: ShellKind, path: string): string {+ if (shell === 'cmd')+ return path.replace(/%/g, '%%')+ if (shell === 'ps1')+ return path.replace(/'/g, '\'\'')+ return shellPath(shell, path).replace(/'/g, '\'\\\'\'')+}++function renderShim(shell: ShellKind, fixture: Pick<Fixture, 'node' | 'bundle'>): string {+ const raw = new RegExp(`^pub fn build_pnpm_${shell}_shim\\([^\\n]*\\)[^\\n]*\\{[\\s\\S]*?r#"([\\s\\S]*?)"#,`, 'm').exec(generatorSource)?.[1]+ const nodeResolve = new RegExp(`const ${shell.toUpperCase()}_NODE_RESOLVE: &str = r#"([\\s\\S]*?)"#;`).exec(fragmentSource)?.[1]+ if (raw === undefined || nodeResolve === undefined)+ throw new Error(`The real ${shell} pnpm template or NODE_RESOLVE constant was not found`)+ const values: Record<string, string> = {+ node_bin: quoteLiteral(shell, fixture.node),+ node_dir: quoteLiteral(shell, dirname(fixture.node)),+ git_dir: quoteLiteral(shell, join(root, 'absent bundled git')),+ pnpm_bin: quoteLiteral(shell, fixture.bundle),+ node_resolve: nodeResolve,+ }+ const content = raw.replace(/\{\{|\}\}|\{([a-z_]+)\}/g, (token, key: string | undefined) => {+ if (token === '{{')+ return '{'+ if (token === '}}')+ return '}'+ if (key === undefined || !(key in values))+ throw new Error(`Unexpected Rust format placeholder: ${token}`)+ return values[key]!+ })+ return shell === 'cmd' ? content.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n') : content+}++function writeScript(shell: ShellKind, path: string, content: string): void {+ writeFileSync(path, shell === 'cmd' ? content.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n') : content)+ if (shell === 'sh')+ chmodSync(path, 0o700)+}++function prepare(shell: ShellKind, forwarding: Forwarding, bundled: boolean): Fixture {+ const home = join(root, 'home')+ const shimDir = join(root, 'desktop bin')+ const userDir = join(root, 'user bin')+ const nodeDir = join(root, 'node fixture')+ const bundle = join(root, 'app', 'dependencies', 'pnpm', 'bin', 'pnpm.cjs')+ for (const path of [home, shimDir, userDir, nodeDir, dirname(bundle), join(home, 'AppData', 'Local'), join(home, 'AppData', 'Roaming')])+ mkdirSync(path, { recursive: true })+ const extension = shell === 'cmd' ? '.cmd' : shell === 'ps1' ? '.ps1' : ''+ const shim = join(shimDir, `pnpm${extension}`)+ const user = join(userDir, `pnpm${extension}`)+ const node = join(nodeDir, shell === 'sh' ? 'node' : 'node.cmd')+ writeScript(shell === 'sh' ? 'sh' : 'cmd', node, shell === 'sh'+ ? '#!/bin/sh\nprintf "%s\\n" BUNDLED\nexit 0\n'+ : '@echo off\necho BUNDLED\nexit /b 0\n')+ if (bundled)+ writeFileSync(bundle, 'isolated bundled pnpm fixture\n')+ const path = shell === 'sh'+ ? `${shellPath(shell, shimDir)}:${shellPath(shell, userDir)}:/usr/bin:/bin`+ : `${shimDir};${userDir};${system32};${powershellRoot}`+ const env: NodeJS.ProcessEnv = {+ SystemRoot: systemRoot,+ WINDIR: systemRoot,+ COMSPEC: programs.cmd,+ OS: 'Windows_NT',+ PATHEXT: '.COM;.EXE;.BAT;.CMD',+ PATH: path,+ PSModulePath: join(powershellRoot, 'Modules'),+ HOME: shellPath(shell, home),+ USERPROFILE: home,+ APPDATA: join(home, 'AppData', 'Roaming'),+ LOCALAPPDATA: join(home, 'AppData', 'Local'),+ TMP: root,+ TEMP: root,+ TMPDIR: root,+ LANG: 'C',+ LC_ALL: 'C',+ DSH_E2E_HOME: home,+ DSH_NODE: shellPath(shell, node),+ }+ if (forwarding === 'selected')+ env.DSH_PNPM = shellPath(shell, user)+ const fixture = { shell, shim, user, node, bundle, home, env }+ writeScript(shell, shim, renderShim(shell, fixture))+ return fixture+}++function writeCycle(fixture: Fixture): void {+ const { shell, user } = fixture+ if (shell === 'cmd') {+ writeScript(shell, user, '@echo off\nset /a FIXTURE_HOPS+=1 >nul\necho HOP\nif %FIXTURE_HOPS% GEQ 24 (\n echo FIXTURE_CYCLE_OVERFLOW 1>&2\n exit /b 97\n)\npnpm %*\nexit /b %ERRORLEVEL%\n')+ }+ else if (shell === 'ps1') {+ writeScript(shell, user, '$env:FIXTURE_HOPS = ([int]$env:FIXTURE_HOPS + 1).ToString()\n[Console]::Out.WriteLine("HOP")\nif ([int]$env:FIXTURE_HOPS -ge 24) {\n [Console]::Error.WriteLine("FIXTURE_CYCLE_OVERFLOW")\n exit 97\n}\n& pnpm @args\nexit $LASTEXITCODE\n')+ }+ else {+ writeScript(shell, user, '#!/bin/sh\nFIXTURE_HOPS=$(( FIXTURE_HOPS + 1 ))\nexport FIXTURE_HOPS\nprintf "%s\\n" HOP\nif [ "$FIXTURE_HOPS" -ge 24 ]; then\n printf "%s\\n" FIXTURE_CYCLE_OVERFLOW >&2\n exit 97\nfi\nexec pnpm "$@"\n')+ }+}++function killOwned(child: ChildProcess): void {+ if (child.pid === undefined || !owned.has(child.pid))+ return+ if (child.pid === process.pid)+ throw new Error('Refusing to terminate the test runner')+ if (process.platform === 'win32') {+ const result = spawnSync(join(system32, 'taskkill.exe'), ['/PID', String(child.pid), '/T', '/F'], {+ shell: false,+ windowsHide: true,+ stdio: 'ignore',+ timeout: 5_000,+ })+ if (result.error !== undefined)+ throw result.error+ if (result.status !== 0)+ throw new Error(`Owned fixture process tree ${child.pid} could not be terminated: ${result.status}`)+ }+ else {+ try {+ process.kill(-child.pid, 'SIGKILL')+ }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH')+ throw error+ }+ }+}++async function runShell(fixture: Fixture, script = fixture.shim, arg = 'cycle'): Promise<ShellResult> {+ const { shell, home, env } = fixture+ const stdoutFile = join(root, `stdout-${runIndex}.log`)+ const stderrFile = join(root, `stderr-${runIndex++}.log`)+ const stdoutFd = openSync(stdoutFile, 'w')+ const stderrFd = openSync(stderrFile, 'w')+ const args = shell === 'cmd'+ ? ['/d', '/s', '/c', `""${script}" "${arg}""`]+ : shell === 'ps1'+ ? ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script, arg]+ : [shellPath(shell, script), arg]+ let child: ChildProcess+ try {+ child = spawn(programs[shell], args, {+ cwd: home,+ env,+ shell: false,+ windowsHide: true,+ windowsVerbatimArguments: shell === 'cmd',+ detached: process.platform !== 'win32',+ stdio: ['ignore', stdoutFd, stderrFd],+ })+ }+ finally {+ closeSync(stdoutFd)+ closeSync(stderrFd)+ }+ if (child.pid !== undefined)+ owned.set(child.pid, child)+ return await new Promise<ShellResult>((resolve, reject) => {+ let settled = false+ let stopTimer: ReturnType<typeof setTimeout> | undefined+ let failure: unknown+ const timer = setTimeout(() => {+ if (settled)+ return+ failure = new Error(`${shell} isolated fixture exceeded its 12-second deadline`)+ try {+ if (child.exitCode === null && child.signalCode === null)+ killOwned(child)+ }+ catch (error) {+ failure = error+ }+ stopTimer = setTimeout(() => {+ if (!settled) {+ settled = true+ reject(failure)+ }+ }, 5_000)+ }, 12_000)+ child.once('error', (error) => {+ clearTimeout(timer)+ clearTimeout(stopTimer)+ if (child.pid !== undefined)+ owned.delete(child.pid)+ if (!settled) {+ settled = true+ reject(error)+ }+ })+ child.once('close', (code, signal) => {+ clearTimeout(timer)+ clearTimeout(stopTimer)+ if (child.pid !== undefined)+ owned.delete(child.pid)+ if (settled)+ return+ settled = true+ if (failure !== undefined) {+ reject(failure)+ return+ }+ resolve({+ code,+ signal,+ stdout: readFileSync(stdoutFile, 'utf8').replace(/\r\n/g, '\n'),+ stderr: readFileSync(stderrFile, 'utf8').replace(/\r\n/g, '\n'),+ })+ })+ })+}++beforeAll(() => {+ for (const shell of shells)+ accessSync(programs[shell], constants.X_OK)+ if (process.platform === 'win32')+ accessSync(join(system32, 'taskkill.exe'), constants.X_OK)+})++beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tempBase, 'pnpm-shim-chain-')))+})++afterEach(async () => {+ try {+ for (const child of [...owned.values()]) {+ await new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error('An owned fixture process did not close after termination')), 5_000)+ child.once('close', () => {+ clearTimeout(timer)+ resolve()+ })+ try {+ if (child.exitCode === null && child.signalCode === null)+ killOwned(child)+ }+ catch (error) {+ clearTimeout(timer)+ reject(error)+ }+ })+ }+ expect(owned.size).toBe(0)+ expect(dirname(root)).toBe(tempBase)+ expect(basename(root)).toMatch(/^pnpm-shim-chain-[a-z0-9]+$/i)+ rmSync(root, { recursive: true, force: true })+ }+ finally {+ vi.restoreAllMocks()+ }+})++describe.each(shells)('%s real pnpm forwarding-chain template', (shell) => {+ it.each<Forwarding>(['selected', 'path'])('bounds a no-bundle %s cycle at 16 forwards before the fixture safety stop', async (forwarding) => {+ const fixture = prepare(shell, forwarding, false)+ writeCycle(fixture)+ const result = await runShell(fixture)+ expect(result).toEqual({+ code: 1,+ signal: null,+ stdout: 'HOP\n'.repeat(16),+ stderr: '[pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls.\n',+ })+ }, 25_000)++ it.each<Forwarding>(['selected', 'path'])('escapes a %s cycle through the existing bundle instead of exhausting the chain', async (forwarding) => {+ const fixture = prepare(shell, forwarding, true)+ writeCycle(fixture)+ const result = await runShell(fixture)+ expect(result).toEqual({ code: 0, signal: null, stdout: 'HOP\nBUNDLED\n', stderr: '' })+ }, 25_000)++ it.each<Forwarding>(['selected', 'path'])('allows one %s forward from a 15-character lexical prefix and refuses a 16-character prefix', async (forwarding) => {+ const fixture = prepare(shell, forwarding, false)+ if (shell === 'cmd') {+ writeScript(shell, fixture.user, '@echo off\necho FORWARDED\necho CHAIN=%DSH_PNPM_SHIM_CHAIN%\nexit /b 37\n')+ }+ else if (shell === 'ps1') {+ writeScript(shell, fixture.user, '[Console]::Out.WriteLine(\'FORWARDED\')\n[Console]::Out.WriteLine(\'CHAIN=\' + $env:DSH_PNPM_SHIM_CHAIN)\nexit 37\n')+ }+ else {+ writeScript(shell, fixture.user, '#!/bin/sh\nprintf "%s\\n" FORWARDED\nprintf "CHAIN=%s\\n" "$DSH_PNPM_SHIM_CHAIN"\nexit 37\n')+ }+ fixture.env.DSH_PNPM_SHIM_CHAIN = 'prefix123456789'+ expect(await runShell(fixture)).toEqual({ code: 37, signal: null, stdout: 'FORWARDED\nCHAIN=prefix1234567891\n', stderr: '' })+ fixture.env.DSH_PNPM_SHIM_CHAIN = 'prefix1234567890'+ expect(await runShell(fixture)).toEqual({ code: 1, signal: null, stdout: '', stderr: '[pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls.\n' })+ }, 25_000)++ it('permits an inherited guard to call the same shim and same user pnpm for a genuine nested invocation', async () => {+ const fixture = prepare(shell, 'selected', false)+ fixture.env.DSH_PNPM_SHIM_GUARD = '1'+ if (shell === 'cmd') {+ writeScript(shell, fixture.user, `@echo off\nif "%~1"=="inner" (\n echo INNER\n exit /b 37\n)\necho OUTER\n"${fixture.shim}" inner\nexit /b %ERRORLEVEL%\n`)+ }+ else if (shell === 'ps1') {+ writeScript(shell, fixture.user, `if ($args[0] -eq 'inner') {\n [Console]::Out.WriteLine('INNER')\n exit 37\n}\n[Console]::Out.WriteLine('OUTER')\n& '${quoteLiteral(shell, fixture.shim)}' inner\nexit $LASTEXITCODE\n`)+ }+ else {+ writeScript(shell, fixture.user, `#!/bin/sh\nif [ "$1" = inner ]; then\n printf "%s\\n" INNER\n exit 37\nfi\nprintf "%s\\n" OUTER\nexec '${quoteLiteral(shell, fixture.shim)}' inner\n`)+ }+ const result = await runShell(fixture, fixture.shim, 'outer')+ expect(result).toEqual({ code: 37, signal: null, stdout: 'OUTER\nINNER\n', stderr: '' })+ }, 25_000)+})++if (process.platform === 'win32') {+ describe('powerShell same-process pnpm environment restoration', () => {+ it.each([+ { name: 'unset', guard: undefined, chain: undefined, output: 'FORWARDED\nGUARD=[]\nCHAIN=[]\n' },+ { name: 'custom prefix', guard: 'caller-guard', chain: 'customprefix', output: 'FORWARDED\nGUARD=[caller-guard]\nCHAIN=[customprefix]\n' },+ ])('restores the $name guard and chain after a selected pnpm returns', async ({ guard, chain, output }) => {+ const fixture = prepare('ps1', 'selected', false)+ const target = join(root, 'returning user.cmd')+ writeScript('cmd', target, '@echo off\necho FORWARDED\nexit /b 37\n')+ fixture.env.DSH_PNPM = target+ if (guard !== undefined)+ fixture.env.DSH_PNPM_SHIM_GUARD = guard+ if (chain !== undefined)+ fixture.env.DSH_PNPM_SHIM_CHAIN = chain+ const driver = join(root, 'same-process driver.ps1')+ writeScript('ps1', driver, `& '${quoteLiteral('ps1', fixture.shim)}' probe\n$code = $LASTEXITCODE\n[Console]::Out.WriteLine('GUARD=[' + $env:DSH_PNPM_SHIM_GUARD + ']')\n[Console]::Out.WriteLine('CHAIN=[' + $env:DSH_PNPM_SHIM_CHAIN + ']')\nexit $code\n`)+ const result = await runShell(fixture, driver, 'restore')+ expect(result).toEqual({ code: 37, signal: null, stdout: output, stderr: '' })+ }, 25_000)+ })+}diff --git a/test/session-projection-types.test.ts b/test/session-projection-types.test.tsnew file mode 100644index 00000000..648079c7--- /dev/null+++ b/test/session-projection-types.test.ts@@ -0,0 +1,18 @@+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-bridge/src/shared/native-model'+import type { KernelBinding } from '../packages/dsh-tauri-bridge/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', () => {+ 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>()+ })+})