DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(kernel): 修复原生内核权限同步、审批与工具结果结算 (#1024)
Mao Mrd2354e7319d7
diff --git a/packages/dsh-tauri-kernel/src/host/apply.ts b/packages/dsh-tauri-kernel/src/host/apply.tsindex c3f248b5..5452315b 100644--- a/packages/dsh-tauri-kernel/src/host/apply.ts+++ b/packages/dsh-tauri-kernel/src/host/apply.ts@@ -22,7 +22,9 @@ export function apply(ctx: HostContext, config: Config = {}): void {yield ctx.on('agent/pre-step', adapter.admit, { global: true, prepend: true })yield ctx.on('agent/request', adapter.request, { global: true, prepend: true })yield ctx.on('llm/stream', adapter.capture, { global: true, prepend: true })+ yield ctx.on('tools/pre-execute', sink.admitTool, { global: true, prepend: true })yield ctx.on('tools/execute', sink.executeTool, { global: true, prepend: true })+ yield ctx.on('tools/post-execute', sink.finishTool, { global: true, prepend: true })yield ctx.on('tools/result', sink.acceptTool, { global: true })yield ctx.on('agent/turn-stopping', ({ agent, turn }) => session.finish(agent, turn), { global: true })yield ctx.on('session/event', adapter.end, { global: true })diff --git a/packages/dsh-tauri-kernel/src/host/backends/claude.test.ts b/packages/dsh-tauri-kernel/src/host/backends/claude.test.tsindex fcb07fab..9f413607 100644--- a/packages/dsh-tauri-kernel/src/host/backends/claude.test.ts+++ b/packages/dsh-tauri-kernel/src/host/backends/claude.test.ts@@ -1,5 +1,5 @@import type { Frame } from './process.fixture'-import type { NativeSession, NativeSessionOpenOptions } from './types'+import type { NativeAttachments, NativePermission, NativeSession, NativeSessionOpenOptions } from './types'import { spawn } from 'node:child_process'import { createUserMessage } from '@deepseek-ai/dsh-llm'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -63,12 +63,15 @@ function claudeProcess(options: {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)+async function open(nativeId: string | null = null, sink = createSink(), options?: NativeSessionOpenOptions, attachments?: NativeAttachments) {+ const session = await createClaudeSession(command, 'C:/fixture/workspace', nativeId, sink, new AbortController().signal, options, attachments)sessions.push(session)return session}+/** Official image block; the attachment brand is opaque to this package. */+const image = (attachment: { id: string, mediaType: string, bytes: number }) => createUserMessage({ source: { kind: 'user' }, content: [{ type: 'image', attachment } as never] })+const modelInfo = (value: string, levels: string[] = ['low', 'high']) => ({ value, displayName: `Native ${value}`, description: `${value} description`, supportsEffort: true, supportedEffortLevels: levels })const user = () => createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'inspect the workspace' }] })const result = (fixture: ProcessFixture, id: string, extra: Frame = {}) => fixture.send({ type: 'result', subtype: 'success', is_error: false, session_id: id, result: 'final text, not another assistant message', ...extra })@@ -98,6 +101,9 @@ describe('claude native stream-json control contract', () => {'--include-partial-messages','--permission-prompt-tool','stdio',+ '--allow-dangerously-skip-permissions',+ '--settings',+ '{"useAutoModeDuringPlan":false}',`--session-id=${session.id}`,])expect(spawn).toHaveBeenCalledWith('C:/fixture/claude.exe', args, {@@ -480,20 +486,34 @@ describe('claude native stream-json control contract', () => {])})- 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' })+ it.each(['resume', 'fork'] as const)('clears model and effort flags on an explicit reset after an override following %s', async (mode) => {+ const fixture = claudeProcess({ useSystemInit: true, model: 'persisted-override', models: [modelInfo('chosen')] })const session = await open(mode === 'resume' ? storedId : null, createSink(), mode === 'fork' ? { forkFrom: storedId } : undefined)- const input = fixture.next(frame => frame.type === 'user')- const submitted = session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: null })- await input+ const signal = new AbortController().signal+ const first = fixture.next(frame => frame.type === 'user')+ const inherited = session.submit([user()], signal, { model: null, reasoningEffort: null })+ await firstresult(fixture, session.id)- await submitted+ await inherited+ expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([initialization])+ const changed = fixture.next(frame => frame.type === 'user')+ const override = session.submit([user()], signal, { model: 'chosen', reasoningEffort: 'high' })+ await changed+ result(fixture, session.id)+ await override+ const reset = fixture.next(frame => frame.type === 'user')+ const restored = session.submit([user()], signal, { model: null, reasoningEffort: null })+ await reset+ result(fixture, session.id)+ await restoredexpect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([initialization,+ { subtype: 'set_model', model: 'chosen' },+ { subtype: 'apply_flag_settings', settings: { effortLevel: 'high' } },{ subtype: 'set_model', model: null },{ subtype: 'apply_flag_settings', settings: { effortLevel: null } },])- expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(1)+ expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(3)expect(spawn).toHaveBeenCalledTimes(1)})@@ -623,6 +643,20 @@ describe('claude native stream-json control contract', () => {expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')})+ it.each(['resume', 'fork'] as const)('preserves inherited native settings on the first null preference after %s without model discovery', async (mode) => {+ const fixture = claudeProcess({ useSystemInit: true, model: 'inherited-native-model', intercept: (frame, child) => {+ if (frame.type !== 'user')+ return false+ result(child, String(frame.session_id))+ return true+ } })+ const session = await open(mode === 'resume' ? storedId : null, createSink(), mode === 'fork' ? { forkFrom: storedId } : undefined)+ await session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: null })+ expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([initialization])+ expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(1)+ expect(spawn).toHaveBeenCalledOnce()+ })+it('keeps live and authoritative block identities while suppressing a duplicate final frame', async () => {const fixture = claudeProcess()const sink = createSink()@@ -786,6 +820,129 @@ describe('claude native stream-json control contract', () => {expect(sink.toolEnd.mock.calls).toEqual([['tool-1', 'not a git repository', true]])})+ it.each(['ask', 'never'] as const)('applies native planning and workspace edits with %s approvals on each turn of a resumed session', async (approval) => {+ const fixture = claudeProcess({ intercept: (frame, child) => {+ if (frame.type !== 'user')+ return false+ result(child, String(frame.session_id))+ return true+ } })+ const session = await open(storedId, createSink(), { permission: { sandbox: 'danger-full-access', approval } })+ const signal = new AbortController().signal+ await session.submit([user()], signal)+ await session.submit([user()], signal, undefined, { sandbox: 'read-only', approval })+ await session.submit([user()], signal, undefined, { sandbox: 'workspace-write', approval })+ await session.submit([user()], signal, undefined, { sandbox: 'workspace-write', approval })+ await session.submit([user()], signal, undefined, { sandbox: 'danger-full-access', approval })+ expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([+ initialization,+ initialization,+ { subtype: 'set_permission_mode', mode: approval === 'never' ? 'bypassPermissions' : 'default' },+ { subtype: 'set_permission_mode', mode: 'plan' },+ { subtype: 'set_permission_mode', mode: 'acceptEdits' },+ { subtype: 'set_permission_mode', mode: 'acceptEdits' },+ { subtype: 'set_permission_mode', mode: approval === 'never' ? 'bypassPermissions' : 'default' },+ ])+ expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(5)+ expect(session.id).toBe(storedId)+ expect(spawn).toHaveBeenCalledTimes(1)+ })++ it.each([+ { permission: { sandbox: 'read-only', approval: 'ask' }, tool: 'Write', input: { file_path: 'inside.txt', content: 'unsafe' } },+ { permission: { sandbox: 'read-only', approval: 'ask' }, tool: 'Bash', input: { command: 'touch inside.txt' } },+ { permission: { sandbox: 'read-only', approval: 'ask' }, tool: 'ExitPlanMode', input: {} },+ { permission: { sandbox: 'workspace-write', approval: 'never' }, tool: 'Write', input: { file_path: '../outside.txt', content: 'unsafe' } },+ ] as const)('denies $tool native escalation in $permission.sandbox/$permission.approval without asking', async ({ permission, tool, input }) => {+ const fixture = claudeProcess()+ const sink = createSink()+ sink.approval.mockResolvedValue(true)+ const session = await open(null, sink)+ const entered = fixture.next(frame => frame.type === 'user')+ const submitted = session.submit([user()], new AbortController().signal, undefined, permission)+ await Promise.race([entered, submitted])+ const answered = fixture.next(frame => frame.type === 'control_response')+ fixture.send({ type: 'control_request', request_id: 'restricted-tool', request: { subtype: 'can_use_tool', tool_name: tool, tool_use_id: 'restricted-call', input } })+ expect(await answered).toMatchObject({ response: { request_id: 'restricted-tool', response: { behavior: 'deny' } } })+ expect(sink.approval).not.toHaveBeenCalled()+ result(fixture, session.id)+ await submitted+ })++ it('keeps an approval-only never policy in dontAsk instead of inferring full-access bypass', async () => {+ const fixture = claudeProcess({ intercept: (frame, child) => {+ if (frame.type !== 'user')+ return false+ result(child, String(frame.session_id))+ return true+ } })+ const session = await open()+ await session.submit([user()], new AbortController().signal, undefined, { approval: 'never' })+ expect(fixture.frames.filter(frame => frame.type === 'control_request').map(frame => frame.request)).toEqual([initialization, initialization, { subtype: 'set_permission_mode', mode: 'dontAsk' }])+ })++ it('snapshots explicit permissions and awaits each mode change on the same native session', async () => {+ const fixture = claudeProcess({ intercept: frame => frame.type === 'control_request' && (frame.request as Frame).subtype === 'set_permission_mode' })+ const session = await open(storedId, createSink(), { permission: { sandbox: 'danger-full-access', approval: 'ask' } })+ const permission: NativePermission = { sandbox: 'danger-full-access', approval: 'never' }+ const mode = fixture.next(frame => frame.type === 'control_request' && (frame.request as Frame).subtype === 'set_permission_mode')+ const submitted = session.submit([user()], new AbortController().signal, undefined, permission)+ permission.sandbox = 'read-only'+ permission.approval = 'ask'+ const control = await mode+ expect(control.request).toEqual({ subtype: 'set_permission_mode', mode: 'bypassPermissions' })+ expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)+ const input = fixture.next(frame => frame.type === 'user')+ fixture.send({ type: 'control_response', response: { subtype: 'success', request_id: control.request_id, response: { mode: 'bypassPermissions' } } })+ await input+ result(fixture, session.id)+ await submitted+ const reset = fixture.next(frame => frame.type === 'control_request' && (frame.request as Frame).subtype === 'set_permission_mode')+ const restored = session.submit([user()], new AbortController().signal, undefined, { sandbox: 'danger-full-access', approval: 'ask' })+ const resetControl = await reset+ expect(resetControl.request).toEqual({ subtype: 'set_permission_mode', mode: 'default' })+ expect(fixture.frames.filter(frame => frame.type === 'user')).toHaveLength(1)+ const second = fixture.next(frame => frame.type === 'user')+ fixture.send({ type: 'control_response', response: { subtype: 'success', request_id: resetControl.request_id, response: { mode: 'default' } } })+ await second+ result(fixture, session.id)+ await restored+ expect(session.id).toBe(storedId)+ expect(spawn).toHaveBeenCalledTimes(1)+ })++ it.each(['error', 'mismatched-mode'] as const)('fails closed on a permission control %s without submitting user input', async (outcome) => {+ const fixture = claudeProcess({ intercept: (frame, child) => {+ if (frame.type !== 'control_request' || (frame.request as Frame).subtype !== 'set_permission_mode')+ return false+ child.send({ type: 'control_response', response: outcome === 'error'+ ? { subtype: 'error', request_id: frame.request_id, error: 'Mode denied by native policy' }+ : { subtype: 'success', request_id: frame.request_id, response: { mode: 'bypassPermissions' } } })+ return true+ } })+ const session = await open()+ await expect(session.submit([user()], new AbortController().signal, undefined, { sandbox: 'danger-full-access', approval: 'ask' })).rejects.toMatchObject({ code: outcome === 'error' ? 'BRIDGE_NATIVE_REQUEST' : 'BRIDGE_PERMISSION_MISMATCH' })+ expect(fixture.frames.some(frame => frame.type === 'user')).toBe(false)+ expect(fixture.kill).toHaveBeenCalledWith('SIGTERM')+ })++ it.each([+ { tool: 'Bash', input: { command: 'echo first\necho second', description: 'Inspect environment', dangerouslyDisableSandbox: true }, reason: '\u001B[31mOutside sandbox\u001B[0m', details: 'Outside sandbox\n\nInspect environment\n\ncommand: echo first\necho second\n\ndangerouslyDisableSandbox: true' },+ { tool: 'WebSearch', input: { query: 'Claude protocol', allowed_domains: ['example.org'] }, reason: 'Network permission', details: 'Network permission\n\nquery: Claude protocol\n\nallowed_domains: [\n "example.org"\n]' },+ { tool: 'Write', input: { file_path: '../outside.txt', content: 'full file contents' }, reason: 'External file write', details: 'External file write\n\nfile_path: ../outside.txt\n\ncontent: full file contents' },+ ])('formats $tool approval without hiding input while preserving denial', async ({ tool, input, reason, details }) => {+ const fixture = claudeProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const submitted = session.submit([user()], new AbortController().signal)+ const answered = fixture.next(frame => frame.type === 'control_response')+ fixture.send({ type: 'control_request', request_id: 'readable-permission', request: { subtype: 'can_use_tool', tool_name: tool, tool_use_id: 'readable-tool', input, decision_reason: reason } })+ expect(await answered).toEqual({ type: 'control_response', response: { subtype: 'success', request_id: 'readable-permission', response: { behavior: 'deny', message: 'Native tool request is unavailable or cancelled' } } })+ expect(sink.approval.mock.calls[0]?.[1].details).toBe(details)+ result(fixture, session.id)+ await submitted+ })+it('returns nested permission allow-once with the original native input', async () => {const fixture = claudeProcess()const sink = createSink()@@ -795,17 +952,19 @@ describe('claude native stream-json control contract', () => {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"}}' }])+ expect(sink.approval.mock.calls[0]?.slice(0, 2)).toEqual(['tool-approval', { kind: 'command', title: 'Read repository state', details: 'command: git status' }])result(fixture, session.id)await submitted})- it('maps AskUserQuestion multi-selection back into native updatedInput answers', async () => {+ it.each([undefined, { sandbox: 'read-only', approval: 'ask' }] as const)('maps AskUserQuestion multi-selection back into native updatedInput answers under %j', async (permission) => {const fixture = claudeProcess()const sink = createSink()sink.questions.mockResolvedValue({ 'Which areas?': ['Events', 'Cancel'] })const session = await open(null, sink)- const submitted = session.submit([user()], new AbortController().signal)+ const entered = fixture.next(frame => frame.type === 'user')+ const submitted = session.submit([user()], new AbortController().signal, undefined, permission)+ await Promise.race([entered, submitted])const answered = fixture.next(frame => frame.type === 'control_response')const input = { questions: [{ question: 'Which areas?', header: 'Scope', multiSelect: true, options: [{ label: 'Events', description: 'Logs and UI' }, { label: 'Cancel', description: 'Quiescence' }] }] }fixture.send({ type: 'control_request', request_id: 'questions-1', request: { subtype: 'can_use_tool', tool_name: 'AskUserQuestion', tool_use_id: 'question-tool', input } })@@ -929,6 +1088,40 @@ describe('claude native stream-json control contract', () => {expect(spawn).toHaveBeenCalledTimes(1)})+ it('keeps the official text and image order in one mixed native prompt', async () => {+ const fixture = claudeProcess()+ const attachments: NativeAttachments = { path: () => undefined, read: vi.fn(async () => ({ mediaType: 'image/png', base64: 'Zm FrZQ==' })) }+ const session = await open(null, createSink(), undefined, attachments)+ const mixed = createUserMessage({ source: { kind: 'user' }, content: [+ { type: 'text', text: 'before ' },+ { type: 'image', attachment: { id: 'image-1', mediaType: 'image/png', bytes: 3 } as never },+ { type: 'text', text: ' after' },+ ] })+ const submitted = session.submit([mixed], new AbortController().signal)+ result(fixture, session.id)+ await submitted+ expect(fixture.frames.filter(frame => frame.type === 'user').flatMap(frame => (frame.message as Frame).content as Frame[])).toEqual([+ { type: 'text', text: 'before ' },+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'Zm FrZQ==' } },+ { type: 'text', text: ' after' },+ ])+ })++ it('forwards an official image as an inline base64 content block', async () => {+ const fixture = claudeProcess()+ const attachments: NativeAttachments = { path: () => undefined, read: vi.fn(async () => ({ mediaType: 'image/png', base64: 'Zm FrZQ==' })) }+ const session = await open(null, createSink(), undefined, attachments)+ const submitted = session.submit([user(), image({ id: 'image-1', mediaType: 'image/png', bytes: 3 })], new AbortController().signal)+ result(fixture, session.id)+ await submitted+ expect(fixture.frames.filter(frame => frame.type === 'user')).toEqual([+ { type: 'user', session_id: session.id, uuid: expect.any(String), parent_tool_use_id: null, message: { role: 'user', content: [+ { type: 'text', text: 'inspect the workspace' },+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'Zm FrZQ==' } },+ ] } },+ ])+ })+it('rejects nontext input instead of sending only its text portion', async () => {const fixture = claudeProcess()const session = await open()diff --git a/packages/dsh-tauri-kernel/src/host/backends/claude.ts b/packages/dsh-tauri-kernel/src/host/backends/claude.tsindex 02f9c1b0..f99d82a3 100644--- a/packages/dsh-tauri-kernel/src/host/backends/claude.ts+++ b/packages/dsh-tauri-kernel/src/host/backends/claude.ts@@ -1,9 +1,10 @@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 type { NativeAttachments, NativeCommand, NativeContent, NativeModelCatalog, NativeModelInfo, NativePermission, NativeQuestion, NativeSession, NativeSessionOpenOptions, NativeSink, NativeTurnOptions } from './types'import { randomUUID } from 'node:crypto'+import { stripVTControlCharacters } from 'node:util'import { nativeEnvironment } from '../utils/detection'-import { abortError, deferred, errorFrom, INTERRUPT_TIMEOUT_MS, JsonLinesProcess, NativeBridgeError, PendingRequests, record, REQUEST_TIMEOUT_MS, stringField, textMessages } from './transport'+import { abortError, deferred, errorFrom, INTERRUPT_TIMEOUT_MS, JsonLinesProcess, NativeBridgeError, nativeRuns, PendingRequests, record, REQUEST_TIMEOUT_MS, stringField } from './transport'interface ClaudeBlock {type: string@@ -97,10 +98,12 @@ class ClaudeSession implements NativeSession {private defaultsPending: booleanprivate catalog?: NativeModelCatalogprivate appliedOptions: NativeTurnOptions = { model: null, reasoningEffort: null }+ private permission?: NativePermission- constructor(command: NativeCommand, cwd: string, storedId: string | null, private readonly sink: NativeSink, private readonly options?: NativeSessionOpenOptions) {+ constructor(command: NativeCommand, cwd: string, storedId: string | null, private readonly sink: NativeSink, private readonly options?: NativeSessionOpenOptions, private readonly attachments?: NativeAttachments) {this.nativeId = options?.forkFrom ? '' : storedId ?? randomUUID()this.defaultsPending = storedId !== null || options?.forkFrom !== undefined+ this.permission = options?.permission ? { ...options.permission } : undefinedthis.transport = new JsonLinesProcess({ ...command, env: { ...(command.env ?? nativeEnvironment()), CLAUDE_CODE_SDK_READS_SESSION_STATE: '1' } }, ['--print','--verbose',@@ -111,6 +114,10 @@ class ClaudeSession implements NativeSession {'--include-partial-messages','--permission-prompt-tool','stdio',+ '--allow-dangerously-skip-permissions',+ '--settings',+ '{"useAutoModeDuringPlan":false}',+ ...options?.permission ? ['--permission-mode', 'default'] : [],...options?.forkFrom ? [`--resume=${options.forkFrom}`, '--fork-session'] : [storedId === null ? `--session-id=${this.id}` : `--resume=${this.id}`],], cwd)this.requests = new PendingRequests(value => this.transport.write(value))@@ -211,6 +218,8 @@ class ClaudeSession implements NativeSession {}private async applyOptions(options: NativeTurnOptions, signal: AbortSignal): Promise<void> {+ if (options.model === null && options.reasoningEffort === null && this.appliedOptions.model === null && this.appliedOptions.reasoningEffort === null)+ returnconst modelChanged = this.defaultsPending || options.model !== this.appliedOptions.modelconst effortChanged = this.defaultsPending || options.reasoningEffort !== this.appliedOptions.reasoningEffortif (!modelChanged && !effortChanged)@@ -247,16 +256,35 @@ class ClaudeSession implements NativeSession {}}- async submit(messages: readonly UserMessage[], signal: AbortSignal, options?: NativeTurnOptions): Promise<void> {+ private async applyPermission(permission: NativePermission, signal: AbortSignal): Promise<void> {+ // ponytail: native modes do not isolate preapproved tools or existing tasks; use an OS sandbox for hard boundaries.+ const mode = permission.sandbox === 'read-only'+ ? 'plan'+ : permission.sandbox === 'workspace-write'+ ? 'acceptEdits'+ : permission.approval === 'never' ? permission.sandbox === 'danger-full-access' ? 'bypassPermissions' : 'dontAsk' : 'default'+ try {+ const response = record(await this.control({ subtype: 'set_permission_mode', mode }, signal))+ if (response.mode !== undefined && response.mode !== mode)+ throw new NativeBridgeError('BRIDGE_PERMISSION_MISMATCH', 'Claude 未确认请求的权限模式,已阻止本轮运行。')+ }+ catch (error) {+ this.transport.fail(errorFrom(error))+ throw error+ }+ }++ async submit(messages: readonly UserMessage[], signal: AbortSignal, options?: NativeTurnOptions, permission?: NativePermission): Promise<void> {signal.throwIfAborted()if (this.disposed || this.failure)throw this.failure ?? new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Claude session was disposed')if (this.active)throw new NativeBridgeError('BRIDGE_BUSY', 'Claude native session already has an active run')- const texts = textMessages(messages)- if (texts.length === 0)+ const runs = nativeRuns(messages, this.attachments)+ if (runs.length === 0)throw new NativeBridgeError('BRIDGE_EMPTY_INPUT', 'Claude native run requires a user message')const selection = options ? { ...options } : undefined+ const policy = permission ? { ...permission } : this.permissionconst run: ClaudeRun = {result: deferred<void>(),signal,@@ -281,16 +309,32 @@ class ClaudeSession implements NativeSession {}signal.addEventListener('abort', aborted, { once: true })try {+ if (policy) {+ await this.applyPermission(policy, signal)+ this.permission = policy+ }if (selection && (this.defaultsPending || selection.model !== this.appliedOptions.model || selection.reasoningEffort !== this.appliedOptions.reasoningEffort))await this.applyOptions(selection, signal)signal.throwIfAborted()+ const content: Record<string, unknown>[] = []+ for (const run of runs.flat()) {+ if (run.type === 'text') {+ content.push({ type: 'text', text: run.text })+ continue+ }+ const source = await this.attachments!.read(run.ref, signal)+ if (source.base64 === undefined)+ throw new NativeBridgeError('BRIDGE_PROTOCOL', 'The official attachment store returned no readable image bytes')+ content.push({ type: 'image', source: { type: 'base64', media_type: source.mediaType, data: source.base64 } })+ }+ signal.throwIfAborted()run.submitted = truethis.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 })) },+ message: { role: 'user', content },})await run.result.promisesignal.throwIfAborted()@@ -661,11 +705,18 @@ class ClaudeSession implements NativeSession {if (!signal.aborted)response = { behavior: 'allow', updatedInput: { ...input, answers } }}- else {+ else if (this.permission?.sandbox === 'read-only') {+ response = { behavior: 'deny', message: '当前会话为只读;请先在权限菜单切换模式。' }+ }+ else if (this.permission?.approval !== 'never') {const allowed = await this.sink.approval(callId, {kind: tool === 'Bash' ? 'command' : ['Write', 'Edit', 'MultiEdit', 'NotebookEdit'].includes(tool) ? 'file' : 'tool',title: typeof request.title === 'string' ? request.title : tool,- details: JSON.stringify({ tool, input, ...typeof request.description === 'string' ? { description: request.description } : {} }),+ details: stripVTControlCharacters([+ ...new Set([request.decision_reason, request.description, input.description].filter((value): value is string => typeof value === 'string' && value !== '')),+ ...typeof request.blocked_path === 'string' ? [`blocked_path: ${request.blocked_path}`] : [],+ ...Object.entries(input).filter(([key, value]) => key !== 'description' || typeof value !== 'string').map(([key, value]) => `${key}: ${typeof value === 'string' ? value : JSON.stringify(value, null, 2)}`),+ ].join('\n\n')),}, signal)if (allowed && !signal.aborted)response = { behavior: 'allow', updatedInput: input }@@ -690,10 +741,10 @@ class ClaudeSession implements NativeSession {}}-export async function createClaudeSession(command: NativeCommand, cwd: string, nativeSessionId: string | null, sink: NativeSink, signal: AbortSignal, options?: NativeSessionOpenOptions): Promise<NativeSession> {+export async function createClaudeSession(command: NativeCommand, cwd: string, nativeSessionId: string | null, sink: NativeSink, signal: AbortSignal, options?: NativeSessionOpenOptions, attachments?: NativeAttachments): Promise<NativeSession> {if (options?.forkFrom !== undefined && (nativeSessionId !== null || options.forkFrom === ''))throw new NativeBridgeError('BRIDGE_FORK_INVALID', 'Claude fork requires a source session and no existing native binding')- const session = new ClaudeSession(command, cwd, nativeSessionId, sink, options)+ const session = new ClaudeSession(command, cwd, nativeSessionId, sink, options, attachments)await session.open(signal)return session}diff --git a/packages/dsh-tauri-kernel/src/host/backends/codex.test.ts b/packages/dsh-tauri-kernel/src/host/backends/codex.test.tsindex 79925c7d..9cb86697 100644--- a/packages/dsh-tauri-kernel/src/host/backends/codex.test.ts+++ b/packages/dsh-tauri-kernel/src/host/backends/codex.test.ts@@ -1,5 +1,5 @@import type { Frame } from './process.fixture'-import type { NativeSession, NativeSessionOpenOptions } from './types'+import type { NativeAttachments, NativePermission, NativeSession, NativeSessionOpenOptions } from './types'import { spawn } from 'node:child_process'import { createUserMessage } from '@deepseek-ai/dsh-llm'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -80,12 +80,15 @@ function codexProcess(options: {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)+async function open(storedId: string | null = null, sink = createSink(), options?: NativeSessionOpenOptions, attachments?: NativeAttachments) {+ const session = await createCodexSession(command, 'C:/fixture/workspace', storedId, sink, new AbortController().signal, options, attachments)sessions.push(session)return session}+/** Official image block; the attachment brand is opaque to this package. */+const image = (attachment: { id: string, mediaType: string, bytes: number }) => createUserMessage({ source: { kind: 'user' }, content: [{ type: 'image', attachment } as never] })+const modelInfo = (id: string, levels: string[] = ['low', 'high'], defaultEffort = 'low') => ({ id: `catalog:${id}`, model: id, displayName: `Native ${id}`, description: `${id} description`, supportedReasoningEfforts: levels.map(reasoningEffort => ({ reasoningEffort, description: `${reasoningEffort} reasoning` })), defaultReasoningEffort: defaultEffort, isDefault: false })const user = () => createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'inspect the workspace' }] })const completed = (fixture: ProcessFixture, status = 'completed') => fixture.send({ method: 'turn/completed', params: { threadId: 'thread-1', turn: { id: 'turn-1', status } } })@@ -115,6 +118,90 @@ describe('codex native app-server contract', () => {expect(fixture.frames[2]).toEqual({ id: 2, method: 'thread/start', params: { cwd: 'C:/fixture/workspace' } })})+ describe.each(['start', 'resume', 'fork'] as const)('thread/%s permissions', (mode) => {+ it.each((['read-only', 'workspace-write', 'danger-full-access'] as const).flatMap(sandbox => (['ask', 'never'] as const).map(approval => ({ sandbox, approval }))))('sends SandboxMode $sandbox and approval $approval on the native wire', async (permission) => {+ const { fixture } = codexProcess()+ await open(mode === 'resume' ? 'thread-1' : null, createSink(), { ...mode === 'fork' ? { forkFrom: 'source-thread' } : {}, permission })+ expect(fixture.frames[2]).toEqual({ id: 2, method: `thread/${mode}`, params: {+ ...mode === 'start' ? {} : { threadId: mode === 'resume' ? 'thread-1' : 'source-thread' },+ cwd: 'C:/fixture/workspace',+ approvalPolicy: permission.approval === 'ask' ? 'on-request' : 'never',+ sandbox: permission.sandbox,+ } })+ })+ })++ it.each(['start', 'resume', 'fork'] as const)('applies each permission switch to the next turn of the cached %s thread', async (mode) => {+ const { fixture } = codexProcess()+ const session = await open(mode === 'resume' ? 'thread-1' : null, createSink(), { ...mode === 'fork' ? { forkFrom: 'source-thread' } : {}, permission: { sandbox: 'read-only', approval: 'ask' } })+ const permissions: { permission: NativePermission, approvalPolicy: string, sandboxPolicy: Frame }[] = [+ { permission: { sandbox: 'read-only', approval: 'ask' }, approvalPolicy: 'on-request', sandboxPolicy: { type: 'readOnly', networkAccess: false } },+ { permission: { sandbox: 'danger-full-access', approval: 'never' }, approvalPolicy: 'never', sandboxPolicy: { type: 'dangerFullAccess' } },+ { permission: { sandbox: 'danger-full-access', approval: 'ask' }, approvalPolicy: 'on-request', sandboxPolicy: { type: 'dangerFullAccess' } },+ { permission: { sandbox: 'workspace-write', approval: 'never' }, approvalPolicy: 'never', sandboxPolicy: { type: 'workspaceWrite', writableRoots: ['C:/fixture/workspace'], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: false } },+ { permission: { sandbox: 'workspace-write', approval: 'ask' }, approvalPolicy: 'on-request', sandboxPolicy: { type: 'workspaceWrite', writableRoots: ['C:/fixture/workspace'], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: false } },+ { permission: { sandbox: 'read-only', approval: 'never' }, approvalPolicy: 'never', sandboxPolicy: { type: 'readOnly', networkAccess: false } },+ ]+ for (const { permission, approvalPolicy, sandboxPolicy } of permissions) {+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal, undefined, permission)+ const request = await started+ completed(fixture)+ await submitted+ expect(request.params).toEqual({ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }], approvalPolicy, sandboxPolicy })+ }+ expect(fixture.frames.filter(frame => frame.method === `thread/${mode}`)).toHaveLength(1)+ expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(permissions.length)+ expect(spawn).toHaveBeenCalledOnce()+ expect(session.id).toBe('thread-1')+ })++ it.each([+ { permission: { approval: 'never' } as NativePermission, policy: { approvalPolicy: 'never' } },+ { permission: { sandbox: 'read-only' } as NativePermission, policy: { sandboxPolicy: { type: 'readOnly', networkAccess: false } } },+ ])('leaves missing permission fields to the native defaults: $permission', async ({ permission, policy }) => {+ const { fixture } = codexProcess()+ const session = await open(null, createSink(), { permission })+ expect(fixture.frames[2]?.params).toEqual({ cwd: 'C:/fixture/workspace', ...permission.approval ? { approvalPolicy: 'never' } : {}, ...permission.sandbox ? { sandbox: 'read-only' } : {} })+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal, undefined, permission)+ const request = await started+ completed(fixture)+ await submitted+ expect(request.params).toEqual({ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }], ...policy })+ })++ it('snapshots permission before waiting for native turn preparation', async () => {+ const { fixture } = codexProcess()+ const session = await open()+ const permission: NativePermission = { sandbox: 'danger-full-access', approval: 'never' }+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal, undefined, permission)+ permission.sandbox = 'read-only'+ permission.approval = 'ask'+ const request = await started+ completed(fixture)+ await submitted+ expect(request.params).toEqual({ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }], approvalPolicy: 'never', sandboxPolicy: { type: 'dangerFullAccess' } })+ })++ it('never autoapproves a native request under never plus read-only', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const permission: NativePermission = { sandbox: 'read-only', approval: 'never' }+ const session = await open(null, sink, { permission })+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal, undefined, permission)+ await started+ const answered = fixture.next(frame => frame.id === 'readonly-approval')+ fixture.send({ id: 'readonly-approval', method: 'item/commandExecution/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'write-outside', command: 'write outside workspace' } })+ const response = await answered+ completed(fixture)+ await submitted+ expect(response).toEqual({ id: 'readonly-approval', result: { decision: 'decline' } })+ expect(sink.approval).toHaveBeenCalledOnce()+ })+it('resumes exactly the stored native thread without starting a replacement', async () => {const { fixture } = codexProcess({ threadId: 'stored-thread' })const session = await open('stored-thread')@@ -561,7 +648,7 @@ describe('codex native app-server contract', () => {await restored})- it.each(['resume', 'fork'] as const)('restores thread-agnostic defaults on the first null selection after %s', async (mode) => {+ it.each(['resume', 'fork'] as const)('restores thread-agnostic defaults after an explicit override and reset following %s', async (mode) => {const { fixture } = codexProcess({model: 'persisted-override',reasoningEffort: 'high',@@ -569,19 +656,29 @@ describe('codex native app-server contract', () => {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+ const signal = new AbortController().signal+ const first = fixture.next(frame => frame.method === 'turn/start')+ const inherited = session.submit([user()], signal, { model: null, reasoningEffort: null })+ expect((await first).params).toEqual({ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }] })completed(fixture)- await 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)+ await inherited+ const changed = fixture.next(frame => frame.method === 'turn/start')+ const override = session.submit([user()], signal, { model: 'persisted-override', reasoningEffort: 'high' })+ expect((await changed).params).toMatchObject({ model: 'persisted-override', effort: 'high' })+ completed(fixture)+ await override+ const reset = fixture.next(frame => frame.method === 'turn/start')+ const restored = session.submit([user()], signal, { model: null, reasoningEffort: null })+ expect((await reset).params).toMatchObject({ threadId: 'thread-1', model: 'cli-default', effort: 'low' })+ completed(fixture)+ await restored+ expect((await session.models!(signal)).defaultModel).toBe('cli-default')+ expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(3)expect(fixture.frames.some(frame => frame.method === 'thread/start')).toBe(false)expect(session.id).toBe('thread-1')})- it('refuses an unknown resumed CLI default instead of using the persisted acknowledgement or catalog default', async () => {+ it('refuses an explicit reset to an unknown resumed CLI default instead of guessing from the catalog', async () => {const { fixture } = codexProcess({model: 'persisted-override',reasoningEffort: 'high',@@ -595,12 +692,14 @@ describe('codex native app-server contract', () => {},})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)+ const signal = new AbortController().signal+ expect((await session.models!(signal)).defaultModel).toBeUndefined()+ await session.submit([user()], signal, { model: 'catalog-default', reasoningEffort: 'high' })+ await expect(session.submit([user()], signal, { model: null, reasoningEffort: null })).rejects.toMatchObject({ code: 'BRIDGE_DEFAULT_UNAVAILABLE' })+ expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)})- it('refuses a resumed effort reset when only the persisted override is known', async () => {+ it('refuses an explicit resumed effort reset when only the persisted override is known', async () => {const { fixture } = codexProcess({model: 'persisted-override',reasoningEffort: 'high',@@ -615,8 +714,10 @@ describe('codex native app-server contract', () => {},})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)+ const signal = new AbortController().signal+ await session.submit([user()], signal, { model: 'persisted-override', reasoningEffort: 'high' })+ await expect(session.submit([user()], signal, { model: null, reasoningEffort: null })).rejects.toMatchObject({ code: 'BRIDGE_DEFAULT_UNAVAILABLE' })+ expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)expect(session.id).toBe('thread-1')})@@ -663,6 +764,79 @@ describe('codex native app-server contract', () => {expect(fixture.frames.some(frame => frame.method === 'turn/start' || frame.method === 'turn/interrupt')).toBe(false)})+ it('records function-call outputs without inventing another native execution', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ const item = { id: 'function-output', type: 'functionCallOutput', name: 'read_file', namespace: 'functions', output: [{ type: 'input_text', text: 'native text' }, { type: 'input_image', image_url: 'data:image/png;base64,fixture' }] }+ notify(fixture, 'item/completed', { item })+ notify(fixture, 'item/completed', { item })+ completed(fixture)+ await submitted+ expect(sink.assistant.mock.calls).toEqual([['function-output', [{ type: 'text', text: '{"id":"function-output","type":"functionCallOutput","name":"read_file","namespace":"functions","output":[{"type":"input_text","text":"native text"},{"type":"input_image","image_url":"data:image/png;base64,fixture"}]}' }]]])+ expect(sink.toolStart).not.toHaveBeenCalled()+ expect(sink.toolEnd).not.toHaveBeenCalled()+ expect(fixture.frames.some(frame => frame.method === 'turn/interrupt')).toBe(false)+ expect(fixture.kill).not.toHaveBeenCalled()+ })++ it('rejects a malformed completed item instead of treating it as an unknown read-only event', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ const rejected = expect(submitted).rejects.toMatchObject({ code: 'BRIDGE_PROTOCOL', message: 'Missing native protocol field: type' })+ await started+ notify(fixture, 'item/completed', { item: { id: 'malformed-native-item', text: 'missing type' } })+ completed(fixture)+ await rejected+ expect(sink.assistant).not.toHaveBeenCalled()+ expect(sink.toolStart).not.toHaveBeenCalled()+ })++ it('records unrecognized completed native items without terminating the native turn', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ notify(fixture, 'item/completed', { item: { id: 'future-native-item', type: 'futureNativeItem', details: { text: 'native event', count: 2 } } })+ completed(fixture)+ await submitted+ expect(sink.assistant.mock.calls).toEqual([['future-native-item', [{ type: 'text', text: '{"id":"future-native-item","type":"futureNativeItem","details":{"text":"native event","count":2}}' }]]])+ expect(sink.toolStart).not.toHaveBeenCalled()+ expect(sink.toolEnd).not.toHaveBeenCalled()+ expect(fixture.kill).not.toHaveBeenCalled()+ })++ it.each(['resume', 'fork'] as const)('preserves inherited native settings on the first null preference after %s without model discovery', async (mode) => {+ const { fixture } = codexProcess({+ model: 'inherited-native-model',+ reasoningEffort: 'high',+ intercept: (frame, child) => {+ if (frame.method === 'config/read' || frame.method === 'model/list') {+ child.send({ id: frame.id, error: { code: -32601, message: 'Native catalog is unavailable' } })+ return true+ }+ if (frame.method !== 'turn/start')+ return false+ child.send({ id: frame.id, result: { turn: { id: 'turn-1' } } })+ completed(child)+ return true+ },+ })+ const session = await open(mode === 'resume' ? 'thread-1' : null, createSink(), mode === 'fork' ? { forkFrom: 'source-thread' } : undefined)+ await session.submit([user()], new AbortController().signal, { model: null, reasoningEffort: null })+ expect(fixture.frames.filter(frame => frame.method === 'turn/start').map(frame => frame.params)).toEqual([{ threadId: 'thread-1', input: [{ type: 'text', text: 'inspect the workspace', text_elements: [] }] }])+ expect(fixture.frames.some(frame => frame.method === 'config/read' || frame.method === 'model/list')).toBe(false)+ expect(spawn).toHaveBeenCalledOnce()+ })+it('commits authoritative assistant content once after live text and reasoning deltas', async () => {const { fixture } = codexProcess()const sink = createSink()@@ -725,6 +899,170 @@ describe('codex native app-server contract', () => {expect(sink.toolEnd.mock.calls).toEqual([['command-1', 'fatal: not a git repository', true]])})+ it.each(['completed', 'failed'])('preserves a native Node REPL MCP text-image-text result with status %s exactly once', async (status) => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ const item = { id: 'node-repl-image', type: 'mcpToolCall', server: 'node_repl', tool: 'js', arguments: { code: 'await nodeRepl.emitImage(image)' }, status: 'inProgress', result: null, error: null }+ const result = { content: [+ { type: 'text', text: 'before image' },+ { type: 'image', data: 'cG5nLWZpeHR1cmU=', mimeType: 'image/png' },+ { type: 'text', text: 'after image' },+ ], isError: status === 'failed' }+ notify(fixture, 'item/started', { item })+ notify(fixture, 'item/completed', { item: { ...item, status, result } })+ notify(fixture, 'item/completed', { item: { ...item, status, result } })+ completed(fixture)+ await submitted+ const arguments_ = '{"code":"await nodeRepl.emitImage(image)"}'+ expect(sink.assistant.mock.calls).toEqual([['node-repl-image:call', [{ type: 'tool-call', id: 'node-repl-image', name: 'mcp::node_repl/js', arguments: arguments_ }]]])+ expect(sink.toolStart.mock.calls).toEqual([['node-repl-image', 'mcp::node_repl/js', arguments_]])+ expect(sink.toolEnd.mock.calls).toEqual([['node-repl-image', `{"content":[{"type":"text","text":"before image"},{"type":"image","data":"cG5nLWZpeHR1cmU=","mimeType":"image/png"},{"type":"text","text":"after image"}],"isError":${status === 'failed' ? 'true' : 'false'}}`, status === 'failed']])+ expect(fixture.frames.filter(frame => frame.method === 'turn/start')).toHaveLength(1)+ })++ it.each(['completed', 'failed', 'declined'])('settles an announced file change from native turn items with terminal status %s', async (status) => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal, undefined, { sandbox: 'workspace-write', approval: 'ask' })+ await started+ const item = { id: 'edit-terminal', type: 'fileChange', status: 'inProgress', changes: [+ { path: 'C:/fixture/workspace/probe.svg', kind: { type: 'add' }, diff: '<svg>probe</svg>\n' },+ { path: 'C:/fixture/workspace/probe.txt', kind: { type: 'add' }, diff: 'native-capability-probe\n' },+ ] }+ notify(fixture, 'item/started', { item })+ notify(fixture, 'item/started', { item })+ fixture.send({ method: 'turn/completed', params: { threadId: 'thread-1', turn: { id: 'turn-1', status: 'completed', items: [+ { ...item, status },+ { id: 'unannounced-history', type: 'fileChange', status: 'completed', changes: [] },+ ], itemsView: 'full' } } })+ await submitted+ expect(sink.toolStart).toHaveBeenCalledOnce()+ expect(sink.toolStart.mock.calls[0]?.slice(0, 2)).toEqual(['edit-terminal', 'fileChange'])+ expect(sink.toolEnd.mock.calls).toEqual([['edit-terminal', '[{"path":"C:/fixture/workspace/probe.svg","kind":{"type":"add"},"diff":"<svg>probe</svg>\\n"},{"path":"C:/fixture/workspace/probe.txt","kind":{"type":"add"},"diff":"native-capability-probe\\n"}]', status !== 'completed']])+ expect(sink.assistant).toHaveBeenCalledOnce()+ })++ it.each(['inProgress', 'unknown', undefined])('does not invent a file-change result from nonterminal turn items with status %s', async (status) => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ const item = { id: 'edit-unsettled', type: 'fileChange', changes: [], status }+ notify(fixture, 'item/started', { item })+ fixture.send({ method: 'turn/completed', params: { threadId: 'thread-1', turn: { id: 'turn-1', status: 'completed', items: [item], itemsView: 'summary' } } })+ await submitted+ expect(sink.toolStart).toHaveBeenCalledExactlyOnceWith('edit-unsettled', 'fileChange', '{"changes":[]}')+ expect(sink.toolEnd).not.toHaveBeenCalled()+ })++ it.each(['completed', 'failed', 'declined', undefined])('settles a completed file-change notification once with status %s', async (status) => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ const item = { id: 'edit-completed', type: 'fileChange', changes: [], status }+ notify(fixture, 'item/started', { item: { ...item, status: 'inProgress' } })+ notify(fixture, 'item/completed', { item })+ notify(fixture, 'item/completed', { item })+ fixture.send({ method: 'turn/completed', params: { threadId: 'thread-1', turn: { id: 'turn-1', status: 'completed', items: [{ ...item, status: 'failed' }], itemsView: 'full' } } })+ await submitted+ expect(sink.toolStart).toHaveBeenCalledOnce()+ expect(sink.toolEnd.mock.calls).toEqual([['edit-completed', '[]', status === 'failed' || status === 'declined']])+ expect(sink.assistant).toHaveBeenCalledOnce()+ })++ it('leaves an announced file change unsettled when the native turn contains no result', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ notify(fixture, 'item/started', { item: { id: 'edit-missing', type: 'fileChange', changes: [], status: 'inProgress' } })+ completed(fixture)+ await submitted+ expect(sink.toolStart).toHaveBeenCalledExactlyOnceWith('edit-missing', 'fileChange', '{"changes":[]}')+ expect(sink.toolEnd).not.toHaveBeenCalled()+ })++ it.each(['thread', 'turn'])('ignores terminal file-change items from another native %s', async (scope) => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ const item = { id: 'edit-current', type: 'fileChange', changes: [], status: 'inProgress' }+ notify(fixture, 'item/started', { item })+ fixture.send({ method: 'turn/completed', params: { threadId: scope === 'thread' ? 'other-thread' : 'thread-1', turn: { id: scope === 'turn' ? 'other-turn' : 'turn-1', status: 'completed', items: [{ ...item, status: 'completed' }], itemsView: 'full' } } })+ completed(fixture)+ await submitted+ expect(sink.toolStart).toHaveBeenCalledOnce()+ expect(sink.toolEnd).not.toHaveBeenCalled()+ })++ it.each([true, false])('settles a native file change after approval returns %s without substituting the decision for a result', async (allowed) => {+ const { fixture } = codexProcess()+ const sink = createSink()+ sink.approval.mockResolvedValue(allowed)+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ const item = { id: 'edit-approval', type: 'fileChange', changes: [], status: 'inProgress' }+ notify(fixture, 'item/started', { item })+ const answered = fixture.next(frame => frame.id === 'patch-approval')+ fixture.send({ id: 'patch-approval', method: 'item/fileChange/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'edit-approval' } })+ expect(await answered).toEqual({ id: 'patch-approval', result: { decision: allowed ? 'accept' : 'decline' } })+ expect(sink.toolEnd).not.toHaveBeenCalled()+ notify(fixture, 'item/completed', { item: { ...item, status: allowed ? 'completed' : 'declined' } })+ completed(fixture)+ await submitted+ expect(sink.toolEnd.mock.calls).toEqual([['edit-approval', '[]', !allowed]])+ })++ it('does not present a streamed patch preview as a completed native file change', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ notify(fixture, 'item/fileChange/patchUpdated', { itemId: 'edit-preview', changes: [{ path: 'C:/fixture/workspace/probe.txt', kind: { type: 'add' }, diff: 'partial patch' }] })+ completed(fixture)+ await submitted+ expect(sink.assistant).not.toHaveBeenCalled()+ expect(sink.toolStart).not.toHaveBeenCalled()+ expect(sink.toolEnd).not.toHaveBeenCalled()+ })++ it('preserves native file-change output deltas on a failed completion', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ const item = { id: 'edit-denied', type: 'fileChange', status: 'inProgress', changes: [{ path: 'C:/fixture/workspace/probe.txt', kind: { type: 'delete' }, diff: 'probe\n' }] }+ notify(fixture, 'item/started', { item })+ notify(fixture, 'item/fileChange/outputDelta', { itemId: 'edit-denied', delta: 'AccessDenied: ' })+ notify(fixture, 'item/fileChange/outputDelta', { itemId: 'edit-denied', delta: 'delete denied by sandbox\n' })+ notify(fixture, 'item/completed', { item: { ...item, status: 'failed' } })+ completed(fixture)+ await submitted+ expect(sink.toolEnd.mock.calls).toEqual([['edit-denied', 'AccessDenied: delete denied by sandbox\n', true]])+ })+it.each(['item/started', 'item/completed'] as const)('presents each tool before starting it when the first native notification is %s', async (first) => {const { fixture } = codexProcess()const sink = createSink()@@ -777,6 +1115,24 @@ describe('codex native app-server contract', () => {expect(fixture.kill).not.toHaveBeenCalled()})+ it('rejects unknown native server requests instead of granting or executing them', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ const answered = fixture.next(frame => frame.id === 'unknown-control')+ fixture.send({ id: 'unknown-control', method: 'futureNative/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'future-tool' } })+ expect(await answered).toEqual({ id: 'unknown-control', error: { code: -32601, message: 'Unsupported native server request: futureNative/requestApproval' } })+ expect(sink.approval).not.toHaveBeenCalled()+ expect(sink.questions).not.toHaveBeenCalled()+ expect(sink.toolStart).not.toHaveBeenCalled()+ completed(fixture)+ await submitted+ expect(fixture.kill).not.toHaveBeenCalled()+ })+it('routes a parked approval while RPC traffic continues and returns only allow-once', async () => {const { fixture } = codexProcess()const sink = createSink()@@ -791,7 +1147,7 @@ describe('codex native app-server contract', () => {const submitted = session.submit([user()], new AbortController().signal)await startedconst 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' } })+ fixture.send({ id: 77, method: 'item/commandExecution/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'command-approval', command: 'git status', cwd: 'D:\\work', reason: 'command needs to read the repository', availableDecisions: ['accept', 'cancel'] } })await asked.promisenotify(fixture, 'item/agentMessage/delta', { itemId: 'assistant-1', delta: 'awaiting your answer' })expect(sink.text).toHaveBeenCalledWith('assistant-1', 'awaiting your answer')@@ -800,8 +1156,68 @@ describe('codex native app-server contract', () => {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"}',+ details: 'command needs to read the repository\ncommand: git status\ncwd: D:\\work',}])+ expect(sink.approval.mock.calls[0]![1].details).not.toContain('threadId')+ completed(fixture)+ await submitted+ })++ it('names the proposed files in a file-change approval prompt', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ sink.approval.mockResolvedValue(true)+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ notify(fixture, 'item/started', { item: { id: 'edit-1', type: 'fileChange', status: 'inProgress', changes: [+ { path: 'src/harness/session.ts', kind: { type: 'update' }, diff: '@@' },+ { path: 'src/harness/new.ts', kind: { type: 'add' }, diff: '@@' },+ ] } })+ const answered = fixture.next(frame => frame.id === 81 && 'result' in frame)+ fixture.send({ id: 81, method: 'item/fileChange/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'edit-1', reason: 'edit the harness session' } })+ expect(await answered).toEqual({ id: 81, result: { decision: 'accept' } })+ expect(sink.approval.mock.calls[0]![1]).toEqual({+ kind: 'file',+ title: 'Codex file changes',+ details: 'edit the harness session\nsrc/harness/session.ts\nsrc/harness/new.ts',+ })+ completed(fixture)+ await submitted+ })++ it('cancels instead of answering accept when the native decision menu offers no one-shot grant', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ sink.approval.mockResolvedValue(true)+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ const answered = fixture.next(frame => frame.id === 79 && 'result' in frame)+ fixture.send({ id: 79, method: 'item/commandExecution/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'command-approval', command: 'rm -rf build', availableDecisions: [{ acceptWithExecpolicyAmendment: { execpolicy_amendment: ['rm', '-rf', 'build'] } }, 'cancel'] } })+ expect(await answered).toEqual({ id: 79, result: { decision: 'cancel' } })+ completed(fixture)+ await submitted+ })++ it('reports requested permissions without the raw native envelope', async () => {+ const { fixture } = codexProcess()+ const sink = createSink()+ sink.approval.mockResolvedValue(true)+ const session = await open(null, sink)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user()], new AbortController().signal)+ await started+ const answered = fixture.next(frame => frame.id === 80 && 'result' in frame)+ fixture.send({ id: 80, method: 'item/permissions/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1', itemId: 'permissions-1', reason: 'write access is required', permissions: { network: { enabled: false }, fileSystem: { read: ['D:\\work'] } } } })+ expect(await answered).toEqual({ id: 80, result: { permissions: { network: { enabled: false }, fileSystem: { read: ['D:\\work'] } }, scope: 'turn' } })+ expect(sink.approval.mock.calls[0]![1]).toEqual({+ kind: 'tool',+ title: 'Codex additional permissions',+ details: 'write access is required\npermissions: {"network":{"enabled":false},"fileSystem":{"read":["D:\\\\work"]}}',+ })completed(fixture)await submitted})@@ -940,7 +1356,62 @@ describe('codex native app-server contract', () => {expect(fixture.frames.some(frame => frame.method === 'turn/interrupt')).toBe(false)})- it('rejects nontext user content rather than submitting a partial native prompt', async () => {+ it('keeps the official text and image order in one mixed native prompt', async () => {+ const { fixture } = codexProcess()+ const attachments: NativeAttachments = { path: () => 'C:/fixture/native.png', read: vi.fn() }+ const session = await open(null, createSink(), undefined, attachments)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const mixed = createUserMessage({ source: { kind: 'user' }, content: [+ { type: 'text', text: 'before ' },+ { type: 'image', attachment: { id: 'image-1', mediaType: 'image/png', bytes: 3 } as never },+ { type: 'text', text: ' after' },+ ] })+ const submitted = session.submit([mixed], new AbortController().signal)+ expect((await started).params).toEqual({+ threadId: 'thread-1',+ input: [+ { type: 'text', text: 'before ', text_elements: [] },+ { type: 'localImage', path: 'C:/fixture/native.png' },+ { type: 'text', text: ' after', text_elements: [] },+ ],+ })+ completed(fixture)+ await submitted+ })++ it('forwards an official image as native input instead of rejecting the prompt', async () => {+ const { fixture } = codexProcess()+ const attachments: NativeAttachments = { path: () => 'C:/fixture/native.png', read: vi.fn() }+ const session = await open(null, createSink(), undefined, attachments)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([user(), image({ id: 'image-1', mediaType: 'image/png', bytes: 3 })], new AbortController().signal)+ expect((await started).params).toEqual({+ threadId: 'thread-1',+ input: [+ { type: 'text', text: 'inspect the workspace', text_elements: [] },+ { type: 'localImage', path: 'C:/fixture/native.png' },+ ],+ })+ completed(fixture)+ await submitted+ expect(attachments.read).not.toHaveBeenCalled()+ })++ it('inlines an official image as a data URL when the provider stores no host file', async () => {+ const { fixture } = codexProcess()+ const attachments: NativeAttachments = { path: () => undefined, read: vi.fn(async () => ({ mediaType: 'image/png', base64: 'Zm FrZQ==' })) }+ const session = await open(null, createSink(), undefined, attachments)+ const started = fixture.next(frame => frame.method === 'turn/start')+ const submitted = session.submit([image({ id: 'image-2', mediaType: 'image/png', bytes: 3 })], new AbortController().signal)+ expect((await started).params).toEqual({+ threadId: 'thread-1',+ input: [{ type: 'image', url: 'data:image/png;base64,Zm FrZQ==' }],+ })+ completed(fixture)+ await submitted+ })++ it('refuses nontext user content rather than submitting a partial native prompt', async () => {const { fixture } = codexProcess()const session = await open()const input = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'reasoning', text: 'not user text' }] })diff --git a/packages/dsh-tauri-kernel/src/host/backends/codex.ts b/packages/dsh-tauri-kernel/src/host/backends/codex.tsindex 285aa393..8c1b582e 100644--- a/packages/dsh-tauri-kernel/src/host/backends/codex.ts+++ b/packages/dsh-tauri-kernel/src/host/backends/codex.ts@@ -1,7 +1,7 @@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'+import type { NativeAttachments, NativeCommand, NativeContent, NativeImageRef, NativeModelCatalog, NativeModelInfo, NativePermission, NativeQuestion, NativeSession, NativeSessionOpenOptions, NativeSink, NativeTurnOptions } from './types'+import { abortError, deferred, errorFrom, INTERRUPT_TIMEOUT_MS, JsonLinesProcess, NativeBridgeError, nativeRuns, PendingRequests, record, REQUEST_TIMEOUT_MS, stringField } from './transport'const INITIALIZATION = {clientInfo: { name: 'dsh-tauri-kernel', title: 'DSH native session bridge', version: '1.0.0' },@@ -47,6 +47,48 @@ interface CodexTurn {interruptTimer?: ReturnType<typeof setTimeout>}+/**+ * Human-readable approval text: the native reason plus only the fields that+ * identify what is being approved. The raw request envelope (ids, timestamps,+ * decision menus) is protocol plumbing and is unreadable in a permission prompt.+ */+function approvalDetails(fallback: string, params: Record<string, unknown>, fields: readonly string[], extra: readonly string[] = []): string {+ const lines = [typeof params.reason === 'string' && params.reason.trim() !== '' ? params.reason : fallback]+ for (const field of fields) {+ const value = params[field]+ if (value === undefined || value === null || value === '')+ continue+ lines.push(`${field}: ${typeof value === 'string' ? value : JSON.stringify(value)}`)+ }+ return [...lines, ...extra].join('\n')+}++/**+ * Read the proposed file changes a `fileChange` item carries. The approval+ * request itself names no files, so the prompt can only list them from the item+ * the native kernel announced for the same identity.+ */+function changedLines(item: Record<string, unknown>): string[] {+ if (!Array.isArray(item.changes))+ return []+ return item.changes.flatMap((value) => {+ if (!value || typeof value !== 'object' || Array.isArray(value))+ return []+ const path = (value as Record<string, unknown>).path+ return typeof path === 'string' && path !== '' ? [path] : []+ })+}++/**+ * Whether the native request still offers a plain one-shot `accept`. The DSH+ * approval seam only grants `allowed-once`, so a decision menu without that+ * entry cannot be answered truthfully; cancelling leaves the choice to the user+ * instead of silently minting an execpolicy amendment or a session-scoped grant.+ */+function acceptsOnce(params: Record<string, unknown>): boolean {+ return !Array.isArray(params.availableDecisions) || params.availableDecisions.includes('accept')+}+function nativeTool(item: Record<string, unknown>): { name: string, arguments: string } | undefined {switch (item.type) {case 'commandExecution':@@ -87,6 +129,8 @@ class CodexSession implements NativeSession {private readonly interruptedTurns = new Set<string>()private backgroundBaseline?: Set<string>private readonly commandItems = new Set<string>()+ /** Proposed file changes per announced `fileChange` item, for its approval prompt. */+ private readonly changedFiles = new Map<string, string[]>()private baselineModel?: stringprivate baselineProvider?: stringprivate baselineEffort?: string | null@@ -96,7 +140,7 @@ class CodexSession implements NativeSession {private appliedOptions: NativeTurnOptions = { model: null, reasoningEffort: null }private effortOverridden = false- constructor(private readonly command: NativeCommand, private readonly sink: NativeSink, private readonly cwd: string) {+ constructor(private readonly command: NativeCommand, private readonly sink: NativeSink, private readonly cwd: string, private readonly attachments?: NativeAttachments) {this.transport = new JsonLinesProcess(command, ['app-server', '--listen', 'stdio://'], cwd)this.requests = new PendingRequests(value => this.transport.write(value))this.transport.onFailure((error) => {@@ -122,9 +166,12 @@ class CodexSession implements NativeSession {await this.request('initialize', INITIALIZATION, signal)this.transport.write({ method: 'initialized', params: {} })const forkFrom = options?.forkFrom+ const permission = options?.permissionconst response = record(await this.request(forkFrom ? 'thread/fork' : storedId === null ? 'thread/start' : 'thread/resume', {...forkFrom ? { threadId: forkFrom } : storedId === null ? {} : { threadId: storedId },cwd,+ ...permission?.approval === undefined ? {} : { approvalPolicy: permission.approval === 'never' ? 'never' : 'on-request' },+ ...permission?.sandbox === undefined ? {} : { sandbox: permission.sandbox },}, signal))const id = stringField(record(response.thread), 'id')if (storedId !== null && id !== storedId)@@ -282,7 +329,7 @@ class CodexSession implements NativeSession {private async turnOptions(options: NativeTurnOptions, signal: AbortSignal): Promise<{ model?: string, effort?: string }> {const modelChanged = this.defaultsPending || options.model !== this.appliedOptions.modelconst effortChanged = this.defaultsPending || options.reasoningEffort !== this.appliedOptions.reasoningEffort- if (options.model === null && options.reasoningEffort === null && !modelChanged && !effortChanged)+ if (options.model === null && options.reasoningEffort === null && this.appliedOptions.model === null && this.appliedOptions.reasoningEffort === null)return {}const catalog = this.catalog ?? await this.models(signal)const model = options.model ?? this.baselineModel@@ -303,16 +350,27 @@ class CodexSession implements NativeSession {return { ...options.model !== null || modelChanged ? { model } : {}, ...effort === null ? {} : { effort } }}- async submit(messages: readonly UserMessage[], signal: AbortSignal, options?: NativeTurnOptions): Promise<void> {+ async submit(messages: readonly UserMessage[], signal: AbortSignal, options?: NativeTurnOptions, permission?: NativePermission): Promise<void> {signal.throwIfAborted()if (this.disposed || this.failure)throw this.failure ?? new NativeBridgeError('BRIDGE_PROCESS_CLOSED', 'Codex session was disposed')if (this.active)throw new NativeBridgeError('BRIDGE_BUSY', 'Codex native session already has an active turn')- const input = textMessages(messages).map(text => ({ type: 'text', text, text_elements: [] }))- if (input.length === 0)+ const runs = nativeRuns(messages, this.attachments)+ if (runs.length === 0)throw new NativeBridgeError('BRIDGE_EMPTY_INPUT', 'Codex native turn requires a user message')+ this.changedFiles.clear()const selection = options ? { ...options } : undefined+ const policy = {+ ...permission?.approval === undefined ? {} : { approvalPolicy: permission.approval === 'never' ? 'never' : 'on-request' },+ ...permission?.sandbox === undefined+ ? {}+ : { sandboxPolicy: {+ 'read-only': { type: 'readOnly', networkAccess: false },+ 'workspace-write': { type: 'workspaceWrite', writableRoots: [this.cwd], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: false },+ 'danger-full-access': { type: 'dangerFullAccess' },+ }[permission.sandbox] },+ }const turn: CodexTurn = {result: deferred<void>(),signal,@@ -334,14 +392,24 @@ class CodexSession implements NativeSession {signal.addEventListener('abort', aborted, { once: true })try {const overrides = selection ? await this.turnOptions(selection, signal) : {}+ const input: Record<string, unknown>[] = []+ for (const run of runs.flat()) {+ if (run.type === 'text') {+ input.push({ type: 'text', text: run.text, text_elements: [] })+ continue+ }+ input.push(await this.imageInput(run.ref, signal))+ }+ signal.throwIfAborted()turn.baseline = new Set((await this.listTerminals(signal)).map(terminal => terminal.processId))signal.throwIfAborted()turn.submitted = true// turn/started may precede the response; retain its id even during cancel.- const response = record(await this.request('turn/start', { threadId: this.id, input, ...overrides }))+ const response = record(await this.request('turn/start', { threadId: this.id, input, ...overrides, ...policy }))if (selection) {this.appliedOptions = selection- this.defaultsPending = false+ if (overrides.model !== undefined || overrides.effort !== undefined)+ this.defaultsPending = false}if (overrides.model !== undefined)this.effectiveModel = overrides.model@@ -527,6 +595,14 @@ class CodexSession implements NativeSession {case 'turn/started':returncase 'turn/completed': {+ if (Array.isArray(nativeTurn!.items)) {+ for (const value of nativeTurn!.items) {+ const item = record(value)+ const tool = turn.tools.get(stringField(item, 'id'))+ if (tool && !tool.ended && (item.status === 'completed' || item.status === 'failed' || item.status === 'declined'))+ this.item(turn, item, true)+ }+ }const status = stringField(nativeTurn!, 'status')if (status === 'interrupted' && !turn.signal.aborted)turn.terminalError = new NativeBridgeError('BRIDGE_NATIVE_INTERRUPTED', 'Codex interrupted the native turn')@@ -560,7 +636,8 @@ class CodexSession implements NativeSession {this.sink.thinking(id, delta)return}- case 'item/commandExecution/outputDelta': {+ case 'item/commandExecution/outputDelta':+ case 'item/fileChange/outputDelta': {const tool = turn.tools.get(stringField(params, 'itemId'))if (tool)tool.output += typeof params.delta === 'string' ? params.delta : ''@@ -574,10 +651,16 @@ class CodexSession implements NativeSession {private item(turn: CodexTurn, item: Record<string, unknown>, completed: boolean): void {const id = stringField(item, 'id')+ const type = stringField(item, 'type')if (item.type === 'commandExecution') {turn.commandItems.add(id)this.commandItems.add(id)}+ else if (item.type === 'fileChange') {+ const lines = changedLines(item)+ if (lines.length > 0)+ this.changedFiles.set(id, lines)+ }const tool = nativeTool(item)if (tool) {if (!turn.tools.has(id)) {@@ -597,7 +680,7 @@ class CodexSession implements NativeSession {if (!completed || turn.assistants.has(id))returnconst content: NativeContent[] = []- switch (item.type) {+ switch (type) {case 'agentMessage':case 'plan':content.push({ type: 'text', text: typeof item.text === 'string' ? item.text : turn.text.get(id) ?? '' })@@ -618,12 +701,24 @@ class CodexSession implements NativeSession {content.push({ type: 'text', text: typeof item.review === 'string' ? item.review : '' })breakdefault:- throw new NativeBridgeError('BRIDGE_UNSUPPORTED_EVENT', `Unsupported Codex item type: ${String(item.type)}`)+ content.push({ type: 'text', text: JSON.stringify(item) })+ break}turn.assistants.add(id)this.sink.assistant(id, content)}+ /** Official image as native `UserInput`; a host path avoids re-encoding the bytes. */+ private async imageInput(ref: NativeImageRef, signal: AbortSignal): Promise<Record<string, unknown>> {+ const path = this.attachments?.path(ref)+ if (path !== undefined)+ return { type: 'localImage', path }+ const source = await this.attachments!.read(ref, signal)+ if (source.base64 === undefined)+ throw new NativeBridgeError('BRIDGE_PROTOCOL', 'The official attachment store returned no readable image bytes')+ return { type: 'image', url: `data:${source.mediaType};base64,${source.base64}` }+ }+private async answer(id: string | number, method: string, params: Record<string, unknown>): Promise<void> {const controller = new AbortController()this.approvals.set(id, controller)@@ -639,13 +734,14 @@ class CodexSession implements NativeSession {? 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),+ details: approvalDetails(command ? 'Codex needs to run a command' : 'Codex needs to change files', params, command ? ['command', 'cwd'] : ['grantRoot'], command ? [] : this.changedFiles.get(itemId) ?? []),}, signal): false- result = { decision: allowed && !signal.aborted ? 'accept' : 'decline' }+ const once = acceptsOnce(params)+ result = { decision: once ? (allowed && !signal.aborted ? 'accept' : 'decline') : 'cancel' }}else if (method === 'item/permissions/requestApproval') {- const allowed = belongs ? await this.sink.approval(itemId, { kind: 'tool', title: 'Codex additional permissions', details: JSON.stringify(params) }, signal) : false+ const allowed = belongs ? await this.sink.approval(itemId, { kind: 'tool', title: 'Codex additional permissions', details: approvalDetails('Codex requests additional permissions', params, ['permissions']) }, signal) : falseresult = { permissions: allowed && !signal.aborted ? record(params.permissions) : {}, scope: 'turn' }}else if (method === 'item/tool/requestUserInput') {@@ -689,10 +785,10 @@ class CodexSession implements NativeSession {}}-export async function createCodexSession(command: NativeCommand, cwd: string, nativeSessionId: string | null, sink: NativeSink, signal: AbortSignal, options?: NativeSessionOpenOptions): Promise<NativeSession> {+export async function createCodexSession(command: NativeCommand, cwd: string, nativeSessionId: string | null, sink: NativeSink, signal: AbortSignal, options?: NativeSessionOpenOptions, attachments?: NativeAttachments): Promise<NativeSession> {if (options?.forkFrom !== undefined && (nativeSessionId !== null || options.forkFrom === ''))throw new NativeBridgeError('BRIDGE_FORK_INVALID', 'Codex fork requires a source thread and no existing native binding')- const session = new CodexSession(command, sink, cwd)+ const session = new CodexSession(command, sink, cwd, attachments)await session.open(cwd, nativeSessionId, signal, options)return session}diff --git a/packages/dsh-tauri-kernel/src/host/backends/transport.ts b/packages/dsh-tauri-kernel/src/host/backends/transport.tsindex 5d2f3683..5c637848 100644--- a/packages/dsh-tauri-kernel/src/host/backends/transport.ts+++ b/packages/dsh-tauri-kernel/src/host/backends/transport.ts@@ -1,6 +1,6 @@import type { UserMessage } from '@deepseek-ai/dsh-llm'import type { ChildProcessWithoutNullStreams } from 'node:child_process'-import type { NativeCommand } from './types'+import type { NativeAttachments, NativeCommand, NativeImageRef } from './types'import { spawn } from 'node:child_process'import { nativeEnvironment } from '../utils/detection'@@ -38,12 +38,40 @@ export function stringField(value: Record<string, unknown>, key: string): stringreturn value[key]}-export function textMessages(messages: readonly UserMessage[]): string[] {- return messages.map(message => message.content.map((block) => {- if (block.type !== 'text')+/** One ordered piece of an official user message handed to a native kernel. */+export type NativeRun = { type: 'text', text: string } | { type: 'image', ref: NativeImageRef }++/**+ * Split official user content into ordered native runs, preserving the model's+ * original text/image interleaving. Adjacent text merges into one run, an image+ * keeps its durable reference so each kernel resolves the host path or the+ * verified bytes it needs, and a message with no blocks keeps one empty text+ * run. Content no native kernel accepts fails closed rather than submitting a+ * partial prompt.+ * @param messages - the admitted official user messages.+ * @param attachments - official attachment access, absent without an image provider.+ * @returns one ordered run list per message.+ */+export function nativeRuns(messages: readonly UserMessage[], attachments: NativeAttachments | undefined): NativeRun[][] {+ return messages.map((message) => {+ const runs: NativeRun[] = []+ for (const block of message.content) {+ if (block.type === 'text') {+ const last = runs.at(-1)+ if (last?.type === 'text')+ runs[runs.length - 1] = { type: 'text', text: last.text + block.text }+ else+ runs.push({ type: 'text', text: block.text })+ continue+ }+ if (block.type === 'image' && attachments !== undefined) {+ runs.push({ type: 'image', ref: block.attachment })+ continue+ }throw new NativeBridgeError('BRIDGE_UNSUPPORTED_CONTENT', `Native bridge does not yet support user content: ${block.type}`)- return block.text- }).join(''))+ }+ return runs.length === 0 ? [{ type: 'text', text: '' }] : runs+ })}export interface Deferred<T> {diff --git a/packages/dsh-tauri-kernel/src/host/backends/types.ts b/packages/dsh-tauri-kernel/src/host/backends/types.tsindex cfaf4403..7a24ac0c 100644--- a/packages/dsh-tauri-kernel/src/host/backends/types.ts+++ b/packages/dsh-tauri-kernel/src/host/backends/types.ts@@ -1,10 +1,16 @@-import type { UserMessage } from '@deepseek-ai/dsh-llm'+import type { ImageBlock, UserMessage } from '@deepseek-ai/dsh-llm'import type { NativeModelCatalog, NativeTurnOptions } from '../../shared/native-model'export type { NativeModelCatalog, NativeModelInfo, NativeTurnOptions } from '../../shared/native-model'+export interface NativePermission {+ sandbox?: 'read-only' | 'workspace-write' | 'danger-full-access'+ approval?: 'ask' | 'never'+}+export interface NativeSessionOpenOptions {forkFrom?: string+ permission?: NativePermission}export interface NativeCommand {@@ -13,6 +19,28 @@ export interface NativeCommand {env?: Record<string, string | undefined>}+/** One official image resolved for a native kernel prompt. */+export interface NativeImageSource {+ mediaType: string+ /** Absolute host path when the mounted provider is host-file-backed. */+ path?: string+ /** Verified base64 bytes, used by kernels that inline the image. */+ base64?: string+}++/** Durable official image reference, as carried by one user-message block. */+export type NativeImageRef = ImageBlock['attachment']++/**+ * Official attachment access for native prompts. `path` is a non-reading host+ * lookup; `read` verifies stored bytes for kernels that must inline the image.+ * Absent when the deployment mounts no image provider.+ */+export interface NativeAttachments {+ path: (ref: NativeImageRef) => string | undefined+ read: (ref: NativeImageRef, signal: AbortSignal) => Promise<NativeImageSource>+}+export type NativeContent= | { type: 'text', text: string }| { type: 'thinking', text: string }@@ -42,6 +70,6 @@ export interface NativeSink {export interface NativeSession {readonly id: stringmodels?: (signal: AbortSignal) => Promise<NativeModelCatalog>- submit: (messages: readonly UserMessage[], signal: AbortSignal, options?: NativeTurnOptions) => Promise<void>+ submit: (messages: readonly UserMessage[], signal: AbortSignal, options?: NativeTurnOptions, permission?: NativePermission) => Promise<void>dispose: () => Promise<void>}diff --git a/packages/dsh-tauri-kernel/src/host/config/runtime.ts b/packages/dsh-tauri-kernel/src/host/config/runtime.tsindex 240fc99a..08c3b72b 100644--- a/packages/dsh-tauri-kernel/src/host/config/runtime.ts+++ b/packages/dsh-tauri-kernel/src/host/config/runtime.ts@@ -17,7 +17,6 @@ export const runtime = {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>>(),@@ -58,7 +57,6 @@ export async function resetRuntime(): Promise<void> {runtime.sinks.clear()runtime.exchanges.clear()runtime.steps.clear()- runtime.coldRoutes.clear()runtime.modelWrites.clear()runtime.checkpoints.clear()runtime.verified.clear()diff --git a/packages/dsh-tauri-kernel/src/host/server/index.test.ts b/packages/dsh-tauri-kernel/src/host/server/index.test.tsindex 0c6c9b93..168404fe 100644--- a/packages/dsh-tauri-kernel/src/host/server/index.test.ts+++ b/packages/dsh-tauri-kernel/src/host/server/index.test.ts@@ -10,6 +10,7 @@ import type { NativeSession } from '../backends/types'import type { HostContext, PlatformLoader, RuntimeModules } from '../types'import { createServer } from 'node:http'import { createRequire } from 'node:module'+import { join } from 'node:path'import process from 'node:process'import { pathToFileURL } from 'node:url'import { Context } from '@deepseek-ai/cordis'@@ -311,6 +312,21 @@ describe('exported bridge plugin HTTP dependency boundary', () => {expect(projections.stateOf(sessionModule.Session.create(sessionModule.SessionId('guard-regression')), 'bridgeKernel')?.binding).toBeNull()})+ it('answers an unusable session location with the bridge reason instead of an opaque server error', async () => {+ const base = await start()+ const cases = [+ { body: { backend: 'codex', cwd: join(cwd, 'bridge-missing-session-directory') }, reason: 'BRIDGE_CWD_INVALID: 会话目录必须是已存在的绝对目录。' },+ { body: { backend: 'codex', workspaceId: 'bridge-missing-workspace' }, reason: 'BRIDGE_WORKSPACE_NOT_FOUND: 工作区不存在。' },+ ] as const+ for (const { body, reason } of cases) {+ const response = await fetch(`${base}/api/tauri/bridge/sessions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })+ expect(response.status).toBe(400)+ expect(await response.json()).toMatchObject({ message: reason })+ }+ expect(createCodexSession).not.toHaveBeenCalled()+ expect(runtime.sessions.size).toBe(0)+ })+it.each([401, 403] as const)('preserves connection rejection %s on every declared bridge route before native detection', async (status) => {rejection = statusconst base = await start()diff --git a/packages/dsh-tauri-kernel/src/host/server/routes/sessions/post.ts b/packages/dsh-tauri-kernel/src/host/server/routes/sessions/post.tsindex b428770b..cecacf53 100644--- a/packages/dsh-tauri-kernel/src/host/server/routes/sessions/post.ts+++ b/packages/dsh-tauri-kernel/src/host/server/routes/sessions/post.ts@@ -13,5 +13,13 @@ export default defineEventHandler<EventHandlerRequest, Promise<{ sessionId: stri}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)+ try {+ return await session.create(body.backend, body.workspaceId, body.cwd, body.agentPreset)+ }+ catch (error) {+ const message = error instanceof Error ? error.message : ''+ if (!message.startsWith('BRIDGE_'))+ throw error+ throw new HTTPError({ statusCode: 400, message })+ }})diff --git a/packages/dsh-tauri-kernel/src/host/service/adapter.ts b/packages/dsh-tauri-kernel/src/host/service/adapter.tsindex 1329e2d5..7fee691a 100644--- a/packages/dsh-tauri-kernel/src/host/service/adapter.ts+++ b/packages/dsh-tauri-kernel/src/host/service/adapter.ts@@ -14,6 +14,15 @@ import { model } from './model'import { session } from './session'import { sink } from './sink'+/**+ * Sources that carry DSH-side environment state rather than content addressed to+ * the model: policy switches, cwd notices, plugin run outcomes, and snapshots.+ * The native kernel owns its own equivalents, so these never become native input+ * and must not abort a running native turn. Real user instructions stay absent+ * on purpose — steering a running native turn is still refused.+ */+const ENVIRONMENT_SOURCES = new Set(['runtime-context', 'time-context', 'user-approval', 'working-directory', 'cordis-host-runner', 'ptc-mode', 'skill-catalog'])+export const adapter = defineService({async register(): Promise<() => void> {const ctx = getServerContext<HostContext>(server)@@ -94,7 +103,7 @@ export const adapter = defineService({},async request(payload: { agent: Agent, signal: AbortSignal }, next: () => Promise<LlmCallConfig>): Promise<LlmCallConfig> {- let config = await next()+ const config = await next()const ctx = getServerContext<HostContext>(server)const projected = ctx.sessionProjections.stateOf(payload.agent.session, 'bridgeKernel')?.bindingif (projected === null || projected === undefined) {@@ -104,15 +113,16 @@ export const adapter = defineService({}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.+ // The API controller answers every headerless session with the deployment default route, so an+ // unstarted bound session keeps its kernel instead of failing its first message on that default.const fallback = ctx.get('agentDefaultModel')?.currentSelection()- 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+ const bound = config.provider === BRIDGE_PROVIDER && config.model === binding.backend+ const ambient = payload.agent.session.requestHeader() === undefined && fallback !== undefined && config.provider === fallback.provider && config.model === fallback.model && config.reasoningEffort === fallback.reasoningEffort && config.maxTokens === undefined && config.temperature === undefined && config.stop === undefined+ if (!bound && !ambient)+ throw new Error(`BRIDGE_KERNEL_IMMUTABLE: 已绑定会话不能切换内核或由 DSH 覆写原生选项(请求 ${config.provider}/${config.model},当前内核 ${binding.backend})。`)+ // The native kernel owns model, effort, and generation options: DSH values never reach it.+ const { reasoningEffort: _effort, maxTokens: _maxTokens, temperature: _temperature, stop: _stop, ...native } = config+ return { ...native, provider: BRIDGE_PROVIDER, model: binding.backend }},async* capture(options: GenerateOptions, next: () => AsyncIterable<StreamChunk>): AsyncIterable<StreamChunk> {@@ -205,7 +215,6 @@ export const adapter = defineService({},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)@@ -216,11 +225,6 @@ export const adapter = defineService({},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)@@ -234,8 +238,7 @@ export const adapter = defineService({})function nativeMessage(message: UserMessage): boolean {- const source: string = message.source.kind- return source !== 'runtime-context' && source !== 'time-context'+ return !ENVIRONMENT_SOURCES.has(message.source.kind)}function continuationMessage(message: UserMessage, entered: readonly UserMessage[]): boolean {diff --git a/packages/dsh-tauri-kernel/src/host/service/identity.ts b/packages/dsh-tauri-kernel/src/host/service/identity.tsindex 600ec05f..f372a304 100644--- a/packages/dsh-tauri-kernel/src/host/service/identity.ts+++ b/packages/dsh-tauri-kernel/src/host/service/identity.ts@@ -67,8 +67,6 @@ export const identity = defineService({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)@@ -80,7 +78,6 @@ export const identity = defineService({unregister()if (runtime.bindingSchema === bindingSchema)runtime.bindingSchema = undefined- runtime.coldRoutes.clear()}},diff --git a/packages/dsh-tauri-kernel/src/host/service/model.test.ts b/packages/dsh-tauri-kernel/src/host/service/model.test.tsindex 1e80d55d..9b08035c 100644--- a/packages/dsh-tauri-kernel/src/host/service/model.test.ts+++ b/packages/dsh-tauri-kernel/src/host/service/model.test.ts@@ -297,6 +297,49 @@ function checkUnchangedRoute(agent: Agent, started = false) {expect(context.agentDefaultModel.currentSelection()).toEqual({ provider: 'global-provider', model: 'global-model', reasoningEffort: 'global-effort' })}+describe('official native skill catalog admission', () => {+ it.each(['codex', 'claude'] as const)('omits DSH skill catalogs from %s input without cancelling catalog updates or removing explicit instructions', async (backend) => {+ const catalogText = '<available_skills>find-skills</available_skills>'+ const catalog = llmModule.createUserMessage({+ source: { kind: 'skill-catalog', form: 'catalog', entries: [{ name: 'find-skills', description: 'DSH-only skill' }] } as unknown as llmModule.UserMessage['source'],+ content: [{ type: 'text', text: catalogText }],+ })+ const update = llmModule.createUserMessage({+ source: { ...catalog.source, update: true } as unknown as llmModule.UserMessage['source'],+ content: [{ type: 'text', text: '<available_skills>replacement</available_skills>' }],+ })+ const invocation = llmModule.createUserMessage({+ source: { kind: 'skill-invocation', name: 'find-skills', form: 'instructions' } as unknown as llmModule.UserMessage['source'],+ content: [{ type: 'text', text: '<skill_content name="find-skills">explicit instructions</skill_content>' }],+ })+ context.on('agent/pre-step', async ({ step }, next) => {+ const decision = await next()+ return decision.kind === 'reject' ? decision : { ...decision, messages: [...decision.messages, ...step === 1 ? [catalog, invocation] : [update]] }+ })+ const connection = native(`skills-${backend}`)+ vi.mocked(backend === 'codex' ? createCodexSession : createClaudeSession).mockImplementationOnce(async (_command, _cwd, _storedId, output) => {+ connection.submit.mockImplementation(async () => {+ output.assistant('native-skill-call', [{ type: 'tool-call', id: 'native-skill', name: 'Skill', arguments: '{"skill":"keybindings-help"}' }])+ output.toolStart('native-skill', 'Skill', '{"skill":"keybindings-help"}')+ output.toolEnd('native-skill', 'native skill instructions')+ output.assistant('native-skill-finished', [{ type: 'text', text: 'native skill finished' }])+ })+ return connection+ })+ const created = await session.create(backend, undefined, cwd)+ const agent = agents.get(sessionModule.SessionId(created.sessionId))!+ await followup(agent, catalogText)+ expect(connection.submit).toHaveBeenCalledOnce()+ expect(connection.submit.mock.calls[0]![0].map(message => ({ source: message.source, content: message.content }))).toEqual([+ { source: { kind: 'user' }, content: [{ type: 'text', text: catalogText }] },+ { source: invocation.source, content: [{ type: 'text', text: '<skill_content name="find-skills">explicit instructions</skill_content>' }] },+ ])+ expect(agent.session.snapshotEvents().filter(event => event.type === 'step/start').map(event => event.data)).toEqual([{ turn: 1, step: 1 }, { turn: 1, step: 2 }])+ expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/end').map(event => event.data)).toEqual([{ turn: 1, reason: { kind: 'completed' } }])+ expect(errors).toEqual([])+ }, 10_000)+})+describe('official native model selection', () => {it.each(['codex', 'claude'] as const)('reads the actual %s catalog without submitting or creating model records', async (backend) => {const { agent, connection } = await create(native(`catalog-${backend}`), backend)diff --git a/packages/dsh-tauri-kernel/src/host/service/session.test.ts b/packages/dsh-tauri-kernel/src/host/service/session.test.tsindex a210a722..a0029574 100644--- a/packages/dsh-tauri-kernel/src/host/service/session.test.ts+++ b/packages/dsh-tauri-kernel/src/host/service/session.test.ts@@ -7,15 +7,18 @@ 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 { join } from 'node:path'import process from 'node:process'import { pathToFileURL } from 'node:url'import { Context } from '@deepseek-ai/cordis'import { AgentRegistry } from '@deepseek-ai/dsh-agent'import { AgentLoop } from '@deepseek-ai/dsh-agent-loop'import * as llmModule from '@deepseek-ai/dsh-llm'+import { PermissionPresetService } from '@deepseek-ai/dsh-permission-presets'import { assertContiguous, materializeAppendBatch, materializeCreateHeader, SessionPersistence, SessionPersistenceRevision, validateStoredEvents } from '@deepseek-ai/dsh-session-persistence'import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'import { ToolRuntime } from '@deepseek-ai/dsh-tools'+import { ApprovalService } from '@deepseek-ai/dsh-user-approval'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import * as zodModule from 'zod'import { apply } from '../apply'@@ -905,7 +908,7 @@ describe('official cold native route restoration', () => {expect(restored.session.requestHeader()).toBeUndefined()expect(identity.resolve(restored)).toEqual(binding)expect(factory).toHaveBeenCalledOnce()- expect(runtime.coldRoutes.has(restored)).toBe(true)+ expect(restored.session.requestHeader()).toBeUndefined()const resumed = native(original.id)factory.mockImplementationOnce(async (_command, _cwd, storedId, output) => {expect(storedId).toBe(original.id)@@ -921,7 +924,6 @@ describe('official cold native route restoration', () => {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' }] },@@ -929,11 +931,7 @@ describe('official cold native route restoration', () => {])}, 10_000)- it.each([- { provider: 'cloud-provider', model: 'global-default' },- { provider: 'dsh-tauri-kernel', model: 'claude' },- { provider: 'dsh-tauri-kernel', model: 'codex', reasoningEffort: llmModule.ReasoningEffortId('high') },- ])('rejects an explicit cold model selection instead of restoring over it: %j', async (selected) => {+ it('rejects a bound-session kernel switch before its first request', async () => {const original = native('api-cold-selected')vi.mocked(createCodexSession).mockResolvedValueOnce(original)await creating()@@ -944,16 +942,62 @@ describe('official cold native route restoration', () => {expect(found).not.toHaveProperty('error')if ('error' in found)throw found.error+ const selected = { provider: BRIDGE_PROVIDER, model: 'claude' }controller.selectForNextRequest(found.agent, selected)await followup(found.agent, 'reject switching the bound native kernel')- expect(errors).toEqual([expect.objectContaining({ message: 'BRIDGE_KERNEL_IMMUTABLE: 已绑定会话不能切换内核或由 DSH 覆写原生选项。' })])+ expect(errors).toEqual([expect.objectContaining({ message: expect.stringContaining('BRIDGE_KERNEL_IMMUTABLE') })])expect(createCodexSession).toHaveBeenCalledOnce()expect(createClaudeSession).not.toHaveBeenCalled()expect(original.submit).not.toHaveBeenCalled()expect(found.agent.session.requestHeader()).toBeUndefined()expect(found.agent.session.snapshotEvents().filter((event: SessionEvent) => event.type === 'model/selection').map((event: SessionEvent) => event.data)).toEqual([selected])expect(identity.resolve(found.agent)).toEqual({ backend: 'codex', nativeSessionId: original.id, sessionId: previous.agent.id })- expect(runtime.coldRoutes.has(found.agent)).toBe(false)+ expect(() => restoreSerialized(found.agent.session)).not.toThrow()+ }, 10_000)++ it('keeps the bound kernel when a created session still receives the deployment default route', async () => {+ const original = native('api-created-default-route')+ vi.mocked(createCodexSession).mockResolvedValueOnce(original)+ await creating()+ const agent = officialHandle!.agent+ const started = deferred<AbortSignal>()+ const gate = deferred<void>()+ releases.push(() => gate.resolve())+ context.on('agent/pre-step', async ({ signal }) => {+ started.resolve(signal)+ await gate.promise+ return { kind: 'reject' }+ }, { global: true, prepend: true })+ const turn = followup(agent, 'keep the kernel the session was created with')+ const signal = await started.promise+ await expect(adapter.request({ agent, signal }, async () => defaultSelection)).resolves.toEqual({ provider: BRIDGE_PROVIDER, model: 'codex' })+ expect(identity.resolve(agent)).toEqual({ backend: 'codex', nativeSessionId: original.id, sessionId: agent.id })+ gate.resolve()+ await turn+ expect(errors).toEqual([])+ }, 10_000)++ it('drops a DSH reasoning effort on the bound native route instead of failing the first turn', async () => {+ const original = native('api-native-effort')+ const resumed = native(original.id)+ vi.mocked(createCodexSession).mockResolvedValueOnce(original).mockResolvedValueOnce(resumed)+ await creating()+ const previous = officialHandle!+ await previous.dispose()+ await session.remove(previous.agent.id)+ const found = await controller.resolveAgent(previous.agent.id)+ expect(found).not.toHaveProperty('error')+ if ('error' in found)+ throw found.error+ const selected = { provider: BRIDGE_PROVIDER, model: 'codex', reasoningEffort: llmModule.ReasoningEffortId('high') }+ controller.selectForNextRequest(found.agent, selected)+ await followup(found.agent, 'keep the native kernel while DSH proposes an effort')+ expect(errors).toEqual([])+ expect(resumed.submit).toHaveBeenCalledOnce()+ expect(resumed.submit.mock.calls[0]![2]).toEqual({ model: null, reasoningEffort: null })+ expect(found.agent.session.requestHeader()?.config).toEqual({ provider: BRIDGE_PROVIDER, model: 'codex' })+ expect(found.agent.session.snapshotEvents().filter((event: SessionEvent) => event.type === 'model/selection').map((event: SessionEvent) => event.data)).toEqual([selected])+ expect(identity.resolve(found.agent)).toEqual({ backend: 'codex', nativeSessionId: original.id, sessionId: previous.agent.id })expect(() => restoreSerialized(found.agent.session)).not.toThrow()}, 10_000)@@ -985,7 +1029,7 @@ describe('official cold native route restoration', () => {}, { 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 覆写原生选项。')+ await expect(adapter.request({ agent: found.agent, signal }, async () => override)).rejects.toThrow(expect.objectContaining({ message: expect.stringContaining(`BRIDGE_KERNEL_IMMUTABLE: 已绑定会话不能切换内核或由 DSH 覆写原生选项(请求 ${override.provider}/${override.model},当前内核 codex)。`) }))expect(createCodexSession).toHaveBeenCalledOnce()expect(original.submit).not.toHaveBeenCalled()expect(found.agent.session.requestHeader()).toBeUndefined()@@ -1090,6 +1134,41 @@ describe('official native session lifecycle', () => {expect(runtime.sessions.size).toBe(0)}, 10_000)+ it('rejects a session directory that does not exist with the location error instead of a filesystem error', async () => {+ await expect(session.create('codex', undefined, join(cwd, 'bridge-missing-session-directory'))).rejects.toThrow('BRIDGE_CWD_INVALID: 会话目录必须是已存在的绝对目录。')+ expect(createCodexSession).not.toHaveBeenCalled()+ expect(runtime.sessions.size).toBe(0)+ }, 10_000)++ it('refreshes official permission presets for each turn on a cached native connection', async () => {+ context.provide('shell', { sandboxMode: 'workspace-write' })+ await context.plugin(ApprovalService, { policy: 'ask' }).await()+ await context.plugin(PermissionPresetService).await()+ const connection = native('permission-native')+ vi.mocked(createCodexSession).mockImplementation(async (_command, _cwd, _storedId, output) => {+ connection.submit.mockImplementation(async () => output.assistant('permission-answer', [{ type: 'text', text: 'permission reply' }]))+ return connection+ })+ await creating()+ const agent = officialHandle!.agent+ await followup(agent, 'use the pinned initial permissions')+ context.permissionPresets.set(agent.session, 'danger-full-access')+ await followup(agent, 'use full permissions without reconnecting')+ context.permissionPresets.set(agent.session, 'workspace-write')+ await followup(agent, 'restore approval mode without reconnecting')+ expect(errors).toEqual([])+ expect(createCodexSession).toHaveBeenCalledOnce()+ expect(connection.submit.mock.calls.map(call => call[3])).toEqual([+ { sandbox: 'workspace-write', approval: 'ask' },+ { sandbox: 'danger-full-access', approval: 'never' },+ { sandbox: 'workspace-write', approval: 'ask' },+ ])+ await session.remove(agent.id, agent)+ vi.mocked(createCodexSession).mockClear()+ await session.connect(agent, new AbortController().signal)+ expect(vi.mocked(createCodexSession).mock.calls[0]![5]).toEqual({ permission: { sandbox: 'workspace-write', approval: 'ask' } })+ }, 10_000)+it.each(['codex', 'claude'] as const)('publishes %s only after native ACK and official identity commit', async (id) => {const ack = deferred<NativeSession>()const started = deferred<void>()@@ -1195,7 +1274,6 @@ describe('official native session lifecycle', () => {}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) => {@@ -1211,17 +1289,12 @@ describe('official native session lifecycle', () => {await creating()const agent = officialHandle!.agentconst { events } = observe(agent)- agent.ctx.on('tools/execute', async (exec, next) => {- if (exec.callId === 'native-wait')- dispatched.resolve()- return next()- })let idle = falseconst turn = followup(agent, 'read through the native kernel').then(() => {idle = true})background.push(turn)- await dispatched.promise+ await vi.waitFor(() => expect(events.filter(event => event.type === 'tool/call').map(event => event.data.callId)).toEqual(['native-wait']))expect(idle).toBe(false)expect(body).not.toHaveBeenCalled()expect(connection.submit).toHaveBeenCalledOnce()diff --git a/packages/dsh-tauri-kernel/src/host/service/session.ts b/packages/dsh-tauri-kernel/src/host/service/session.tsindex e0ad32b6..2c5d786e 100644--- a/packages/dsh-tauri-kernel/src/host/service/session.ts+++ b/packages/dsh-tauri-kernel/src/host/service/session.ts@@ -2,9 +2,10 @@ import type { Agent, AgentHandle, AgentSetupCommit } from '@deepseek-ai/dsh-agenimport 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 { NativeAttachments, NativePermission, NativeSession, NativeSessionOpenOptions, NativeSink } from '../backends/types'import type { HostContext, NativeEntry, NativeExecution } from '../types'import type { OfficialSink } from './sink.types'+import { Buffer } from 'node:buffer'import { randomUUID } from 'node:crypto'import { mkdir, realpath, stat } from 'node:fs/promises'import { isAbsolute } from 'node:path'@@ -12,6 +13,7 @@ import { getServerContext } from 'dsh-h3/utils'import { defineService, resolveUngroupedSessionPath } from 'dsh-tauri'import { createClaudeSession } from '../backends/claude'import { createCodexSession } from '../backends/codex'+import { NativeBridgeError } from '../backends/transport'import { BRIDGE_PROVIDER, KERNEL_RECORD_TYPE } from '../config/constants'import { resetRuntime, runtime } from '../config/runtime'import { server } from '../server'@@ -40,7 +42,8 @@ export const session = defineService({cwd = resolveUngroupedSessionPath()await mkdir(cwd, { recursive: true })}- if (!isAbsolute(cwd) || !(await stat(cwd)).isDirectory())+ const location = await stat(cwd).catch(() => undefined)+ if (!isAbsolute(cwd) || location?.isDirectory() !== true)throw new Error('BRIDGE_CWD_INVALID: 会话目录必须是已存在的绝对目录。')cwd = await realpath(cwd)lifetime.signal.throwIfAborted()@@ -233,7 +236,7 @@ export const session = defineService({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)+ await entry.session.submit(input.messages, state.signal, input.options, permissionOf(input.agent.session))official.settle()}catch (error) {@@ -464,7 +467,8 @@ async function connect(agent: Agent, id: KernelBinding['backend'], storedId: strquestions: (...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)+ const permission = permissionOf(agent.session)+ const native = await factory(resolved.command, agent.session.header.cwd!, storedId, nativeSink, signal, permission === undefined ? options : { ...options, permission }, nativeAttachments(getServerContext<HostContext>(server)))try {signal.throwIfAborted()if (!native.id || (storedId !== null && storedId !== native.id))@@ -484,6 +488,22 @@ async function connect(agent: Agent, id: KernelBinding['backend'], storedId: str}}+/** Official attachment access for native prompts; absent without an image provider. */+function nativeAttachments(ctx: HostContext): NativeAttachments | undefined {+ const store = ctx.get('attachments')+ if (store === undefined)+ return undefined+ return {+ path: ref => store.imageHostPath(ref),+ async read(ref, signal) {+ const stored = await store.readImage(ref, signal)+ if (!(stored.data instanceof Uint8Array) || stored.ref.mediaType.length === 0)+ throw new NativeBridgeError('BRIDGE_PROTOCOL', 'The official attachment store returned an unreadable image')+ return { mediaType: stored.ref.mediaType, base64: Buffer.from(stored.data).toString('base64') }+ },+ }+}+function ownsSession(sessionId: string, owner: Agent): boolean {const entry = runtime.sessions.get(sessionId)const pending = runtime.pending.get(sessionId)@@ -499,6 +519,13 @@ function activeSink(agent: Agent, controller: AbortController): NativeSink {return exchange.state.native}+function permissionOf(value: Session): NativePermission | undefined {+ const state = getServerContext<HostContext>(server).sessionProjections.stateOf(value, 'permissions')+ if (!state || (state.sandbox === null && state.approval === null))+ return undefined+ return { sandbox: state.sandbox ?? undefined, approval: state.approval ?? undefined }+}+function sameBinding(left: KernelBinding | null | undefined, right: KernelBinding): boolean {return left?.backend === right.backend && left.nativeSessionId === right.nativeSessionId && left.sessionId === right.sessionId}diff --git a/packages/dsh-tauri-kernel/src/host/service/sink.test.ts b/packages/dsh-tauri-kernel/src/host/service/sink.test.tsindex 7171f331..e7d6eac0 100644--- a/packages/dsh-tauri-kernel/src/host/service/sink.test.ts+++ b/packages/dsh-tauri-kernel/src/host/service/sink.test.ts@@ -273,6 +273,86 @@ describe('real official cross-step native sink', () => {expect(runtime.exchanges.size).toBe(0)}, 10_000)+ it('keeps a native command turn alive when DSH replaces a committed long result in model history', async () => {+ const full = `${'H'.repeat(4_096)}${'M'.repeat(4_096)}${'T'.repeat(1_024)}`+ const pruned = `${'H'.repeat(4_096)}\n\n[... tool result middle pruned ...]\n\n${'T'.repeat(1_024)}`+ let current!: OfficialSink+ context.on('agent/pre-step', async (payload, next) => {+ if (payload.agent === agent && payload.step === 2) {+ current = runtime.exchanges.get(agent.id)!+ const original = toolResults()[0]!+ agent.session.append('tool/result', {+ ...original.data,+ message: { ...original.data.message, content: [{ type: 'text', text: pruned }] },+ }, {+ surfaceOp: { op: 'replace', startSeq: original.seq, endSeq: original.seq },+ sourceEventSeqs: [original.seq],+ })+ }+ return next()+ })+ nativeScript = async (native) => {+ nativeCall(native, 'long-command', '{}', 'commandExecution')+ native.toolEnd('long-command', full)+ native.assistant('final', [{ type: 'text', text: 'continued after history pruning' }])+ }+ await runTurn()+ expect(errors).toEqual([])+ expect(current.state.failure).toBeUndefined()+ expect(current.state.tools.get('long-command')!.committed).toBe(true)+ const [original, replacement] = toolResults()+ expect(original!.surfaceOp).toBe('append')+ expect(original!.data.message.content).toEqual([{ type: 'text', text: full }])+ expect(replacement).toMatchObject({ surfaceOp: { op: 'replace', startSeq: original!.seq, endSeq: original!.seq }, sourceEventSeqs: [original!.seq], data: { turn: 1, step: 1, message: { toolCallId: 'long-command', content: [{ type: 'text', text: pruned }] } } })+ expect(agent.session.deriveMessages().filter(message => message.role === 'tool').map(message => message.content)).toEqual([[{ type: 'text', text: pruned }]])+ expect(assistants().map(event => event.data.step)).toEqual([1, 2])+ expect(assistants()[1]!.data.message.content).toEqual([{ type: 'text', text: 'continued after history pruning' }])+ expect(runtime.exchanges.size).toBe(0)+ }, 10_000)++ it.each(['content', 'isError', 'meta'] as const)('rejects a first official native result append with changed %s', async (field) => {+ const current = await exchange()+ nativeCall(current.state.native, 'first-append')+ current.state.native.toolEnd('first-append', 'complete native output')+ await execute('first-append', current.state.signal)+ current.state.tools.get('first-append')!.step = 1+ const message = llmModule.createToolResultMessage({ callId: llmModule.ToolCallId('first-append'), isError: field === 'isError', content: [{ type: 'text', text: field === 'content' ? 'pruned output' : 'complete native output' }] })+ agent.session.append('tool/result', { turn: 1, step: 1, message, ...(field === 'meta' ? { meta: { rewritten: true } } : {}) }, { surfaceOp: 'append' })+ expect(current.state.tools.get('first-append')!.committed).toBe(false)+ expect(current.state.signal.aborted).toBe(true)+ expect(current.state.failure).toMatchObject({ message: 'BRIDGE_TOOL_RESULT_REJECTED: 官方日志没有完整保留原生工具结果。' })+ })++ it.each(['identical', 'changed'] as const)('rejects a genuinely duplicated official native result append with %s content', async (duplicate) => {+ const current = await exchange()+ nativeCall(current.state.native, 'duplicate-append')+ current.state.native.toolEnd('duplicate-append', 'complete native output')+ await execute('duplicate-append', current.state.signal)+ current.state.tools.get('duplicate-append')!.step = 1+ const message = llmModule.createToolResultMessage({ callId: llmModule.ToolCallId('duplicate-append'), isError: false, content: [{ type: 'text', text: 'complete native output' }] })+ agent.session.append('tool/result', { turn: 1, step: 1, message }, { surfaceOp: 'append' })+ expect(current.state.tools.get('duplicate-append')!.committed).toBe(true)+ expect(current.state.signal.aborted).toBe(false)+ agent.session.append('tool/result', { turn: 1, step: 1, message: { ...message, content: [{ type: 'text', text: duplicate === 'identical' ? 'complete native output' : 'changed output' }] } }, { surfaceOp: 'append' })+ expect(current.state.signal.aborted).toBe(true)+ expect(current.state.failure).toMatchObject({ message: 'BRIDGE_TOOL_RESULT_REJECTED: 官方日志没有完整保留原生工具结果。' })+ })++ it('identifies only unsettled native tools without exposing their arguments or inventing results', async () => {+ nativeScript = async (native) => {+ nativeCall(native, 'finished-native', '{}', 'commandExecution')+ native.toolEnd('finished-native', 'native result')+ nativeCall(native, 'missing-native', '{"code":"private user input"}', 'mcp::node_repl/js')+ native.assistant('final', [{ type: 'text', text: 'native done' }])+ }+ await runTurn()+ expect(errors).toHaveLength(1)+ expect(errors[0]).toMatchObject({ message: 'BRIDGE_TOOL_UNSETTLED: 原生内核没有确认全部工具结果。未确认工具:[{"id":"missing-native","name":"mcp::node_repl/js"}]' })+ expect(toolResults().some(event => event.data.message.toolCallId === 'missing-native')).toBe(false)+ expect(agent.status).toBe('idle')+ expect(runtime.exchanges.size).toBe(0)+ }, 10_000)+it('preserves native error text through the real tool pipeline and official result log', async () => {const inherited = inheritedTool()nativeScript = async (native) => {@@ -291,10 +371,151 @@ describe('real official cross-step native sink', () => {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) => {+ it('preserves a native failure when the host loader uses a distinct HarnessError module instance', async () => {+ const reloaded = await import(`${pathToFileURL(require.resolve('@deepseek-ai/dsh-llm')).href}?native-error-reload`) as typeof llmModule+ expect(new reloaded.HarnessError('probe', 'PROBE')).not.toBeInstanceOf(llmModule.HarnessError)+ const originalImport = context.loader.import.bind(context.loader)+ vi.spyOn(context.loader, 'import').mockImplementation(async id => id === '@deepseek-ai/dsh-llm' ? { ...llmModule, HarnessError: reloaded.HarnessError } : originalImport(id))+ const stderr = 'Failed to create unified exec process: helper_unknown_error: setup refresh had errors'+ nativeScript = async (native) => {+ nativeCall(native, 'sandbox-refresh-failure', '{"command":"Get-Content -LiteralPath \'C:/fixture/skills/openai-docs/SKILL.md\'","cwd":"C:/fixture/workspace"}', 'commandExecution')+ native.toolEnd('sandbox-refresh-failure', stderr, true)+ native.assistant('final', [{ type: 'text', text: 'native failure acknowledged' }])+ }+ await runTurn()+ expect(errors).toEqual([])+ expect(results.map(({ result }) => result)).toEqual([{ isError: true, error: { message: stderr, info: { name: 'NativeToolError', code: 'BRIDGE_NATIVE_TOOL_ERROR' } }, content: [{ type: 'text', text: stderr }] }])+ expect(toolResults().map(event => event.data.message)).toMatchObject([{ toolCallId: 'sandbox-refresh-failure', isError: true, content: [{ type: 'text', text: stderr }] }])+ expect(assistants().map(event => event.data.step)).toEqual([1, 2])+ expect(runtime.exchanges.size).toBe(0)+ }, 10_000)++ it('accepts semantically identical content properties at the final-result boundary', async () => {+ const current = await exchange()+ nativeCall(current.state.native, 'reordered')+ current.state.native.toolEnd('reordered', 'canonical native output')+ const result = await execute('reordered', current.state.signal)+ expect(result).toEqual({ isError: false, value: 'canonical native output', content: [{ type: 'text', text: 'canonical native output' }] })+ expect(sink.acceptTool(results[0]!.exec, { ...result, content: [{ text: 'canonical native output', type: 'text' }] })).toBeUndefined()+ expect(current.state.tools.get('reordered')!.accepted).toBe(true)+ expect(current.state.signal.aborted).toBe(false)+ })++ it.each([false, true])('rejects changed native isError=%s content at the final-result boundary', async (isError) => {+ const current = await exchange()+ nativeCall(current.state.native, 'rewritten-error')+ current.state.native.toolEnd('rewritten-error', 'canonical native output', isError)+ const result = await execute('rewritten-error', current.state.signal)+ expect(result.isError).toBe(isError)+ expect(sink.acceptTool(results[0]!.exec, { ...result, content: [{ type: 'text', text: 'rewritten native error' }] })).toBeUndefined()+ expect(current.state.signal.aborted).toBe(true)+ expect(current.state.failure).toMatchObject({ message: expect.stringContaining('BRIDGE_TOOL_RESULT_REJECTED') })+ })++ it('replays native results without duplicate DSH pre, around, or post policies while preserving core guards', async () => {+ const inherited = inheritedTool()+ const pre = vi.fn(async () => ({ kind: 'deny' as const, reason: 'DSH policy must not gate native replay' }))+ const guard = vi.fn(() => undefined)+ const around = vi.fn(async () => ({ isError: false as const, value: 'DSH replacement', content: [{ type: 'text' as const, text: 'DSH replacement' }] }))+ const post = vi.fn(async (): Promise<PostToolDecision> => ({ kind: 'block', feedback: [{ type: 'text', text: 'DSH spill or repeat replacement' }] }))+ context.on('tools/pre-execute', pre, { global: true })+ context.tools.guard(guard)+ agent.ctx.on('tools/execute', around)+ agent.ctx.on('tools/post-execute', post)+ nativeScript = async (native) => {+ nativeCall(native, 'native-policy-isolation')+ native.toolEnd('native-policy-isolation', 'canonical native output')+ native.assistant('final', [{ type: 'text', text: 'native done' }])+ }+ await runTurn()+ expect(errors).toEqual([])+ expect(pre).not.toHaveBeenCalled()+ expect(guard).toHaveBeenCalledOnce()+ expect(around).not.toHaveBeenCalled()+ expect(post).not.toHaveBeenCalled()+ expect(inherited).not.toHaveBeenCalled()+ expect(toolResults().map(event => event.data.message)).toMatchObject([{ toolCallId: 'native-policy-isolation', isError: false, content: [{ type: 'text', text: 'canonical native output' }] }])+ expect(assistants().map(event => event.data.step)).toEqual([1, 2])+ expect(runtime.exchanges.size).toBe(0)+ }, 10_000)++ it.each(['global', 'scoped'] as const)('retains a %s monotonic guard denial rather than silently force-allowing native replay', async (scope) => {+ const inherited = inheritedTool()+ const guard = vi.fn(() => 'composition guard denied replay')+ ;(scope === 'global' ? context.tools : agent.ctx.tools).guard(guard)+ nativeScript = async (native) => {+ nativeCall(native, 'native-guard')+ native.toolEnd('native-guard', 'canonical native output')+ native.assistant('final', [{ type: 'text', text: 'must not override guard' }])+ }+ await runTurn()+ expect(guard).toHaveBeenCalledOnce()+ expect(inherited).not.toHaveBeenCalled()+ expect(errors).toHaveLength(1)+ expect(errors[0]).toMatchObject({ message: expect.stringContaining('BRIDGE_TOOL_RESULT_REJECTED') })+ expect(results.map(({ result }) => result)).toMatchObject([{ isError: true, error: { message: 'composition guard denied replay' }, content: [{ type: 'text', text: 'Error: composition guard denied replay' }] }])+ expect(assistants()).toHaveLength(1)+ expect(runtime.exchanges.size).toBe(0)+ }, 10_000)++ it('leaves ordinary DSH policies active outside a native exchange', async () => {+ const body = inheritedTool('ordinary_dsh_tool')+ const pre = vi.fn(async (_exec: ToolExecution, next: () => Promise<import('@deepseek-ai/dsh-tools').PreToolDecision>) => next())+ const guard = vi.fn(() => undefined)+ const around = vi.fn(async (_exec: ToolExecution, next: () => Promise<ToolExecutionResult>) => next())+ const post = vi.fn(async (): Promise<PostToolDecision> => ({ kind: 'accept', content: [{ type: 'text', text: 'ordinary DSH post policy' }] }))+ agent.ctx.on('tools/pre-execute', pre)+ agent.ctx.tools.guard(guard)+ agent.ctx.on('tools/execute', around)+ agent.ctx.on('tools/post-execute', post)+ const result = await execute('ordinary', new AbortController().signal, {}, 'ordinary_dsh_tool')+ expect(pre).toHaveBeenCalledOnce()+ expect(guard).toHaveBeenCalledOnce()+ expect(around).toHaveBeenCalledOnce()+ expect(post).toHaveBeenCalledOnce()+ expect(body).toHaveBeenCalledOnce()+ expect(result).toEqual({ isError: false, value: 'inherited DSH body must not run', content: [{ type: 'text', text: 'ordinary DSH post policy' }] })+ })++ it('keeps a native turn alive when DSH injects a mid-turn approval-policy notice', async () => {+ context.on('tools/result', (exec) => {+ if (exec.callId === 'policy-notice')+ agent.inject(llmModule.createUserMessage({ source: { kind: 'user-approval' }, content: [{ type: 'text', text: 'Approval prompts are disabled in this session.' }] }))+ return undefined+ })+ nativeScript = async (native) => {+ nativeCall(native, 'policy-notice')+ native.toolEnd('policy-notice', 'native output')+ native.assistant('final', [{ type: 'text', text: 'continued after the policy switch' }])+ }+ await runTurn()+ expect(errors).toEqual([])+ expect(connection.submit).toHaveBeenCalledOnce()+ expect(connection.submit.mock.calls[0]![0]).toMatchObject([{ content: [{ type: 'text', text: 'native task' }] }])+ expect(assistants().map(event => event.data.step)).toEqual([1, 2])+ expect(toolResults().map(event => event.data.message.toolCallId)).toEqual(['policy-notice'])+ expect(events.filter((event): event is Extract<SessionEvent, { type: 'agent/inbox/spliced' }> => event.type === 'agent/inbox/spliced' && event.data.target === 'next-step').flatMap(event => event.data.inserted).map(message => message.source.kind)).toEqual(['user-approval'])+ expect(events.filter(event => event.type === 'user/message').map(event => event.data.source.kind)).toEqual(['user', 'user-approval'])+ expect(runtime.exchanges.size).toBe(0)+ }, 10_000)++ it('preserves an empty native error without adding fallback text to its content', async () => {+ nativeScript = async (native) => {+ nativeCall(native, 'empty-error')+ native.toolEnd('empty-error', '', true)+ native.assistant('final', [{ type: 'text', text: 'native done' }])+ }+ await runTurn()+ expect(errors).toEqual([])+ expect(results.map(({ result }) => result)).toEqual([{ isError: true, error: { message: 'Native tool failed', info: { name: 'NativeToolError', code: 'BRIDGE_NATIVE_TOOL_ERROR' } }, content: [{ type: 'text', text: '' }] }])+ expect(toolResults().map(event => event.data.message.content)).toEqual([[{ type: 'text', text: '' }]])+ expect(assistants().map(event => event.data.step)).toEqual([1, 2])+ }, 10_000)++ it.each(['block', 'value', 'content', 'context'] as const)('keeps native output unchanged instead of applying duplicate post-execute %s policy', async (policy) => {const inherited = inheritedTool()const additional = llmModule.createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: 'extra policy context' }] })- agent.ctx.on('tools/post-execute', async (): Promise<PostToolDecision> => {+ const rewrite = vi.fn(async (): Promise<PostToolDecision> => {if (policy === 'block')return { kind: 'block', feedback: [{ type: 'text', text: 'policy denied native output' }] }if (policy === 'value')@@ -303,20 +524,20 @@ describe('real official cross-step native sink', () => {return { kind: 'accept', content: [{ type: 'text', text: 'rewritten native content' }] }return { kind: 'accept', additionalContexts: [additional] }})+ agent.ctx.on('tools/post-execute', rewrite)nativeScript = async (native) => {- nativeCall(native, 'rewritten')- native.toolEnd('rewritten', 'canonical native output')- native.assistant('final', [{ type: 'text', text: 'must not enter another official step' }])+ nativeCall(native, 'native-policy')+ native.toolEnd('native-policy', 'canonical native output')+ native.assistant('final', [{ type: 'text', text: 'native done' }])}await runTurn()expect(connection.submit).toHaveBeenCalledOnce()expect(inherited).not.toHaveBeenCalled()- expect(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(rewrite).not.toHaveBeenCalled()+ expect(errors).toEqual([])+ expect(toolResults().map(event => event.data.message)).toMatchObject([{ toolCallId: 'native-policy', isError: false, content: [{ type: 'text', text: 'canonical native output' }] }])+ expect(assistants().map(event => event.data.step)).toEqual([1, 2])+ expect(events.filter(event => event.type === 'user/message').map(event => event.data.id)).not.toContain(additional.id)expect(runtime.exchanges.size).toBe(0)}, 10_000)diff --git a/packages/dsh-tauri-kernel/src/host/service/sink.ts b/packages/dsh-tauri-kernel/src/host/service/sink.tsindex a4f05ec3..896192b2 100644--- a/packages/dsh-tauri-kernel/src/host/service/sink.ts+++ b/packages/dsh-tauri-kernel/src/host/service/sink.ts@@ -1,8 +1,9 @@import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'-import type { ToolDispatchExecution, ToolExecution, ToolExecutionResult, ToolRunContext } from '@deepseek-ai/dsh-tools'+import type { PostToolDecision, PreToolDecision, ToolDispatchExecution, ToolExecution, ToolExecutionResult, ToolRunContext } from '@deepseek-ai/dsh-tools'import type { HostContext, NativeExecution } from '../types'import type { NativeToolResult, OfficialSink, SinkState, StreamTrack, ToolTrack } from './sink.types'import { Buffer } from 'node:buffer'+import { isDeepStrictEqual } from 'node:util'import { getServerContext } from 'dsh-h3/utils'import { defineService } from 'dsh-tauri'import { runtime } from '../config/runtime'@@ -220,35 +221,8 @@ export const sink = defineService({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+ async execute(): Promise<never> {+ throw new Error('BRIDGE_TOOL_ROUTE_UNAVAILABLE: 原生调用未经过官方工具检查。')},})state.registrations.set(name, dispose)@@ -260,10 +234,14 @@ export const sink = defineService({if (!state.active)returnif (error === undefined && !state.signal.aborted) {- if ([...state.streams.values()].some(current => current.content === undefined))+ 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: 原生内核没有确认全部工具结果。')+ }+ else {+ const pending = [...state.tools].filter(([, tool]) => tool.result === undefined).map(([id, tool]) => ({ id, name: tool.name }))+ if (pending.length > 0)+ error = new Error(`BRIDGE_TOOL_UNSETTLED: 原生内核没有确认全部工具结果。未确认工具:${JSON.stringify(pending)}`)+ }}state.failure = error ?? (state.signal.aborted ? state.signal.reason : undefined)state.active = false@@ -308,16 +286,64 @@ export const sink = defineService({return official},+ async admitTool(exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision> {+ const official = exec.agent === undefined ? undefined : runtime.exchanges.get(exec.agent.id)+ if (!official)+ return next()+ try {+ expectedTool(official.state, exec)+ official.state.signal.throwIfAborted()+ exec.signal.throwIfAborted()+ // ponytail: 核心单调 guard 仍生效;上游公开原生结果回放接口后再消除这层差异。+ return { kind: 'allow' }+ }+ catch (error) {+ official.state.controller.abort(error)+ await official.state.task+ throw error+ }+ },+async executeTool(exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> {const official = exec.agent === undefined ? undefined : runtime.exchanges.get(exec.agent.id)if (!official)return next()+ const state = official.state+ const abort = (): void => state.controller.abort(exec.signal.reason)try {- const tool = expectedTool(official.state, exec)+ const tool = expectedTool(state, exec)if (tool.dispatched)throw new Error('BRIDGE_TOOL_ALREADY_DISPATCHED: 不能重复派发原生工具调用。')tool.dispatched = true- return await next()+ exec.signal.addEventListener('abort', abort, { once: true })+ if (exec.signal.aborted)+ abort()+ state.signal.throwIfAborted()+ const result = await tool.wait+ exec.signal.throwIfAborted()+ state.signal.throwIfAborted()+ const content = [{ type: 'text' as const, text: result.output }]+ return result.isError+ ? { isError: true, error: { message: result.output || 'Native tool failed', info: { name: 'NativeToolError', code: 'BRIDGE_NATIVE_TOOL_ERROR' } }, content }+ : { isError: false, value: result.output, content }+ }+ catch (error) {+ state.controller.abort(error)+ await state.task+ throw error+ }+ finally {+ exec.signal.removeEventListener('abort', abort)+ }+ },++ async finishTool(exec: ToolExecution, _result: Readonly<ToolExecutionResult>, next: () => Promise<PostToolDecision>): Promise<PostToolDecision> {+ const official = exec.agent === undefined ? undefined : runtime.exchanges.get(exec.agent.id)+ if (!official)+ return next()+ try {+ expectedTool(official.state, exec)+ return { kind: 'accept' }}catch (error) {official.state.controller.abort(error)@@ -327,14 +353,14 @@ export const sink = defineService({},commitTool(value: Session, event: SessionEvent): void {- if (event.type !== 'tool/result')+ if (event.type !== 'tool/result' || event.surfaceOp !== 'append')returnconst official = runtime.exchanges.get(value.id)if (!official || official.state.input.agent.session !== value || official.state.input.turn !== event.data.turn)returnconst state = official.stateconst 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) {+ if (!tool || tool.step !== event.data.step || !tool.accepted || tool.committed || !tool.result || tool.result.isError !== (event.data.message.isError === true) || !isDeepStrictEqual(event.data.message.content, [{ type: 'text', text: tool.result.output }]) || (tool.result.isError && event.data.error?.code !== 'BRIDGE_NATIVE_TOOL_ERROR') || event.data.meta !== undefined) {state.failure = new Error('BRIDGE_TOOL_RESULT_REJECTED: 官方日志没有完整保留原生工具结果。')state.controller.abort(state.failure)return@@ -348,7 +374,7 @@ export const sink = defineService({return undefinedtry {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'))+ if (!tool.dispatched || !tool.result || result.isError !== tool.result.isError || result.additionalContexts?.length || result.concludesTurn || !isDeepStrictEqual(result.content, [{ type: 'text', text: tool.result.output }]) || (!result.isError && result.value !== tool.result.output) || (result.isError && result.error.info?.code !== 'BRIDGE_NATIVE_TOOL_ERROR'))throw new Error('BRIDGE_TOOL_RESULT_REJECTED: 官方工具结果与原生结果不一致,不能继续原生回合。')tool.accepted = true}@@ -380,7 +406,7 @@ function expectedTool(state: SinkState, exec: Readonly<ToolExecution> | ToolRunCfunction sameArguments(raw: string, value: unknown): boolean {try {- return JSON.stringify(raw === '' ? {} : JSON.parse(raw)) === JSON.stringify(value)+ return isDeepStrictEqual(raw === '' ? {} : JSON.parse(raw), value)}catch {return raw === valuediff --git a/packages/dsh-tauri-kernel/src/host/types/index.ts b/packages/dsh-tauri-kernel/src/host/types/index.tsindex 1a850eb4..3611aee1 100644--- a/packages/dsh-tauri-kernel/src/host/types/index.ts+++ b/packages/dsh-tauri-kernel/src/host/types/index.ts@@ -22,7 +22,6 @@ export interface PlatformLoader {export interface RuntimeModules {ToolCallId: typeof LlmRuntime.ToolCallId- HarnessError: typeof LlmRuntime.HarnessErrorLlmAdapter: typeof LlmRuntime.LlmAdapterisAgentLoopRequest: typeof LlmRuntime.isAgentLoopRequestappendPluginRecord?: (session: Session, type: 'plugin:dsh-tauri-kernel/kernel' | 'plugin:dsh-tauri-kernel/model', data: KernelBinding | NativeTurnOptions) => numberdiff --git a/packages/dsh-tauri-kernel/src/host/utils/runtime-modules.ts b/packages/dsh-tauri-kernel/src/host/utils/runtime-modules.tsindex f68f54c3..2a219411 100644--- a/packages/dsh-tauri-kernel/src/host/utils/runtime-modules.ts+++ b/packages/dsh-tauri-kernel/src/host/utils/runtime-modules.ts@@ -14,7 +14,6 @@ export async function loadRuntimeModules(loader: PlatformLoader): Promise<Runtimconst [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'),