diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9ebb375..5b8b9b0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -2,16 +2,49 @@ name: Build and Release on: push: + branches: + - main + - 'feat/**' + - 'fix/**' tags: - 'v*' + pull_request: + branches: + - main + - 'feat/**' + - 'fix/**' workflow_dispatch: permissions: contents: write jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + + - name: Install frontend dependencies + run: npm ci + + - name: Run tests + run: npm test + + - name: Typecheck & build (tsc -b + vite build) + run: npm run build + build-windows: + needs: test runs-on: windows-latest + if: startsWith(github.ref, 'refs/tags/v') steps: - name: Checkout repository @@ -60,7 +93,9 @@ jobs: prerelease: false build-ubuntu: + needs: test runs-on: ubuntu-22.04 + if: startsWith(github.ref, 'refs/tags/v') steps: - name: Checkout repository @@ -114,7 +149,9 @@ jobs: prerelease: false build-macos: + needs: test runs-on: macos-latest + if: startsWith(github.ref, 'refs/tags/v') steps: - name: Checkout repository diff --git a/.gitignore b/.gitignore index 0bbeb5b..0dd3be1 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,13 @@ coverage/ test-report.html test-results.json AGENTS.md + +# BYOK local credentials (never commit) — for nlp-smoke evidence run +.byok.local.json +.env.local + +# personal harness docs + demo + e2e tooling (kept local, not released) +docs/ +scripts/e2e-shots.mjs +scripts/e2e-scenarios.mjs +scripts/gen-demo-html.mjs diff --git a/package-lock.json b/package-lock.json index f17fede..30ccfe2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "focus-flow", - "version": "1.0.0", + "version": "2.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "focus-flow", - "version": "1.0.0", + "version": "2.3.0", "dependencies": { "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", diff --git a/package.json b/package.json index 2b1b392..5402081 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "focus-flow", "description": "A floating todo app with Pomodoro timer - stay focused and organized", "private": true, - "version": "1.0.0", + "version": "2.3.0", "type": "module", "scripts": { "dev": "vite", diff --git a/scripts/gen-nlp-io-report.mjs b/scripts/gen-nlp-io-report.mjs new file mode 100644 index 0000000..1d4a1be --- /dev/null +++ b/scripts/gen-nlp-io-report.mjs @@ -0,0 +1,191 @@ +// 把 BYOK NLP 编辑内核(apply-core)的【真实 I/O】渲成一份分层 HTML。 +// 三层:形态层(概述,像将来 diff 预览)→ 原始数据层(详情,ops in / PlanResult out)→ 协议层(边界)。 +// 它同时是 Phase 1 的「可视化证据」和 apply-core 的「架构边界文档」。 +// +// 关键:所有输出都是【真实跑 apply-core】得到的,不是手写。fixture 只是输入(模拟 LLM 会吐的 ops), +// 被测对象(核心逻辑)是真的 —— 故用 fixture 是诚实的(被测在罐头输入的下游)。 +// +// 用法: node scripts/gen-nlp-io-report.mjs [out.html] +import { build } from 'esbuild'; +import { writeFileSync } from 'node:fs'; + +const outFile = process.argv[2] || 'docs/delivery/phase1-io-contract.html'; + +// ---- 1. 把真实 TS 内核转译成可运行的 ESM(import type 全擦除,无运行时依赖)---- +async function loadTs(entry) { + const r = await build({ entryPoints: [entry], bundle: false, write: false, format: 'esm', platform: 'node' }); + const code = r.outputFiles[0].text; + return import('data:text/javascript;base64,' + Buffer.from(code).toString('base64')); +} +const applyCore = await loadTs('src/lib/nlp-edit/apply-core.ts'); +const schema = await loadTs('src/lib/nlp-edit/schema.ts'); +const { planOps, OP_LIMIT } = applyCore; +const { PRIORITY_VALUES, DEADLINE_TYPE_VALUES, OP_KINDS } = schema; + +// ---- 2. 构造快照(含一棵树,用来展级联删除)---- +const mkTask = (id, title, o = {}) => ({ + id, title, zoneId: o.zoneId, parentId: o.parentId ?? null, + description: o.description ?? '', completed: o.completed ?? false, + priority: o.priority ?? 'medium', urgency: 'low', + deadline: o.deadline ?? null, deadlineType: o.deadlineType ?? 'none', + order: o.order ?? 0, createdAt: 0, isCollapsed: false, expanded: false, totalWorkTime: 0, +}); +const ZONES = [ + { id: 'z-work', name: '工作区', color: '#3b82f6', order: 0, createdAt: 0 }, + { id: 'z-life', name: '生活', color: '#22c55e', order: 1, createdAt: 0 }, +]; +const TASKS = [ + mkTask('t-proj', '项目A', { zoneId: 'z-work', parentId: null }), + mkTask('t-design', '设计稿', { zoneId: 'z-work', parentId: 't-proj' }), + mkTask('t-wire', '画线框', { zoneId: 'z-work', parentId: 't-design' }), + mkTask('t-impl', '写实现', { zoneId: 'z-work', parentId: 't-proj' }), + mkTask('t-bug', '修登录bug', { zoneId: 'z-work', parentId: null }), + mkTask('t-shop', '买菜', { zoneId: 'z-life', parentId: null }), +]; +const SNAP = { zones: ZONES, tasks: TASKS }; +const titleOf = (id) => TASKS.find((t) => t.id === id)?.title ?? id; +const zoneNameOf = (id) => ZONES.find((z) => z.id === id)?.name ?? id; + +// ---- 3. fixtures:每条模拟「LLM 对某句自然语言会吐的 ops」---- +const FIXTURES = [ + { label: '新增单个任务', nl: '在工作区加个「写周报」,高优先级', ops: [{ op: 'add_task', zoneId: 'z-work', title: '写周报', priority: 'high' }] }, + { label: '改优先级 + 截止', nl: '把「修登录bug」设为高优先级、明天截止', ops: [{ op: 'update_task', id: 't-bug', priority: 'high', deadlineType: 'tomorrow' }] }, + { label: '删叶子任务(无级联)', nl: '删掉「买菜」', ops: [{ op: 'delete_task', id: 't-shop' }] }, + { label: '删父任务(级联爆炸半径)', nl: '把「项目A」整个删掉', ops: [{ op: 'delete_task', id: 't-proj' }] }, + { label: '一句话多步', nl: '加个「发周报」,把修bug设高优,删掉买菜', ops: [{ op: 'add_task', zoneId: 'z-work', title: '发周报' }, { op: 'update_task', id: 't-bug', priority: 'high' }, { op: 'delete_task', id: 't-shop' }] }, + { label: '子任务 · 挂到已存在父 ✅', nl: '给「项目A」加子任务「写测试」', ops: [{ op: 'add_task', zoneId: 'z-work', title: '写测试', parentId: 't-proj' }] }, + { label: '建新树 · tempId 批内引用 ✅(TP7/T1)', nl: '新建项目「上线」,下面加「部署」「回归」', ops: [{ op: 'add_task', zoneId: 'z-work', title: '上线', tempId: 'u1' }, { op: 'add_task', zoneId: 'z-work', title: '部署', parentId: 'u1' }, { op: 'add_task', zoneId: 'z-work', title: '回归', parentId: 'u1' }] }, + { label: '护栏 · 成环 re-parent ❌(TP9)', nl: '把「项目A」挪到它自己的子任务「画线框」下', ops: [{ op: 'update_task', id: 't-proj', parentId: 't-wire' }] }, + { label: '护栏 · 未知任务 id', nl: '改一个不存在的任务', ops: [{ op: 'update_task', id: 't-nope', title: 'x' }] }, + { label: '护栏 · 未知分区', nl: '往不存在的分区加任务', ops: [{ op: 'add_task', zoneId: 'z-nope', title: 'x' }] }, + { label: '护栏 · 空操作', nl: '(模型没产出任何 op)', ops: [] }, + { label: '护栏 · 超过 op 上限', nl: `(模型失控,批量 ${OP_LIMIT + 1} 个)`, ops: Array.from({ length: OP_LIMIT + 1 }, (_, i) => ({ op: 'add_task', zoneId: 'z-work', title: 't' + i })) }, +]; + +// ---- 4. 真跑 ---- +const RUNS = FIXTURES.map((f) => ({ ...f, result: planOps(SNAP, f.ops) })); + +// ---- 5. 渲染 ---- +const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); +const j = (v) => esc(JSON.stringify(v, null, 2)); + +function overview(r) { + if (r.kind === 'noop') return `
∅ 空操作 · 合法但不落地
`; + if (r.kind === 'error') return `
✗ ${esc(r.error.code)} @op[${r.error.opIndex}]
${esc(r.error.message)}
`; + const lines = []; + for (const a of r.diff.added) lines.push(`
+ 新增「${esc(a.title)}」(${esc(zoneNameOf(a.zoneId))}${a.parentLabel ? ' · 挂到「' + esc(a.parentLabel) + '」下' : ''})
`); + for (const u of r.diff.updated) { + const ch = Object.entries(u.changes).map(([k, v]) => `${esc(k)}=${esc(String(v))}`).join(' '); + lines.push(`
~ 改「${esc(titleOf(u.id))}」 ${ch}
`); + } + const d = r.diff.deleted; + if (d.removedIds.length) { + const names = d.requestedIds.map(titleOf).join('、'); + const warn = d.cascadeCount > 0 ? `⚠ 含级联 ${d.cascadeCount} 个子孙` : ''; + lines.push(`
− 删除 ${r.deleteCount} 个:${esc(names)} ${warn}
`); + } + return `
${lines.join('')}
落地动作 ${r.actions.length} 步
`; +} + +const card = (r) => ` +
+
+ ${esc(r.label)} + “${esc(r.nl)}” +
+ ${overview(r.result)} +
+ 原始数据态(输入 ops → PlanResult 输出) +
+
输入 ops(fixture,模拟 LLM 产出)${r.ops.length > 6 ? ` · 共 ${r.ops.length} 条,截前 3` : ''}
${j(r.ops.length > 6 ? r.ops.slice(0, 3) : r.ops)}
+
apply-core 真实输出 PlanResult
${j(r.result)}
+
+
+
`; + +const opSchemaRow = (kind, required, fields) => ` + ${kind}${required.map((x) => `${x}`).join(' ')}${fields}`; + +const html = ` + +apply-core · I/O 契约 & 架构边界 +
+

