prompt optimizer desktop plugin
This commit is contained in:
commit
3d3c12f98f
1 file changed
+373
@@ -0,0 +1,373 @@
|
|||||||
|
/**
|
||||||
|
* 模板:带「输入框按钮」的桌面插件(最小可用)。
|
||||||
|
*
|
||||||
|
* 覆盖三件事,改两个常量即可复用:
|
||||||
|
* 1. 聊天输入框右侧的按钮(composer.actions)—— 读草稿 → 调后端 → 写回
|
||||||
|
* 2. 一个面板页(routes)+ 侧栏入口(sidebar.nav)
|
||||||
|
* 3. 四个负向分支(空草稿 / 后端失败 / 写回失败 / 路由未挂载)
|
||||||
|
*
|
||||||
|
* 落点:<hermes家目录>/desktop-plugins/<插件id>/plugin.js
|
||||||
|
* 目录名必须等于下面的 ID。保存即热加载,无需重启。
|
||||||
|
*
|
||||||
|
* 三条硬约束(违反必挂):
|
||||||
|
* · 只能 import @hermes/plugin-sdk / react / react/jsx-runtime
|
||||||
|
* · 不能写 JSX,必须 jsx()/jsxs()
|
||||||
|
* · 只能用应用源码里已出现过的 Tailwind 类(改动后跑 po_css_check 核对)
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Button, Codicon, SegmentedControl, StatusDot, Textarea, host } from '@hermes/plugin-sdk'
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { jsx, jsxs } from 'react/jsx-runtime'
|
||||||
|
|
||||||
|
// ── 改这两处 ────────────────────────────────────────────────────────────────
|
||||||
|
const ID = 'my-optimizer' // 必须与目录名、后端 manifest.json 的 name 一致
|
||||||
|
const PATH = '/my-optimizer' // 自定义路由,避开内置路由(如 /kanban)
|
||||||
|
// ───────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// 模型生成类调用必须显式放大超时:插件 REST 默认只有 30s(hardening.ts)。
|
||||||
|
// 取值应略大于后端自己的超时,让「超时」由后端先给出友好文案。
|
||||||
|
const OPTIMIZE_TIMEOUT_MS = 220000
|
||||||
|
|
||||||
|
// 面板与按钮共享「上次选的模式」。模块级普通变量,不参与渲染。
|
||||||
|
let sharedMode = 'user'
|
||||||
|
|
||||||
|
const FALLBACK_MODES = [
|
||||||
|
{ id: 'user', label: '用户提示词', hint: '', needs_requirements: false },
|
||||||
|
{ id: 'system', label: '系统提示词', hint: '', needs_requirements: false }
|
||||||
|
]
|
||||||
|
|
||||||
|
// ─── 健康探测:区分「安装未生效」与「服务没起来」──────────────────────────
|
||||||
|
// ⚠️ 不能靠状态码猜「路由没挂载」:未挂载时 POST 落到 SPA 的 GET 兜底 → 405(不是 404),
|
||||||
|
// GET 则返回 200 + HTML。判据只能是「响应是不是我们约定的 JSON」。
|
||||||
|
function classifyHealth(payload) {
|
||||||
|
if (payload && typeof payload === 'object' && typeof payload.ok === 'boolean') {
|
||||||
|
return payload.ok
|
||||||
|
? { ok: true, needsRestart: false, error: null }
|
||||||
|
: { ok: false, needsRestart: false, error: payload.error || null }
|
||||||
|
}
|
||||||
|
return { ok: false, needsRestart: true, error: null }
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetchHealth(ctx, force) {
|
||||||
|
return ctx
|
||||||
|
.rest(force ? '/health?force=true' : '/health')
|
||||||
|
.then(d => classifyHealth(d))
|
||||||
|
.catch(() => classifyHealth(null))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 桌面端把「重启后端」暴露给了渲染进程(底层只做拆除,靠桌面端重连拉起)。
|
||||||
|
// 给用户的最可靠指引仍是「完全退出桌面端再打开」。
|
||||||
|
async function recycleBackend() {
|
||||||
|
try {
|
||||||
|
const b = window.hermesDesktop
|
||||||
|
if (!b || typeof b.recycleBackend !== 'function') return false
|
||||||
|
await b.recycleBackend()
|
||||||
|
return true
|
||||||
|
} catch (_) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyText(text) {
|
||||||
|
if (!text) return false
|
||||||
|
try {
|
||||||
|
if (window.hermesDesktop && window.hermesDesktop.writeClipboard) {
|
||||||
|
await window.hermesDesktop.writeClipboard(text)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
} catch (_) { /* 落回下面的方式 */ }
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text)
|
||||||
|
return true
|
||||||
|
} catch (_) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── ★ 输入框里的按钮 ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function ComposerButton({ ctx }) {
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
const [flash, setFlash] = useState(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!flash) return undefined
|
||||||
|
const id = setTimeout(() => setFlash(null), 2400)
|
||||||
|
return () => clearTimeout(id)
|
||||||
|
}, [flash])
|
||||||
|
|
||||||
|
const composer = host.composer
|
||||||
|
|
||||||
|
const run = async () => {
|
||||||
|
if (busy) return
|
||||||
|
// 能力探测:老版本 SDK 可能没有 composer 通道
|
||||||
|
if (!composer || typeof composer.getDraft !== 'function' || typeof composer.setDraft !== 'function') {
|
||||||
|
setFlash('此版本不支持')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setBusy(true)
|
||||||
|
try {
|
||||||
|
// null = 用户最后点进去的那个输入框(也支持会话 id / 'new')
|
||||||
|
const draft = await composer.getDraft(null)
|
||||||
|
const text = typeof draft === 'string' ? draft.trim() : ''
|
||||||
|
if (!text) {
|
||||||
|
setFlash('输入框是空的') // ① 空草稿直接返回,别白花一次调用
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await ctx.rest('/optimize', {
|
||||||
|
method: 'POST',
|
||||||
|
body: { mode: sharedMode, prompt: text },
|
||||||
|
timeoutMs: OPTIMIZE_TIMEOUT_MS
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res || !res.ok) {
|
||||||
|
setFlash((res && res.error) || '优化失败') // ② 失败绝不覆盖用户草稿
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const applied = await composer.setDraft(null, res.text || '')
|
||||||
|
if (applied === false) {
|
||||||
|
setFlash('写回失败') // ③ 明确提示,别假装成功
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setFlash('已替换')
|
||||||
|
} catch (_) {
|
||||||
|
setFlash('请先重启服务') // ④ 未挂载(405)/超时/断连都落这里
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const label = flash || '优化'
|
||||||
|
|
||||||
|
return jsxs('button', {
|
||||||
|
type: 'button',
|
||||||
|
title: flash ? label : '改写输入框里的内容',
|
||||||
|
disabled: busy,
|
||||||
|
onClick: run,
|
||||||
|
// ⚠️ 外层是 flex justify-end,贡献元素不要自带 ml-auto ——
|
||||||
|
// 在 stacked 布局下会把按钮从发送簇拽到行首。
|
||||||
|
className:
|
||||||
|
'inline-flex shrink-0 cursor-pointer items-center gap-1 whitespace-nowrap rounded-md px-2 py-1 text-xs text-(--ui-text-secondary) transition-colors hover:bg-(--ui-bg-tertiary) hover:text-(--ui-text-primary) disabled:opacity-50',
|
||||||
|
children: [
|
||||||
|
jsx(Codicon, { name: 'sparkle', size: 13, spinning: busy }),
|
||||||
|
jsx('span', { children: label })
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 面板页 ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function PanelPage({ ctx }) {
|
||||||
|
const [modes, setModes] = useState(FALLBACK_MODES)
|
||||||
|
const [mode, setMode] = useState(sharedMode)
|
||||||
|
const [prompt, setPrompt] = useState('')
|
||||||
|
const [result, setResult] = useState('')
|
||||||
|
const [error, setError] = useState(null)
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
const [health, setHealth] = useState(null)
|
||||||
|
const [justRestarted, setJustRestarted] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true
|
||||||
|
ctx.rest('/modes')
|
||||||
|
.then(d => { if (alive && Array.isArray(d && d.modes) && d.modes.length) setModes(d.modes) })
|
||||||
|
.catch(() => { /* 用内置兜底 */ })
|
||||||
|
return () => { alive = false }
|
||||||
|
}, [ctx])
|
||||||
|
|
||||||
|
const refresh = force => fetchHealth(ctx, force).then(h => {
|
||||||
|
if (h.ok) setJustRestarted(false)
|
||||||
|
setHealth(h)
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
refresh(false)
|
||||||
|
// 轮询间隔必须 < 后端健康缓存 TTL,否则缓存永不命中、每轮真探测一次
|
||||||
|
const id = setInterval(() => refresh(false), 60000)
|
||||||
|
return () => clearInterval(id)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [ctx])
|
||||||
|
|
||||||
|
const run = () => {
|
||||||
|
if (busy || !prompt.trim()) return
|
||||||
|
setBusy(true); setError(null); setResult('')
|
||||||
|
ctx.rest('/optimize', { method: 'POST', body: { mode, prompt }, timeoutMs: OPTIMIZE_TIMEOUT_MS })
|
||||||
|
.then(d => {
|
||||||
|
if (d && d.ok) setResult(d.text || '')
|
||||||
|
else setError((d && d.error) || '优化失败,请稍后重试')
|
||||||
|
})
|
||||||
|
.catch(() => { setError('服务尚未加载,请重启'); setHealth({ ok: false, needsRestart: true }) })
|
||||||
|
.then(() => setBusy(false))
|
||||||
|
}
|
||||||
|
|
||||||
|
const fillComposer = async () => {
|
||||||
|
if (!result.trim()) return
|
||||||
|
const c = host.composer
|
||||||
|
if (c && typeof c.setDraft === 'function') {
|
||||||
|
const applied = await c.setDraft(null, result)
|
||||||
|
if (applied !== false) return
|
||||||
|
}
|
||||||
|
copyText(result) // 没有可见输入框时退回剪贴板
|
||||||
|
}
|
||||||
|
|
||||||
|
const needsRestart = Boolean(health && !health.ok && health.needsRestart)
|
||||||
|
|
||||||
|
return jsxs('div', {
|
||||||
|
className: 'flex h-full min-h-0 flex-col',
|
||||||
|
children: [
|
||||||
|
jsxs('div', {
|
||||||
|
className: 'shrink-0 flex items-center justify-between gap-3 border-b border-(--ui-stroke-tertiary) px-4 py-3',
|
||||||
|
children: [
|
||||||
|
jsx('div', { className: 'text-sm font-semibold text-(--ui-text-primary)', children: '提示词优化' }),
|
||||||
|
jsxs('div', {
|
||||||
|
className: 'flex shrink-0 items-center gap-2',
|
||||||
|
children: [
|
||||||
|
jsx(StatusDot, { tone: busy ? 'warn' : health === null ? 'muted' : health.ok ? 'good' : 'bad' }),
|
||||||
|
jsx('span', {
|
||||||
|
className: 'text-xs text-(--ui-text-tertiary) whitespace-nowrap',
|
||||||
|
children: busy ? '处理中…' : health === null ? '检测中…' : health.ok ? '服务就绪' : '服务未就绪'
|
||||||
|
})
|
||||||
|
]
|
||||||
|
})
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
jsx('div', {
|
||||||
|
className: 'min-h-0 flex-1 overflow-auto p-4',
|
||||||
|
children: jsxs('div', {
|
||||||
|
className: 'flex max-w-2xl flex-col gap-4',
|
||||||
|
children: [
|
||||||
|
jsx(SegmentedControl, {
|
||||||
|
options: modes.map(m => ({ id: m.id, label: m.label })),
|
||||||
|
value: mode,
|
||||||
|
disabled: busy,
|
||||||
|
onChange: id => { setMode(id); sharedMode = id; setError(null) }
|
||||||
|
}),
|
||||||
|
jsx(Textarea, {
|
||||||
|
className: 'h-32 w-full resize-none text-sm leading-relaxed',
|
||||||
|
placeholder: '输入要处理的内容…',
|
||||||
|
value: prompt, disabled: busy,
|
||||||
|
onChange: e => setPrompt(e.target.value)
|
||||||
|
}),
|
||||||
|
jsxs('div', {
|
||||||
|
className: 'flex flex-wrap items-center gap-3',
|
||||||
|
children: [
|
||||||
|
jsx(Button, { variant: 'default', size: 'sm', disabled: busy || !prompt.trim(), onClick: run,
|
||||||
|
children: busy ? '处理中…' : '开始' }),
|
||||||
|
jsx(Button, { variant: 'ghost', size: 'sm',
|
||||||
|
onClick: () => { setPrompt(''); setResult(''); setError(null) },
|
||||||
|
children: '清空' })
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
// 未挂载 → 给可操作按钮;服务没起来 → 只给重测
|
||||||
|
needsRestart
|
||||||
|
? jsxs('div', {
|
||||||
|
className: 'flex flex-wrap items-center justify-between gap-3 rounded-md border border-(--ui-stroke-secondary) bg-(--ui-bg-tertiary) px-3 py-2',
|
||||||
|
children: [
|
||||||
|
jsx('span', {
|
||||||
|
className: 'text-sm text-(--ui-text-secondary)',
|
||||||
|
children: justRestarted ? '正在重启服务…' : '安装尚未生效,需要重启服务'
|
||||||
|
}),
|
||||||
|
jsx(Button, {
|
||||||
|
variant: 'default', size: 'xs',
|
||||||
|
onClick: async () => { if (await recycleBackend()) { setJustRestarted(true); setTimeout(() => refresh(true), 7000) } },
|
||||||
|
children: '重启服务'
|
||||||
|
})
|
||||||
|
]
|
||||||
|
})
|
||||||
|
: null,
|
||||||
|
error
|
||||||
|
? jsx('div', {
|
||||||
|
className: 'rounded-md border border-(--ui-stroke-secondary) bg-(--ui-bg-tertiary) px-3 py-2 text-sm text-(--ui-text-secondary)',
|
||||||
|
children: error
|
||||||
|
})
|
||||||
|
: null,
|
||||||
|
result
|
||||||
|
? jsxs('div', {
|
||||||
|
className: 'flex flex-col gap-2 pb-2',
|
||||||
|
children: [
|
||||||
|
jsxs('div', {
|
||||||
|
className: 'flex flex-wrap items-center justify-between gap-3',
|
||||||
|
children: [
|
||||||
|
jsx('span', { className: 'text-xs font-medium text-(--ui-text-secondary)', children: '结果' }),
|
||||||
|
jsxs('div', {
|
||||||
|
className: 'flex items-center gap-2',
|
||||||
|
children: [
|
||||||
|
jsx(Button, { variant: 'ghost', size: 'xs', onClick: () => copyText(result), children: '复制' }),
|
||||||
|
jsx(Button, { variant: 'ghost', size: 'xs', onClick: fillComposer, children: '填入输入框' })
|
||||||
|
]
|
||||||
|
})
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
jsx('div', {
|
||||||
|
className: 'whitespace-pre-wrap break-words rounded-md border border-(--ui-stroke-tertiary) bg-(--ui-bg-secondary) px-3 py-3 text-sm leading-relaxed text-(--ui-text-primary)',
|
||||||
|
children: result
|
||||||
|
})
|
||||||
|
]
|
||||||
|
})
|
||||||
|
: null
|
||||||
|
].filter(Boolean)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 状态栏芯片 ────────────────────────────────────────────────────────────
|
||||||
|
// ⚠️ 必须给 toggleLabel,否则它不会进右键菜单,用户<b>永远无法隐藏</b>它。
|
||||||
|
|
||||||
|
function HealthChip({ ctx }) {
|
||||||
|
const [health, setHealth] = useState(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true
|
||||||
|
const load = () => fetchHealth(ctx, false).then(h => { if (alive) setHealth(h) })
|
||||||
|
load()
|
||||||
|
const id = setInterval(load, 60000)
|
||||||
|
return () => { alive = false; clearInterval(id) }
|
||||||
|
}, [ctx])
|
||||||
|
|
||||||
|
const tone = health === null ? 'muted' : health.ok ? 'good' : 'bad'
|
||||||
|
|
||||||
|
return jsx('button', {
|
||||||
|
type: 'button',
|
||||||
|
title: health === null ? '检测中' : health.ok ? '服务就绪' : '服务未就绪',
|
||||||
|
className: 'inline-flex cursor-pointer items-center gap-1.5 rounded-md px-2 py-1 text-xs text-(--ui-text-secondary) transition-colors hover:bg-(--ui-bg-tertiary)',
|
||||||
|
onClick: () => host.navigate(PATH),
|
||||||
|
children: jsxs('span', {
|
||||||
|
className: 'inline-flex items-center gap-1.5',
|
||||||
|
children: [jsx(StatusDot, { tone }), jsx('span', { children: '提示词优化' })]
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 注册 ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const chipContribution = {
|
||||||
|
id: 'chip',
|
||||||
|
area: 'statusBar.right',
|
||||||
|
order: 131,
|
||||||
|
toggleLabel: '提示词优化状态',
|
||||||
|
render: () => jsx(HealthChip, { ctx: null })
|
||||||
|
}
|
||||||
|
|
||||||
|
export default {
|
||||||
|
id: ID,
|
||||||
|
name: '提示词优化',
|
||||||
|
register(ctx) {
|
||||||
|
ctx.registerMany([
|
||||||
|
{ id: 'page', area: 'routes', data: { path: PATH }, render: () => jsx(PanelPage, { ctx }) },
|
||||||
|
{ id: 'nav', area: 'sidebar.nav', order: 56,
|
||||||
|
data: { codicon: 'sparkle', label: '提示词优化', path: PATH } },
|
||||||
|
// ★ 输入框按钮。注意 Slot 不给 prop,ctx 只能靠闭包传。
|
||||||
|
{ id: 'composer', area: 'composer.actions', order: 20,
|
||||||
|
render: () => jsx(ComposerButton, { ctx }) },
|
||||||
|
{ ...chipContribution, render: () => jsx(HealthChip, { ctx }) },
|
||||||
|
{ id: 'open', area: 'palette',
|
||||||
|
data: { id: `${ID}.open`, label: '提示词优化: 打开',
|
||||||
|
keywords: ['prompt', '提示词', '优化'],
|
||||||
|
run: () => host.navigate(PATH) } }
|
||||||
|
])
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user