feat: show approval key hints and add Ctrl/Cmd+Enter always-allow
Option A from the preview: the action row shows Enter <allow label> / Ctrl+Enter <always label> / Esc <reject label>. Labels come from the card's real buttons, the hint is pointer-transparent and aria-hidden, disappears when the card is answered and is rebuilt after React re-renders. Ctrl+Enter (Cmd+Enter on Apple platforms) clicks the always-allow button, only when the card has one; the official card ignores modified keys, so the chord is handled even while focus is inside the card. Typing in an input still suppresses everything. Adds tests/chat/key-hint.test.ts and extends the approval-key decisions; version 0.4.1.
This commit is contained in:
parent
f50d36874d
commit
a4844006a6
|
|
@ -3,3 +3,5 @@ node_modules/
|
|||
.DS_Store
|
||||
.pnpm-store/
|
||||
.build-spike/
|
||||
.preview/
|
||||
dsh-image-gen/
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
# Changelog
|
||||
|
||||
## 0.4.1 — 2026-11-12
|
||||
|
||||
- 审批卡新增键盘提示(方案 A):操作行左侧显示 `Enter 允许(单次) · Ctrl+Enter 始终允许 · Esc 拒绝` 的键帽提示,文案直接取卡片按钮的实际文字;卡片作答后立即移除,React 重渲染后自动重建。鼠标不可点、不参与焦点,纯说明。
|
||||
- 新增 **Ctrl+Enter / Cmd+Enter = 始终允许**(仅当卡片有第三个按钮时生效)。官方卡片原本对带修饰键的按键不作答,所以这条即使在卡片内(自动送入焦点后)也由本插件处理;正在输入控件里打字时不拦截。Mac 上提示显示 Cmd+Enter。
|
||||
- 新增 `tests/chat/key-hint.test.ts`(提示分段、平台键、插入/移除),并补充 Ctrl/Cmd+Enter 的判定测试。
|
||||
|
||||
## 0.4.0 — 2026-11-12
|
||||
|
||||
- 合并 **dsh-better-display 0.3.12** 的阅读视图:源码、样式、文档、技能包、设置页与
|
||||
|
|
|
|||
13
README.en.md
13
README.en.md
|
|
@ -35,7 +35,7 @@ tools and approvals remain.
|
|||
whether the `generative-mcpapps` skill is installed in the host skill roots.
|
||||
- Upstream design notes, extension points and runbooks live in [`docs/`](docs/).
|
||||
|
||||
## Feature 2: Enter approves, Esc rejects on approval cards (v0.1.0)
|
||||
## Feature 2: Enter approves, Esc rejects on approval cards (v0.1.0, hints and always-allow chord in v0.4.1)
|
||||
|
||||
DSH's approval card handles Enter / Esc itself, but only when focus is already
|
||||
inside the card. This plugin adds:
|
||||
|
|
@ -44,10 +44,15 @@ inside the card. This plugin adds:
|
|||
focus moves into the card's detail region.
|
||||
2. **Document-level routing**: with focus outside the card, Enter clicks
|
||||
"Allow once" (never "Always allow") and Esc clicks "Reject".
|
||||
3. **Key hint**: the action row shows `Enter Allow once · Ctrl+Enter Always allow
|
||||
· Esc Reject` keycaps, using the card's real button labels. It disappears once
|
||||
the card is answered, is not focusable and is not clickable. macOS shows Cmd.
|
||||
4. **Ctrl+Enter / Cmd+Enter = Always allow**, only when the card has the third
|
||||
button. The official card ignores modified keys, so this chord is handled here
|
||||
even while focus is inside the card. It never fires while typing in an input.
|
||||
|
||||
It never intercepts while typing, when focus is inside the card, with modifier
|
||||
keys / auto-repeat / IME composition, when Enter lands on another button or link,
|
||||
or when the card is already answered.
|
||||
It never intercepts while typing, with Shift/Alt, auto-repeat, IME composition,
|
||||
when Enter lands on another button or link, or when the card is answered.
|
||||
|
||||
## Feature 3: permission UI (v0.2.0, tightened in v0.3.1)
|
||||
|
||||
|
|
|
|||
12
README.md
12
README.md
|
|
@ -29,16 +29,22 @@ dsh plugin --profile desktop add git+https://git.qyhhh.top/DeepsSeekHarness/dsh-
|
|||
(默认开),并检测 `generative-mcpapps` 技能是否已装进宿主技能目录。
|
||||
- 上游的设计说明、扩展点文档与开发 runbook 一并保留在 [`docs/`](docs/)。
|
||||
|
||||
## 功能二:审批卡片的回车批准 / Esc 拒绝(v0.1.0)
|
||||
## 功能二:审批卡片的回车批准 / Esc 拒绝(v0.1.0,v0.4.1 加提示与始终允许快捷键)
|
||||
|
||||
DSH 官方审批卡本身支持 Enter 批准、Esc 拒绝,但前提是焦点先落在卡内。本插件补上:
|
||||
|
||||
1. **自动送入焦点**:审批卡出现时,若没有正在别处输入,把焦点送进卡片详情区。
|
||||
2. **全局兜底路由**:焦点不在卡内时,在 document 捕获阶段接住回车 / Esc —— 回车
|
||||
永远点「允许(单次)」(不会误触「始终允许」),Esc 点「拒绝」。
|
||||
3. **键盘提示**:操作行左侧显示 `Enter 允许(单次) · Ctrl+Enter 始终允许 · Esc 拒绝`
|
||||
的键帽提示,文案取卡片按钮的实际文字,卡片作答后自动消失;只做说明,不占焦点、
|
||||
不可点击。Mac 上显示 Cmd+Enter。
|
||||
4. **Ctrl+Enter / Cmd+Enter = 始终允许**:仅当卡片有第三个按钮时生效。官方卡片对带
|
||||
修饰键的按键不作答,所以这条即使在卡片内也由本插件处理;正在输入控件里打字时
|
||||
不拦截。
|
||||
|
||||
防误触:正在输入控件里打字、焦点已在卡内、带修饰键 / 长按连发 / 输入法组词、
|
||||
回车落在别的按钮或链接上、卡片已作答或按钮禁用时,都不拦截。
|
||||
防误触:正在输入控件里打字、焦点已在卡内(Ctrl/Cmd+Enter 除外)、带 Shift/Alt、
|
||||
长按连发、输入法组词、回车落在别的按钮或链接上、卡片已作答或按钮禁用时,都不拦截。
|
||||
|
||||
## 功能三:权限 UI(v0.2.0,v0.3.1 收紧)
|
||||
|
||||
|
|
|
|||
194
lib/client.js
194
lib/client.js
|
|
@ -32,7 +32,7 @@ window.__ModuleLoader__.load({
|
|||
* 2. 焦点不在卡片内时兜底路由:document 捕获阶段拦 keydown,点击卡片
|
||||
* 操作行里的按钮 —— 回车点「允许(单次)」,Esc 点「拒绝」。
|
||||
*/
|
||||
const CARD_SELECTOR = "[data-approval-key]";
|
||||
const CARD_SELECTOR$1 = "[data-approval-key]";
|
||||
const SCROLL_SELECTOR = "[data-approval-scroll]";
|
||||
const EDITABLE_SELECTOR = "input, textarea, select, [contenteditable=\"true\"], [contenteditable=\"\"]";
|
||||
/** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */
|
||||
|
|
@ -41,7 +41,7 @@ window.__ModuleLoader__.load({
|
|||
}
|
||||
/** 找当前可作答的审批卡(DOM 顺序第一张未作答、按钮齐全的卡)。 */
|
||||
function findPendingCard(doc) {
|
||||
for (const card of doc.querySelectorAll(CARD_SELECTOR)) {
|
||||
for (const card of doc.querySelectorAll(CARD_SELECTOR$1)) {
|
||||
if (card.getAttribute("aria-busy") === "true") continue;
|
||||
const buttons = actionButtons(card);
|
||||
if (buttons.length >= 2 && !buttons[0].disabled && !buttons[1].disabled) return card;
|
||||
|
|
@ -50,20 +50,28 @@ window.__ModuleLoader__.load({
|
|||
}
|
||||
/**
|
||||
* 纯判定:这次 keydown 是否应该路由到审批卡。
|
||||
* @returns 'allow' | 'reject' | null
|
||||
*
|
||||
* - Enter → 允许(单次)
|
||||
* - Esc → 拒绝
|
||||
* - Ctrl/Cmd+Enter → 始终允许(仅当卡片有第三个按钮时;官方卡片本身
|
||||
* 对带修饰键的按键不作答,所以这条即使在卡内也由本插件处理)
|
||||
*
|
||||
* @returns 'allow' | 'reject' | 'always' | null
|
||||
*/
|
||||
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 (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;
|
||||
if (target && typeof target.closest === "function" && target.closest(EDITABLE_SELECTOR) !== null) return null;
|
||||
if (ctrlKey || metaKey) {
|
||||
if (key !== "Enter" || !input.hasAlways) return null;
|
||||
return "always";
|
||||
}
|
||||
if (activeElement && card.contains(activeElement)) return null;
|
||||
if (key === "Enter" && target && typeof target.closest === "function" && target.closest("button, a[href], [role=\"button\"]") !== null) return null;
|
||||
return key === "Enter" ? "allow" : "reject";
|
||||
}
|
||||
/** 纯判定:审批卡出现时是否应该把焦点送进详情区。 */
|
||||
|
|
@ -93,6 +101,9 @@ window.__ModuleLoader__.load({
|
|||
tryAutoFocus();
|
||||
const onKeyDown = (event) => {
|
||||
const card = findPendingCard(doc);
|
||||
if (!card) return;
|
||||
const buttons = actionButtons(card);
|
||||
const hasAlways = buttons.length >= 3 && !buttons[2].disabled;
|
||||
const action = decideKeyAction({
|
||||
key: event.key,
|
||||
ctrlKey: event.ctrlKey,
|
||||
|
|
@ -105,11 +116,11 @@ window.__ModuleLoader__.load({
|
|||
defaultPrevented: event.defaultPrevented,
|
||||
target: event.target,
|
||||
activeElement: doc.activeElement,
|
||||
card
|
||||
card,
|
||||
hasAlways
|
||||
});
|
||||
if (!action || !card) return;
|
||||
const buttons = actionButtons(card);
|
||||
const button = action === "allow" ? buttons[1] : buttons[0];
|
||||
if (!action) return;
|
||||
const button = action === "allow" ? buttons[1] : action === "always" ? buttons[2] : buttons[0];
|
||||
if (!button || button.disabled) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
|
@ -121,6 +132,164 @@ window.__ModuleLoader__.load({
|
|||
doc.removeEventListener("keydown", onKeyDown, true);
|
||||
};
|
||||
}
|
||||
// src/client/chat/key-hint.ts
|
||||
/**
|
||||
* 审批卡键盘提示:在操作行左侧显示「Enter 允许(单次) · Ctrl+Enter
|
||||
* 始终允许 · Esc 拒绝」的键帽提示,文案直接取卡片按钮的实际文字。
|
||||
*
|
||||
* 提示只是说明,不参与点击:pointer-events: none、aria-hidden,且只挂在
|
||||
* 卡片操作行里(详情滚动区之外)。React 重渲染把提示冲掉时,MutationObserver
|
||||
* 会按按钮文案的签名重新挂回去;卡片作答后(aria-busy)立即移除。
|
||||
*/
|
||||
const HINT_ATTR = "data-better-chat-keyhint";
|
||||
const CARD_SELECTOR = "[data-approval-key]";
|
||||
const SEPARATOR = "·";
|
||||
/** 纯判定:当前平台是否用 Cmd 代替 Ctrl(只影响提示文案)。 */
|
||||
function isMacPlatform(platform) {
|
||||
return typeof platform === "string" && /Mac|iPhone|iPad|iPod/.test(platform);
|
||||
}
|
||||
/**
|
||||
* 纯函数:根据卡片上实际存在的按钮文案,生成提示的分段。
|
||||
* 没有「始终允许」按钮时就不显示 Ctrl+Enter。
|
||||
*/
|
||||
function hintParts(labels, mac) {
|
||||
const parts = [];
|
||||
if (labels.allow) parts.push({
|
||||
key: "Enter",
|
||||
label: labels.allow
|
||||
});
|
||||
if (labels.always) parts.push({
|
||||
key: mac ? "Cmd+Enter" : "Ctrl+Enter",
|
||||
label: labels.always
|
||||
});
|
||||
if (labels.reject) parts.push({
|
||||
key: "Esc",
|
||||
label: labels.reject
|
||||
});
|
||||
return parts;
|
||||
}
|
||||
/** 纯函数:提示内容的签名,用于判断是否需要重建。 */
|
||||
function hintSignature(parts) {
|
||||
return parts.map((part) => `${part.key}=${part.label}`).join("|");
|
||||
}
|
||||
const HINT_CSS = [
|
||||
"margin-right:auto",
|
||||
"display:inline-flex",
|
||||
"flex-wrap:wrap",
|
||||
"align-items:center",
|
||||
"gap:6px",
|
||||
"font-size:12px",
|
||||
"line-height:18px",
|
||||
"color:var(--dsw-alias-label-tertiary,#8b919b)",
|
||||
"user-select:none",
|
||||
"pointer-events:none"
|
||||
].join(";");
|
||||
const KEYCAP_CSS = [
|
||||
"display:inline-flex",
|
||||
"align-items:center",
|
||||
"justify-content:center",
|
||||
"height:18px",
|
||||
"padding:0 5px",
|
||||
"border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.35))",
|
||||
"border-bottom-width:2px",
|
||||
"border-radius:5px",
|
||||
"background:var(--dsw-alias-bg-module-platform,rgba(127,127,127,.08))",
|
||||
"font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Consolas,monospace)",
|
||||
"font-size:11px",
|
||||
"line-height:1",
|
||||
"letter-spacing:.2px"
|
||||
].join(";");
|
||||
const PAIR_CSS = "display:inline-flex;align-items:center;gap:5px";
|
||||
const SEPARATOR_CSS = "opacity:.45;margin:0 2px";
|
||||
function labelOf(button) {
|
||||
if (!button) return void 0;
|
||||
const text = button.textContent?.trim();
|
||||
return text ? text : void 0;
|
||||
}
|
||||
function buildHint(doc, parts) {
|
||||
const hint = doc.createElement("div");
|
||||
hint.setAttribute(HINT_ATTR, "");
|
||||
hint.setAttribute("role", "note");
|
||||
hint.setAttribute("aria-hidden", "true");
|
||||
hint.style.cssText = HINT_CSS;
|
||||
parts.forEach((part, index) => {
|
||||
if (index > 0) {
|
||||
const separator = doc.createElement("span");
|
||||
separator.textContent = SEPARATOR;
|
||||
separator.style.cssText = SEPARATOR_CSS;
|
||||
hint.append(separator);
|
||||
}
|
||||
const pair = doc.createElement("span");
|
||||
pair.style.cssText = PAIR_CSS;
|
||||
const keycap = doc.createElement("span");
|
||||
keycap.textContent = part.key;
|
||||
keycap.style.cssText = KEYCAP_CSS;
|
||||
const label = doc.createElement("span");
|
||||
label.textContent = part.label;
|
||||
pair.append(keycap, label);
|
||||
hint.append(pair);
|
||||
});
|
||||
return hint;
|
||||
}
|
||||
function removeHints(doc) {
|
||||
for (const hint of doc.querySelectorAll(`[${HINT_ATTR}]`)) hint.remove();
|
||||
}
|
||||
/**
|
||||
* 安装审批卡键盘提示,返回卸载函数。
|
||||
* @param platform 用于区分 Cmd/Ctrl;默认读 navigator.platform。
|
||||
*/
|
||||
function installKeyHints(doc, platform = doc.defaultView?.navigator?.platform) {
|
||||
const mac = isMacPlatform(platform);
|
||||
let disposed = false;
|
||||
const syncCard = (card) => {
|
||||
const buttons = actionButtons(card);
|
||||
const existing = card.querySelector(`[${HINT_ATTR}]`);
|
||||
if (card.getAttribute("aria-busy") === "true" || buttons.length < 2 || buttons[0].disabled || buttons[1].disabled) {
|
||||
existing?.remove();
|
||||
return;
|
||||
}
|
||||
const always = buttons.length >= 3 && !buttons[2].disabled ? buttons[2] : void 0;
|
||||
const parts = hintParts({
|
||||
allow: labelOf(buttons[1]),
|
||||
always: labelOf(always),
|
||||
reject: labelOf(buttons[0])
|
||||
}, mac);
|
||||
if (parts.length === 0) {
|
||||
existing?.remove();
|
||||
return;
|
||||
}
|
||||
const signature = hintSignature(parts);
|
||||
if (existing && existing.getAttribute("data-signature") === signature) return;
|
||||
existing?.remove();
|
||||
const row = buttons[0].parentElement;
|
||||
if (!row) return;
|
||||
const hint = buildHint(doc, parts);
|
||||
hint.setAttribute("data-signature", signature);
|
||||
row.insertBefore(hint, row.firstChild);
|
||||
};
|
||||
const sync = () => {
|
||||
if (disposed) return;
|
||||
const cards = doc.querySelectorAll(CARD_SELECTOR);
|
||||
if (cards.length === 0) {
|
||||
removeHints(doc);
|
||||
return;
|
||||
}
|
||||
for (const card of cards) syncCard(card);
|
||||
};
|
||||
const observer = new MutationObserver(sync);
|
||||
observer.observe(doc.documentElement, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ["aria-busy", "disabled"]
|
||||
});
|
||||
sync();
|
||||
return () => {
|
||||
disposed = true;
|
||||
observer.disconnect();
|
||||
removeHints(doc);
|
||||
};
|
||||
}
|
||||
// src/client/chat/permission-policy.ts
|
||||
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
|
||||
const FULL_ACCESS_LABELS = ["完全权限", "Full access"];
|
||||
|
|
@ -53101,6 +53270,7 @@ ${trimmed}
|
|||
];
|
||||
function apply(ctx) {
|
||||
ctx.effect(() => install(document), "dsh-better-chat: approval enter/esc routing");
|
||||
ctx.effect(() => installKeyHints(document), "dsh-better-chat: approval key hints");
|
||||
ctx.effect(() => installPermissionPolicy(document), "dsh-better-chat: permission policy (no full access)");
|
||||
try {
|
||||
ctx.plugin(storeUpdatePlugin);
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-better-chat",
|
||||
"version": "0.4.0",
|
||||
"version": "0.4.1",
|
||||
"description": "DSH 聊天增强插件:审批回车批准 / Esc 拒绝、权限 UI、插件商店更新,以及 reading view(合并自 dsh-better-display)",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -28,6 +28,8 @@ export interface KeyActionInput {
|
|||
target?: Element | null
|
||||
activeElement?: Element | null
|
||||
card?: Element | null
|
||||
/** 卡片是否有可用的「始终允许」按钮(第三个操作按钮)。 */
|
||||
hasAlways?: boolean
|
||||
}
|
||||
|
||||
/** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */
|
||||
|
|
@ -49,9 +51,15 @@ export function findPendingCard(doc: Document): Element | null {
|
|||
|
||||
/**
|
||||
* 纯判定:这次 keydown 是否应该路由到审批卡。
|
||||
* @returns 'allow' | 'reject' | null
|
||||
*
|
||||
* - Enter → 允许(单次)
|
||||
* - Esc → 拒绝
|
||||
* - Ctrl/Cmd+Enter → 始终允许(仅当卡片有第三个按钮时;官方卡片本身
|
||||
* 对带修饰键的按键不作答,所以这条即使在卡内也由本插件处理)
|
||||
*
|
||||
* @returns 'allow' | 'reject' | 'always' | null
|
||||
*/
|
||||
export function decideKeyAction(input: KeyActionInput): 'allow' | 'reject' | null {
|
||||
export function decideKeyAction(input: KeyActionInput): 'allow' | 'reject' | 'always' | null {
|
||||
const {
|
||||
key, ctrlKey, metaKey, altKey, shiftKey, repeat, isComposing,
|
||||
keyCode, defaultPrevented, target, activeElement, card,
|
||||
|
|
@ -59,12 +67,24 @@ export function decideKeyAction(input: KeyActionInput): 'allow' | 'reject' | nul
|
|||
if (!card) return null
|
||||
if (defaultPrevented) return null
|
||||
if (key !== 'Enter' && key !== 'Escape') return null
|
||||
if (ctrlKey || metaKey || altKey || shiftKey) return null
|
||||
if (altKey || shiftKey) return null
|
||||
if (repeat || isComposing || keyCode === 229) return null
|
||||
|
||||
// 正在输入控件里打字时一律不拦截(含卡片内的输入框)。
|
||||
if (target && typeof target.closest === 'function' && target.closest(EDITABLE_SELECTOR) !== null) {
|
||||
return null
|
||||
}
|
||||
|
||||
const chord = ctrlKey || metaKey
|
||||
if (chord) {
|
||||
if (key !== 'Enter' || !input.hasAlways) return null
|
||||
return 'always'
|
||||
}
|
||||
|
||||
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
|
||||
if (key === 'Enter' && target && typeof target.closest === 'function'
|
||||
&& target.closest('button, a[href], [role="button"]') !== null) {
|
||||
return null // 回车落在别的按钮/链接上:保留它自己的行为
|
||||
}
|
||||
return key === 'Enter' ? 'allow' : 'reject'
|
||||
}
|
||||
|
|
@ -99,16 +119,22 @@ export function install(doc: Document): () => void {
|
|||
|
||||
const onKeyDown = (event: KeyboardEvent): void => {
|
||||
const card = findPendingCard(doc)
|
||||
if (!card) return
|
||||
const buttons = actionButtons(card)
|
||||
const hasAlways = buttons.length >= 3 && !buttons[2].disabled
|
||||
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 as Element | null, activeElement: doc.activeElement, card,
|
||||
target: event.target as Element | null, activeElement: doc.activeElement, card, hasAlways,
|
||||
})
|
||||
if (!action || !card) return
|
||||
const buttons = actionButtons(card)
|
||||
const button = action === 'allow' ? buttons[1] : buttons[0]
|
||||
if (!action) return
|
||||
const button = action === 'allow'
|
||||
? buttons[1]
|
||||
: action === 'always'
|
||||
? buttons[2]
|
||||
: buttons[0]
|
||||
if (!button || button.disabled) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,181 @@
|
|||
/**
|
||||
* 审批卡键盘提示:在操作行左侧显示「Enter 允许(单次) · Ctrl+Enter
|
||||
* 始终允许 · Esc 拒绝」的键帽提示,文案直接取卡片按钮的实际文字。
|
||||
*
|
||||
* 提示只是说明,不参与点击:pointer-events: none、aria-hidden,且只挂在
|
||||
* 卡片操作行里(详情滚动区之外)。React 重渲染把提示冲掉时,MutationObserver
|
||||
* 会按按钮文案的签名重新挂回去;卡片作答后(aria-busy)立即移除。
|
||||
*/
|
||||
import { actionButtons } from './approval-keys.js'
|
||||
|
||||
export const HINT_ATTR = 'data-better-chat-keyhint'
|
||||
const CARD_SELECTOR = '[data-approval-key]'
|
||||
const SEPARATOR = '·'
|
||||
|
||||
export interface HintPart {
|
||||
key: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface HintLabels {
|
||||
allow?: string
|
||||
always?: string
|
||||
reject?: string
|
||||
}
|
||||
|
||||
/** 纯判定:当前平台是否用 Cmd 代替 Ctrl(只影响提示文案)。 */
|
||||
export function isMacPlatform(platform: string | undefined | null): boolean {
|
||||
return typeof platform === 'string' && /Mac|iPhone|iPad|iPod/.test(platform)
|
||||
}
|
||||
|
||||
/**
|
||||
* 纯函数:根据卡片上实际存在的按钮文案,生成提示的分段。
|
||||
* 没有「始终允许」按钮时就不显示 Ctrl+Enter。
|
||||
*/
|
||||
export function hintParts(labels: HintLabels, mac: boolean): HintPart[] {
|
||||
const parts: HintPart[] = []
|
||||
if (labels.allow) parts.push({ key: 'Enter', label: labels.allow })
|
||||
// Use the word "Cmd" instead of the ⌘ glyph: the glyph falls back to a CJK
|
||||
// character under some font stacks, while "Cmd" is always legible.
|
||||
if (labels.always) parts.push({ key: mac ? 'Cmd+Enter' : 'Ctrl+Enter', label: labels.always })
|
||||
if (labels.reject) parts.push({ key: 'Esc', label: labels.reject })
|
||||
return parts
|
||||
}
|
||||
|
||||
/** 纯函数:提示内容的签名,用于判断是否需要重建。 */
|
||||
export function hintSignature(parts: readonly HintPart[]): string {
|
||||
return parts.map((part) => `${part.key}=${part.label}`).join('|')
|
||||
}
|
||||
|
||||
const HINT_CSS = [
|
||||
'margin-right:auto',
|
||||
'display:inline-flex',
|
||||
'flex-wrap:wrap',
|
||||
'align-items:center',
|
||||
'gap:6px',
|
||||
'font-size:12px',
|
||||
'line-height:18px',
|
||||
'color:var(--dsw-alias-label-tertiary,#8b919b)',
|
||||
'user-select:none',
|
||||
'pointer-events:none',
|
||||
].join(';')
|
||||
|
||||
const KEYCAP_CSS = [
|
||||
'display:inline-flex',
|
||||
'align-items:center',
|
||||
'justify-content:center',
|
||||
'height:18px',
|
||||
'padding:0 5px',
|
||||
'border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.35))',
|
||||
'border-bottom-width:2px',
|
||||
'border-radius:5px',
|
||||
'background:var(--dsw-alias-bg-module-platform,rgba(127,127,127,.08))',
|
||||
'font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Consolas,monospace)',
|
||||
'font-size:11px',
|
||||
'line-height:1',
|
||||
'letter-spacing:.2px',
|
||||
].join(';')
|
||||
|
||||
const PAIR_CSS = 'display:inline-flex;align-items:center;gap:5px'
|
||||
const SEPARATOR_CSS = 'opacity:.45;margin:0 2px'
|
||||
|
||||
function labelOf(button: HTMLButtonElement | undefined): string | undefined {
|
||||
if (!button) return undefined
|
||||
const text = button.textContent?.trim()
|
||||
return text ? text : undefined
|
||||
}
|
||||
|
||||
function buildHint(doc: Document, parts: readonly HintPart[]): HTMLElement {
|
||||
const hint = doc.createElement('div')
|
||||
hint.setAttribute(HINT_ATTR, '')
|
||||
hint.setAttribute('role', 'note')
|
||||
hint.setAttribute('aria-hidden', 'true')
|
||||
hint.style.cssText = HINT_CSS
|
||||
parts.forEach((part, index) => {
|
||||
if (index > 0) {
|
||||
const separator = doc.createElement('span')
|
||||
separator.textContent = SEPARATOR
|
||||
separator.style.cssText = SEPARATOR_CSS
|
||||
hint.append(separator)
|
||||
}
|
||||
const pair = doc.createElement('span')
|
||||
pair.style.cssText = PAIR_CSS
|
||||
const keycap = doc.createElement('span')
|
||||
keycap.textContent = part.key
|
||||
keycap.style.cssText = KEYCAP_CSS
|
||||
const label = doc.createElement('span')
|
||||
label.textContent = part.label
|
||||
pair.append(keycap, label)
|
||||
hint.append(pair)
|
||||
})
|
||||
return hint
|
||||
}
|
||||
|
||||
function removeHints(doc: Document): void {
|
||||
for (const hint of doc.querySelectorAll(`[${HINT_ATTR}]`)) hint.remove()
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装审批卡键盘提示,返回卸载函数。
|
||||
* @param platform 用于区分 Cmd/Ctrl;默认读 navigator.platform。
|
||||
*/
|
||||
export function installKeyHints(
|
||||
doc: Document,
|
||||
platform: string | undefined | null = doc.defaultView?.navigator?.platform,
|
||||
): () => void {
|
||||
const mac = isMacPlatform(platform)
|
||||
let disposed = false
|
||||
|
||||
const syncCard = (card: Element): void => {
|
||||
const buttons = actionButtons(card)
|
||||
const existing = card.querySelector(`[${HINT_ATTR}]`)
|
||||
const answered = card.getAttribute('aria-busy') === 'true'
|
||||
if (answered || buttons.length < 2 || buttons[0].disabled || buttons[1].disabled) {
|
||||
existing?.remove()
|
||||
return
|
||||
}
|
||||
const always = buttons.length >= 3 && !buttons[2].disabled ? buttons[2] : undefined
|
||||
const parts = hintParts({
|
||||
allow: labelOf(buttons[1]),
|
||||
always: labelOf(always),
|
||||
reject: labelOf(buttons[0]),
|
||||
}, mac)
|
||||
if (parts.length === 0) {
|
||||
existing?.remove()
|
||||
return
|
||||
}
|
||||
const signature = hintSignature(parts)
|
||||
if (existing && existing.getAttribute('data-signature') === signature) return
|
||||
existing?.remove()
|
||||
const row = buttons[0].parentElement
|
||||
if (!row) return
|
||||
const hint = buildHint(doc, parts)
|
||||
hint.setAttribute('data-signature', signature)
|
||||
row.insertBefore(hint, row.firstChild)
|
||||
}
|
||||
|
||||
const sync = (): void => {
|
||||
if (disposed) return
|
||||
const cards = doc.querySelectorAll(CARD_SELECTOR)
|
||||
if (cards.length === 0) {
|
||||
removeHints(doc)
|
||||
return
|
||||
}
|
||||
for (const card of cards) syncCard(card)
|
||||
}
|
||||
|
||||
const observer = new MutationObserver(sync)
|
||||
observer.observe(doc.documentElement, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ['aria-busy', 'disabled'],
|
||||
})
|
||||
sync()
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
observer.disconnect()
|
||||
removeHints(doc)
|
||||
}
|
||||
}
|
||||
|
|
@ -10,6 +10,7 @@
|
|||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { install as installApprovalKeys } from './chat/approval-keys.js'
|
||||
import { installKeyHints } from './chat/key-hint.js'
|
||||
import { installPermissionPolicy } from './chat/permission-policy.js'
|
||||
import { storeUpdatePlugin } from './chat/store-update.js'
|
||||
import { apply as applyReader, name as readerName } from './reader-plugin.js'
|
||||
|
|
@ -29,6 +30,7 @@ export const inject = [
|
|||
export function apply(ctx: Context): void {
|
||||
// 聊天增强:纯 DOM 观察,不依赖任何宿主服务。
|
||||
ctx.effect(() => installApprovalKeys(document), 'dsh-better-chat: approval enter/esc routing')
|
||||
ctx.effect(() => installKeyHints(document), 'dsh-better-chat: approval key hints')
|
||||
ctx.effect(
|
||||
() => installPermissionPolicy(document),
|
||||
'dsh-better-chat: permission policy (no full access)',
|
||||
|
|
|
|||
|
|
@ -68,10 +68,12 @@ test('回车 → allow,Esc → reject(焦点不在卡内、非输入状态
|
|||
test('没有待审批卡 → 不管', () => {
|
||||
assert.equal(decideKeyAction({ ...baseInput, card: null }), null)
|
||||
})
|
||||
test('焦点已在卡内 → 交给官方处理', () => {
|
||||
test('焦点已在卡内 → 交给官方处理(Ctrl/Cmd+Enter 例外)', () => {
|
||||
const card = approvalCard()
|
||||
const inside = card.querySelector('[data-approval-scroll]')
|
||||
assert.equal(decideKeyAction({ ...baseInput, card, activeElement: inside }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, card, activeElement: inside, ctrlKey: true, hasAlways: true }), 'always')
|
||||
assert.equal(decideKeyAction({ ...baseInput, card, activeElement: inside, metaKey: true, hasAlways: true }), 'always')
|
||||
})
|
||||
test('正在输入控件里打字 → 不管(textarea / input / contenteditable)', () => {
|
||||
for (const target of [new El('textarea'), new El('input'), new El('div', { contenteditable: 'true' })]) {
|
||||
|
|
@ -79,14 +81,29 @@ test('正在输入控件里打字 → 不管(textarea / input / contenteditabl
|
|||
assert.equal(decideKeyAction({ ...baseInput, target, key: 'Escape', keyCode: 27 }), null)
|
||||
}
|
||||
})
|
||||
test('修饰键、连发、输入法组词、已被处理 → 不管', () => {
|
||||
test('修饰键、连发、输入法组词、已被处理 → 不管(Ctrl/Cmd+Enter 始终允许是唯一例外)', () => {
|
||||
assert.equal(decideKeyAction({ ...baseInput, ctrlKey: true }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, metaKey: true }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, ctrlKey: true, hasAlways: true }), 'always')
|
||||
assert.equal(decideKeyAction({ ...baseInput, metaKey: true, hasAlways: true }), 'always')
|
||||
assert.equal(decideKeyAction({ ...baseInput, ctrlKey: true, shiftKey: true, hasAlways: true }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, ctrlKey: true, altKey: true, hasAlways: true }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, shiftKey: true }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, repeat: true }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, repeat: true, hasAlways: true }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, isComposing: true }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, keyCode: 229 }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, defaultPrevented: true }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, key: 'a', keyCode: 65 }), null)
|
||||
assert.equal(decideKeyAction({ ...baseInput, key: 'Escape', ctrlKey: true, hasAlways: true }), null)
|
||||
})
|
||||
test('Ctrl/Cmd+Enter 只在卡片确实有可用的「始终允许」按钮时成立', () => {
|
||||
const withAlways = approvalCard({ withAlways: true })
|
||||
const withoutAlways = approvalCard()
|
||||
assert.equal(decideKeyAction({ ...baseInput, card: withAlways, ctrlKey: true, hasAlways: true }), 'always')
|
||||
assert.equal(decideKeyAction({ ...baseInput, card: withoutAlways, ctrlKey: true }), null)
|
||||
// 正在输入控件里打字时,带修饰键的组合键也不拦截。
|
||||
assert.equal(decideKeyAction({ ...baseInput, target: new El('textarea'), ctrlKey: true, hasAlways: true }), null)
|
||||
})
|
||||
test('回车落在别的按钮上 → 保留按钮原生行为;Esc 不受此限', () => {
|
||||
const btn = new El('button')
|
||||
|
|
|
|||
|
|
@ -0,0 +1,173 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { test } from 'vitest'
|
||||
import {
|
||||
HINT_ATTR,
|
||||
hintParts,
|
||||
hintSignature,
|
||||
installKeyHints,
|
||||
isMacPlatform,
|
||||
} from '../../src/client/chat/key-hint.ts'
|
||||
|
||||
test('hintParts: Ctrl+Enter only appears when the always button exists', () => {
|
||||
const withAlways = hintParts({ allow: '允许(单次)', always: '始终允许', reject: '拒绝' }, false)
|
||||
assert.deepEqual(withAlways.map((part) => part.key), ['Enter', 'Ctrl+Enter', 'Esc'])
|
||||
const mac = hintParts({ allow: '允许(单次)', always: '始终允许', reject: '拒绝' }, true)
|
||||
assert.equal(mac[1]?.key, 'Cmd+Enter')
|
||||
const withoutAlways = hintParts({ allow: '允许(单次)', reject: '拒绝' }, false)
|
||||
assert.deepEqual(withoutAlways.map((part) => part.key), ['Enter', 'Esc'])
|
||||
})
|
||||
|
||||
test('hintSignature changes with labels and platform keys', () => {
|
||||
const a = hintParts({ allow: '允许', reject: '拒绝' }, false)
|
||||
const b = hintParts({ allow: '允许', reject: '拒绝' }, false)
|
||||
const c = hintParts({ allow: 'Allow', reject: 'Reject' }, false)
|
||||
assert.equal(hintSignature(a), hintSignature(b))
|
||||
assert.notEqual(hintSignature(a), hintSignature(c))
|
||||
})
|
||||
|
||||
test('isMacPlatform detects Apple platforms only', () => {
|
||||
assert.equal(isMacPlatform('MacIntel'), true)
|
||||
assert.equal(isMacPlatform('iPhone'), true)
|
||||
assert.equal(isMacPlatform('Win32'), false)
|
||||
assert.equal(isMacPlatform('Linux x86_64'), false)
|
||||
assert.equal(isMacPlatform(undefined), false)
|
||||
})
|
||||
|
||||
// --- 极小假 DOM:只实现提示模块用到的表面 ---
|
||||
function matches(el: any, selector: string): boolean {
|
||||
return selector.split(',').some((part) => {
|
||||
const s = part.trim()
|
||||
if (s.startsWith('[')) {
|
||||
const m = s.match(/^\[([a-zA-Z-]+)(?:="([^"]*)")?\]$/)
|
||||
if (!m) return false
|
||||
const value = el.attrs[m[1]]
|
||||
return m[2] === undefined ? value !== undefined : value === m[2]
|
||||
}
|
||||
return el.tag === s
|
||||
})
|
||||
}
|
||||
class FakeEl {
|
||||
tag: string
|
||||
attrs: Record<string, string> = {}
|
||||
children: FakeEl[] = []
|
||||
parent: FakeEl | null = null
|
||||
style = { cssText: '' }
|
||||
disabled = false
|
||||
textContent = ''
|
||||
get parentElement(): FakeEl | null { return this.parent }
|
||||
constructor(tag: string) { this.tag = tag }
|
||||
setAttribute(name: string, value: string) { this.attrs[name] = value }
|
||||
getAttribute(name: string) { return this.attrs[name] ?? null }
|
||||
append(...nodes: FakeEl[]) { for (const node of nodes) { node.parent = this; this.children.push(node) } return this }
|
||||
insertBefore(node: FakeEl, ref: FakeEl | null) {
|
||||
node.parent = this
|
||||
const index = ref ? this.children.indexOf(ref) : -1
|
||||
if (index < 0) this.children.unshift(node)
|
||||
else this.children.splice(index, 0, node)
|
||||
return node
|
||||
}
|
||||
remove() {
|
||||
if (!this.parent) return
|
||||
const index = this.parent.children.indexOf(this)
|
||||
if (index >= 0) this.parent.children.splice(index, 1)
|
||||
this.parent = null
|
||||
}
|
||||
closest(selector: string): FakeEl | null {
|
||||
let current: FakeEl | null = this
|
||||
while (current) {
|
||||
if (matches(current, selector)) return current
|
||||
current = current.parent
|
||||
}
|
||||
return null
|
||||
}
|
||||
querySelectorAll(selector: string): FakeEl[] {
|
||||
const out: FakeEl[] = []
|
||||
const walk = (node: FakeEl) => {
|
||||
for (const child of node.children) {
|
||||
if (matches(child, selector)) out.push(child)
|
||||
walk(child)
|
||||
}
|
||||
}
|
||||
walk(this)
|
||||
return out
|
||||
}
|
||||
querySelector(selector: string): FakeEl | null {
|
||||
return this.querySelectorAll(selector)[0] ?? null
|
||||
}
|
||||
}
|
||||
class FakeDoc {
|
||||
root = new FakeEl('div')
|
||||
documentElement = this.root
|
||||
defaultView = { navigator: { platform: 'Win32' } }
|
||||
createElement(tag: string) { return new FakeEl(tag) }
|
||||
querySelectorAll(selector: string) { return this.root.querySelectorAll(selector) }
|
||||
}
|
||||
|
||||
let observerFire: (() => void) | null = null
|
||||
;(globalThis as any).MutationObserver = class {
|
||||
constructor(callback: () => void) { observerFire = callback }
|
||||
observe() {}
|
||||
disconnect() { observerFire = null }
|
||||
}
|
||||
|
||||
function button(text: string): FakeEl {
|
||||
const el = new FakeEl('button')
|
||||
el.textContent = text
|
||||
return el
|
||||
}
|
||||
|
||||
function cardWithButtons(labels: string[]): { doc: FakeDoc; card: FakeEl; row: FakeEl } {
|
||||
const doc = new FakeDoc()
|
||||
const card = new FakeEl('div')
|
||||
card.setAttribute('data-approval-key', 'k1')
|
||||
const row = new FakeEl('div')
|
||||
for (const label of labels) row.append(button(label))
|
||||
card.append(row)
|
||||
doc.root.append(card)
|
||||
return { doc, card, row }
|
||||
}
|
||||
|
||||
function textOf(node: FakeEl): string {
|
||||
const own = node.textContent
|
||||
return own + node.children.map(textOf).join('')
|
||||
}
|
||||
|
||||
test('installKeyHints inserts the hint as the first child of the action row', () => {
|
||||
const { doc, card, row } = cardWithButtons(['拒绝', '允许(单次)', '始终允许'])
|
||||
const dispose = installKeyHints(doc as unknown as Document, 'Win32')
|
||||
const hint = card.querySelector(`[${HINT_ATTR}]`) as FakeEl | null
|
||||
assert.ok(hint, 'hint must be inserted')
|
||||
assert.equal(row.children[0], hint, 'hint sits before the buttons')
|
||||
const text = textOf(hint)
|
||||
for (const expected of ['Enter', '允许(单次)', 'Ctrl+Enter', '始终允许', 'Esc', '拒绝']) {
|
||||
assert.ok(text.includes(expected), `hint should contain ${expected}; got ${text}`)
|
||||
}
|
||||
dispose()
|
||||
assert.equal(card.querySelector(`[${HINT_ATTR}]`), null, 'dispose removes the hint')
|
||||
})
|
||||
|
||||
test('installKeyHints omits Ctrl+Enter when there is no always button', () => {
|
||||
const { doc, card } = cardWithButtons(['拒绝', '允许'])
|
||||
const dispose = installKeyHints(doc as unknown as Document, 'Win32')
|
||||
const hint = card.querySelector(`[${HINT_ATTR}]`) as FakeEl
|
||||
assert.equal(textOf(hint).includes('Ctrl+Enter'), false)
|
||||
dispose()
|
||||
})
|
||||
|
||||
test('installKeyHints uses Cmd on Apple platforms', () => {
|
||||
const { doc, card } = cardWithButtons(['拒绝', '允许', '始终允许'])
|
||||
const dispose = installKeyHints(doc as unknown as Document, 'MacIntel')
|
||||
const hint = card.querySelector(`[${HINT_ATTR}]`) as FakeEl
|
||||
assert.ok(textOf(hint).includes('Cmd+Enter'))
|
||||
dispose()
|
||||
})
|
||||
|
||||
test('installKeyHints removes the hint once the card is answered', () => {
|
||||
const { doc, card } = cardWithButtons(['拒绝', '允许', '始终允许'])
|
||||
const dispose = installKeyHints(doc as unknown as Document, 'Win32')
|
||||
assert.ok(card.querySelector(`[${HINT_ATTR}]`))
|
||||
card.setAttribute('aria-busy', 'true')
|
||||
observerFire?.()
|
||||
assert.equal(card.querySelector(`[${HINT_ATTR}]`), null)
|
||||
dispose()
|
||||
})
|
||||
Loading…
Reference in New Issue