apply-core · I/O 契约 & 架构边界

+

BYOK NLP 编辑 Phase 1 · 输出由真实 planOps 跑 fixture 得到(非手写)· 由 scripts/gen-nlp-io-report.mjs 生成

+
+ 这块是纯逻辑、没有 UI,但它是 LLM 对话功能的起点。所以这里画的是它的 I/O 契约,不是页面:
+ 形态层(每张卡上半,像将来 diff 预览)→ 点开 原始数据态(ops 进 / PlanResult 出)→ 末尾 协议层(边界)。
+ 对纯逻辑模块,I/O + 协议 就是它的架构边界,无需另画依赖图。 +
+ +

① 形态层 + 详情层:真实 I/O(${RUNS.length} 例)

+ ${RUNS.map(card).join('')} + +

② 协议层 = 架构边界(apply-core 的边)

+

边界的两半:「收什么 / 吐什么 / 保证什么」(下表)+「绝不碰什么」(见末尾 forbidden)。

+ +

入口 op(schema 锁死,additionalProperties:false 防越权)

+ + ${opSchemaRow('add_task', ['op', 'zoneId', 'title'], 'description, priority, deadline, deadlineType, parentId, tempId(批内句柄·建新树)')} + ${opSchemaRow('update_task', ['op', 'id'], 'title, description, completed, priority, deadline, deadlineType, parentId(按 id 部分更新)')} + ${opSchemaRow('delete_task', ['op', 'id'], '(无)· 注意级联删整棵子树')} +
op必填可选字段
+ +

