diff --git a/licenses/DSH-native-NOTICES.md b/licenses/DSH-native-NOTICES.md new file mode 100644 index 0000000..7beaad0 --- /dev/null +++ b/licenses/DSH-native-NOTICES.md @@ -0,0 +1,11 @@ +# DSH native interaction adaptation + +Source: https://github.com/deepseek-ai/deepseek-harness + +Fixed npm version: 0.2.1-rc.2. Copyright (c) 2026 DeepSeek, MIT; see [license](DeepSeek-Harness-MIT.txt). + +`web/modules/assistant/dsh-native.js` extracts `clampWidth`, `computeColumns` and `groupOptions` from the installed official `@deepseek-ai/dsh-client-ui-layout/lib/client.js` and `@deepseek-ai/dsh-client-ui-commands/lib/client.js`. Geometry and grouping function bodies are preserved. The popup's substring matching policy and exact-name command resolution are adapted to this project's fixed command catalog, excluding host aliases and React/Cordis services. + +The original three-column precedence, collapsible process groups, stable transcript nodes, command popup keyboard behavior and per-conversation detail pane are adapted to the existing Tabler workspace. These browser helpers are actually used by the layout and command menu. No native shell, filesystem, plugin manager, internal reasoning viewer, or separate DSH Web host is mounted. + +The existing server adapter continues to run the pinned official DSH session/agent/headless profile. Its NDJSON lifecycle is consumed through a narrow business-safe event adapter; final responses retain the application schema validation. diff --git a/licenses/DeepSeek-Harness-MIT.txt b/licenses/DeepSeek-Harness-MIT.txt new file mode 100644 index 0000000..c1f7a78 --- /dev/null +++ b/licenses/DeepSeek-Harness-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 DeepSeek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/Marked-MIT.txt b/licenses/Marked-MIT.txt new file mode 100644 index 0000000..4bd2d4a --- /dev/null +++ b/licenses/Marked-MIT.txt @@ -0,0 +1,44 @@ +# License information + +## Contribution License Agreement + +If you contribute code to this project, you are implicitly allowing your code +to be distributed under the MIT license. You are also implicitly verifying that +all code is your original work. `` + +## Marked + +Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/) +Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +## Markdown + +Copyright © 2004, John Gruber +http://daringfireball.net/ +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. diff --git a/package-lock.json b/package-lock.json index 94657c8..7fc64f4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "imapflow": "2.4.3", "jszip": "3.10.1", "mailparser": "3.12.4", + "marked": "18.1.2", "nodemailer": "10.2.1", "photoswipe": "5.4.4", "playwright-core": "1.62.1", @@ -3116,6 +3117,18 @@ "node": ">=20.0.0" } }, + "node_modules/marked": { + "version": "18.1.2", + "resolved": "https://registry.npmjs.org/marked/-/marked-18.1.2.tgz", + "integrity": "sha512-DfOnvLAQ6WYeWxWO1u4RyFOeqyHup6dks5PPqnoFiooU7ipRvidO/2j8plhAHIiZg574E9ZlzSjUiPMLAzFkgg==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz", diff --git a/package.json b/package.json index adacc69..e6ab4ce 100644 --- a/package.json +++ b/package.json @@ -13,8 +13,9 @@ "service:stop": "node scripts/service.cjs stop", "service:restart": "node scripts/service.cjs restart", "test": "npm run test:business", - "test:business": "node --test --test-concurrency=1 tests/service/supervisor-crash.test.cjs tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-validator.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/template-test-policy.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs", - "test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"" + "test:business": "node --test --test-concurrency=1 tests/service/supervisor-crash.test.cjs tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/workspace-events.test.cjs tests/assistant/dsh-events.test.cjs tests/assistant/workspace-http.test.cjs tests/assistant/events-client.test.cjs tests/assistant/diagnostic-workspace-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-validator.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/template-test-policy.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs", + "test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"", + "test:assistant": "node --test --test-concurrency=1 \"tests/assistant/*.test.cjs\"" }, "engines": { "node": ">=22.13" @@ -25,15 +26,16 @@ "@whyour/qinglong-cli": "0.1.2", "docx-preview": "0.4.1", "exceljs": "4.4.0", + "html-to-text": "10.0.1", "imapflow": "2.4.3", "jszip": "3.10.1", "mailparser": "3.12.4", + "marked": "18.1.2", "nodemailer": "10.2.1", "photoswipe": "5.4.4", "playwright-core": "1.62.1", "sanitize-html": "2.18.1", - "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz", - "html-to-text": "10.0.1" + "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz" }, "overrides": { "exceljs": { diff --git a/src/app/assets.cjs b/src/app/assets.cjs index dc82854..1ada20d 100644 --- a/src/app/assets.cjs +++ b/src/app/assets.cjs @@ -49,6 +49,9 @@ function createAssets(){ '/notifications.js':{path:path.join(webRoot,'modules/notifications/view.js'),type:'text/javascript'}, '/assistant-operations.js':{path:path.join(webRoot,'modules/assistant/operations.js'),type:'text/javascript'}, '/assistant.js':{path:path.join(webRoot,'modules/assistant/view.js'),type:'text/javascript'}, + ...Object.fromEntries(['dsh-native','layout','conversation','commands','context-panel','events-client'].map(name=>['/assistant-'+name+'.js',{path:path.join(webRoot,'modules/assistant',name+'.js'),type:'text/javascript'}])), + '/assistant-workspace.css':{path:path.join(webRoot,'modules/assistant/workspace.css'),type:'text/css'}, + '/vendor/marked.js':{path:path.join(path.dirname(require.resolve('marked')),'marked.umd.js'),type:'text/javascript'}, '/health.js':{path:path.join(webRoot,'modules/health/view.js'),type:'text/javascript'}, '/app.css':{path:path.join(webRoot,'app.css'),type:'text/css'}, '/vendor/tabler.css':{path:require.resolve('@tabler/core/dist/css/tabler.min.css'),type:'text/css'}, diff --git a/tests/assistant/assistant-http-ui.test.cjs b/tests/assistant/assistant-http-ui.test.cjs index 53ef3db..9409e90 100644 --- a/tests/assistant/assistant-http-ui.test.cjs +++ b/tests/assistant/assistant-http-ui.test.cjs @@ -23,7 +23,7 @@ test('chat UI persists conversations, shows escaped messages and explicit fixed const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));page.setDefaultTimeout(15000); await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click(); await page.getByLabel('发送给 DSH',{exact:true}).fill('分析订单运行状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.locator('.assistant-reply').getByText('已读取运行状态。',{exact:true}).waitFor();assert.equal(await page.locator('.assistant-reply img').count(),0);assert.equal(checks(),0); - await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).click();await page.getByText('操作已完成',{exact:true}).waitFor();assert.equal(checks(),1);await page.reload();await page.locator('.assistant-reply').getByText('已读取运行状态。',{exact:true}).waitFor(); + await page.getByRole('button',{name:'查看操作(1)',exact:true}).click();await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).click();await page.getByText('操作已完成',{exact:true}).waitFor();assert.equal(checks(),1);await page.reload();await page.locator('.assistant-reply').getByText('已读取运行状态。',{exact:true}).waitFor(); await page.getByLabel('发送给 DSH',{exact:true}).fill('挂起诊断');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'停止回复',exact:true}).click();await page.getByText('已停止本轮回复。',{exact:true}).waitFor(); await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/zcode-chat-desktop.png',fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]); }); @@ -31,7 +31,7 @@ test('chat UI persists conversations, shows escaped messages and explicit fixed test('a long action displays persisted sampling progress before its POST completes',{timeout:60000},async t=>{ const {base,store}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'fixture',apiKey:'PRIVATE_PROGRESS_KEY',allowActions:true}); const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();page.setDefaultTimeout(8000); - await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();await page.getByLabel('发送给 DSH',{exact:true}).fill('读取状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).waitFor(); + await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();await page.getByLabel('发送给 DSH',{exact:true}).fill('读取状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'查看操作(1)',exact:true}).click();await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).waitFor(); let started=false,finished=false,release;const gate=new Promise(resolve=>release=resolve);t.after(()=>release()); await page.route('**/api/assistant/conversations/*',async route=>{const response=await route.fetch(),data=await response.json();if(started)for(const turn of data.turns)for(const action of turn.actions||[])Object.assign(action,{status:finished?'success':'running',progress:{completed:1,total:3,captured:1,failed:0}});await route.fulfill({json:data});}); await page.route('**/api/assistant/conversations/*/actions/*/execute',async route=>{started=true;await gate;finished=true;await route.fulfill({json:{status:'success'}});}); @@ -42,15 +42,15 @@ test('a long action displays persisted sampling progress before its POST complet test('personal conversation UI archives, pages and restores evidence without sending a model request',{timeout:60000},async t=>{ const {base,store}=await fixture(t);const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:390,height:844}});page.setDefaultTimeout(10000); - await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click(); + await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'会话列表',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click(); await page.getByRole('button',{name:'归档会话',exact:true}).click();await page.getByRole('button',{name:'归档会话',exact:true}).waitFor({state:'hidden'}); - await page.getByLabel('会话范围',{exact:true}).selectOption('archived');await page.locator('[data-assistant-conversation]').first().click(); + await page.getByRole('button',{name:'会话列表',exact:true}).click();await page.getByLabel('会话范围',{exact:true}).selectOption('archived');await page.locator('[data-assistant-conversation]').first().click(); await page.getByRole('button',{name:'恢复会话',exact:true}).click();await page.getByRole('button',{name:'恢复会话',exact:true}).waitFor({state:'hidden'}); - await page.getByLabel('会话范围',{exact:true}).selectOption('active');await page.locator('[data-assistant-conversation]').first().waitFor(); + await page.getByRole('button',{name:'会话列表',exact:true}).click();await page.getByLabel('会话范围',{exact:true}).selectOption('active');await page.locator('[data-assistant-conversation]').first().waitFor(); assert.equal(store.listConversations(store.db.prepare('SELECT owner FROM conversations').get().owner,{scope:'archived'}).total,0);assert.equal(store.usage().calls,0);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true); }); test('admin reviews selected code changes before isolated repair and sees the rollback result',{timeout:120000},async t=>{ const {base,store,assistant}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/anthropic',model:'fixture',apiKey:'PRIVATE_REPAIR_KEY',allowActions:true,allowCodeRepair:true,repairRepository:process.cwd()});let runs=0;assistant.repairFactory=()=>({readSources:paths=>{assert.deepEqual(paths,['src/demo.cjs']);return {baselineCommit:'a'.repeat(40),files:[{path:'src/demo.cjs',content:'BEFORE'}]};},run:async()=>{runs++;return {operationId:'repair-test',status:'rolled_back',previousCommit:'a'.repeat(40),resultCommit:'b'.repeat(40),testOutcome:'failed'};}});assistant.runtime.chat=async()=>JSON.stringify({reply:'修复建议',actions:[],repair:{files:[{path:'src/demo.cjs',content:'AFTER'}]}}); - const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}});await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByText('提出代码修复',{exact:true}).click();await page.locator('#repair-paths').fill('src/demo.cjs');await page.locator('#repair-goal').fill('修复问题');await page.getByRole('button',{name:'生成修复建议',exact:true}).click();await page.getByText('修复建议',{exact:true}).waitFor();assert.equal(runs,0);await page.getByText('src/demo.cjs · 查看修改前后',{exact:true}).click();await page.getByText('BEFORE',{exact:true}).waitFor();await page.getByText('AFTER',{exact:true}).waitFor();await page.getByRole('button',{name:'执行:审查并执行隔离代码修复',exact:true}).click();await page.getByText('测试未通过,已回退',{exact:true}).waitFor();assert.equal(runs,1); + const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}});await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('tab',{name:'记录',exact:true}).click();await page.getByText('提出代码修复',{exact:true}).click();await page.locator('#repair-paths').fill('src/demo.cjs');await page.locator('#repair-goal').fill('修复问题');await page.getByRole('button',{name:'生成修复建议',exact:true}).click();await page.getByText('修复建议',{exact:true}).waitFor();assert.equal(runs,0);await page.getByText('src/demo.cjs · 查看修改前后',{exact:true}).click();await page.getByText('BEFORE',{exact:true}).waitFor();await page.getByText('AFTER',{exact:true}).waitFor();await page.getByRole('button',{name:'执行:审查并执行隔离代码修复',exact:true}).click();await page.getByText('测试未通过,已回退',{exact:true}).waitFor();assert.equal(runs,1); }); -test('operation history loads older audit events instead of hiding everything beyond the newest hundred',{timeout:120000},async t=>{const {base,assistant}=await fixture(t);const events=Array.from({length:125},(_,i)=>({id:125-i,operationId:'op-'+i,actor:'admin-fixture',createdAt:'2026-10-27T01:00:00Z',step:'model',status:'success',detail:'TRACE-'+i}));assistant.journal={list:({beforeId})=>events.filter(e=>!beforeId||e.idbrowser.close());const page=await browser.newPage();await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByText('TRACE-0',{exact:true}).waitFor();assert.equal(await page.getByText('TRACE-124',{exact:true}).count(),0);await page.getByRole('button',{name:'加载更早记录',exact:true}).click();await page.getByText('TRACE-124',{exact:true}).waitFor();assert.equal(await page.getByText('TRACE-0',{exact:true}).count(),1);}); +test('operation history loads older audit events instead of hiding everything beyond the newest hundred',{timeout:120000},async t=>{const {base,assistant}=await fixture(t);const events=Array.from({length:125},(_,i)=>({id:125-i,operationId:'op-'+i,actor:'admin-fixture',createdAt:'2026-10-27T01:00:00Z',step:'model',status:'success',detail:'TRACE-'+i}));assistant.journal={list:({beforeId})=>events.filter(e=>!beforeId||e.idbrowser.close());const page=await browser.newPage();await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('tab',{name:'记录',exact:true}).click();await page.getByText('TRACE-0',{exact:true}).waitFor();assert.equal(await page.getByText('TRACE-124',{exact:true}).count(),0);await page.getByRole('button',{name:'加载更早记录',exact:true}).click();await page.getByText('TRACE-124',{exact:true}).waitFor();assert.equal(await page.getByText('TRACE-0',{exact:true}).count(),1);}); diff --git a/tests/assistant/diagnostic-workspace-ui.test.cjs b/tests/assistant/diagnostic-workspace-ui.test.cjs new file mode 100644 index 0000000..4c066bd --- /dev/null +++ b/tests/assistant/diagnostic-workspace-ui.test.cjs @@ -0,0 +1,37 @@ +'use strict'; +const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'); +async function fixture(t){ + const {Store}=require('../../src/modules/dashboard/store.cjs'),{AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'); + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-workspace-ui-')),users=new Store(path.join(dir,'users'));users.bootstrap('admin','Test-password-123');const store=new AssistantStore(path.join(dir,'assistant'));let calls=0; + const assistant=new AssistantService({store,dashboard:users,runtime:{chat:async({onEvent})=>{calls++;onEvent?.({kind:'model',data:{phase:'step_start'}});await new Promise(r=>setTimeout(r,150));return JSON.stringify({reply:'## 诊断结论\n\n连接状态正常。\n\n| 项目 | 结果 |\n|---|---|\n| 存储 | 正常 |',actions:[]});}}}); + const server=createDashboard({store:users,assistant,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r)); + const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1366,height:768}});page.setDefaultTimeout(10000); + t.after(async()=>{await browser.close();server.closeAssistantStreams?.();await assistant.stop();server.closeAllConnections();await new Promise(r=>server.close(r));store.close();await fs.rm(dir,{recursive:true,force:true});}); + await page.goto('http://127.0.0.1:'+server.address().port+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click(); + return {page,store,assistant,calls:()=>calls}; +} +test('three-column workspace keeps input visible and diagnostic commands have no hidden side effects',{timeout:90000},async t=>{ + const {page,calls}=await fixture(t);await page.locator('.assistant-workspace').waitFor();const input=page.getByLabel('发送给 DSH',{exact:true}),rect=await input.boundingBox();assert.ok(rect.y+rect.height<=768); + await input.fill('/help');await input.press('Enter');await page.getByText('固定诊断命令',{exact:true}).waitFor();assert.equal(calls(),0); + await input.fill('/status');await input.press('Enter');await page.getByRole('heading',{name:'诊断概况',exact:true}).waitFor();assert.equal(calls(),0); + await input.fill('/shell');await input.press('Enter');await page.locator('#assistant-error').filter({hasText:'此命令未开放'}).waitFor();assert.equal(await input.inputValue(),'/shell');assert.equal(calls(),0); + await input.fill('/status');await input.press('Enter');await page.getByRole('heading',{name:'诊断概况',exact:true}).waitFor();await fs.mkdir('output/verification/dsh-workspace',{recursive:true});for(const [width,height]of [[1600,900],[1366,768],[1024,768],[390,844]]){await page.setViewportSize({width,height});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:`output/verification/dsh-workspace/workspace-${width}.png`,fullPage:true});} +}); +test('replies render structured content and preserve DOM nodes across context refresh',{timeout:90000},async t=>{ + const {page,store}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'fixture',apiKey:'TEST_ONLY_KEY',allowActions:false});await page.reload(); + const input=page.getByLabel('发送给 DSH',{exact:true});await input.fill('诊断连接');await page.getByRole('button',{name:'发送',exact:true}).click();await page.locator('.assistant-answer table').waitFor();assert.equal(await page.locator('.assistant-answer h2').textContent(),'诊断结论'); + await page.locator('.assistant-answer').evaluate(node=>{node.dataset.identity='retained';});await page.getByRole('button',{name:'刷新概况',exact:true}).click();assert.equal(await page.locator('.assistant-answer').getAttribute('data-identity'),'retained'); + await page.getByRole('button',{name:'诊断依据',exact:true}).click();await page.locator('#aw-panel-evidence').filter({hasText:'实际用于该轮分析'}).waitFor();await input.fill('未发送的草稿');await page.getByRole('button',{name:'新建对话',exact:true}).click();assert.match(await page.locator('#aw-panel-evidence').textContent(),/点击回答/);await input.fill('另一个草稿');await page.locator('[data-assistant-conversation]').filter({hasText:'诊断连接'}).click();assert.equal(await input.inputValue(),'未发送的草稿'); +}); +test('native-style action presentation keeps unknown and blocked results distinct from success',{timeout:90000},async t=>{ + const {page}=await fixture(t);const labels=await page.evaluate(()=>({unknown:AssistantConversation.actionState({status:'needs_review'}),blocked:AssistantConversation.actionState({status:'success',result:{status:'blocked'}})}));assert.equal(labels.unknown,'结果待核验');assert.equal(labels.blocked,'操作受阻'); +}); +test('a failed late submission cannot replace the draft or error of a newer conversation',{timeout:90000},async t=>{ + const {page,store}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'fixture',apiKey:'TEST_ONLY_KEY',allowActions:false});await page.reload();await page.getByRole('button',{name:'新建对话',exact:true}).click(); + let release;const gate=new Promise(r=>release=r);t.after(()=>release());await page.route('**/api/assistant/conversations/*/messages',async route=>{await gate;await route.fulfill({status:503,json:{error:'OLD_REQUEST_FAILED'}});}); + const input=page.getByLabel('发送给 DSH',{exact:true});await input.fill('旧会话请求');const started=page.waitForRequest(r=>r.url().endsWith('/messages'));await page.getByRole('button',{name:'发送',exact:true}).click();await started;await page.getByRole('button',{name:'新建对话',exact:true}).click();await input.fill('新会话草稿');const returned=page.waitForResponse(r=>r.url().endsWith('/messages')&&r.status()===503);release();await returned;await page.evaluate(()=>new Promise(r=>setTimeout(r,100)));assert.equal(await input.inputValue(),'新会话草稿');assert.equal(await page.locator('#assistant-error').textContent(),''); +}); +test('local status commands clear an old diagnostic target before the next ordinary question',{timeout:90000},async t=>{ + const {page,store,assistant}=await fixture(t);assistant.deps.workspace={snapshot:()=>({connections:[{id:'bpm-a',name:'测试连接 A',owner:'admin',status:'connected'}],exceptions:[]}),getConnection:()=>({id:'bpm-a',owner:'admin'})};store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'fixture',apiKey:'TEST_ONLY_KEY',allowActions:false});await page.reload(); + const input=page.getByLabel('发送给 DSH',{exact:true});await input.fill('/bpm');await input.press('Enter');await page.getByRole('option',{name:/测试连接 A/}).click();await input.fill('/status');await input.press('Enter');await page.getByRole('heading',{name:'诊断概况',exact:true}).waitFor();await input.fill('查看全部运行状态');const submitted=page.waitForRequest(r=>r.url().endsWith('/messages'));await page.getByRole('button',{name:'发送',exact:true}).click();assert.equal((await submitted).postDataJSON().diagnostic,undefined); +}); diff --git a/tests/assistant/events-client.test.cjs b/tests/assistant/events-client.test.cjs new file mode 100644 index 0000000..6fa3742 --- /dev/null +++ b/tests/assistant/events-client.test.cjs @@ -0,0 +1,31 @@ +'use strict'; +const {test}=require('node:test'),assert=require('node:assert/strict'),vm=require('node:vm'),fs=require('node:fs'); +const source=fs.readFileSync('web/modules/assistant/events-client.js','utf8'); +const settle=async()=>{for(let i=0;i<15;i++)await Promise.resolve();}; +test('event transport falls back after stream failures, resumes by cursor and never posts messages',async t=>{ + t.mock.timers.enable({apis:['setTimeout']});let fetches=0,polls=0,changes=0;const accepted=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{fetches++;throw new TypeError('disconnected');}};vm.runInNewContext(source,scope); + const client=scope.window.AssistantEvents.connect({id:'own',api:async route=>{assert.match(route,/\/events\?after=0$/);polls++;return {events:[{conversationId:'own',seq:1,kind:'completed'}],nextCursor:1,hasMore:false};},onEvents:rows=>accepted.push(...rows),onChange:async()=>{changes++;}});await settle();t.mock.timers.tick(1000);await settle();t.mock.timers.tick(2000);await settle();assert.equal(fetches,3);assert.equal(polls,1);assert.equal(client.cursor,1);assert.equal(changes,1);assert.equal(accepted.length,1);client.dispose();t.mock.timers.tick(120000);await settle();assert.equal(polls,1); +}); +test('event transport treats login failure as terminal instead of reconnecting forever',async t=>{ + t.mock.timers.enable({apis:['setTimeout']});let failures=0,requests=0;const scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{requests++;return new Response('{}',{status:401});}};vm.runInNewContext(source,scope);scope.window.AssistantEvents.connect({id:'own',api:async()=>assert.fail('no fallback after auth failure'),onEvents:()=>assert.fail('no data'),onChange:async()=>{},onAuth:error=>{assert.equal(error.status,401);failures++;}});await settle();t.mock.timers.tick(60000);await settle();assert.equal(failures,1);assert.equal(requests,1); +}); +test('SSE parsing tolerates chunk boundaries and ignores replayed sequence IDs',async()=>{ + const received=[];let controller,changed=0;const scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async(_url,options)=>new Response(new ReadableStream({start(c){controller=c;options.signal.addEventListener('abort',()=>c.close(),{once:true});}}),{headers:{'Content-Type':'text/event-stream'}})};vm.runInNewContext(source,scope); + const client=scope.window.AssistantEvents.connect({id:'own',cursor:1,api:async()=>assert.fail('no polling on a healthy stream'),onEvents:rows=>received.push(...rows),onChange:async()=>{changed++;}});await settle();const encoder=new TextEncoder(),frame=seq=>'event: assistant_event\ndata: '+JSON.stringify({conversationId:'own',seq,kind:'completed'})+'\n\n';controller.enqueue(encoder.encode(frame(1)+frame(2).slice(0,20)));controller.enqueue(encoder.encode(frame(2).slice(20)));await settle();assert.equal(received.length,1);assert.equal(received[0].seq,2);assert.equal(changed,1);client.dispose(); +}); +test('a failed authoritative reload does not acknowledge the final event before recovery',async t=>{ + t.mock.timers.enable({apis:['setTimeout']});let streamCount=0,reloads=0;const cursors=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async url=>{cursors.push(url);streamCount++;return new Response(new ReadableStream({start(c){c.enqueue(new TextEncoder().encode('event: assistant_event\ndata: '+JSON.stringify({conversationId:'own',seq:1,kind:'completed'})+'\n\n'));}}),{headers:{'Content-Type':'text/event-stream'}});}};vm.runInNewContext(source,scope); + const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>assert.fail('not polling yet'),onEvents:()=>{},onChange:async()=>{reloads++;if(reloads===1)throw Error('temporary GET failure');}});await settle();assert.equal(client.cursor,0);t.mock.timers.tick(1000);await settle();assert.equal(streamCount,2);assert.match(cursors[1],/after=0$/);assert.equal(client.cursor,1);client.dispose(); +}); +test('a failed SSE probe does not start a second outstanding polling loop',async t=>{ + t.mock.timers.enable({apis:['setTimeout']});let polls=0;const releases=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{throw Error('offline');}};vm.runInNewContext(source,scope); + const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>{polls++;return await new Promise(resolve=>releases.push(()=>resolve({events:[],nextCursor:0,hasMore:false})));},onEvents:()=>{},onChange:async()=>{}});await settle();t.mock.timers.tick(1000);await settle();t.mock.timers.tick(2000);await settle();assert.equal(polls,1);t.mock.timers.tick(60000);await settle();assert.equal(polls,1);client.dispose();for(const release of releases)release();await settle(); +}); +test('stream negotiation is bounded even when the proxy never returns headers',async t=>{ + t.mock.timers.enable({apis:['setTimeout']});let signal;const scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async(_url,options)=>{signal=options.signal;return await new Promise((_resolve,reject)=>signal.addEventListener('abort',()=>reject(Error('connection timed out')),{once:true}));}};vm.runInNewContext(source,scope); + const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>assert.fail('not polling yet'),onEvents:()=>{},onChange:async()=>{}});await settle();t.mock.timers.tick(45000);await settle();assert.equal(signal.aborted,true);client.dispose(); +}); +test('a probe that connects then ends cannot overlap the pending polling owner',async t=>{ + t.mock.timers.enable({apis:['setTimeout']});let fetches=0,polls=0;const releases=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{if(++fetches<=3)throw Error('offline');return new Response(new ReadableStream({start(c){c.close();}}),{headers:{'Content-Type':'text/event-stream'}});}};vm.runInNewContext(source,scope); + const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>{polls++;return new Promise(resolve=>releases.push(()=>resolve({events:[],hasMore:false})));},onEvents:()=>{},onChange:async()=>{}});await settle();t.mock.timers.tick(1000);await settle();t.mock.timers.tick(2000);await settle();assert.equal(polls,1);t.mock.timers.tick(60000);await settle();assert.equal(fetches,4);assert.equal(polls,1);client.dispose();for(const release of releases)release();await settle(); +}); diff --git a/tests/assistant/pagination-ui.test.cjs b/tests/assistant/pagination-ui.test.cjs index 67bef37..a86ca59 100644 --- a/tests/assistant/pagination-ui.test.cjs +++ b/tests/assistant/pagination-ui.test.cjs @@ -2,13 +2,13 @@ const test=require('node:test'),assert=require('node:assert/strict'),path=require('node:path'); const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); async function fixture(t){ - const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.route('https://synthetic.invalid/**',route=>route.fulfill({body:'
',contentType:'text/html'}));await page.goto('https://synthetic.invalid/');await page.addScriptTag({path:path.resolve('web/modules/assistant/view.js')}); + const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.route('https://synthetic.invalid/**',route=>route.fulfill({body:'
',contentType:'text/html'}));await page.goto('https://synthetic.invalid/');for(const name of ['dsh-native','layout','conversation','commands','context-panel','events-client','view'])await page.addScriptTag({path:path.resolve('web/modules/assistant/'+name+'.js')}); await page.evaluate(async()=>{ window.requests=[];window.failNext=false;window.hold=false;window.release=null; const items=Array.from({length:26},(_,i)=>({id:'active-'+i,title:'Active '+i,updatedAt:'2026-10-21',version:1})); const api=async route=>{ if(route==='/assistant')return {settings:{enabled:false},usage:{calls:0,limit:100},conversations:items}; - if(route.includes('?')){const url=new URL(route,location.origin),scope=url.searchParams.get('scope'),page=Number(url.searchParams.get('page'));window.requests.push(scope+':'+page);if(window.hold&&scope==='active'&&page===2)await new Promise((resolve,reject)=>{window.release=()=>reject(Error('Stale failure'));});if(window.failNext){window.failNext=false;throw Error('Synthetic page failure');}const list=scope==='active'?items:[{id:'archived',title:'Archived only',updatedAt:'2026-10-21'}];return {items:list.slice((page-1)*25,page*25),page,total:list.length};} + if(route==='/assistant/context')return {connections:[],servers:[],archives:[],runs:[]};if(route.includes('/events?'))return {events:[],nextCursor:0,hasMore:false};if(route.includes('?')){const url=new URL(route,location.origin),scope=url.searchParams.get('scope'),page=Number(url.searchParams.get('page'));window.requests.push(scope+':'+page);if(window.hold&&scope==='active'&&page===2)await new Promise((resolve,reject)=>{window.release=()=>reject(Error('Stale failure'));});if(window.failNext){window.failNext=false;throw Error('Synthetic page failure');}const list=scope==='active'?items:[{id:'archived',title:'Archived only',updatedAt:'2026-10-21'}];return {items:list.slice((page-1)*25,page*25),page,total:list.length};} return {id:route.split('/').at(-1),title:'Synthetic',version:1,turns:[],archived:route.endsWith('archived')}; }; window.AssistantViews.configure({api,esc:String,formatDate:String,notify:()=>{},user:{username:'synthetic',role:'admin'}});await window.AssistantViews.render(document.querySelector('#fixture')); diff --git a/web/index.html b/web/index.html index 71c0580..d2f39c7 100644 --- a/web/index.html +++ b/web/index.html @@ -1,3 +1,3 @@ -订单通知中心 -
正在连接订单通知中心…
+订单通知中心 +
正在连接订单通知中心…
diff --git a/web/modules/assistant/commands.js b/web/modules/assistant/commands.js new file mode 100644 index 0000000..c874166 --- /dev/null +++ b/web/modules/assistant/commands.js @@ -0,0 +1,20 @@ +'use strict'; +window.AssistantCommands={mount(root,{getContext,onStatus,onSelect,onError}){ + const input=root.querySelector('#assistant-input'),menu=root.querySelector('#assistant-command-menu');let rows=[],index=0,mode='command',generation=0; + const catalog=[{name:'help',label:'帮助',detail:'/help · 固定诊断命令'},{name:'status',label:'运行概况',detail:'/status · 只读刷新'},{name:'bpm',label:'BPM 连接',detail:'/bpm · 选择连接并诊断'},{name:'storage',label:'存储连接',detail:'/storage · 选择存储并诊断'},{name:'archive',label:'归档失败',detail:'/archive · 选择归档记录'}]; + function close(){generation++;menu.hidden=true;menu.replaceChildren();input.removeAttribute('aria-activedescendant');input.setAttribute('aria-expanded','false');} + function draw(){menu.replaceChildren();menu.hidden=false;input.setAttribute('aria-expanded','true');for(const [i,row]of rows.entries()){const b=document.createElement('button');b.type='button';b.role='option';b.id='aw-command-'+i;b.setAttribute('aria-selected',String(i===index));const label=document.createElement('span');label.textContent=row.label;const detail=document.createElement('small');detail.textContent=row.detail||'';b.append(label,detail);b.onclick=()=>choose(row);menu.append(b);}if(!rows.length){const note=document.createElement('div');note.className='p-3 text-secondary small';note.textContent='没有可见的匹配目标';menu.append(note);}input.setAttribute('aria-activedescendant','aw-command-'+index);} + function commands(query=''){mode='command';rows=window.AssistantNative.filterOptions(catalog.map(c=>({...c,detail:c.detail+' '+c.name})),query);index=0;draw();} + async function choose(row){ + if(mode!=='command'){const command=mode;close();onSelect(command,row);input.focus();return;} + const command=row.name; + if(command==='help'){close();input.dataset.diagnostic='';onStatus('help',catalog);input.value='';return;} + if(command==='status'){close();input.dataset.diagnostic='';input.value='';await onStatus('status');return;} + const at=++generation;try{const context=await getContext();if(at!==generation)return;mode=command;rows=({bpm:context.connections,storage:context.servers,archive:context.archives}[command]||[]).map(item=>({id:item.id,label:item.name||item.orderNumber||item.id,detail:item.status||'',...item}));index=0;draw();input.focus();}catch(error){if(at===generation)onError(error);} + } + input.setAttribute('aria-controls','assistant-command-menu');input.setAttribute('aria-expanded','false');menu.role='listbox'; + const onInput=()=>{if(/^\/[^\s]*$/.test(input.value))commands(input.value.slice(1));else if(mode==='command')close();};input.addEventListener('input',onInput); + const button=root.querySelector('#assistant-commands');button.onclick=()=>{if(menu.hidden){commands();input.focus();}else close();}; + const onKey=event=>{if(event.isComposing)return;if(event.key==='Escape'&&!menu.hidden){event.preventDefault();event.stopPropagation();close();input.focus();return;}if(!menu.hidden&&['ArrowDown','ArrowUp'].includes(event.key)){event.preventDefault();index=(index+(event.key==='ArrowDown'?1:-1)+Math.max(rows.length,1))%Math.max(rows.length,1);draw();return;}if(!menu.hidden&&['Tab','Enter'].includes(event.key)&&!event.shiftKey&&rows[index]){event.preventDefault();event.stopImmediatePropagation();void choose(rows[index]);}};input.addEventListener('keydown',onKey); + return {close,async consume(){const value=input.value.trim();if(!value.startsWith('/'))return false;const found=window.AssistantNative.resolveCommand(value.slice(1),catalog);if(!found){close();onError(new Error('此命令未开放,请使用固定诊断命令。'));return true;}mode='command';await choose(found);return true;},open(name){const found=window.AssistantNative.resolveCommand(name,catalog);if(found){mode='command';void choose(found);}},dispose(){close();input.removeEventListener('input',onInput);input.removeEventListener('keydown',onKey);button.onclick=null;}}; +}}; diff --git a/web/modules/assistant/context-panel.js b/web/modules/assistant/context-panel.js new file mode 100644 index 0000000..0be7641 --- /dev/null +++ b/web/modules/assistant/context-panel.js @@ -0,0 +1,18 @@ +'use strict'; +window.AssistantContextPanel={mount(root,{api,esc,formatDate,user,settings,isActive,onExecute,onRepair,showRight}){ + let active='overview',context=null,conversation=null,events=[],selected=null,auditMounted=false,actionSignature=''; + const panels=Object.fromEntries(['overview','evidence','actions','events'].map(id=>[id,root.querySelector('#aw-panel-'+id)])); + function select(id){active=id;for(const [key,panel]of Object.entries(panels)){panel.hidden=key!==id;root.querySelector('[data-context-tab='+key+']').setAttribute('aria-selected',String(key===id));}showRight();if(id==='events')mountAudit();} + root.querySelectorAll('[data-context-tab]').forEach(b=>b.onclick=()=>select(b.dataset.contextTab)); + const row=(title,detail)=>`
${esc(title)}${esc(detail)}
`; + function drawOverview(){const c=context;if(!c){panels.overview.innerHTML='

正在读取授权状态…

';return;}panels.overview.innerHTML=`

诊断概况

本机状态快照 · ${esc(formatDate(c.observedAt||c.at))}

BPM 连接

${c.connections?.map(item=>row(item.name,item.status||'未观测')).join('')||'

没有可见连接

'}

最近扫描

${c.runs?.map(item=>row(item.status||'未知',formatDate(item.finishedAt||item.startedAt)+' · 新增 '+(item.added??'未知'))).join('')||'

暂无可见扫描记录

'}

存储与归档

${c.servers?.map(item=>row(item.name,item.state?.message||'最近观测:'+(item.state?.readable?'可读':'未确认'))).join('')||'

暂无配置

'}${row('归档记录',`${c.archives?.length||0} 条,最多展示 15 条`)}

通知阻断

${c.business?.blockers?.map(item=>row(item.status,item.error||item.step||'请到原页面核验')).join('')||'

授权快照内没有阻断记录

'}

最近观测不等于实时健康;刷新不会连接外部系统。

`;panels.overview.querySelector('[data-context-refresh]').onclick=()=>refresh().catch(showError);} + function showError(e){if(isActive()){let error=panels.overview.querySelector('[role=alert]');if(!error){error=document.createElement('p');error.role='alert';error.className='text-danger';panels.overview.append(error);}error.textContent=e.message;}} + async function refresh(){const next=await api('/assistant/context');if(!isActive())return next;context=next;drawOverview();return next;} + function evidence(turn){selected=turn;const c=turn?.diagnosticSnapshot;panels.evidence.innerHTML='

本轮诊断依据

'+(c?`

实际用于该轮分析的授权快照,时间 ${esc(formatDate(c.at||c.observedAt))}

${row('BPM 连接',c.connections?.map(x=>x.name||x.id).join('、')||'无')}${row('最近记录',`${c.runs?.length||0} 条扫描 / ${c.archives?.length||0} 条归档 / ${c.jobs?.length||0} 条导出`)}${row('诊断范围',c.diagnostic?c.diagnostic.command+' · '+(c.diagnostic.targetId||'全部授权目标'):'全部授权目标')}

扫描最多10条,归档/导出最多15条;不代表全部历史。

`:turn?.evidence?.map(e=>row(e.label,e.value)).join('')||'

此历史轮次没有保留完整快照。

');select('evidence');} + function drawActions(){const turns=conversation?.turns||[],sig=JSON.stringify([conversation?.archived,turns.map(t=>t.actions)]);if(sig===actionSignature)return;actionSignature=sig;const list=turns.flatMap(t=>(t.actions||[]).map(a=>({a,t})));panels.actions.innerHTML='

待确认与操作结果

'+list.map(({a,t})=>`
${esc(a.label)}
目标:${esc(a.targetId)}
影响:${esc({check_storage:'发起一次存储连接检查',scan_bpm:'只读重新扫描,更新到达记录',retry_archive:'向原目标重试明确失败的归档',collect_field_samples:'读取待办样本并保存字段证据',collect_history_samples:'只读采集历史字段样本',prepare_field_mapping:'生成并检查草稿,不自动生效',repair_code:'在隔离 Git 工作区执行固定测试,不自动合并部署'}[a.kind]||'仅执行已列出的受控操作')}
操作编号:${esc(a.id)}
${a.kind==='repair_code'?`

以本机服务身份运行固定测试;工作区不是操作系统沙箱,通过后仍待人工审查。

${a.files.map(f=>`
${esc(f.path)} · 查看修改前后
修改前
${esc(a.beforeFiles?.find(b=>b.path===f.path)?.content||'')}
建议内容
${esc(f.content)}
`).join('')}`:''}${a.progress?`

采样进度 ${esc(a.progress.completed)} / ${esc(a.progress.total)},成功 ${esc(a.progress.captured)},受阻 ${esc(a.progress.failed)}

`:''}
${a.status==='proposed'?``:`${esc(window.AssistantConversation.actionState(a))}`}
${a.error?`

${esc(a.error)}

`:''}${a.result?`
结果详情
${esc(JSON.stringify(a.result,null,2))}
`:''}${a.result?.link?'查看字段映射':''}
`).join('')+(list.length?'':'

建议将在这里展示,确认前不会执行。

');panels.actions.querySelectorAll('[data-assistant-action]').forEach(button=>button.onclick=()=>onExecute(button.dataset.assistantAction,button));} + const timeline=document.createElement('div');panels.events.append(timeline);const audit=document.createElement('div');panels.events.append(audit); + function mountAudit(){if(auditMounted)return;auditMounted=true;window.AssistantOperations?.mount(audit,{api,esc,formatDate,user,settings,isActive,onRepair});} + function drawEvents(){timeline.innerHTML='

当前会话阶段

'+(events.length?events.map(e=>`
${esc(window.AssistantConversation.labels[e.kind]||'阶段更新')}
`).join(''):'

历史阶段未记录

');} + drawOverview();panels.evidence.innerHTML='

点击回答下方“诊断依据”查看该轮快照。

';drawActions();drawEvents(); + return {refresh,getContext:async()=>context||refresh(),select,evidence,help(catalog){panels.overview.innerHTML='

固定诊断命令

'+catalog.map(c=>row('/'+c.name,c.label+' · '+c.detail)).join('');select('overview');},update(c,rows){if(conversation?.id!==c?.id){selected=null;panels.evidence.innerHTML='

点击回答下方“诊断依据”查看该轮快照。

';}conversation=c;events=rows;drawActions();drawEvents();},showActions(){select('actions');},dispose(){context=null;conversation=null;events=[];selected=null;}}; +}}; diff --git a/web/modules/assistant/conversation.js b/web/modules/assistant/conversation.js new file mode 100644 index 0000000..78cdc9e --- /dev/null +++ b/web/modules/assistant/conversation.js @@ -0,0 +1,37 @@ +'use strict'; +window.AssistantConversation=(()=>{ + const labels={queued:'请求已接受',snapshot:'已读取诊断快照',runtime:'DSH 运行包就绪',model:'DSH 正在分析',validation:'校验回复',proposal:'已生成操作建议',awaiting_confirmation:'等待确认',completed:'回答完成',error:'诊断失败',cancel_requested:'正在停止',cancelled:'已停止',interrupted:'已中断',needs_review:'结果待核验',action_running:'操作进行中',action_progress:'操作进展',action_result:'操作结果'}; + const states={running:'正在分析',success:'已完成',error:'失败',cancelled:'已停止',interrupted:'已中断',needs_review:'待核验'}; + function actionState(a){if(a.status==='proposed')return '等待确认';if(a.status==='running')return '操作进行中';if(['interrupted','needs_review','unknown'].includes(a.status))return '结果待核验';if(a.status==='error')return '操作未完成';return {ready_for_review:'测试通过,待审查',rolled_back:'测试未通过,已回退',needs_review:'结果待核验',blocked:'操作受阻','needs-selection':'需人工选择',failed:'操作失败',error:'操作失败',interrupted:'结果待核验',unknown:'结果待核验',checked:'草稿已检查'}[a.result?.status]||'操作已完成';} + function markdown(text,esc){ + if(!window.marked)return esc(text).replace(/\n/g,'
'); + const renderer={html:token=>esc(token.text),image:token=>esc(token.text||'图片'),link(token){const label=this.parser.parseInline(token.tokens);let url;try{url=new URL(token.href,location.href);}catch{return label;}if(!['http:','https:'].includes(url.protocol)||url.username||url.password)return label;const internal=url.origin===location.origin;if(internal&&!/^#(?:bpm|storage|records(?:-pdf)?|rule-fields|order-rules|health|exceptions|notification-(?:orders|batches|execution|settings)|assistant-settings)(?:\?|$)/.test(url.hash))return label;return `${label}`;}}; + return new window.marked.Marked({renderer,gfm:true,breaks:true}).parse(String(text)); + } + function mount(messages,{esc,formatDate,user,onActions,onEvidence,onRetry}){ + const nodes=new Map();let following=true; + const jump=messages.parentElement.querySelector('#assistant-new-progress'); + messages.onscroll=()=>{following=messages.scrollHeight-messages.scrollTop-messages.clientHeight<70;if(following)jump.hidden=true;};jump.onclick=()=>{messages.scrollTop=messages.scrollHeight;following=true;jump.hidden=true;}; + function update(c,events){ + const turns=c?.turns||[]; + if(!turns.length){if(!messages.querySelector('.aw-welcome'))messages.innerHTML='
DSH

从运行情况开始

查看连接健康、扫描异常与归档失败。
诊断依据和待确认操作会出现在右侧。

';nodes.clear();return;} + messages.querySelector('.aw-welcome')?.remove();let changed=false; + for(const t of turns){ + let row=nodes.get(t.id);if(!row){const element=document.createElement('article');element.className='assistant-turn';element.dataset.turnId=t.id;element.innerHTML='
DSH
本轮过程
    ';messages.append(element);row={element,answer:'',signature:''};nodes.set(t.id,row);element.querySelector('.assistant-user').textContent=t.text;changed=true;} + const relevant=events.filter(e=>e.turnId===t.id),signature=JSON.stringify([t.status,t.error,t.reply,t.cancelRequested,t.actions,relevant.at(-1)?.seq]);if(signature===row.signature)continue;row.signature=signature;changed=true; + const badge=row.element.querySelector('.aw-state');badge.textContent=t.cancelRequested&&t.status==='running'?'正在停止':states[t.status]||t.status;badge.classList.toggle('error',['error','needs_review','interrupted'].includes(t.status)); + const process=row.element.querySelector('.aw-process'),ol=process.querySelector('ol');ol.replaceChildren();if(relevant.length){for(const e of relevant){const li=document.createElement('li');li.textContent=(labels[e.kind]||'阶段更新')+' · '+formatDate(e.at);ol.append(li);}}else{const li=document.createElement('li');li.textContent='历史阶段未记录';ol.append(li);}process.open=t.status==='running'||process.open; + const answer=t.reply||t.error||(t.status==='running'?'正在分析授权范围内的运行状态…':'暂无回复');if(answer!==row.answer){row.element.querySelector('.assistant-answer').innerHTML=markdown(answer,esc);row.answer=answer;} + const actions=row.element.querySelector('.aw-turn-actions');actions.replaceChildren(); + function button(text,callback){const b=document.createElement('button');b.type='button';b.className='btn btn-sm';b.textContent=text;b.onclick=callback;actions.append(b);} + if(t.reply)button('复制回答',async()=>{try{await navigator.clipboard.writeText(t.reply);}catch{const selection=getSelection(),range=document.createRange();range.selectNodeContents(row.element.querySelector('.assistant-answer'));selection.removeAllRanges();selection.addRange(range);}}); + button('诊断依据',()=>onEvidence(t));if(t.actions?.length)button('查看操作('+t.actions.length+')',()=>onActions(t)); + if(['error','cancelled','interrupted','needs_review'].includes(t.status))button('重新诊断',()=>onRetry(t)); + } + for(const [id,row]of nodes)if(!turns.some(t=>t.id===id)){row.element.remove();nodes.delete(id);} + if(changed){if(following)messages.scrollTop=messages.scrollHeight;else jump.hidden=false;} + } + return {update,dispose(){messages.onscroll=null;jump.onclick=null;},reset(){nodes.clear();messages.replaceChildren();following=true;}}; + } + return {mount,labels,actionState,markdown}; +})(); diff --git a/web/modules/assistant/dsh-native.js b/web/modules/assistant/dsh-native.js new file mode 100644 index 0000000..4bb63d9 --- /dev/null +++ b/web/modules/assistant/dsh-native.js @@ -0,0 +1,65 @@ +/* Adapted from DeepSeek Harness 0.2.1-rc.2, Copyright (c) 2026 DeepSeek. + * MIT; see licenses/DeepSeek-Harness-MIT.txt and DSH-native-NOTICES.md. + * Geometry/grouping bodies are upstream; wrapper and fixed-catalog resolution + * remove React/Cordis and native host command aliases. */ +(function(root){ +'use strict'; +const SIDEBAR_AUTO_COLLAPSE = 1024; + /** Maximum normal right panel width as a fraction of the frame. */ + const RIGHTBAR_MAX_RATIO = .7; + /** First-open right panel preference as a fraction of the frame. */ + const RIGHTBAR_DEFAULT_RATIO = .45; + /** + * Clamp a panel width into its contract range. + * @param px - requested width. + * @param min - range lower bound. + * @param max - range upper bound. + * @returns the clamped width. + */ + function clampWidth(px, min, max) { + return Math.min(max, Math.max(min, Math.round(px))); + } + /** + * Solve the three column widths for one viewport frame. + * @param viewport - available frame width in px. + * @param sidebar - sidebar width preference in px (0 = closed). + * @param rightbar - requested right panel width in px (0 = no track). + * @param collapsedWidth - track width of the closed sidebar; the default keeps + * the icon rail, 0 hides the column entirely (macOS desktop). + * @returns actual widths after shrinking or removing the right track; only + * without that track may the center fall below its minimum, down to zero. + */ + function computeColumns(viewport, sidebar, rightbar, collapsedWidth = 56) { + const s = sidebar === 0 ? collapsedWidth : clampWidth(sidebar, 264, 420); + const available = viewport - s - 400; + const r = rightbar === 0 || available < 300 ? 0 : Math.min(available, clampWidth(rightbar, 300, viewport * RIGHTBAR_MAX_RATIO)); + return { + sidebar: s, + center: Math.max(0, viewport - s - r), + rightbar: r + }; + } + +function groupOptions(options) { + const groups = /* @__PURE__ */ new Map(); + for (const option of options) { + const name = option.group?.name; + const existing = groups.get(name); + if (existing !== void 0) existing.rows.push(option); + else groups.set(name, { + group: option.group, + rows: [option] + }); + } + return [...groups.values()]; + } + function resolveCommand(token,descriptors){return descriptors.find(descriptor=>descriptor.name===token);} +// Native popup substring policy; fuzzy mode and its React primitives omitted. +function filterOptions(options,search){ + const query=search.trim().toLowerCase(),groups=groupOptions(options); + const ordered=groups.some(group=>group.group!==undefined)?groups.flatMap(group=>group.rows):options; + return query===''?ordered:ordered.filter(o=>o.label.toLowerCase().includes(query)||(o.detail?.toLowerCase().includes(query)??false)); +} +const api={clampWidth,computeColumns,resolveCommand,filterOptions,groupOptions}; +if(typeof module==='object'&&module.exports)module.exports=api;else root.AssistantNative=api; +})(typeof window==='object'?window:globalThis); diff --git a/web/modules/assistant/events-client.js b/web/modules/assistant/events-client.js new file mode 100644 index 0000000..50594f0 --- /dev/null +++ b/web/modules/assistant/events-client.js @@ -0,0 +1,30 @@ +'use strict'; +window.AssistantEvents={connect({id,cursor=0,api,onEvents,onChange,onAuth,isActive=()=>true}){ + let disposed=false,controller=null,retryTimer=null,pollTimer=null,probeTimer=null,failures=0,backoff=0,polling=false,pollInFlight=false,delivery=Promise.resolve();const lifetime=new AbortController(); + const alive=()=>!disposed&&isActive(); + function auth(error){if(error.status===401||error.status===403){dispose();onAuth?.(error);return true;}return false;} + function consume(events){const work=delivery.catch(()=>{}).then(async()=>{if(!alive())return;const fresh=[];let next=cursor;for(const e of events){if(e.conversationId!==id||!Number.isSafeInteger(e.seq)||e.seq<=next)continue;if(e.seq!==next+1)throw new Error('事件序列不连续');next=e.seq;fresh.push(e);}if(fresh.length){await onChange();if(!alive())return;onEvents(fresh);cursor=next;}});delivery=work;return work;} + async function catchUp(){let more=true;while(alive()&&more){const batch=await api('/assistant/conversations/'+id+'/events?after='+cursor,undefined,{signal:lifetime.signal});if(!alive())return;await consume(batch.events);more=batch.hasMore;}} + function beginPolling(){if(!alive())return;clearTimeout(probeTimer);probeTimer=setTimeout(()=>{if(alive())void stream();},60000);if(polling)return;polling=true;const poll=async()=>{if(pollInFlight)return;pollInFlight=true;try{await catchUp();}catch(e){if(auth(e))return;if(e.status===400){cursor=0;await onChange();}}finally{pollInFlight=false;if(alive()&&polling)pollTimer=setTimeout(poll,3000);}};void poll();} + async function stream(){ + if(!alive())return;controller?.abort();const mine=new AbortController();controller=mine;let buffer='',idleTimer;const resetIdle=()=>{clearTimeout(idleTimer);idleTimer=setTimeout(()=>mine.abort(),45000);}; + resetIdle();try{ + const response=await fetch('/api/assistant/conversations/'+id+'/stream?after='+cursor,{credentials:'same-origin',signal:mine.signal,headers:cursor?{'Last-Event-ID':String(cursor)}:{}}); + if(!response.ok)throw Object.assign(new Error('事件连接失败'),{status:response.status}); + if(!/^text\/event-stream/.test(response.headers.get('content-type')||''))throw new Error('事件协议无效'); + polling=false;clearTimeout(pollTimer);clearTimeout(probeTimer);const reader=response.body.getReader(),decoder=new TextDecoder();resetIdle(); + while(alive()){ + const {done,value}=await reader.read();if(done)break;resetIdle();buffer+=decoder.decode(value,{stream:true}).replace(/\r\n/g,'\n');if(buffer.length>256*1024)throw new Error('事件数据超过限制'); + let end;while((end=buffer.indexOf('\n\n'))>=0){const frame=buffer.slice(0,end);buffer=buffer.slice(end+2);const type=frame.split('\n').find(l=>l.startsWith('event:'))?.slice(6).trim();const data=frame.split('\n').filter(l=>l.startsWith('data:')).map(l=>l.slice(5).trimStart()).join('\n'); + if(type==='auth_required')throw Object.assign(new Error('登录或权限已变化'),{status:401}); + if(type==='stream_error')throw new Error('事件服务暂不可用'); + if(type==='assistant_event'&&data){await consume([JSON.parse(data)]);failures=0;backoff=0;} + } + } + if(alive())throw new Error('事件连接中断'); + }catch(error){if(!alive()||controller!==mine||auth(error))return;mine.abort();failures++;const delays=[1000,2000,4000,8000,15000];if(failures>=3){beginPolling();}else retryTimer=setTimeout(()=>void stream(),delays[Math.min(backoff++,delays.length-1)]); + }finally{clearTimeout(idleTimer);} + } + function dispose(){disposed=true;controller?.abort();lifetime.abort();clearTimeout(retryTimer);clearTimeout(pollTimer);clearTimeout(probeTimer);} + void stream();return {dispose,get cursor(){return cursor;}}; +}}; diff --git a/web/modules/assistant/layout.js b/web/modules/assistant/layout.js new file mode 100644 index 0000000..fc90c3e --- /dev/null +++ b/web/modules/assistant/layout.js @@ -0,0 +1,21 @@ +'use strict'; +window.AssistantLayout={mount(host,{settings,usage,esc}){ + host.innerHTML=`
    ← 工具DSH 助手${esc(settings.model||'模型未配置')}${settings.enabled?'诊断已启用':'待配置 / 已暂停'}今日 ${usage.calls} / ${usage.limit}

    新对话

    ${[['连接健康','status'],['扫描异常','bpm'],['归档失败','archive'],['通知阻断','blockers']].map(([label,command])=>``).join('')}
    Enter 发送 · Shift + Enter 换行
    `; + const root=host.querySelector('.assistant-workspace'),body=root.querySelector('.aw-body'),leftButton=root.querySelector('[data-aw-left]'),rightButton=root.querySelector('[data-aw-right]');let width=0,leftOpen=true,rightOpen=true,leftWidth=264,rightWidth=320,lastWidth=0; + const shell=document.querySelector('#app>.page');shell?.classList.add('dsh-focused'); + function measure(){root.style.height=Math.max(240,(window.visualViewport?.height||innerHeight)-root.getBoundingClientRect().top)+'px';width=root.clientWidth;if(width!==lastWidth){if(width<880){leftOpen=false;rightOpen=false;}else if(width<1180){leftOpen=false;rightOpen=false;}else if(!lastWidth){leftOpen=true;rightOpen=true;}lastWidth=width;}apply();} + function apply(){const narrow=width<880;const columns=window.AssistantNative.computeColumns(width,leftOpen?leftWidth:0,rightOpen?rightWidth:0,narrow?0:56); + if(!narrow&&rightOpen&&columns.rightbar===0)rightOpen=false; + root.classList.toggle('aw-narrow',narrow);root.classList.toggle('aw-left-open',leftOpen);root.classList.toggle('aw-right-open',rightOpen);root.classList.toggle('aw-left-collapsed',!leftOpen);leftButton.setAttribute('aria-expanded',String(leftOpen));rightButton.setAttribute('aria-expanded',String(rightOpen)); + body.style.gridTemplateColumns=narrow?'minmax(0,1fr)':`${columns.sidebar}px ${leftOpen?'5px':'0px'} minmax(0,1fr) ${rightOpen?'5px '+columns.rightbar+'px':'0px 0px'}`; + root.querySelector('.aw-sidebar').inert=!leftOpen;root.querySelector('.aw-context').inert=!rightOpen; + } + leftButton.onclick=()=>{leftOpen=!leftOpen;if(width<880&&leftOpen)rightOpen=false;apply();if(leftOpen)root.querySelector('#assistant-search').focus();}; + rightButton.onclick=()=>{rightOpen=!rightOpen;if(width<1180&&rightOpen)leftOpen=false;apply();if(rightOpen)root.querySelector('[data-context-tab][aria-selected=true]').focus();}; + const onKey=event=>{if(event.key==='Escape'&&!root.querySelector('dialog[open]')&&root.querySelector('#assistant-command-menu').hidden){if(width<880&&leftOpen){leftOpen=false;apply();leftButton.focus();}else if(rightOpen){rightOpen=false;apply();rightButton.focus();}}};root.addEventListener('keydown',onKey); + const disposers=[];for(const [side,selector] of [['left','.aw-drag-left'],['right','.aw-drag-right']]){const bar=root.querySelector(selector);let drag=null; + const move=event=>{if(!drag)return;if(side==='left')leftWidth=window.AssistantNative.clampWidth(drag.value+event.clientX-drag.x,264,420);else rightWidth=window.AssistantNative.clampWidth(drag.value-event.clientX+drag.x,300,width*.7);apply();}; + bar.onpointerdown=event=>{drag={x:event.clientX,value:side==='left'?leftWidth:rightWidth};bar.setPointerCapture(event.pointerId);};bar.onpointermove=move;bar.onpointerup=bar.onpointercancel=()=>{drag=null;};bar.onkeydown=event=>{if(!['ArrowLeft','ArrowRight'].includes(event.key))return;event.preventDefault();const delta=event.key==='ArrowRight'?16:-16;if(side==='left')leftWidth=window.AssistantNative.clampWidth(leftWidth+delta,264,420);else rightWidth=window.AssistantNative.clampWidth(rightWidth-delta,300,width*.7);apply();};disposers.push(()=>{bar.onpointerdown=bar.onpointermove=bar.onpointerup=bar.onpointercancel=bar.onkeydown=null;});} + const observer=new ResizeObserver(measure);observer.observe(root);window.visualViewport?.addEventListener('resize',measure);measure(); + return {root,showRight(){rightOpen=true;if(width<1180)leftOpen=false;apply();},closeLeft(){if(width<880){leftOpen=false;apply();}},dispose(){observer.disconnect();window.visualViewport?.removeEventListener('resize',measure);for(const dispose of disposers)dispose();root.removeEventListener('keydown',onKey);shell?.classList.remove('dsh-focused');}}; +}}; diff --git a/web/modules/assistant/operations.js b/web/modules/assistant/operations.js index 7e0ccb1..aaab65d 100644 --- a/web/modules/assistant/operations.js +++ b/web/modules/assistant/operations.js @@ -1,7 +1,7 @@ 'use strict'; window.AssistantOperations={mount(container,{api,esc,formatDate,user,settings,isActive,onRepair}){ const stepNames={sample_progress:'逐项采样',context:'读取上下文',model:'模型分析',prepare:'准备工作区',files_written:'写入建议文件',commit:'Git提交',validate:'运行测试',rollback:'恢复基线',review:'提交审查',restart_recovery:'重启核验',execute:'执行受控操作',reject:'请求被拒绝',error:'异常'},statusNames={running:'执行中',success:'已完成',ready_for_review:'测试通过,待审查',rolled_back:'已回退',needs_review:'待人工核验',cancelled:'已取消',error:'失败',rejected:'已拒绝'}; - const host=document.createElement('section');host.className='card mb-3';container.querySelector('.assistant-layout').before(host); + const host=document.createElement('section');host.className='card mb-3';const layout=container.querySelector('.assistant-layout');if(layout)layout.before(host);else container.append(host); host.innerHTML='

    AI 操作记录

    正在读取操作记录…
    '+(user.role==='admin'?'
    提出代码修复

    仅将选定源码发送给已配置的模型。先生成可审查建议,不直接修改代码;执行时在独立 Git 工作区运行本机测试。工作区不是操作系统沙箱,通过后仍需人工审查合并,不自动部署。

    '+(!settings.allowCodeRepair?'请先在助手设置开启代码修复并指定源码仓库。':'')+'
    ':'')+'
    '; const error=host.querySelector('[data-operation-error]');let rows=[],busy=false;const more=document.createElement('button');more.type='button';more.className='btn btn-sm mt-2';more.textContent='加载更早记录';more.hidden=true;host.querySelector('[data-operation-list]').after(more);async function refresh(append=false){if(busy)return;busy=true;more.disabled=true;try{const {events}=await api('/assistant/operations'+(append&&rows.length?'?beforeId='+rows.at(-1).id:''));if(!isActive()||!host.isConnected)return;rows=append?[...rows,...events]:events;more.hidden=events.length<100;host.querySelector('[data-operation-list]').innerHTML=rows.length?'
    '+rows.map(e=>'').join('')+'
    时间 / 操作编号步骤 / 状态结果与依据
    '+esc(formatDate(e.createdAt))+' · '+esc(e.actorLabel||e.actor)+'
    '+esc(e.operationId)+'
    '+esc(stepNames[e.step]||e.step)+' / '+esc(statusNames[e.status]||e.status)+''+esc(e.detail||'')+(e.resultCommit?'
    提交:'+esc(e.resultCommit)+'
    ':'')+(e.recovery?'
    恢复:'+esc(e.recovery)+'
    ':'')+'
    ':'暂无操作记录。诊断和恢复操作均会记录,代码修改另有 Git 提交。';}catch(e){if(isActive())error.textContent=e.message;}finally{busy=false;more.disabled=false;}} host.querySelector('[data-operation-refresh]').onclick=()=>refresh();more.onclick=()=>refresh(true);void refresh();const form=host.querySelector('[data-repair-form]');if(form)form.onsubmit=async e=>{e.preventDefault();const button=e.submitter;button.disabled=true;error.textContent='';try{await onRepair(form.querySelector('#repair-goal').value,form.querySelector('#repair-paths').value.split(/\r?\n/).map(s=>s.trim()).filter(Boolean));if(isActive())await refresh();}catch(cause){if(isActive())error.textContent=cause.message;}finally{if(button.isConnected)button.disabled=false;}}; diff --git a/web/modules/assistant/view.js b/web/modules/assistant/view.js index 0a1a2a5..3abe65d 100644 --- a/web/modules/assistant/view.js +++ b/web/modules/assistant/view.js @@ -3,47 +3,51 @@ let api,esc,formatDate,notify,user; const states={running:'正在分析',success:'已完成',error:'失败',cancelled:'已停止',interrupted:'已中断'}; async function render(container,isActive=()=>true){ - let data=await api('/assistant');if(!isActive())return;const key='order-assistant:'+user.username,admin=user.role==='admin'; - let currentId=sessionStorage.getItem(key),conversation=null,polling=false,revision=0,scope='active',listPage=1,listTotal=data.conversations.length,listRevision=0,managing=false;const pendingActions=new Map(); - if(!data.conversations.some(c=>c.id===currentId))currentId=data.conversations[0]?.id||''; - const live=()=>isActive()&&container.isConnected; - container.innerHTML=`
    AI

    DSH 运行助手

    对话分析运行情况 · 操作结果可追溯 · 个人会话
    ${(data.skills||[]).map(s=>esc(s.name)+' v'+esc(s.version)+' · 已加载').join('、')}
    ${data.settings.enabled?'已启用,回复时验证模型':'待配置 / 已暂停'}今日对话 ${data.usage.calls} / ${data.usage.limit}

    新对话

    ${esc(data.settings.model||'模型未配置')}
    `; - container.querySelector('#assistant-conversations').insertAdjacentHTML('beforebegin',''); - container.querySelector('#assistant-conversations').insertAdjacentHTML('afterend','
    '); - container.querySelector('#assistant-title').parentElement.insertAdjacentHTML('afterend','
    '); - const input=container.querySelector('#assistant-input'),send=container.querySelector('#assistant-send'),stop=container.querySelector('#assistant-stop'),error=container.querySelector('#assistant-error'),messages=container.querySelector('#assistant-messages'); - function drawLifecycle(){const box=container.querySelector('#assistant-lifecycle'),note=container.querySelector('#assistant-history-note');box.innerHTML=conversation?``:'';note.textContent=conversation?.archived?'已归档,历史与操作记录保留;恢复后可继续。':conversation?.turns.length>=100?'已达100轮;继续新对话将归档本会话并带入最近3轮上下文。':'归档释放活跃会话额度,历史与操作记录保留。';box.querySelectorAll('button').forEach(button=>{button.disabled=managing||conversation.turns.some(t=>t.status==='running'||t.actions?.some(a=>a.status==='running'));button.onclick=async()=>{if(managing)return;managing=true;drawLifecycle();try{const action=button.dataset.conversationManage,c=await api('/assistant/conversations/'+currentId+'/'+action,{version:conversation.version});if(!live())return;if(action==='continue'){scope='active';listPage=1;container.querySelector('#assistant-scope').value=scope;}await refreshList();await select(action==='continue'?c.id:data.conversations[0]?.id||'');}catch(e){showError(e);}finally{managing=false;if(live())drawLifecycle();}};});} - window.AssistantOperations?.mount(container,{api,esc,formatDate,user,settings:data.settings,isActive:live,onRepair:async(text,paths)=>{if(!currentId){const c=await api('/assistant/conversations',{});currentId=c.id;sessionStorage.setItem(key,currentId);revision++;}await api('/assistant/conversations/'+currentId+'/repair-messages',{text,paths});if(live()){await refreshList();await loadCurrent();}}}); - function showError(e){if(live()){error.textContent=e.message;notify(e.message,'danger');}} - function drawList(){container.querySelector('#assistant-conversations').innerHTML=data.conversations.map(c=>``).join('')||'
    新建对话后,可连续追问运行情况。
    ';container.querySelectorAll('[data-assistant-conversation]').forEach(button=>button.onclick=()=>select(button.dataset.assistantConversation).catch(showError));} - function drawMessages(){ - container.querySelector('#assistant-title').textContent=conversation?.title||'新对话';const turns=conversation?.turns||[],running=turns.some(t=>t.status==='running');send.disabled=running||!data.settings.enabled||!!conversation?.archived||turns.length>=100;input.disabled=!!conversation?.archived;stop.hidden=!running;drawLifecycle(); - messages.innerHTML=turns.map(t=>`
    ${esc(user.username)} · ${esc(formatDate(t.createdAt))}
    ${esc(t.text)}
    DSH${esc(states[t.status]||t.status)}
    ${esc(t.reply||t.error||(t.status==='running'?'正在读取允许范围内的运行快照并分析…':'暂无回复'))}
    ${t.evidence?.length?`
    诊断依据${t.evidence.map(e=>`
    ${esc(e.label)}:${esc(e.value)}
    `).join('')}
    `:''}${t.actions?.length?`
    ${t.actions.map(a=>`
    ${esc(a.label)}${a.status==='proposed'?``:`${a.status==='success'?({ready_for_review:'测试通过,待审查',rolled_back:'测试未通过,已回退',needs_review:'结果待核验'}[a.result?.status]||'操作已完成'):a.status==='running'?'操作进行中':a.status==='interrupted'?'结果待核实':'操作未完成'}`}
    目标:${esc(a.targetId)}
    ${a.kind==='repair_code'?`
    仅修改独立 Git 工作区;将以本机服务身份运行固定测试。失败恢复基线,不自动部署。
    ${a.files.map(f=>`
    ${esc(f.path)} · 查看修改前后
    修改前
    ${esc(a.beforeFiles?.find(b=>b.path===f.path)?.content||'')}
    建议内容
    ${esc(f.content)}
    `).join('')}`:''}${a.progress?`
    采样进度 ${esc(a.progress.completed)} / ${esc(a.progress.total)},成功 ${esc(a.progress.captured)},受阻 ${esc(a.progress.failed)}
    `:''}${a.result?.link?'查看字段映射':''}${a.result?`
    ${esc(JSON.stringify(a.result,null,2))}
    `:''}${a.error?`
    ${esc(a.error)}
    `:''}
    `).join('')}
    `:''}
    `).join('')||`
    Z

    从运行情况开始

    查询 BPM 连接、扫描、导出与归档状态,
    或描述你遇到的问题。

    ${data.settings.enabled?'诊断基于授权的状态快照,建议不代表操作已执行。':'请管理员前往系统设置中的助手设置,配置官方运行包和模型。'}
    `; - messages.querySelectorAll('[data-assistant-action]').forEach(button=>button.onclick=async()=>{const id=currentId,at=revision,actionId=button.dataset.assistantAction,owned=()=>live()&&id===currentId&&at===revision;if(pendingActions.has(actionId))return;pendingActions.set(actionId,id);button.disabled=true;error.textContent='';watch();try{await api('/assistant/conversations/'+id+'/actions/'+actionId+'/execute',{});if(owned())await loadCurrent();}catch(e){if(owned()){showError(e);await loadCurrent();}}finally{pendingActions.delete(actionId);}}); - if(running||[...pendingActions.values()].includes(currentId)||turns.some(t=>t.actions?.some(a=>a.status==='running')))watch(); + const data=await api('/assistant');if(!isActive())return; + const key='order-assistant:'+user.username,drafts=new Map(),pendingActions=new Map();let disposed=false,currentId=sessionStorage.getItem(key)||'',conversation=null,events=[],revision=0,listRevision=0,loadChain=Promise.resolve(),listPage=1,listTotal=0,scope='active',managing=false,watchTimer=null,eventClient=null,searchTimer=null,pendingRequest=null; + const live=()=>!disposed&&isActive()&&container.isConnected; + const layout=window.AssistantLayout.mount(container,{settings:data.settings,usage:data.usage,esc}),root=layout.root; + const input=root.querySelector('#assistant-input'),send=root.querySelector('#assistant-send'),stop=root.querySelector('#assistant-stop'),error=root.querySelector('#assistant-error'),messages=root.querySelector('#assistant-messages'); + function showError(e){if(live())error.textContent=e.message;} + const panel=window.AssistantContextPanel.mount(root,{api,esc,formatDate,user,settings:data.settings,isActive:live,showRight:()=>layout.showRight(),onExecute:execute,onRepair:repair}); + const transcript=window.AssistantConversation.mount(messages,{esc,formatDate,user,onActions:()=>panel.showActions(),onEvidence:turn=>panel.evidence(turn),onRetry:turn=>{input.value=turn.text;input.dataset.diagnostic=turn.diagnosticSnapshot?.diagnostic?JSON.stringify(turn.diagnosticSnapshot.diagnostic):'';pendingRequest=null;input.focus();error.textContent='重新诊断将创建新一轮并使用新快照;不会重新执行旧操作。';}}); + const commands=window.AssistantCommands.mount(root,{getContext:()=>panel.getContext(),onStatus:async(kind,catalog)=>{error.textContent='';if(kind==='help')panel.help(catalog);else{await panel.refresh();panel.select('overview');}},onSelect:(command,row)=>{input.value=({bpm:'分析此 BPM 连接及最近扫描异常',storage:'分析此存储连接的最近状态',archive:'分析这次归档的失败原因'})[command]+':'+(row.name||row.orderNumber||row.id);input.dataset.diagnostic=JSON.stringify({command,targetId:row.id});pendingRequest=null;input.dispatchEvent(new Event('input'));input.focus();},onError:showError}); + function updateComposer(){const running=conversation?.turns.some(t=>t.status==='running');send.disabled=!!running||!data.settings.enabled||!!conversation?.archived||(conversation?.turns.length||0)>=100;input.disabled=!!conversation?.archived;stop.hidden=!running;stop.disabled=!!conversation?.turns.some(t=>t.status==='running'&&t.cancelRequested);stop.textContent=stop.disabled?'正在停止…':'停止回复';} + function drawLifecycle(){const box=root.querySelector('#assistant-lifecycle');box.replaceChildren();if(!conversation)return;for(const [action,label]of [[conversation.archived?'restore':'archive',conversation.archived?'恢复会话':'归档会话'],['continue','继续新对话']]){const b=document.createElement('button');b.type='button';b.className='btn btn-sm';b.textContent=label;b.disabled=managing||conversation.turns.some(t=>t.status==='running'||t.actions?.some(a=>a.status==='running'));b.onclick=async()=>{if(managing)return;managing=true;drawLifecycle();const id=currentId,at=revision;try{const result=await api('/assistant/conversations/'+id+'/'+action,{version:conversation.version});if(!live()||id!==currentId||at!==revision)return;if(action==='continue'){scope='active';root.querySelector('#assistant-scope').value=scope;}await refreshList(1);await select(action==='continue'?result.id:data.conversations[0]?.id||'');}catch(e){showError(e);}finally{managing=false;if(live())drawLifecycle();}};box.append(b);}root.querySelector('#assistant-history-note').textContent=conversation.archived?'已归档;恢复后可继续。':conversation.turns.length>=100?'已达100轮,继续新对话带入最近3轮。':'';} + function draw(){root.querySelector('#assistant-title').textContent=conversation?.title||'新对话';updateComposer();drawLifecycle();transcript.update(conversation,events);panel.update(conversation,events);if(conversation?.turns.some(t=>t.status==='running'||t.actions?.some(a=>a.status==='running'))||[...pendingActions.values()].includes(currentId))watch();} + function watch(){if(watchTimer||!live())return;watchTimer=setTimeout(async()=>{watchTimer=null;if(!live())return;try{await loadCurrent();}catch(e){showError(e);}},1200);} + function loadCurrent(){if(!currentId||!live())return Promise.resolve();const id=currentId,at=revision;const work=loadChain.catch(()=>{}).then(async()=>{if(!live()||currentId!==id||revision!==at)return;const next=await api('/assistant/conversations/'+id);if(!live()||currentId!==id||revision!==at)return;conversation=next;draw();return next;});loadChain=work;return work;} + function drawList(){const box=root.querySelector('#assistant-conversations');box.innerHTML=data.conversations.map(c=>``).join('')||'

    没有匹配会话。

    ';box.querySelectorAll('[data-assistant-conversation]').forEach(b=>b.onclick=()=>{layout.closeLeft();void select(b.dataset.assistantConversation).catch(showError);});} + function drawPager(){root.querySelector('#assistant-page').textContent=listPage+' / '+Math.max(1,Math.ceil(listTotal/25));root.querySelector('#assistant-prev').disabled=listPage<=1;root.querySelector('#assistant-next').disabled=listPage*25>=listTotal;} + async function refreshList(page=listPage,requestedScope=scope){const at=++listRevision,owned=()=>live()&&at===listRevision;root.querySelector('#assistant-prev').disabled=root.querySelector('#assistant-next').disabled=true;try{const query=root.querySelector('#assistant-search').value.trim();const next=await api('/assistant/conversations?scope='+requestedScope+'&page='+page+'&pageSize=25'+(query?'&query='+encodeURIComponent(query):''));if(!owned())return false;data.conversations=next.items;listPage=next.page;listTotal=next.total;scope=requestedScope;error.textContent='';root.querySelector('#assistant-search-note').textContent=next.search?.truncated?'仅搜索最近 '+next.search.maximum+' 个归档会话。':'';drawList();return true;}catch(e){if(owned()){root.querySelector('#assistant-scope').value=scope;showError(e);}return false;}finally{if(owned())drawPager();}} + async function select(id){ + if(currentId)drafts.set(currentId,{text:input.value,diagnostic:input.dataset.diagnostic||'',scroll:messages.scrollTop,request:pendingRequest}); + eventClient?.dispose();eventClient=null;clearTimeout(watchTimer);watchTimer=null;currentId=id;conversation=null;events=[];loadChain=Promise.resolve();const at=++revision;sessionStorage.setItem(key,id);const saved=drafts.get(id);input.value=saved?.text||'';input.dataset.diagnostic=saved?.diagnostic||'';pendingRequest=saved?.request||null;transcript.reset();commands.close();drawList();draw(); + if(!id)return;await loadCurrent();if(!live()||revision!==at)return; + try{let cursor=0,more=true;while(more){const batch=await api('/assistant/conversations/'+id+'/events?after='+cursor);if(!live()||revision!==at)return;events.push(...batch.events);cursor=batch.nextCursor;more=batch.hasMore;}draw();if(saved)messages.scrollTop=saved.scroll;eventClient=window.AssistantEvents.connect({id,cursor,api,isActive:()=>live()&&revision===at,onEvents:rows=>{const known=new Set(events.map(e=>e.seq));events.push(...rows.filter(e=>!known.has(e.seq)));draw();},onChange:loadCurrent,onAuth:()=>{if(live()&&revision===at){conversation=null;events=[];input.value='';input.disabled=true;transcript.reset();panel.update(null,[]);showError(new Error('登录或权限已变化,请重新登录。'));void api('/me').catch(()=>{});}}});}catch(e){if(live()&&revision===at){if(e.status===401||e.status===403)showError(e);else if(e.status!==404)showError(e);}} } - async function loadCurrent(){if(!currentId)return;const id=currentId,at=revision,c=await api('/assistant/conversations/'+id);if(!live()||id!==currentId||at!==revision)return;conversation=c;drawMessages();} - function watch(){if(polling)return;polling=true;setTimeout(async()=>{polling=false;if(!live())return;try{await loadCurrent();}catch(e){showError(e);}},1200);} - async function select(id){currentId=id;conversation=null;revision++;sessionStorage.setItem(key,id);drawList();if(id)await loadCurrent();else drawMessages();} - function drawPager(){container.querySelector('#assistant-page').textContent=listPage+' / '+Math.max(1,Math.ceil(listTotal/25));container.querySelector('#assistant-prev').disabled=listPage<=1;container.querySelector('#assistant-next').disabled=listPage*25>=listTotal;} - async function refreshList(page=listPage,requestedScope=scope){ - const at=++listRevision,owned=()=>live()&&at===listRevision;container.querySelector('#assistant-prev').disabled=container.querySelector('#assistant-next').disabled=true; - try{const next=await api('/assistant/conversations?scope='+requestedScope+'&page='+page+'&pageSize=25');if(!owned())return false;scope=requestedScope;data.conversations=next.items;listTotal=next.total;listPage=next.page;error.textContent='';drawList();return true;} - catch(e){if(owned()){container.querySelector('#assistant-scope').value=scope;showError(e);}return false;} - finally{if(owned())drawPager();} + async function ensureConversation(){if(currentId)return {id:currentId,at:revision};const before=revision,c=await api('/assistant/conversations',{});if(!live()||revision!==before)return null;currentId=c.id;conversation=c;sessionStorage.setItem(key,c.id);revision++;const at=revision;await refreshList(1);return live()&&revision===at?{id:c.id,at}:null;} + async function repair(text,paths){const owner=await ensureConversation();if(!owner)return;await api('/assistant/conversations/'+owner.id+'/repair-messages',{text,paths});if(!live()||revision!==owner.at||currentId!==owner.id)return;await refreshList();if(revision!==owner.at)return;await select(owner.id);panel.showActions();} + async function execute(actionId,button){if(pendingActions.has(actionId))return;const id=currentId,at=revision;pendingActions.set(actionId,id);button.disabled=true;error.textContent='';watch();try{await api('/assistant/conversations/'+id+'/actions/'+actionId+'/execute',{});}catch(e){if(live()&&id===currentId&&revision===at)showError(e);}finally{pendingActions.delete(actionId);if(live()&&id===currentId&&revision===at)await loadCurrent();}} + async function sendMessage(event){event.preventDefault();if(await commands.consume())return;if(send.disabled||!input.value.trim())return;send.disabled=true;error.textContent='';const text=input.value,diagnostic=input.dataset.diagnostic?JSON.parse(input.dataset.diagnostic):undefined;let owner={id:currentId,at:revision};const owns=()=>live()&¤tId===owner.id&&revision===owner.at; + try{const ensured=await ensureConversation();if(!ensured)return;owner=ensured;if(!owns())return;const {id}=owner,stamp=JSON.stringify([text,diagnostic]);if(!pendingRequest||pendingRequest.stamp!==stamp)pendingRequest={stamp,id:window.PageLifecycle?.requestKey?.()||crypto.randomUUID()};const requestId=pendingRequest.id; + await api('/assistant/conversations/'+id+'/messages',{text,diagnostic,requestId}, {managedOutcome:true});if(!owns())return;input.value='';input.dataset.diagnostic='';pendingRequest=null;drafts.delete(id);await refreshList();if(owns())await select(id); + }catch(e){if(owns()){showError(e);await loadCurrent().catch(()=>{});if(!owns())return;if(e.outcome==='uncertain')error.textContent='提交结果待核实,已查询当前会话;再次发送同一草稿将使用原请求编号。';updateComposer();}} } - container.querySelector('#assistant-scope').onchange=async event=>{try{if(await refreshList(1,event.target.value))await select(data.conversations[0]?.id||'');}catch(e){showError(e);}}; - for(const [id,delta]of [['assistant-prev',-1],['assistant-next',1]])container.querySelector('#'+id).onclick=()=>refreshList(listPage+delta); - container.querySelector('#assistant-new').onclick=async()=>{try{const c=await api('/assistant/conversations',{});if(!live())return;scope='active';listPage=1;container.querySelector('#assistant-scope').value=scope;await refreshList();await select(c.id);input.focus();}catch(e){showError(e);}}; - container.querySelectorAll('[data-suggestion]').forEach(button=>button.onclick=()=>{input.value=button.textContent;input.focus();}); - container.querySelector('#assistant-compose').onsubmit=async event=>{event.preventDefault();if(send.disabled||!input.value.trim())return;send.disabled=true;error.textContent='';const text=input.value; - try{if(!currentId){const c=await api('/assistant/conversations',{});if(!live())return;currentId=c.id;sessionStorage.setItem(key,currentId);revision++;}await api('/assistant/conversations/'+currentId+'/messages',{text});if(!live())return;input.value='';await refreshList();await loadCurrent();messages.scrollTop=messages.scrollHeight;}catch(e){showError(e);if(live())send.disabled=!data.settings.enabled;} - }; - input.onkeydown=event=>{if(event.key==='Enter'&&!event.shiftKey&&!event.isComposing){event.preventDefault();container.querySelector('#assistant-compose').requestSubmit();}}; - stop.onclick=async()=>{stop.disabled=true;try{await api('/assistant/conversations/'+currentId+'/cancel',{});if(live()){await loadCurrent();watch();}}catch(e){showError(e);}finally{if(live())stop.disabled=false;}}; - - await refreshList();if(currentId)await select(currentId);else drawMessages(); + root.querySelector('#assistant-compose').onsubmit=sendMessage; + input.onkeydown=event=>{if(event.defaultPrevented||event.isComposing)return;if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();root.querySelector('#assistant-compose').requestSubmit();}}; + input.addEventListener('input',()=>{input.style.height='auto';input.style.height=Math.min(input.scrollHeight,180)+'px';}); + stop.onclick=async()=>{const id=currentId,at=revision;stop.disabled=true;try{await api('/assistant/conversations/'+id+'/cancel',{});if(live()&&id===currentId&&revision===at){await loadCurrent();watch();}}catch(e){showError(e);}finally{if(live())updateComposer();}}; + root.querySelector('#assistant-new').onclick=async()=>{try{const c=await api('/assistant/conversations',{});if(!live())return;scope='active';root.querySelector('#assistant-scope').value=scope;root.querySelector('#assistant-search').value='';await refreshList(1);await select(c.id);layout.closeLeft();input.focus();}catch(e){showError(e);}}; + root.querySelector('#assistant-scope').onchange=async event=>{if(await refreshList(1,event.target.value))await select(data.conversations[0]?.id||'');}; + root.querySelector('#assistant-search').oninput=()=>{clearTimeout(searchTimer);searchTimer=setTimeout(()=>void refreshList(1),250);}; + for(const [id,delta]of [['assistant-prev',-1],['assistant-next',1]])root.querySelector('#'+id).onclick=()=>refreshList(listPage+delta); + root.querySelectorAll('[data-diagnostic-start]').forEach(b=>b.onclick=()=>{if(b.dataset.diagnosticStart==='blockers'){input.value='根据当前授权快照,分析通知受阻原因;不要发送邮件。';input.dataset.diagnostic='';input.focus();}else commands.open(b.dataset.diagnosticStart);}); + function dispose(){if(disposed)return;disposed=true;revision++;eventClient?.dispose();clearTimeout(watchTimer);clearTimeout(searchTimer);commands.dispose();transcript.dispose();panel.dispose();layout.dispose();drafts.clear();pendingActions.clear();input.value='';} + window.PageLifecycle?.onDispose(dispose); + await refreshList(1);if(!data.conversations.some(c=>c.id===currentId))currentId=data.conversations[0]?.id||'';await select(currentId);void panel.refresh().catch(showError); } + async function settings(container,isActive=()=>true){const data=await api('/assistant');if(!isActive())return;const live=isActive;container.innerHTML='
    ';const showError=e=>{if(live())container.querySelector('#assistant-settings-error').textContent=e.message;}; if(user.role==='admin'){const s=data.settings;container.querySelector('#assistant-settings').innerHTML=`
    DSH 接入设置
    自动识别本机已校验的 DeepSeek Harness 0.2.1-rc.2。模型密钥加密保存,不会回传。
    仅在独立分支工作,固定测试失败自动恢复;不会修改运行服务、合并或部署。工作区不等同操作系统沙箱。
    `; container.querySelector('#assistant-settings-form').onsubmit=async event=>{event.preventDefault();const button=event.submitter;button.disabled=true;const get=id=>container.querySelector('#assistant-'+id),body={version:data.settings.version,runtimePath:get('runtime').value,apiBase:get('api-base').value,model:get('model').value,apiKey:get('key').value,enabled:get('enabled').checked,allowActions:get('allow-actions').checked,allowCodeRepair:get('code-repair').checked,repairRepository:get('repository').value,timeoutSeconds:Number(get('timeout').value),dailyLimit:Number(get('limit').value)}; diff --git a/web/modules/assistant/workspace.css b/web/modules/assistant/workspace.css new file mode 100644 index 0000000..2b5702b --- /dev/null +++ b/web/modules/assistant/workspace.css @@ -0,0 +1,4 @@ +/* DSH interaction adapted within the Tabler identity; geometry uses upstream computeColumns. */ +.dsh-focused>.navbar-vertical{display:none!important}.dsh-focused>.page-wrapper,.dsh-focused>.navbar{margin-left:0!important}.dsh-focused>.navbar{min-height:48px}.dsh-focused .page-header,.dsh-focused #settings-tabs,.dsh-focused>.page-wrapper>.footer{display:none!important}.dsh-focused .page-body{margin:0}.dsh-focused .page-body>.container-xl{max-width:none;padding:0}.assistant-workspace{height:calc(100dvh - 50px);min-height:420px;background:#fff;display:flex;flex-direction:column;color:#253b36;--aw-border:#e6ece8;font-size:14px}.aw-header{height:50px;min-height:50px;display:flex;align-items:center;gap:12px;padding:8px 18px;border-bottom:1px solid var(--aw-border)}.aw-header strong{font-size:15px}.aw-model,.aw-connection,.aw-usage{font-size:11px;color:#7b8c84}.aw-model{margin-left:auto}.aw-body{display:grid;flex:1;min-height:0;position:relative;overflow:hidden}.aw-sidebar{background:#f7f9f7;min-width:0;display:flex;flex-direction:column;overflow:hidden}.aw-sidebar-top{padding:18px 14px 8px;display:grid;gap:10px}.aw-conversations{flex:1;overflow:auto;padding:8px}.aw-conversations button{display:block;text-align:left;width:100%;border:0;background:transparent;border-radius:8px;padding:10px;color:#587166;overflow-wrap:anywhere;margin-bottom:4px}.aw-conversations button.active{background:#e4eee7;color:#1c6044}.aw-conversations button:hover{background:#edf2ee}.aw-conversations .small{font-size:10px;opacity:.7;margin-top:5px}.aw-pager{display:flex;gap:4px;align-items:center;justify-content:center;padding:8px}.aw-left-collapsed:not(.aw-narrow) .aw-sidebar>*{visibility:hidden}.aw-left-collapsed:not(.aw-narrow) .aw-sidebar{border-right:1px solid var(--aw-border)}.aw-drag{cursor:col-resize;background:#fff;z-index:2;touch-action:none}.aw-drag:hover,.aw-drag:focus{background:#b9d2c2}.aw-chat{display:flex;flex-direction:column;min-width:0;min-height:0;position:relative;background:#fff}.aw-chat-header{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:14px 22px 6px}.aw-chat-header h2{font-size:15px;margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.aw-chat-header .btn{font-size:10px;padding:4px 6px}.aw-chat>#assistant-history-note{font-size:10px;min-height:16px}.assistant-workspace .assistant-messages{flex:1;min-height:0;max-height:none;overflow:auto;background:#fff;padding:20px clamp(16px,5vw,54px);scrollbar-gutter:stable}.assistant-workspace .assistant-turn{max-width:850px;margin:0 auto 28px}.assistant-workspace .assistant-user{margin-left:12%;background:#eff4f0;border:0;padding:12px 16px;border-radius:18px 18px 4px 18px;font-size:14px}.assistant-workspace .assistant-reply{padding:18px 0 0}.assistant-workspace .assistant-answer{white-space:normal;line-height:1.85;font-size:14px;color:#2c4038}.assistant-answer h1,.assistant-answer h2,.assistant-answer h3{font-size:1.1em;line-height:1.7;margin:12px 0}.assistant-answer p{margin:0 0 10px}.assistant-answer ul,.assistant-answer ol{padding-left:22px}.assistant-answer table{display:block;max-width:100%;overflow:auto;border-collapse:collapse;margin:12px 0;font-size:12px}.assistant-answer th,.assistant-answer td{border:1px solid #e3eae5;padding:7px 10px;white-space:normal}.assistant-answer pre,.assistant-action pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#f5f7f5;border:1px solid #e4eae5;border-radius:8px;padding:12px;max-height:340px;overflow:auto}.aw-process{color:#7c8c83;font-size:12px;margin:12px 0}.aw-process summary{cursor:pointer}.aw-process ol{padding-left:24px}.aw-process li{padding:3px}.aw-reply-header{display:flex;gap:8px;align-items:center;font-size:12px;margin-bottom:6px}.aw-state{font-size:10px;padding:2px 6px;border-radius:6px;background:#edf3ef}.aw-state.error{color:#b84646;background:#fff0f0}.aw-turn-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}.aw-turn-actions button{font-size:11px}.aw-composer{padding:10px 24px 14px;background:#fff;border-top:1px solid #f0f3f0}.aw-input-wrap{position:relative}.aw-input-wrap textarea{min-height:64px;max-height:180px;border:1px solid #dbe5dd;border-radius:14px;padding:14px;resize:none;background:#fafcf9;line-height:1.7}.aw-compose-tools{display:flex;gap:8px;align-items:center;margin-top:8px}.aw-suggestions{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px}.aw-suggestions .btn{font-size:11px;padding:4px 8px;color:#6b8175;background:#f4f7f3;border-color:transparent}.aw-command-menu{position:absolute;bottom:calc(100% + 8px);left:0;right:0;background:#fff;border:1px solid #dfe7e0;box-shadow:0 8px 32px #2336291a;border-radius:12px;max-height:280px;overflow:auto;padding:6px;z-index:20}.aw-command-menu button{display:flex;gap:12px;text-align:left;align-items:center;width:100%;border:0;background:transparent;padding:10px;border-radius:7px;font-size:13px}.aw-command-menu button[aria-selected=true],.aw-command-menu button:hover{background:#edf4ee}.aw-command-menu small{font-size:11px;color:#85938a}.aw-context{min-width:0;overflow:auto;border-left:1px solid var(--aw-border);background:#fafbf9}.aw-context-tabs{display:flex;gap:2px;padding:10px;position:sticky;top:0;background:#fafbf9;border-bottom:1px solid var(--aw-border);z-index:2}.aw-context-tabs button{flex:1;background:transparent;border:0;padding:9px 4px;border-radius:7px;color:#718578;font-size:12px}.aw-context-tabs button[aria-selected=true]{background:#e8f0e9;color:#245c3d;font-weight:600}.aw-context>[role=tabpanel]{padding:16px;font-size:12px}.aw-context h3{font-size:14px}.aw-context h4{font-size:12px;margin:14px 0 7px}.aw-context .assistant-action{font-size:12px;padding:12px;background:#fff}.aw-context .assistant-action .btn{font-size:11px}.aw-context .card{box-shadow:none}.aw-context .card-header,.aw-context .card-body{padding:10px;min-height:0}.aw-context .card-title{font-size:12px}.aw-context .table th,.aw-context .table td{display:block;padding:4px;max-width:100%;font-size:10px}.aw-context .table tr{display:block;padding:8px 0;border-bottom:1px solid var(--aw-border)}.aw-context .table thead{display:none}.aw-stat{border-bottom:1px solid #e8eee7;padding:10px 0;overflow-wrap:anywhere}.aw-stat strong{display:block;color:#3a5f48}.aw-stat span{display:block;margin-top:4px;color:#859588;font-size:11px}.aw-context time{font-size:10px;color:#8c9b8e}.aw-event{border-left:2px solid #d7e5d9;padding:6px 10px;margin:5px 0;overflow-wrap:anywhere}.aw-context .btn-list{gap:4px}.aw-right-open .aw-context{visibility:visible}.assistant-workspace:not(.aw-right-open) .aw-context{visibility:hidden}.aw-back{font-size:11px;color:#809384}.aw-welcome{padding:clamp(16px,5vh,64px) 0;text-align:center;max-width:480px;margin:auto}.aw-welcome-mark{display:grid;place-items:center;width:48px;height:48px;border-radius:16px;background:#e8f1e9;color:#28745b;font-size:20px;margin:0 auto 18px}.aw-welcome h3{font-size:20px}.aw-welcome p{color:#8a9a8f;font-size:12px;line-height:1.9}.aw-context .text-danger{white-space:pre-wrap}.aw-verify-warning{background:#fff7e8;border:1px solid #f1d7a9;color:#96631c;padding:10px;border-radius:7px;margin:10px 0}#assistant-new-progress{position:absolute;bottom:170px;left:50%;transform:translateX(-50%);font-size:11px;box-shadow:0 2px 12px #23532e15;z-index:3} +.aw-narrow .aw-drag{display:none}.aw-narrow .aw-sidebar,.aw-narrow .aw-context{position:absolute;top:0;bottom:0;z-index:12;width:min(320px,90%);box-shadow:0 8px 36px #173e2926}.aw-narrow .aw-sidebar{left:0;display:none}.aw-narrow .aw-context{right:0;display:none}.aw-narrow.aw-left-open .aw-sidebar,.aw-narrow.aw-right-open .aw-context{display:flex;flex-direction:column}.aw-narrow .aw-context>[role=tabpanel]{overflow:auto}.aw-narrow .aw-chat{grid-column:1}.aw-narrow .aw-chat-header{padding:10px 14px}.aw-narrow .aw-usage,.aw-narrow .aw-back,.aw-narrow .aw-connection{display:none}.aw-narrow .aw-header{padding:6px 10px;gap:8px}.aw-narrow .aw-model{max-width:110px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.aw-narrow .aw-composer{padding:8px 12px 12px}.aw-narrow .aw-compose-tools .small{font-size:9px}.aw-narrow .assistant-messages{padding:16px}.aw-narrow .assistant-user{margin-left:5%}.aw-narrow .aw-chat-header .btn-list{gap:3px;flex-shrink:0}.aw-narrow .aw-chat-header h2{font-size:12px}.aw-narrow .aw-suggestions .btn{font-size:10px} +@media(prefers-reduced-motion:reduce){.assistant-workspace *{scroll-behavior:auto!important;transition:none!important}}@media(max-height:550px){.assistant-workspace{height:calc(100dvh - 48px);min-height:300px}.aw-header{height:40px;min-height:40px}.aw-input-wrap textarea{min-height:42px;max-height:80px}.aw-suggestions{display:none}}