dsh-better-chat/client.js

408 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* dsh-better-chat 客户端:让审批卡片的回车 / Esc 不再挑焦点。
*
* 背景(DSH 0.2.2-rc.1 的 @deepseek-ai/dsh-client-ui-approval):
* 官方审批卡自带键盘处理 —— Enter 批准(单次)、Esc 拒绝 —— 但它的
* keydown 挂在卡片根节点上,且要求焦点先落在卡片内。审批弹出时焦点
* 往往还在对话区/页面主体上,按回车毫无反应,必须先点一下卡片。
*
* 本模块补两件事,不改官方任何逻辑:
* 1. 审批卡出现时,若用户没有正在别处输入,把焦点送进卡片的详情区
* ([data-approval-scroll],本身 tabIndex=0),官方处理立即生效。
* 2. 焦点不在卡片内时兜底路由:在 document 捕获阶段监听 keydown,
* 满足全部防误触条件时,点击卡片操作行里的按钮 —— 顺序由官方渲染
* 固定为 [拒绝, 允许(单次), 始终允许?],回车点「允许(单次)」,
* 永远不会误触「始终允许」;Esc 点「拒绝」。
*
* 防误触(与官方卡片内部规则对齐):
* - 正在任何输入控件(input/textarea/select/contenteditable)里打字 → 不管
* - 焦点已在卡片内 → 官方处理,绝不重复作答
* - 带 Ctrl/Meta/Alt/Shift、长按连发、输入法组词中 → 不管
* - 回车落在某个按钮/链接上 → 保留那个按钮自己的回车行为
* - 卡片已作答(aria-busy=true)或按钮禁用 → 不管
*/
const CARD_SELECTOR = '[data-approval-key]'
const SCROLL_SELECTOR = '[data-approval-scroll]'
const EDITABLE_SELECTOR = 'input, textarea, select, [contenteditable="true"], [contenteditable=""]'
/** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */
export function actionButtons(card) {
return [...card.querySelectorAll('button')].filter((b) => !b.closest(SCROLL_SELECTOR))
}
/** 找当前可作答的审批卡(DOM 顺序第一张未作答、按钮齐全的卡)。 */
export function findPendingCard(doc) {
for (const card of doc.querySelectorAll(CARD_SELECTOR)) {
if (card.getAttribute('aria-busy') === 'true') continue
const buttons = actionButtons(card)
if (buttons.length >= 2 && !buttons[0].disabled && !buttons[1].disabled) return card
}
return null
}
/**
* 纯判定:这次 keydown 是否应该路由到审批卡。
* @returns {'allow'|'reject'|null}
*/
export function decideKeyAction(input) {
const { key, ctrlKey, metaKey, altKey, shiftKey, repeat, isComposing, keyCode, defaultPrevented, target, activeElement, card } = input
if (!card) return null
if (defaultPrevented) return null
if (key !== 'Enter' && key !== 'Escape') return null
if (ctrlKey || metaKey || altKey || shiftKey) return null
if (repeat || isComposing || keyCode === 229) return null
if (activeElement && card.contains(activeElement)) return null // 焦点在卡内:官方处理
if (target && typeof target.closest === 'function') {
if (target.closest(EDITABLE_SELECTOR) !== null) return null // 正在别处输入
if (key === 'Enter' && target.closest('button, a[href], [role="button"]') !== null) return null
}
return key === 'Enter' ? 'allow' : 'reject'
}
/** 纯判定:审批卡出现时是否应该把焦点送进详情区。 */
export function shouldAutoFocus(activeElement, card) {
if (!activeElement) return true
if (activeElement === card.ownerDocument?.body) return true
if (card.contains(activeElement)) return false // 已经在卡里
if (typeof activeElement.closest === 'function' && activeElement.closest(EDITABLE_SELECTOR) !== null) return false // 正在别处输入
return true
}
function install(doc) {
const focusedCards = new WeakSet()
const tryAutoFocus = () => {
const card = findPendingCard(doc)
if (!card || focusedCards.has(card)) return
focusedCards.add(card)
if (!shouldAutoFocus(doc.activeElement, card)) return
const region = card.querySelector(SCROLL_SELECTOR)
if (region && typeof region.focus === 'function') region.focus()
}
const observer = new MutationObserver(tryAutoFocus)
observer.observe(doc.documentElement, { childList: true, subtree: true })
tryAutoFocus()
const onKeyDown = (event) => {
const card = findPendingCard(doc)
const action = decideKeyAction({
key: event.key,
ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey,
repeat: event.repeat, isComposing: event.isComposing, keyCode: event.keyCode,
defaultPrevented: event.defaultPrevented,
target: event.target, activeElement: doc.activeElement, card,
})
if (!action) return
const buttons = actionButtons(card)
const button = action === 'allow' ? buttons[1] : buttons[0]
if (!button || button.disabled) return
event.preventDefault()
event.stopPropagation()
button.click()
}
doc.addEventListener('keydown', onKeyDown, true)
return () => {
observer.disconnect()
doc.removeEventListener('keydown', onKeyDown, true)
}
}
/**
* 功能二:权限 UI —— 去掉「完全权限」选项,不改已有会话权限。
*
* 背景(DSH 0.2.2-rc.1 的权限预设,@deepseek-ai/dsh-client-ui-permission-presets):
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
* 修改)、danger-full-access(完全权限)、auto(自动审查,EXP)。「自动
* 审查」由实验层 @deepseek-ai/dsh-experimental-auto-review 提供:开启该层
* 后才出现在当前会话的选择器里;通用设置不提供 auto,新会话默认值里
* 也选不到它。宿主切换预设的通道是会话对象的 command(`/permission <值>`),
* 带参命令直接生效、不弹风险确认。
*
* 本功能只做一件事:界面移除完全权限。它**不再**在页面加载、刷新或
* 插件重载时遍历已有会话改权限:那会把用户明确选择的只读/工作区权限
* 覆盖成 auto,而且 handled 只在内存里,刷新后会再次执行。默认权限
* 属于宿主的新建会话流程;本插件没有可靠的新建扩展点,因此不拿轮询
* 去补偿,用户仍可在宿主提供的权限选择器里自行选择自动审查。
*/
/** 完全权限的预设机器值。 */
export const FULL_ACCESS_PRESET = 'danger-full-access'
/** 自动审查的预设机器值。 */
export const AUTO_REVIEW_PRESET = 'auto'
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
export const FULL_ACCESS_LABELS = ['完全权限', 'Full access']
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
export function isFullAccessLabel(text) {
if (typeof text !== 'string') return false
const t = text.trim()
return FULL_ACCESS_LABELS.some((label) => t === label || t.startsWith(label))
}
/** 纯判定:这个会话现在是否应该被切到自动审查。 */
export function shouldAutoSwitch(preset, alreadyHandled) {
return preset !== undefined && preset !== null && preset !== AUTO_REVIEW_PRESET && !alreadyHandled
}
/**
* 防御式枚举宿主的 live 会话:优先 keys()+binding(),退回 list()。
* 服务形状对不上时安静返回空数组,绝不抛错。
*/
export function liveSessions(sessions) {
const out = []
if (!sessions || typeof sessions !== 'object') return out
try {
if (typeof sessions.keys === 'function' && typeof sessions.binding === 'function') {
for (const id of sessions.keys()) {
const live = sessions.binding(id)?.session
if (live) out.push({ id, live })
}
return out
}
if (typeof sessions.list === 'function') {
for (const s of sessions.list() ?? []) {
if (s && s.sessionId) out.push({ id: s.sessionId, live: s })
}
}
} catch { /* 服务形状不同:放弃枚举 */ }
return out
}
/** 读会话当前的权限预设值(投影不可用时返回 undefined)。 */
export function currentPreset(live) {
try {
return live?.projections?.faceOf('permissions')?.getSnapshot?.()
} catch {
return undefined
}
}
/**
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
* @returns 摘掉的个数
*/
export function pruneFullAccess(doc) {
let removed = 0
for (const opt of doc.querySelectorAll('option')) {
if (isFullAccessLabel(opt.textContent)) { opt.remove(); removed++ }
}
for (const item of doc.querySelectorAll('[role="listbox"] [role="option"], [role="menu"] [role="menuitem"]')) {
if (isFullAccessLabel(item.textContent)) { item.remove(); removed++ }
}
return removed
}
/**
* 安装权限 UI 策略:只观察 DOM、摘掉「完全权限」选项。
*
* 不接收 `getSessions`,也不启动任何会话轮询:页面加载、刷新和插件重载
* 都不得改变已有会话的权限。新建会话的默认值由宿主自己的新建流程决定。
* @returns 卸载函数
*/
export function installPermissionPolicy(doc, _getSessions, timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }) {
let disposed = false
let scanTimer = 0
const scheduleScan = () => {
if (disposed || scanTimer) return
scanTimer = timers.setTimeout(() => {
scanTimer = 0
if (!disposed) pruneFullAccess(doc)
}, 120)
}
const observer = new MutationObserver(scheduleScan)
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
pruneFullAccess(doc)
return () => {
disposed = true
observer.disconnect()
if (scanTimer) timers.clearTimeout(scanTimer)
}
}
/* ------------------------------------------------------------------ *
* 功能三:插件商店「更新」按钮。
*
* DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有
* 「有新版本」标签、没有按钮,只能手动卸载重装。这里补一个真按钮:
* 数据与动作都走宿主自己的远程服务——pluginMarket 查索引和安装
* 状态,pluginManager.installBundle 按索引给出的精确 spec 覆盖
* 安装——与官方安装流程同一套接口,不模拟点击、不动官方状态。
* 覆盖安装在探针实测中可直接把已装旧版换成新版(changed/applied)。
*
* 服务经子插件声明 inject 取用:主插件保持 inject 为空,审批与
* 权限功能不依赖这些服务;未启用实验性插件索引时子插件不生效,
* 本功能静默关闭。
* ------------------------------------------------------------------ */
export const UPDATE_LABELS = ['有新版本', 'Update available']
/** 索引条目的本地化标题在当前语言下的文本(与发现页行内展示一致)。 */
export function localizedTitle(title, lang) {
if (typeof title === 'string') return title
if (!title || typeof title !== 'object') return ''
const chain = [lang, lang && lang.split('-')[0], 'zh-CN', 'en']
for (const key of chain) {
if (key && typeof title[key] === 'string' && title[key]) return title[key]
}
const values = Object.values(title)
return typeof values[0] === 'string' ? values[0] : ''
}
/** 从各索引的搜索结果里挑出「有新版本」的条目,整理成可执行的更新计划。 */
export function pickUpdates(searchResults, lang) {
const updates = []
for (const result of searchResults ?? []) {
const entries = result?.value?.entries ?? result?.entries ?? []
for (const entry of entries) {
if (entry?.installation?.status !== 'update-available') continue
const versions = entry.versions ?? []
const version = versions.find((v) => v.version === entry.defaultVersion) ?? versions[0]
const spec = version?.install?.spec
if (!entry.name || !version?.version || !spec) continue
updates.push({
name: entry.name,
title: localizedTitle(entry.title, lang) || entry.name,
installedVersion: entry.installation.installedVersion ?? '',
version: version.version,
spec,
registry: version.install.registry,
})
}
}
return updates
}
/** 执行一次更新:按索引 spec 覆盖安装,宿主结果信封原样返回。 */
export async function runUpdate(remote, update, makeRequestId) {
const requestId = makeRequestId ? makeRequestId() : 'better-chat-update-' + Date.now()
return remote.pluginManager.installBundle(update.spec, {
enabled: true,
requestId,
...(update.registry ? { registry: update.registry } : {}),
})
}
/**
* 发现页里某个插件的行:状态标签本身是个按钮,从它向上找第一个
* 同时包含插件标题、且文本总量还像一行的祖先。
*/
export function findUpdateRow(doc, title) {
for (const el of doc.querySelectorAll('button')) {
if (!UPDATE_LABELS.includes(el.textContent?.trim())) continue
let node = el
for (let depth = 0; depth < 6 && node; depth++) {
node = node.parentElement
if (node && node.textContent?.includes(title) && node.textContent.length < 600) return node
}
}
return null
}
/** 更新按钮的点击处理:确认 → 调宿主覆盖安装 → 按结果改按钮文案。 */
export function makeUpdateClickHandler(doc, getRemote, update, button) {
return async (event) => {
event?.preventDefault?.()
event?.stopPropagation?.()
const view = doc.defaultView
const ask = view?.confirm ?? globalThis.confirm
const message = '更新「' + update.title + '」' + (update.installedVersion ? ' ' + update.installedVersion : '') + ' → ' + update.version + '?\n会直接覆盖安装新版,插件数据保留。'
if (ask && !ask.call(view ?? globalThis, message)) return
button.disabled = true
button.textContent = '更新中…'
try {
const result = await runUpdate(getRemote(), update, () => globalThis.crypto?.randomUUID?.() ?? undefined)
if (result?.value?.application === 'applied') {
button.textContent = '已更新,重启 DSH 后生效'
} else {
console.error('[dsh-better-chat] update failed for', update.name, result?.value?.error ?? result)
button.disabled = false
button.textContent = '更新失败,点此重试'
}
} catch (error) {
console.error('[dsh-better-chat] update failed for', update.name, error)
button.disabled = false
button.textContent = '更新失败,点此重试'
}
}
}
/** 发现页增强:轮询索引状态,把「更新」按钮挂到有新版本的行上。 */
export function installStoreUpdateButtons(doc, getRemote, timers = { setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (id) => clearInterval(id) }) {
let disposed = false
let updates = []
const decorate = () => {
for (const update of updates) {
const row = findUpdateRow(doc, update.title)
if (!row || row.querySelector('[data-better-chat-update]')) continue
const button = doc.createElement('button')
button.type = 'button'
button.setAttribute('data-better-chat-update', update.name)
button.textContent = '更新到 ' + update.version
button.style.cssText = 'flex:none;margin-left:8px;padding:2px 10px;border:1px solid #7f7f7f55;border-radius:999px;background:transparent;color:inherit;font-size:12px;cursor:pointer'
button.addEventListener('click', makeUpdateClickHandler(doc, getRemote, update, button))
row.appendChild(button)
}
}
const refresh = async () => {
try {
const remote = getRemote()
if (!remote?.pluginMarket || !remote?.pluginManager) return
const indexes = await remote.pluginMarket.listIndexes()
const urls = (indexes?.value ?? indexes ?? []).map((entry) => entry?.url).filter(Boolean)
const results = []
for (const url of urls) {
results.push(await remote.pluginMarket.search(url, { sort: { kind: 'index' }, offset: 0, limit: 100 }))
}
if (disposed) return
updates = pickUpdates(results, doc.documentElement?.lang || 'zh-CN')
decorate()
} catch {
// 索引服务不可用(未启用实验性插件索引等):静默关闭本功能。
}
}
const observer = new MutationObserver(() => decorate())
observer.observe(doc.documentElement, { childList: true, subtree: true })
const timer = timers.setInterval(() => { void refresh() }, 30000)
void refresh()
return () => {
disposed = true
observer.disconnect()
timers.clearInterval(timer)
}
}
/** 商店更新子插件:单独声明远程服务 inject,与主功能互相隔离。 */
const storeUpdatePlugin = {
name: 'dsh-better-chat-store-update',
inject: ['remote', 'remote.pluginMarket', 'remote.pluginManager'],
apply(childCtx) {
childCtx.effect(
() => installStoreUpdateButtons(document, () => childCtx.remote),
'dsh-better-chat: store update buttons',
)
},
}
/** 本插件不硬依赖任何客户端服务(sessions 服务是可选增强,缺了只是不自动切)。 */
export const inject = []
/** 插件主体:挂载两组增强,卸载时完整摘除。 */
export function apply(ctx) {
ctx.effect(() => install(document), 'dsh-better-chat: approval enter/esc routing')
ctx.effect(
() => installPermissionPolicy(document),
'dsh-better-chat: permission policy (no full access)',
)
try {
ctx.plugin(storeUpdatePlugin)
} catch {
// 子插件挂不上(旧宿主等)不影响主功能。
}
}