枚举锁死 / 上限

+ + +

出口:PlanResult(discriminated union)

+ + +

错误码(协议保证拦截的越界)

+

OP_LIMIT_EXCEEDED · UNKNOWN_TASK_ID · UNKNOWN_ZONE_ID · UNKNOWN_PARENT_ID · DUPLICATE_TEMP_ID · CYCLE · INVALID_OP

+ +

边界另一半:forbidden(这块绝不碰)

+

纯函数:不碰 store / fs / 网络 / 命令;不修改入参 snapshot;副作用(真调 store action + saveSnapshot)留在 wiring 层。→ 与 byok-plan-v2 §4 boundary rules 一致。

+ +

树/层级边界(原 known-gap,现已覆盖 · 见 docs/harness/test-points.md)

+ + + +
`; + +writeFileSync(outFile, html); +console.log(`I/O 契约报告已生成: ${outFile} (${RUNS.length} 例真实 planOps 输出)`); diff --git a/scripts/gen-test-report.mjs b/scripts/gen-test-report.mjs index 86e1f28..47e4edd 100644 --- a/scripts/gen-test-report.mjs +++ b/scripts/gen-test-report.mjs @@ -17,6 +17,8 @@ const FEATURE_NOTES = { 'migration': '数据迁移:DB 设置 → 应用设置的字段映射与布尔/默认值回退', 'file-mirror-core': '文件镜像内核:回声锁不变量(canonical)、镜像解析、启动/轮询动作决策', 'file-mirror-engine': '文件镜像引擎:IO 编排与锁行为', + 'apply-core': 'BYOK NLP 编辑内核:op 校验 + action 计划 + diff 预览(增/改/删)、未知 id/zoneId/parentId 拦截、删除级联展开、op 上限、坏 op 全否决(fail-fast)', + 'schema': 'BYOK NLP 编辑 op 的 JSON Schema:add/update/delete 三类,priority/deadlineType 枚举锁死、additionalProperties:false 防越权、urgency 不可设(派生量)', }; const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); @@ -24,7 +26,7 @@ const fmtMs = (ms) => (ms == null ? '–' : ms < 1 ? '<1ms' : ms < 1000 ? `${ms. const files = data.testResults.map((f) => { const rel = relative(root, f.name); - const base = rel.split('/').pop().replace(/\.test\.tsx?$/, ''); + const base = rel.split(/[\\/]/).pop().replace(/\.test\.tsx?$/, ''); const assertions = f.assertionResults || []; const passed = assertions.filter((a) => a.status === 'passed').length; const failed = assertions.filter((a) => a.status === 'failed').length; diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 4b9538b..a448c2d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "floating-todo" -version = "1.0.0" +version = "2.3.0" description = "A floating todo list app with pomodoro timer" authors = ["Floating Todo"] license = "MIT" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index d1a68a9..264e3ba 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,6 +1,6 @@ { "productName": "FocusFlow", - "version": "2.1.9", + "version": "2.3.0", "identifier": "com.focusflow.app", "build": { "frontendDist": "../dist", diff --git a/src/App.tsx b/src/App.tsx index 8f47a5e..9c2b382 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -683,9 +683,11 @@ function App() { { setActiveZoneId(zoneId); setCurrentView(zoneId === null ? 'global' : 'zones'); diff --git a/src/components/ByokSettingsSection.test.tsx b/src/components/ByokSettingsSection.test.tsx new file mode 100644 index 0000000..23c607d --- /dev/null +++ b/src/components/ByokSettingsSection.test.tsx @@ -0,0 +1,49 @@ +// @vitest-environment jsdom +import { describe, it, expect, vi, afterEach } from 'vitest'; +import '@testing-library/jest-dom/vitest'; +import { render, screen, cleanup } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (k: string) => k }) })); +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +import { ByokSettingsSection } from './ByokSettingsSection'; +import { BYOK_STORAGE_KEY } from '@/lib/nlp-edit/provider'; + +afterEach(() => { + cleanup(); + localStorage.clear(); +}); + +describe('ByokSettingsSection', () => { + it('填写保存 → 写入 byok_v1 + 状态变已配置 + 出现清除按钮', async () => { + const user = userEvent.setup(); + render(); + expect(screen.queryByTestId('byok-clear')).not.toBeInTheDocument(); // 未配置时无「清除」 + await user.type(screen.getByTestId('byok-set-base'), 'https://x/v1'); + await user.type(screen.getByTestId('byok-set-key'), 'sk-abc'); + await user.type(screen.getByTestId('byok-set-model'), 'm'); + await user.click(screen.getByTestId('byok-save')); + const stored = JSON.parse(localStorage.getItem(BYOK_STORAGE_KEY)!); + expect(stored).toMatchObject({ base: 'https://x/v1', key: 'sk-abc', model: 'm' }); + expect(screen.getByTestId('byok-clear')).toBeInTheDocument(); + }); + + it('已配置时预填字段 + 清除 → 移除 byok_v1', async () => { + localStorage.setItem(BYOK_STORAGE_KEY, JSON.stringify({ base: 'https://y/v1', key: 'k', model: 'mm' })); + const user = userEvent.setup(); + render(); + expect(screen.getByTestId('byok-set-base')).toHaveValue('https://y/v1'); // 预填现有配置 + await user.click(screen.getByTestId('byok-clear')); + expect(localStorage.getItem(BYOK_STORAGE_KEY)).toBeNull(); + expect(screen.queryByTestId('byok-clear')).not.toBeInTheDocument(); + }); + + it('字段不全 → 不写入', async () => { + const user = userEvent.setup(); + render(); + await user.type(screen.getByTestId('byok-set-base'), 'https://x/v1'); // 缺 key/model + await user.click(screen.getByTestId('byok-save')); + expect(localStorage.getItem(BYOK_STORAGE_KEY)).toBeNull(); + }); +}); diff --git a/src/components/ByokSettingsSection.tsx b/src/components/ByokSettingsSection.tsx new file mode 100644 index 0000000..23450ac --- /dev/null +++ b/src/components/ByokSettingsSection.tsx @@ -0,0 +1,99 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Wand2, Trash2, AlertTriangle } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { toast } from 'sonner'; +import { readByokConfig, writeByokConfig, clearByokConfig } from '@/lib/nlp-edit/provider'; + +/** + * 设置页的 BYOK 配置区:在 SettingsPanel 里也能填/改/清 byok_v1(不止对话框未配置态)。 + * 读写都走 provider 的 read/write/clearByokConfig(默认 localStorage)。key 明文存本机(UI 标风险)。 + */ +export function ByokSettingsSection() { + const { t } = useTranslation(); + const initial = readByokConfig(); + const cfg = initial.ok ? initial.config : null; + const [base, setBase] = useState(cfg?.base ?? ''); + const [apiKey, setApiKey] = useState(cfg?.key ?? ''); + const [model, setModel] = useState(cfg?.model ?? ''); + const [provider, setProvider] = useState(cfg?.provider ?? ''); + const [configured, setConfigured] = useState(initial.ok); + + const save = () => { + const b = base.trim(); + const k = apiKey.trim(); + const m = model.trim(); + if (!b || !k || !m) { + toast.error(t('nlp.cfgIncomplete')); + return; + } + writeByokConfig({ provider: provider.trim() || undefined, base: b, key: k, model: m }); + setConfigured(true); + toast.success(t('nlp.cfgSaved')); + }; + + const clear = () => { + clearByokConfig(); + setBase(''); + setApiKey(''); + setModel(''); + setProvider(''); + setConfigured(false); + toast.success(t('nlp.cleared')); + }; + + const field = ( + label: string, + value: string, + onChange: (v: string) => void, + testid: string, + opts: { type?: string; placeholder?: string } = {}, + ) => ( +
+ + onChange(e.target.value)} + placeholder={opts.placeholder} + className="bg-black/30 border-white/20" + /> +
+ ); + + return ( +
+

+ + {t('nlp.settingsTitle')} +

+

+ {t('nlp.settingsDesc')} · {configured ? t('nlp.statusOk') : t('nlp.statusNone')} +

+ +
+
+ + {t('nlp.plaintextWarn')} +
+ {field(t('nlp.cfgBase'), base, setBase, 'byok-set-base', { placeholder: 'https://.../v1' })} + {field(t('nlp.cfgKey'), apiKey, setApiKey, 'byok-set-key', { type: 'password', placeholder: 'sk-… / tp-…' })} + {field(t('nlp.cfgModel'), model, setModel, 'byok-set-model', { placeholder: 'model' })} + {field(t('nlp.cfgProvider'), provider, setProvider, 'byok-set-provider', { placeholder: '(optional)' })} +
+ + {configured && ( + + )} +
+
+
+ ); +} diff --git a/src/components/NlpEditDialog.test.tsx b/src/components/NlpEditDialog.test.tsx new file mode 100644 index 0000000..3ec6d05 --- /dev/null +++ b/src/components/NlpEditDialog.test.tsx @@ -0,0 +1,160 @@ +// @vitest-environment jsdom +import { describe, it, expect, vi, afterEach } from 'vitest'; +import '@testing-library/jest-dom/vitest'; +import { render, screen, cleanup } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +// i18n 桩:返回键名;带插值时拼上值,便于断言父任务名等动态内容。 +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (k: string, opts?: Record) => + opts ? `${k}:${Object.values(opts).join(',')}` : k, + i18n: { changeLanguage: () => {} }, + }), +})); +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() } })); + +import { NlpEditDialog } from './NlpEditDialog'; +import type { NlpProvider, RequestOpsResult, ByokConfig } from '@/lib/nlp-edit/provider'; +import type { Task, Zone } from '@/types'; + +// jsdom 缺的几个 DOM API(radix Dialog/ScrollArea/Checkbox 需要),补桩。 +class RO { observe() {} unobserve() {} disconnect() {} } +(globalThis as unknown as { ResizeObserver: typeof RO }).ResizeObserver = RO; +if (!Element.prototype.hasPointerCapture) Element.prototype.hasPointerCapture = () => false; +if (!Element.prototype.releasePointerCapture) Element.prototype.releasePointerCapture = () => {}; +if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = () => {}; + +afterEach(cleanup); + +function zone(id: string): Zone { + return { id, name: id, color: '#fff', order: 0, createdAt: 0 }; +} +function task(id: string, over: Partial = {}): Task { + return { + id, zoneId: 'z1', parentId: null, isCollapsed: false, title: id, description: '', + completed: false, priority: 'medium', urgency: 'low', deadline: null, deadlineType: 'none', + order: 0, createdAt: 0, expanded: false, totalWorkTime: 0, ...over, + }; +} +function makeProvider(result: RequestOpsResult, configured = true): NlpProvider { + return { + readConfig: () => + configured + ? { ok: true, config: { base: 'https://x/v1', key: 'k', model: 'm' } } + : { ok: false, code: 'NOT_CONFIGURED', message: 'x' }, + requestOps: async () => result, + }; +} + +describe('NlpEditDialog', () => { + it('生成 → 预览显示父任务名(TP8 防错挂)→ Apply 回调 actions', async () => { + const user = userEvent.setup(); + const onApply = vi.fn(); + const provider = makeProvider({ + kind: 'ops', + rawArguments: '', + ops: [ + { op: 'add_task', zoneId: 'z1', title: '上线', tempId: 't1' }, + { op: 'add_task', zoneId: 'z1', title: '部署', parentId: 't1' }, + ], + }); + render( provider} />); + + await user.click(screen.getByTestId('nlp-trigger')); + await user.type(screen.getByTestId('nlp-input'), '加上线,下面有部署'); + await user.click(screen.getByTestId('nlp-generate')); + + const added = await screen.findAllByTestId('nlp-added'); + const text = added.map((a) => a.textContent).join('|'); + expect(text).toContain('部署'); + expect(text).toContain('新建:上线'); // TP8:看得出挂到刚新建的「上线」下,而非静默错挂 + + await user.click(screen.getByTestId('nlp-apply')); + expect(onApply).toHaveBeenCalledTimes(1); + expect(onApply.mock.calls[0][0]).toHaveLength(2); + }); + + it('含删除 → Apply 先禁用,勾选确认后才可应用', async () => { + const user = userEvent.setup(); + const onApply = vi.fn(); + const provider = makeProvider({ kind: 'ops', rawArguments: '', ops: [{ op: 'delete_task', id: 'a' }] }); + render( + provider} />, + ); + + await user.click(screen.getByTestId('nlp-trigger')); + await user.type(screen.getByTestId('nlp-input'), '删除旧任务'); + await user.click(screen.getByTestId('nlp-generate')); + + const apply = await screen.findByTestId('nlp-apply'); + expect(apply).toBeDisabled(); // 删除未确认 + await user.click(screen.getByTestId('nlp-delete-confirm')); + expect(apply).toBeEnabled(); + await user.click(apply); + expect(onApply).toHaveBeenCalledTimes(1); + }); + + it('未配置 → 显示配置表单;填写保存 → 调 saveConfig 并进入输入态', async () => { + const user = userEvent.setup(); + let configured = false; + const saveConfig = vi.fn<(c: ByokConfig) => void>(() => { + configured = true; + }); + const provider: NlpProvider = { + readConfig: () => + configured + ? { ok: true, config: { base: 'https://x/v1', key: 'k', model: 'm' } } + : { ok: false, code: 'NOT_CONFIGURED', message: 'x' }, + requestOps: async () => ({ kind: 'ops', ops: [], rawArguments: '' }), + }; + render( + provider} saveConfig={saveConfig} />, + ); + + await user.click(screen.getByTestId('nlp-trigger')); + // 未配置 → 配置表单出现(不再是只读提示),普通用户可在应用内填,不必开 DevTools + expect(await screen.findByTestId('nlp-config')).toBeInTheDocument(); + await user.type(screen.getByTestId('cfg-base'), 'https://x/v1'); + await user.type(screen.getByTestId('cfg-key'), 'sk-abc'); + await user.type(screen.getByTestId('cfg-model'), 'm'); + await user.click(screen.getByTestId('cfg-save')); + + expect(saveConfig).toHaveBeenCalledTimes(1); + expect(saveConfig.mock.calls[0][0]).toMatchObject({ base: 'https://x/v1', key: 'sk-abc', model: 'm' }); + // 保存后配置变 ok → 自动进入输入态(表单消失、textarea 出现) + expect(await screen.findByTestId('nlp-input')).toBeInTheDocument(); + expect(screen.queryByTestId('nlp-config')).not.toBeInTheDocument(); + }); + + it('配置表单字段不全 → 提示且不调 saveConfig', async () => { + const user = userEvent.setup(); + const saveConfig = vi.fn(); + const provider: NlpProvider = { + readConfig: () => ({ ok: false, code: 'NOT_CONFIGURED', message: 'x' }), + requestOps: async () => ({ kind: 'ops', ops: [], rawArguments: '' }), + }; + render( + provider} saveConfig={saveConfig} />, + ); + await user.click(screen.getByTestId('nlp-trigger')); + await screen.findByTestId('nlp-config'); + await user.type(screen.getByTestId('cfg-base'), 'https://x/v1'); // 缺 key/model + await user.click(screen.getByTestId('cfg-save')); + expect(saveConfig).not.toHaveBeenCalled(); + expect(screen.getByTestId('nlp-error')).toHaveTextContent('nlp.cfgIncomplete'); + }); + + it('provider 报错 → 显示错误信息(不进预览态)', async () => { + const user = userEvent.setup(); + const provider = makeProvider({ kind: 'error', error: { code: 'HTTP_ERROR', message: '网关返回 401', status: 401 } }); + render( provider} />); + + await user.click(screen.getByTestId('nlp-trigger')); + await user.type(screen.getByTestId('nlp-input'), 'x'); + await user.click(screen.getByTestId('nlp-generate')); + + expect(await screen.findByTestId('nlp-error')).toHaveTextContent('401'); + expect(screen.queryByTestId('nlp-apply')).not.toBeInTheDocument(); + }); +}); diff --git a/src/components/NlpEditDialog.tsx b/src/components/NlpEditDialog.tsx new file mode 100644 index 0000000..1c9d875 --- /dev/null +++ b/src/components/NlpEditDialog.tsx @@ -0,0 +1,361 @@ +import { useCallback, useMemo, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Wand2, Loader2, AlertTriangle, Plus, Pencil, Trash2, SkipForward, CornerDownRight, Settings } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Textarea } from '@/components/ui/textarea'; +import { Checkbox } from '@/components/ui/checkbox'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { toast } from 'sonner'; +import type { Task, Zone } from '@/types'; +import { planOps, type PlanResult, type Snapshot, type PlannedAction } from '@/lib/nlp-edit/apply-core'; +import { writeByokConfig, type NlpProvider, type ProviderError, type ByokConfig } from '@/lib/nlp-edit/provider'; +import { createAppNlpProvider } from '@/lib/nlp-edit/runtime'; + +type PlanOk = Extract; + +interface NlpEditDialogProps { + zones: Zone[]; + tasks: Task[]; + onApply: (actions: PlannedAction[]) => unknown; + /** 注入点:测试喂 mock provider;默认接真实浏览器运行时(dev 经 vite 代理)。 */ + providerFactory?: () => NlpProvider; + /** 注入点:保存 BYOK 配置;默认写入 localStorage['byok_v1']。 */ + saveConfig?: (cfg: ByokConfig) => void; +} + +function formatProviderError(e: ProviderError, t: (k: string, o?: Record) => string): string { + if (e.code === 'NOT_CONFIGURED' || e.code === 'BAD_CONFIG') return t('nlp.notConfigured'); + return `${t('nlp.errorTitle')}:${e.message}`; +} + +function changeSummary(changes: Partial): string { + return Object.entries(changes) + .filter(([k]) => k !== 'parentId') // parentId(重挂父)单独用解析后的父任务名展示 + .map(([k, v]) => { + if (v !== null && typeof v === 'object') return k; + return `${k} = ${String(v)}`; + }) + .join(','); +} + +export function NlpEditDialog({ + zones, + tasks, + onApply, + providerFactory = createAppNlpProvider, + saveConfig = writeByokConfig, +}: NlpEditDialogProps) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const [step, setStep] = useState<'input' | 'preview'>('input'); + const [input, setInput] = useState(''); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [plan, setPlan] = useState(null); + const [deleteConfirmed, setDeleteConfirmed] = useState(false); + + // BYOK 配置态 + const [configMode, setConfigMode] = useState(false); + // 仅用于「保存配置后强制重渲染」→ 重读 localStorage(首配时表单是靠 !config.ok 显示的, + // configMode 本就是 false,单 setConfigMode(false) 不会触发重渲染,故需显式 tick)。 + const [, bumpCfg] = useState(0); + const [cfgBase, setCfgBase] = useState(''); + const [cfgKey, setCfgKey] = useState(''); + const [cfgModel, setCfgModel] = useState(''); + const [cfgProvider, setCfgProvider] = useState(''); + + const titleById = useMemo(() => new Map(tasks.map((x) => [x.id, x.title] as [string, string])), [tasks]); + + // 按需读 BYOK 配置(localStorage 读很轻);保存后 setConfigMode 触发重渲染即自动刷新。缺失/损坏则进配置态。 + const config = open ? providerFactory().readConfig() : null; + const showConfig = configMode || (config != null && !config.ok); + + const reset = useCallback(() => { + setStep('input'); + setInput(''); + setLoading(false); + setError(null); + setPlan(null); + setDeleteConfirmed(false); + setConfigMode(false); + }, []); + + const handleOpenChange = useCallback( + (o: boolean) => { + setOpen(o); + if (!o) reset(); + }, + [reset], + ); + + const openConfig = useCallback(() => { + const c = providerFactory().readConfig(); + if (c.ok) { + setCfgBase(c.config.base); + setCfgKey(c.config.key); + setCfgModel(c.config.model); + setCfgProvider(c.config.provider ?? ''); + } + setError(null); + setConfigMode(true); + }, [providerFactory]); + + const handleSaveConfig = useCallback(() => { + const base = cfgBase.trim(); + const key = cfgKey.trim(); + const model = cfgModel.trim(); + if (!base || !key || !model) { + setError(t('nlp.cfgIncomplete')); + return; + } + saveConfig({ provider: cfgProvider.trim() || undefined, base, key, model }); + setConfigMode(false); + bumpCfg((n) => n + 1); // 强制重渲染 → 重读配置(首配时 configMode 已是 false,否则不会刷新) + setError(null); + toast.success(t('nlp.cfgSaved')); + }, [cfgBase, cfgKey, cfgModel, cfgProvider, saveConfig, t]); + + const handleGenerate = useCallback(async () => { + const text = input.trim(); + if (!text) { + setError(t('nlp.emptyInput')); + return; + } + setLoading(true); + setError(null); + const snapshot: Snapshot = { zones, tasks }; + const r = await providerFactory().requestOps(text, snapshot); + setLoading(false); + if (r.kind === 'error') { + setError(formatProviderError(r.error, t)); + return; + } + const result = planOps(snapshot, r.ops, { invalidPolicy: 'skip' }); + if (result.kind === 'noop') { + setError(t('nlp.noChanges')); + return; + } + if (result.kind === 'error') { + setError(`${t('nlp.errorTitle')}:${result.error.code}`); + return; + } + setPlan(result); + setDeleteConfirmed(false); + setStep('preview'); + }, [input, zones, tasks, providerFactory, t]); + + const handleApply = useCallback(() => { + if (!plan) return; + onApply(plan.actions); + toast.success(t('nlp.applied', { count: plan.actions.length })); + handleOpenChange(false); + }, [plan, onApply, t, handleOpenChange]); + + const applyDisabled = !plan || plan.actions.length === 0 || (plan.hasDeletes && !deleteConfirmed); + + return ( + + + + + + + + {t('nlp.title')} + {config?.ok && !showConfig && ( + + )} + + + {showConfig ? t('nlp.configTitle') : step === 'input' ? t('nlp.inputLabel') : t('nlp.previewTitle')} + + + + {/* BYOK 配置表单(未配置 / 点改配置时) */} + {showConfig && ( +
+
+ + {t('nlp.plaintextWarn')} +
+ + + + + {error && ( +

+ {error} +

+ )} +
+ {config?.ok && ( + + )} + +
+
+ )} + + {!showConfig && step === 'input' && ( +
+