From bfd0d778292c0e8753d44979e445aa0220930609 Mon Sep 17 00:00:00 2001 From: klarkxy <278370456@qq.com> Date: Fri, 20 Nov 2026 15:33:23 +0800 Subject: [PATCH 1/4] Add @klarkxy/dsh-quick-review: one-click read-only code review in a sidebar tab A new standalone plugin that starts a specified-model, read-only review session from the conversation header, shows it live in a right-sidebar tab, and relays the first-turn verdict back to the source session as an agent-message relay. Defaults to reviewing only the files this session changed (workspace/changes summaries), falling back to all uncommitted workspace changes when no summary survives. Key safety choices: the model route is validated before the session is created, agent.model.select is used instead of sessionController.selectModel so the global default model is never overwritten, the read-only preset is verified up front and pinned before any prompt (a host without the preset or a failed setup refuses rather than spawning a writable reviewer), and the review record is registered before awaiting the prompt so a fast turn/end can never slip past the tracker. Review sessions are tracked explicitly and the header action is hidden inside them; settled records are evicted to bound memory. Registered as testing in the lifecycle manifest: QA acceptance passed (mock provider, isolated dsh web) and the first npm release goes through the manual first_release workflow. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.en.md | 1 + README.md | 1 + plugins/dsh-quick-review/LICENSE | 42 + plugins/dsh-quick-review/README.en.md | 35 + plugins/dsh-quick-review/README.md | 35 + plugins/dsh-quick-review/cordis.patch.yml | 6 + plugins/dsh-quick-review/icon.svg | 15 + plugins/dsh-quick-review/locale/en.json | 6 + plugins/dsh-quick-review/locale/zh.json | 6 + plugins/dsh-quick-review/package.json | 133 +++ .../dsh-quick-review/src/anchored-position.ts | 61 ++ plugins/dsh-quick-review/src/client.spec.tsx | 100 ++ plugins/dsh-quick-review/src/client.tsx | 877 ++++++++++++++++++ plugins/dsh-quick-review/src/contracts.ts | 104 +++ plugins/dsh-quick-review/src/index.ts | 179 ++++ plugins/dsh-quick-review/src/prompts.ts | 33 + plugins/dsh-quick-review/src/service.spec.ts | 334 +++++++ plugins/dsh-quick-review/src/service.ts | 588 ++++++++++++ plugins/dsh-quick-review/src/storage.ts | 41 + plugins/dsh-quick-review/tsconfig.json | 16 + plugins/dsh-quick-review/tsdown.config.ts | 39 + pnpm-lock.yaml | 64 ++ scripts/plugin-release-states.json | 8 + 23 files changed, 2724 insertions(+) create mode 100644 plugins/dsh-quick-review/LICENSE create mode 100644 plugins/dsh-quick-review/README.en.md create mode 100644 plugins/dsh-quick-review/README.md create mode 100644 plugins/dsh-quick-review/cordis.patch.yml create mode 100644 plugins/dsh-quick-review/icon.svg create mode 100644 plugins/dsh-quick-review/locale/en.json create mode 100644 plugins/dsh-quick-review/locale/zh.json create mode 100644 plugins/dsh-quick-review/package.json create mode 100644 plugins/dsh-quick-review/src/anchored-position.ts create mode 100644 plugins/dsh-quick-review/src/client.spec.tsx create mode 100644 plugins/dsh-quick-review/src/client.tsx create mode 100644 plugins/dsh-quick-review/src/contracts.ts create mode 100644 plugins/dsh-quick-review/src/index.ts create mode 100644 plugins/dsh-quick-review/src/prompts.ts create mode 100644 plugins/dsh-quick-review/src/service.spec.ts create mode 100644 plugins/dsh-quick-review/src/service.ts create mode 100644 plugins/dsh-quick-review/src/storage.ts create mode 100644 plugins/dsh-quick-review/tsconfig.json create mode 100644 plugins/dsh-quick-review/tsdown.config.ts diff --git a/README.en.md b/README.en.md index 4b6fa6dd..43d31a90 100644 --- a/README.en.md +++ b/README.en.md @@ -73,6 +73,7 @@ The code is the developer documentation. Releases follow the [release guide](REL | [@klarkxy/dsh-model-route](plugins/dsh-model-route/README.en.md) | Published (`published`) | Published on npm; fixes, testing and version updates keep the Published lifecycle. | | [@klarkxy/dsh-plugin-kit](plugins/dsh-plugin-kit/README.en.md) | Published (`published`) | Published on npm; fixes, testing and version updates keep the Published lifecycle. | | [@klarkxy/dsh-prompt-override](plugins/dsh-prompt-override/README.en.md) | Published (`published`) | Published on npm; subsequent versions follow the normal update workflow. | +| [@klarkxy/dsh-quick-review](plugins/dsh-quick-review/README.en.md) | Testing (`testing`) | Read-only review session and sidebar tab passed first-release acceptance; the first npm release goes through the manual first_release workflow. | | [@klarkxy/dsh-safe-auto](plugins/dsh-safe-auto/README.en.md) | Published (`published`) | Published on npm; fixes, testing and version updates keep the Published lifecycle. | | [@klarkxy/dsh-secret-manager](plugins/dsh-secret-manager/README.en.md) | Published (`published`) | Published on npm; subsequent versions follow the normal update workflow. | | [@klarkxy/dsh-session-manager](plugins/dsh-session-manager/README.en.md) | Published (`published`) | Published on npm; fixes, testing and version updates keep the Published lifecycle. | diff --git a/README.md b/README.md index be005323..2a13cdc4 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ pnpm check | [@klarkxy/dsh-model-route](plugins/dsh-model-route/README.md) | 已发布 (`published`) | 已有 npm 发布记录;后续修复、测试和版本更新保持已发布。 | | [@klarkxy/dsh-plugin-kit](plugins/dsh-plugin-kit/README.md) | 已发布 (`published`) | 已有 npm 发布记录;后续修复、测试和版本更新保持已发布。 | | [@klarkxy/dsh-prompt-override](plugins/dsh-prompt-override/README.md) | 已发布 (`published`) | 已有 npm 发布记录;后续版本按正常更新流程维护。 | +| [@klarkxy/dsh-quick-review](plugins/dsh-quick-review/README.md) | 测试中 (`testing`) | 只读评审会话与侧边栏标签页已完成首次发布验收;首次 npm 发布走手动 first_release 流程。 | | [@klarkxy/dsh-safe-auto](plugins/dsh-safe-auto/README.md) | 已发布 (`published`) | 已有 npm 发布记录;后续修复、测试和版本更新保持已发布。 | | [@klarkxy/dsh-secret-manager](plugins/dsh-secret-manager/README.md) | 已发布 (`published`) | 已有 npm 发布记录;后续版本按正常更新流程维护。 | | [@klarkxy/dsh-session-manager](plugins/dsh-session-manager/README.md) | 已发布 (`published`) | 已有 npm 发布记录;后续修复、测试和版本更新保持已发布。 | diff --git a/plugins/dsh-quick-review/LICENSE b/plugins/dsh-quick-review/LICENSE new file mode 100644 index 00000000..abc9aeef --- /dev/null +++ b/plugins/dsh-quick-review/LICENSE @@ -0,0 +1,42 @@ + The Star And Thank Author License (SATA) + Version 2.1, September 2026 + +Copyright © 2026 Klarkxy(278370456@qq.com) + +Project Url: https://github.com/klarkxy/dsh-editor + https://github.com/klarkxy/sata-license + https://github.com/klarkxy/dsh-plugins + +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. + +And wait, one more thing — an invitation, not a condition: it would be best if +you star/+1/like the project(s) in the project url section above, and thank the +author(s) in the Copyright section. You may, and arguably you should — but the +permissions above hold either way, star or no star. + +Here are some suggested ways: + + - Email the authors a thank-you letter, and make friends with him/her/them. + - Report bugs or issues. + - Tell friends what a wonderful project this is. + - And, sure, you can just express thanks in your mind without telling the world. + +Contributors of this project by forking have the option to add his/her name and +forked project url at copyright and project url sections, but shall not delete +or modify anything else in these two sections. + +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/plugins/dsh-quick-review/README.en.md b/plugins/dsh-quick-review/README.en.md new file mode 100644 index 00000000..4265a8fd --- /dev/null +++ b/plugins/dsh-quick-review/README.en.md @@ -0,0 +1,35 @@ +# Quick Review + + + +[简体中文](README.md) / English + +Start a read-only review session from the current conversation with one click. It streams live in a right-sidebar tab, reviews only this session's own changes, and its first-turn verdict is sent back to the conversation automatically. + +## Install + +```sh +dsh plugin --profile web add @klarkxy/dsh-quick-review +``` + +Replace `web` with your profile name and restart the profile as DSH prompts. + +## Use + +1. Open a conversation that has already produced file changes. +2. Click **Review** in the conversation header. +3. Pick a review model in the popover (your last choice is remembered; leaving it empty follows the host default chat model), optionally add a focus, then click **Start review**. +4. A review tab opens in the right sidebar showing the live review conversation, with its status on top. +5. When the review's first turn finishes, its final answer is sent back to the main session. After chatting further with the reviewer, use **Send to main again** in the tab to relay the newest answer. + +## Limits + +- The review scope comes from the host's session change recording (`workspace/changes` summaries). After a host restart or without recorded changes it falls back to "all uncommitted changes in the workspace", which the popover and the review prompt state plainly. +- The review session is pinned to the host's built-in `read-only` permission preset (read-only sandbox, writes require approval). The plugin refuses to start when the preset is missing rather than launching a writable reviewer. +- The review model is written to the review session only; it never changes your global default model. +- The first-turn verdict is sent back exactly once. An aborted, failed, or empty turn sends nothing and shows as undelivered in the tab. +- Blank and subagent sessions have no review entry. **Send to main again** relies on the plugin's in-memory records and is unavailable after a host restart. + +## License + +[SATA License 2.1](LICENSE) diff --git a/plugins/dsh-quick-review/README.md b/plugins/dsh-quick-review/README.md new file mode 100644 index 00000000..785f2792 --- /dev/null +++ b/plugins/dsh-quick-review/README.md @@ -0,0 +1,35 @@ +# 快速评审 + + + +简体中文 / [English](README.en.md) + +一键从当前对话派出一个只读评审会话:它在右侧面板里实时展开,只评审本会话产生的改动,首轮评审结论自动发回当前对话。 + +## 安装 + +```sh +dsh plugin --profile web add @klarkxy/dsh-quick-review +``` + +将 `web` 替换为你的 profile 名称,按 DSH 提示重启 profile。 + +## 使用 + +1. 打开一个已经产生过文件修改的对话。 +2. 点击对话右上角的「评审」。 +3. 在弹窗中选择评审模型(会记住上次选择;留空跟随宿主默认对话模型),可填写「关注点」,点击「开始评审」。 +4. 右侧面板打开评审标签页,实时显示评审会话的完整对话;标签页顶部显示评审状态。 +5. 评审首轮结束后,最终结论自动发回主会话。与评审会话继续对话后,可点标签页里的「再次发回主会话」把最新回答再发一次。 + +## 主要限制 + +- 评审范围取宿主的会话改动记录(`workspace/changes` 汇总);宿主重启或会话没有改动记录时,回退为「工作区全部未提交改动」,弹窗和评审提示会如实说明。 +- 评审会话固定使用宿主内置的 `read-only` 权限预设(只读沙箱 + 写操作需批准);宿主缺少该预设时插件拒绝启动,不会放行可写评审。 +- 评审模型只写入评审会话,不改动全局默认模型。 +- 首轮评审只自动发回一次;评审被中止、失败或没有产出文本时不会发送,状态在标签页中显示为未成功。 +- 空白会话与子代理会话不显示评审入口;「再次发回主会话」依赖插件运行中的内存记录,宿主重启后不可用。 + +## 许可证 + +[SATA License 2.1](LICENSE) diff --git a/plugins/dsh-quick-review/cordis.patch.yml b/plugins/dsh-quick-review/cordis.patch.yml new file mode 100644 index 00000000..245dde74 --- /dev/null +++ b/plugins/dsh-quick-review/cordis.patch.yml @@ -0,0 +1,6 @@ +# Enabled when installed. Adds a conversation-header quick review action and a +# right-sidebar review tab. +- insert: + - id: quick-review + name: '@klarkxy/dsh-quick-review' + disabled: false diff --git a/plugins/dsh-quick-review/icon.svg b/plugins/dsh-quick-review/icon.svg new file mode 100644 index 00000000..5fa20c5f --- /dev/null +++ b/plugins/dsh-quick-review/icon.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/plugins/dsh-quick-review/locale/en.json b/plugins/dsh-quick-review/locale/en.json new file mode 100644 index 00000000..b012c175 --- /dev/null +++ b/plugins/dsh-quick-review/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Quick Review", + "description": "Start a read-only review session over the current session's changes; its verdict is sent back automatically." + } +} diff --git a/plugins/dsh-quick-review/locale/zh.json b/plugins/dsh-quick-review/locale/zh.json new file mode 100644 index 00000000..20a4a3d8 --- /dev/null +++ b/plugins/dsh-quick-review/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "快速评审", + "description": "一键派出只读评审会话审阅当前会话的改动,结果自动发回本会话。" + } +} diff --git a/plugins/dsh-quick-review/package.json b/plugins/dsh-quick-review/package.json new file mode 100644 index 00000000..1fe3f0d9 --- /dev/null +++ b/plugins/dsh-quick-review/package.json @@ -0,0 +1,133 @@ +{ + "name": "@klarkxy/dsh-quick-review", + "version": "0.1.0", + "description": "Quick Review: start a read-only code review of the current session's changes from the conversation header, with the review shown in a sidebar tab and its verdict relayed back.", + "icon": "./icon.svg", + "license": "SEE LICENSE IN LICENSE", + "type": "module", + "engines": { + "node": ">=22", + "dsh": ">=0.2.1-rc.1" + }, + "main": "./lib/index.js", + "types": "./lib/index.d.ts", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "import": "./lib/index.js", + "default": "./lib/index.js" + }, + "./contracts": { + "types": "./lib/contracts.d.ts", + "import": "./lib/contracts.js", + "default": "./lib/contracts.js" + }, + "./client": { + "default": "./lib/client.js" + }, + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" + }, + "files": [ + "icon.svg", + "locale/*.json", + "lib", + "cordis.patch.yml", + "README.md", + "README.en.md", + "LICENSE" + ], + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + }, + "client": { + "platform": "web", + "inject": [ + "@deepseek-ai/dsh-client-connection", + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-api-session-controller", + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-resources", + "@deepseek-ai/dsh-client-ui-slots", + "@deepseek-ai/dsh-client-ui-session", + "@deepseek-ai/dsh-client-ui-conversation", + "@deepseek-ai/dsh-client-ui-sidebar-right", + "@deepseek-ai/dsh-client-ui-primitives" + ] + } + }, + "scripts": { + "build": "tsdown && node ../../scripts/editor-plugins/wrap-client.mjs @klarkxy/dsh-quick-review", + "typecheck": "tsc --noEmit -p tsconfig.json", + "test": "vitest run --root ../.. --config vitest.editor-plugins.config.ts --maxWorkers=2 plugins/dsh-quick-review/src" + }, + "dependencies": { + "@klarkxy/dsh-model-route": "workspace:*", + "@klarkxy/dsh-plugin-kit": "workspace:*", + "zod": "^4.1.5" + }, + "peerDependencies": { + "@deepseek-ai/cordis": ">=4.0.4", + "@deepseek-ai/dsh-llm": ">=0.2.1-rc.1", + "@deepseek-ai/dsh-session": ">=0.2.1-rc.1", + "@deepseek-ai/dsh-storage-domain": ">=0.2.0-rc.2" + }, + "peerDependenciesMeta": { + "@deepseek-ai/cordis": { + "optional": true + }, + "@deepseek-ai/dsh-llm": { + "optional": true + }, + "@deepseek-ai/dsh-session": { + "optional": true + }, + "@deepseek-ai/dsh-storage-domain": { + "optional": true + } + }, + "devDependencies": { + "@deepseek-ai/cordis": "4.1.0", + "@deepseek-ai/dsh-llm": "0.2.2-rc.5", + "@deepseek-ai/dsh-session": "0.2.2-rc.5", + "@deepseek-ai/dsh-storage-domain": "0.2.2-rc.5", + "zod": "4.4.3", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "@types/react": "18.3.31", + "@types/react-dom": "^18.3.0", + "@deepseek-ai/dsh-agent": "0.2.2-rc.5", + "@deepseek-ai/dsh-api-session-controller": "0.2.2-rc.5", + "@deepseek-ai/dsh-client-resources": "0.2.2-rc.5", + "@deepseek-ai/dsh-client-ui-conversation": "0.2.2-rc.5", + "@deepseek-ai/dsh-client-ui-primitives": "0.2.2-rc.5", + "@deepseek-ai/dsh-client-ui-sidebar-right": "0.2.2-rc.5", + "@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.5", + "jsdom": "29.1.1", + "@types/jsdom": "28.0.3" + }, + "keywords": [ + "dsh", + "dsh-plugin", + "dsh-plugins", + "deepseek-harness", + "deepseek-harness-plugin", + "code-review", + "review", + "quick-review" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/klarkxy/dsh-plugins.git", + "directory": "plugins/dsh-quick-review" + }, + "homepage": "https://klarkxy.github.io/dsh-plugins/plugins/quick-review/", + "bugs": { + "url": "https://github.com/klarkxy/dsh-plugins/issues" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + } +} diff --git a/plugins/dsh-quick-review/src/anchored-position.ts b/plugins/dsh-quick-review/src/anchored-position.ts new file mode 100644 index 00000000..8cdcebcb --- /dev/null +++ b/plugins/dsh-quick-review/src/anchored-position.ts @@ -0,0 +1,61 @@ +import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type RefObject } from 'react' + +/** + * Local replacement for the host's useAnchoredPosition primitive, which was + * removed from @deepseek-ai/dsh-client-ui-primitives after 0.2.2-rc.1. Same + * contract: absolute-placement coordinates for the panel, or null until the + * first measurement. Flips to the side with more room, clamps into the + * viewport margin, and re-measures on resize and scroll while open. + */ +export function useAnchoredPosition(options: { + open: boolean + anchorRef: RefObject + panelRef: RefObject + side?: 'top' | 'bottom' + align?: 'start' | 'end' + gap: number + margin: number +}): CSSProperties | null { + const { open, anchorRef, panelRef, side = 'bottom', align = 'start', gap, margin } = options + const [position, setPosition] = useState(null) + const frame = useRef(0) + + const measure = () => { + const anchor = anchorRef.current + const panel = panelRef.current + if (!anchor) return + const anchorRect = anchor.getBoundingClientRect() + const panelWidth = panel?.offsetWidth ?? 0 + const panelHeight = panel?.offsetHeight ?? 0 + const preferTop = side === 'top' || anchorRect.bottom + gap + panelHeight > window.innerHeight - margin + const top = preferTop + ? Math.max(margin, anchorRect.top - gap - panelHeight) + : Math.min(anchorRect.bottom + gap, window.innerHeight - margin - panelHeight) + const anchorStart = align === 'end' ? anchorRect.right - panelWidth : anchorRect.left + const left = Math.min(Math.max(anchorStart, margin), Math.max(margin, window.innerWidth - margin - panelWidth)) + setPosition({ left, top }) + } + + const schedule = () => { + if (typeof requestAnimationFrame !== 'function') { measure(); return } + if (frame.current) cancelAnimationFrame(frame.current) + frame.current = requestAnimationFrame(measure) + } + + useLayoutEffect(() => { + if (!open) { setPosition(null); return } + measure() + window.addEventListener('resize', schedule) + window.addEventListener('scroll', schedule, true) + return () => { + window.removeEventListener('resize', schedule) + window.removeEventListener('scroll', schedule, true) + if (frame.current && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frame.current) + frame.current = 0 + } + }, [open, anchorRef, panelRef, side, align, gap, margin]) + + useEffect(() => () => { if (frame.current && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frame.current) }, []) + + return position +} diff --git a/plugins/dsh-quick-review/src/client.spec.tsx b/plugins/dsh-quick-review/src/client.spec.tsx new file mode 100644 index 00000000..5081e06f --- /dev/null +++ b/plugins/dsh-quick-review/src/client.spec.tsx @@ -0,0 +1,100 @@ +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { JSDOM } from 'jsdom' +import { describe, expect, it, vi } from 'vitest' +import { QuickReviewAction } from './client.tsx' + +/** + * Renders the header action for real (see client-render.spec.tsx in + * dsh-current-title for the same mount): the popover's model pick reaches + * `start` through `onModelChange`, so an in-flight settings.save can never + * silently reroute a review. + */ + +function mount(): { dom: JSDOM; root: Root; restore: () => Promise } { + const dom = new JSDOM('
') + const previous = new Map() + for (const [key, value] of Object.entries({ + window: dom.window, document: dom.window.document, HTMLElement: dom.window.HTMLElement, + Node: dom.window.Node, MouseEvent: dom.window.MouseEvent, IS_REACT_ACT_ENVIRONMENT: true, + })) { + previous.set(key, (globalThis as Record)[key]) + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }) + } + const root = createRoot(dom.window.document.getElementById('root')!) + return { + dom, + root, + restore: async () => { + await act(async () => root.unmount()) + dom.window.close() + for (const [key, value] of previous) { + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }) + } + }, + } +} + +function fakeClient() { + return { + connection: { generation: { subscribe: () => () => {} } }, + locale: { getSnapshot: () => ({ active: 'zh' }), subscribe: () => () => {} }, + } +} + +describe('quick review action', () => { + it('sends the picker-reported model with start instead of racing settings.update', async () => { + const { dom, root, restore } = mount() + try { + const calls: { endpoint: string; payload: Record }[] = [] + const call = async (endpoint: string, payload: Record) => { + calls.push({ endpoint, payload }) + if (endpoint === 'settings') { + return { ok: true, value: { revision: 0, model: { provider: 'p1', model: 'm1' } } } + } + if (endpoint === 'scope') return { ok: true, value: { kind: 'workspace' } } + if (endpoint === 'start') { + return { ok: true, value: { reviewSessionId: 'review-1', scope: { kind: 'workspace' }, model: { provider: 'p1', model: 'm1' } } } + } + return { ok: true, value: {} } + } + const useSession = ((selector: (snapshot: Record) => unknown) => selector({})) as never + const t = ((key: string) => key) as never + const document = dom.window.document + await act(async () => { + root.render( + , + ) + }) + const trigger = document.querySelector('button[aria-label="title"]')! + expect(trigger).not.toBeNull() + await act(async () => { + trigger.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })) + }) + // The picker's settings load reports its stored route via onModelChange. + await vi.waitFor(() => expect(calls.some(entry => entry.endpoint === 'settings')).toBe(true)) + await act(async () => { await Promise.resolve() }) + const startButton = [...document.querySelectorAll('button')] + .find(button => button.textContent === 'reviewAction')! + expect(startButton).not.toBeNull() + await act(async () => { + startButton.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })) + await Promise.resolve() + }) + await vi.waitFor(() => expect(calls.some(entry => entry.endpoint === 'start')).toBe(true)) + const start = calls.find(entry => entry.endpoint === 'start')! + expect(start.payload).toMatchObject({ + sourceSessionId: 's1', + model: { provider: 'p1', model: 'm1' }, + }) + } finally { + await restore() + } + }) +}) diff --git a/plugins/dsh-quick-review/src/client.tsx b/plugins/dsh-quick-review/src/client.tsx new file mode 100644 index 00000000..88e697a4 --- /dev/null +++ b/plugins/dsh-quick-review/src/client.tsx @@ -0,0 +1,877 @@ +import type { Context } from '@deepseek-ai/cordis' +import type { ISessions, SessionReference } from '@deepseek-ai/dsh-api-session-controller/client' +import type { ResourceProvider } from '@deepseek-ai/dsh-client-resources/client' +import type { ConversationViewsProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { SidebarRightTabDefinition } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' +import type { + PropsRenderFactories, PropsRenderSlots, PropsRuntime, +} from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { + MODEL_CATALOG_INJECT, readModelCatalog, modelMenuEffortLabel, modelMenuEffortOptions, parseModelMenuChoices, +} from '@klarkxy/dsh-model-route' +import { ModelCatalogStatus, ModelMenu, modelMenuCss, useModelCatalog } from '@klarkxy/dsh-model-route/ui' +import { renderModelPicker, useModelMenuAnchor, type RenderFactorySlot } from '@klarkxy/dsh-plugin-kit/model-picker' +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' +import { createPortal } from 'react-dom' +import { Button, IconChevronDownOutlineRegular, IconRefreshOutlineRegular, Tooltip, useDismissOnOutsidePointer } from '@deepseek-ai/dsh-client-ui-primitives' +import { useAnchoredPosition } from './anchored-position.ts' +import { officialUiCss } from '@klarkxy/dsh-plugin-kit/official-ui' +import { installClientPluginLogger } from '@klarkxy/dsh-plugin-kit/client-logger' +import { + PLUGIN_NAME, QUICK_REVIEW_CLIENT_SERVICE, RESOURCE_PROTOCOL, REVIEW_TAB_ID, RPC_CHANNEL, + parseReviewAddress, reviewAddress, + type QuickReviewSettings, type ReviewModelRoute, type ReviewScope, type ReviewStartValue, + type ReviewState, type ReviewStatus, type ReviewStatusValue, type RpcResult, +} from './contracts.ts' + +export const name = 'dsh-quick-review-client' +export const inject = ['slots', 'connection', 'locale', 'sessions', 'sidebarRight', 'resources', 'sidebarRightTabs', ...MODEL_CATALOG_INJECT] as const + +const NS = 'dsh-quick-review.action' + +const zh = { + action: '评审', + title: '快速评审', + reviewAction: '开始评审', + model: '模型', + modelDefault: '默认模型', + modelHint: '留空跟随宿主默认对话模型。', + focus: '关注点(可选)', + focusPlaceholder: '例如:重点看并发与错误处理', + scopeSession: '本会话改动了 {n} 个文件', + scopeWorkspace: '宿主未记录本会话的改动,将评审工作区全部未提交改动', + scopeLoading: '正在读取改动范围…', + running: '评审中', + starting: '正在创建评审会话…', + statusRunning: '评审进行中', + statusSent: '结果已发回主会话', + statusFailed: '评审未成功发回', + resend: '再次发回主会话', + resending: '正在发回…', + refresh: '刷新', + failed: '操作失败', + disabled: '插件已停用', + busy: '已有评审在进行', + stale: '设置已更新,请刷新后重试', + noModel: '未选择模型且宿主没有默认模型', + noSession: '会话不在线', + invalidRequest: '请求无效,请刷新后重试', + permissionUnavailable: '宿主缺少只读权限预设,已拒绝启动', + modelUnavailable: '所选模型不可用', + noCwd: '源会话没有工作区或工作目录', + setupFailed: '评审会话初始化失败', + subagentSession: '子代理会话不支持评审', + noText: '评审会话还没有可发送的回答', + deliveryUnavailable: '主会话无法接收消息', + promptFailed: '提示发送失败', + emptyResponse: '评审没有产出文本', + deliveryFailed: '发回主会话失败', + sessionDisposed: '评审会话已关闭', + turnIncomplete: '评审轮次未完成', + tabTitle: '快速评审', +} + +const en: Record = { + action: 'Review', + title: 'Quick Review', + reviewAction: 'Start review', + model: 'Model', + modelDefault: 'Default model', + modelHint: 'Leave empty to follow the host default chat model.', + focus: 'Focus (optional)', + focusPlaceholder: 'e.g. concentrate on concurrency and error handling', + scopeSession: '{n} files changed by this session', + scopeWorkspace: 'The host recorded no change summary for this session; all uncommitted workspace changes will be reviewed', + scopeLoading: 'Reading the review scope…', + running: 'Reviewing', + starting: 'Creating the review session…', + statusRunning: 'Review in progress', + statusSent: 'Verdict sent to the main session', + statusFailed: 'Review was not delivered', + resend: 'Send to main again', + resending: 'Sending…', + refresh: 'Refresh', + failed: 'Operation failed', + disabled: 'Plugin disabled', + busy: 'A review is already running', + stale: 'Settings changed; refresh and retry', + noModel: 'No model picked and the host has no default model', + noSession: 'Session is not live', + invalidRequest: 'Invalid request; refresh and retry', + permissionUnavailable: 'The host has no read-only preset; review refused', + modelUnavailable: 'The selected model is unavailable', + noCwd: 'The source session has no workspace or working directory', + setupFailed: 'The review session could not be set up', + subagentSession: 'Subagent sessions cannot be reviewed', + noText: 'The review has no answer to send yet', + deliveryUnavailable: 'The main session cannot receive messages', + promptFailed: 'Prompt failed', + emptyResponse: 'The review produced no text', + deliveryFailed: 'Delivery to the main session failed', + sessionDisposed: 'The review session was closed', + turnIncomplete: 'The review turn did not complete', + tabTitle: 'Quick Review', +} + +type Key = keyof typeof zh +type Translate = (key: Key) => string + +interface ConnectionLike { + generation?: { subscribe(listener: () => void): () => void } + rpc: { call(channel: string, endpoint: string, payload: unknown): Promise } +} + +interface SessionSnapshotLike { + blank?: boolean + running?: boolean + subagent?: unknown +} + +interface UseSessionLike { + (selector: (snapshot: SessionSnapshotLike) => T): T +} + +/** A failed RPC keeps its code so the panel can explain a rejection in its own words. */ +class RpcError extends Error { + readonly code: string + constructor(code: string, message: string) { + super(message) + this.name = 'RpcError' + this.code = code + } +} + +async function rpc( + call: (endpoint: string, payload: unknown) => Promise, + endpoint: string, + payload: unknown = {}, + fallback = '', +): Promise { + const result = await call(endpoint, payload) as RpcResult | undefined + if (!result || result.ok !== true) { + const failed = result && 'error' in result ? result.error : undefined + throw new RpcError(failed?.code ?? 'unknown', failed?.message ? failed.message : fallback) + } + return result.value +} + +function errorText(t: Translate, error: { code: string; message: string }): string { + const keys: Record = { + busy: 'busy', stale: 'stale', disposed: 'disabled', 'no-model': 'noModel', + 'session/not-found': 'noSession', 'bad-request': 'invalidRequest', 'not-found': 'invalidRequest', + cancelled: 'failed', + 'permission-unavailable': 'permissionUnavailable', + 'model-unavailable': 'modelUnavailable', + 'no-cwd': 'noCwd', + 'setup-failed': 'setupFailed', + 'subagent-session': 'subagentSession', + 'no-text': 'noText', + 'delivery-unavailable': 'deliveryUnavailable', + } + const key = keys[error.code] + return key ? t(key) : error.message || t('failed') +} + +function panelError(reason: unknown): { code: string; message: string } { + return reason instanceof RpcError + ? { code: reason.code, message: reason.message } + : { code: 'unknown', message: reason instanceof Error ? reason.message : String(reason) } +} + +function ReviewIcon() { + return ( + + ) +} + +export interface QuickReviewActionProps { + sessionId: string + useSession: UseSessionLike + call: (endpoint: string, payload: unknown) => Promise + t: Translate + /** Injected by the slot registration; absent in tests that render the button alone. */ + client?: Client + /** Open the review tab in the right sidebar; injected by the slot registration. */ + openReview?: (address: string) => void + /** Framework-composed factory renderer; absent in tests that render the button alone. */ + renderFactorySlot?: RenderFactorySlot +} + +export function QuickReviewAction({ sessionId, useSession, call, t, client, openReview, renderFactorySlot }: QuickReviewActionProps) { + const [open, setOpen] = useState(false) + const [scope, setScope] = useState() + const [loadingScope, setLoadingScope] = useState(false) + const [running, setRunning] = useState(false) + const [error, setError] = useState<{ code: string; message: string } | null>(null) + const [focus, setFocus] = useState('') + const [model, setModel] = useState() + const [review, setReview] = useState() + // Inside a review session itself the action stays hidden. + const [isReviewSession, setIsReviewSession] = useState(false) + const rootRef = useRef(null) + const triggerRef = useRef(null) + const panelRef = useRef(null) + const generationRef = useRef(0) + const position = useAnchoredPosition({ open, anchorRef: triggerRef, panelRef, gap: 5, margin: 16 }) + const blank = useSession(snapshot => snapshot.blank === true) + const subagent = useSession(snapshot => snapshot.subagent !== null && snapshot.subagent !== undefined) + + // The settings panel's model menu portals to document.body too, so the + // dismiss hook would count a pick click as "outside" and close the whole + // popover before onPick fires — same portal widening as the commit action. + const panelPortalRef = useMemo((): { current: HTMLElement | null } => ({ + get current() { + const panel = panelRef.current + if (!panel) return null + return { + contains: (node: Node | null): boolean => + panel.contains(node) + || [...document.querySelectorAll('.qrv-menu-portal')].some(menu => menu.contains(node)), + } as unknown as HTMLElement + }, + }), []) + + const changeOpen = useCallback((next: boolean) => { + setOpen(next) + if (next) { + setError(null) + } + }, []) + + const positioned = Boolean(position) + useEffect(() => { + if (open && positioned) panelRef.current?.focus() + }, [open, positioned]) + + useDismissOnOutsidePointer(rootRef, open, changeOpen, panelPortalRef) + + useEffect(() => { + generationRef.current += 1 + setOpen(false) + setScope(undefined) + setError(null) + setRunning(false) + setFocus('') + setModel(undefined) + setReview(undefined) + setIsReviewSession(false) + }, [sessionId]) + + const loadScope = useCallback(async () => { + const generation = generationRef.current + setLoadingScope(true) + setError(null) + try { + const next = await rpc(call, 'scope', { sourceSessionId: sessionId }) + if (generationRef.current !== generation) return + setScope(next) + } catch (reason) { + if (generationRef.current !== generation) return + setScope(undefined) + setError(panelError(reason)) + } finally { + if (generationRef.current === generation) setLoadingScope(false) + } + }, [call, sessionId]) + + // Track the latest review for this source session so the button flips to a + // running chip while one is in flight; polling stops as soon as it settles. + useEffect(() => { + if (blank || subagent) return + let live = true + let timer: ReturnType | undefined + const load = async () => { + try { + const value = await rpc(call, 'status', { sourceSessionId: sessionId }) + if (!live) return + setIsReviewSession(value.isReview === true) + setReview(value.review) + if (value.review?.state === 'running') timer = setTimeout(load, 2000) + } catch { + if (!live) return + } + } + void load() + return () => { + live = false + if (timer !== undefined) clearTimeout(timer) + } + }, [call, sessionId, blank, subagent]) + + useEffect(() => { + if (!open) return + void loadScope() + }, [open, loadScope]) + + useEffect(() => { + if (!open) return + const dismiss = (event: KeyboardEvent) => { + if (event.key !== 'Escape') return + event.preventDefault() + changeOpen(false) + triggerRef.current?.focus() + } + document.addEventListener('keydown', dismiss) + return () => document.removeEventListener('keydown', dismiss) + }, [open, changeOpen]) + + const reveal = useCallback((reviewSessionId: string) => { + openReview?.(reviewAddress(reviewSessionId, sessionId)) + }, [openReview, sessionId]) + + const runStart = useCallback(async () => { + const generation = generationRef.current + setRunning(true) + setError(null) + try { + const value = await rpc(call, 'start', { + sourceSessionId: sessionId, + ...(model === undefined ? {} : { model }), + ...(focus.trim() === '' ? {} : { focus: focus.trim() }), + }) + if (generationRef.current !== generation) return + setRunning(false) + changeOpen(false) + reveal(value.reviewSessionId) + setReview({ + reviewSessionId: value.reviewSessionId, + sourceSessionId: sessionId, + state: 'running', + model: value.model, + scope: value.scope, + }) + } catch (reason) { + if (generationRef.current !== generation) return + setError(panelError(reason)) + setRunning(false) + } + }, [call, sessionId, focus, model, changeOpen, reveal]) + + if (blank || subagent || isReviewSession) return null + + const reviewing = review?.state === 'running' + const scopeText = scope === undefined + ? (loadingScope ? t('scopeLoading') : '') + : scope.kind === 'session' + ? t('scopeSession').replace('{n}', String(scope.files.length)) + : t('scopeWorkspace') + + return ( +
+ {reviewing ? ( + + + + ) : ( + + + + )} + {open && createPortal( +
+
+
+ {t('title')} + + +
+ {error !== null &&

{errorText(t, error)}

} + {scopeText !== '' && ( +

{scopeText}

+ )} + {client ? ( + + ) : null} +
+ {t('focus')} +