feat: default new blank sessions to auto-review (v1.0.1)
This commit is contained in:
parent
010a3d4e8b
commit
5c80061f08
|
|
@ -1,5 +1,12 @@
|
||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 1.0.1 — 2026-11-13
|
||||||
|
|
||||||
|
- 恢复并完善「默认打开模式为自动审查(`auto`)」功能:
|
||||||
|
- 宿主侧(`src/host.ts`)监听 `agent/created` 与 `permission-presets/catalog-changed`,当 `@deepseek-ai/dsh-experimental-auto-review` 已启用时,对新建空白顶层会话直接设为 `auto`;
|
||||||
|
- 客户端(`src/client/chat/permission-policy.ts`)适配 DSH 0.2.2 `ClientSessions`(`list.getSnapshot()` / `scopes`)与 `{ currentValue }` 权限投影结构,首次见到空白顶层会话时自动切到 `/permission auto`;
|
||||||
|
- 已处理会话 id 持久化到 `localStorage`(`dsh.better-chat.permission-handled.v1`),且跳过非空白历史会话(`blank === false`)、子代理会话与已手动执行过 `/permission` 的会话,刷新或重启不会覆盖用户手动切换的权限。
|
||||||
|
|
||||||
## 1.0.0 — 2026-11-12
|
## 1.0.0 — 2026-11-12
|
||||||
|
|
||||||
首个可用版本。单个插件同时提供阅读视图(合并自 dsh-better-display 0.3.12)与聊天增强:
|
首个可用版本。单个插件同时提供阅读视图(合并自 dsh-better-display 0.3.12)与聊天增强:
|
||||||
|
|
|
||||||
12
README.en.md
12
README.en.md
|
|
@ -67,13 +67,19 @@ card, for modifier sets that do not match the current binding, on auto-repeat,
|
||||||
during IME composition, when Enter lands on another button or link, or when the
|
during IME composition, when Enter lands on another button or link, or when the
|
||||||
card is answered.
|
card is answered.
|
||||||
|
|
||||||
## Feature 3: permission UI (v0.2.0, tightened in v0.3.1)
|
## Feature 3: permission policy (v0.2.0, default auto-review restored in v1.0.1)
|
||||||
|
|
||||||
- Removes the "Full access / 完全权限" option from the `/permission` popup, the
|
- Removes the "Full access / 完全权限" option from the `/permission` popup, the
|
||||||
composer permission menu and the settings default-permission dropdown.
|
composer permission menu and the settings default-permission dropdown.
|
||||||
UI-only: the slash command still works.
|
UI-only: the slash command still works.
|
||||||
- Never rewrites existing session permissions on page load, reload or plugin
|
- **Defaults new/blank sessions to "Auto review (`auto`)"**: when the
|
||||||
remount; the default is left to the host's new-session flow.
|
`@deepseek-ai/dsh-experimental-auto-review` layer is enabled, newly created or
|
||||||
|
first-opened blank top-level sessions automatically switch to `auto` (backed by
|
||||||
|
both the host `agent/created` hook and the client session observer).
|
||||||
|
- **Never overwrites existing conversations or manual choices**: sessions with
|
||||||
|
existing history (`blank === false`), subagent sessions, and already-handled
|
||||||
|
sessions (persisted under `dsh.better-chat.permission-handled.v1`) are left
|
||||||
|
untouched across page reloads and restarts.
|
||||||
|
|
||||||
## Feature 4: plugin-store update button (v0.3.0)
|
## Feature 4: plugin-store update button (v0.3.0)
|
||||||
|
|
||||||
|
|
|
||||||
12
README.md
12
README.md
|
|
@ -53,12 +53,16 @@ DSH 官方审批卡本身支持 Enter 批准、Esc 拒绝,但前提是焦点
|
||||||
防误触:正在输入控件里打字、裸 Enter/Esc 且焦点已在卡内、与当前绑定不符的修饰键、
|
防误触:正在输入控件里打字、裸 Enter/Esc 且焦点已在卡内、与当前绑定不符的修饰键、
|
||||||
长按连发、输入法组词、回车落在别的按钮或链接上、卡片已作答或按钮禁用时,都不拦截。
|
长按连发、输入法组词、回车落在别的按钮或链接上、卡片已作答或按钮禁用时,都不拦截。
|
||||||
|
|
||||||
## 功能三:权限 UI(v0.2.0,v0.3.1 收紧)
|
## 功能三:权限策略(v0.2.0,v1.0.1 补齐默认自动审查)
|
||||||
|
|
||||||
- 去掉「完全权限 / Full access」选项:`/permission` 弹出菜单、composer 权限菜单与
|
- **去掉「完全权限 / Full access」选项**:`/permission` 弹出菜单、composer 权限菜单与
|
||||||
通用设置的默认权限下拉里都会被摘除。只动界面,手动输入命令仍可达。
|
通用设置的默认权限下拉里都会被摘除。只动界面,手动输入命令仍可达。
|
||||||
- 不覆盖已有会话权限:页面加载、刷新、插件重载都不会遍历会话改权限;默认权限交给
|
- **新建/空白会话默认「自动审查(auto)」**:当实验层 `@deepseek-ai/dsh-experimental-auto-review`
|
||||||
宿主的新建会话流程。
|
已启用时,新建或首次打开的空白顶层会话会自动切到「自动审查」模式(宿主侧创建监听与
|
||||||
|
客户端会话同步双保险)。
|
||||||
|
- **不覆盖已有对话与用户手动选择**:已有对话内容的会话(`blank === false`)、子代理会话
|
||||||
|
以及已处理过的会话(记录在 `dsh.better-chat.permission-handled.v1`)不会在页面刷新、
|
||||||
|
重连或重启时被重置;手动切到「仅可查看」或「工作区内修改」后始终保留。
|
||||||
|
|
||||||
## 功能四:插件商店「更新」按钮(v0.3.0)
|
## 功能四:插件商店「更新」按钮(v0.3.0)
|
||||||
|
|
||||||
|
|
|
||||||
210
lib/client.js
210
lib/client.js
|
|
@ -440,14 +440,121 @@ window.__ModuleLoader__.load({
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// src/client/chat/permission-policy.ts
|
// src/client/chat/permission-policy.ts
|
||||||
|
/** 自动审查的预设机器值。 */
|
||||||
|
const AUTO_REVIEW_PRESET = "auto";
|
||||||
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
|
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
|
||||||
const FULL_ACCESS_LABELS = ["完全权限", "Full access"];
|
const FULL_ACCESS_LABELS = ["完全权限", "Full access"];
|
||||||
|
/** 已处理会话 id 的浏览器持久化键,避免刷新后覆盖用户手动改过的权限。 */
|
||||||
|
const HANDLED_STORAGE_KEY = "dsh.better-chat.permission-handled.v1";
|
||||||
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
|
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
|
||||||
function isFullAccessLabel(text) {
|
function isFullAccessLabel(text) {
|
||||||
if (typeof text !== "string") return false;
|
if (typeof text !== "string") return false;
|
||||||
const trimmed = text.trim();
|
const trimmed = text.trim();
|
||||||
return FULL_ACCESS_LABELS.some((label) => trimmed === label || trimmed.startsWith(label));
|
return FULL_ACCESS_LABELS.some((label) => trimmed === label || trimmed.startsWith(label));
|
||||||
}
|
}
|
||||||
|
/** 纯判定:这个会话现在是否应该被切到自动审查。 */
|
||||||
|
function shouldAutoSwitch(preset, alreadyHandled) {
|
||||||
|
return preset !== void 0 && preset !== null && preset !== "auto" && !alreadyHandled;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 防御式枚举宿主的 live 会话:
|
||||||
|
* 1. `keys() + binding()`(测试桩或旧形状)
|
||||||
|
* 2. DSH 0.2.2 `ClientSessions`:`scopes` Map 与 `list.getSnapshot()`(`ids` / `byId`)配合 `binding(id)`
|
||||||
|
* 3. `list()` 函数回退
|
||||||
|
* 服务形状对不上时安静返回空数组,绝不抛错。
|
||||||
|
*/
|
||||||
|
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.binding === "function" || sessions.scopes instanceof Map) {
|
||||||
|
const seen = /* @__PURE__ */ new Set();
|
||||||
|
const addCandidate = (id) => {
|
||||||
|
if (typeof id !== "string" || !id || seen.has(id)) return;
|
||||||
|
const live = (typeof sessions.binding === "function" ? sessions.binding(id)?.session : void 0) ?? (sessions.scopes instanceof Map ? sessions.scopes.get(id)?.binding?.session : void 0);
|
||||||
|
if (live) {
|
||||||
|
seen.add(id);
|
||||||
|
out.push({
|
||||||
|
id,
|
||||||
|
live
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (sessions.scopes instanceof Map) for (const id of sessions.scopes.keys()) addCandidate(id);
|
||||||
|
const listSnap = typeof sessions.list?.getSnapshot === "function" ? sessions.list.getSnapshot() : void 0;
|
||||||
|
if (Array.isArray(listSnap?.ids)) for (const id of listSnap.ids) addCandidate(id);
|
||||||
|
if (listSnap?.byId && typeof listSnap.byId === "object") for (const id of Object.keys(listSnap.byId)) addCandidate(id);
|
||||||
|
if (out.length > 0 || typeof sessions.list !== "function") return out;
|
||||||
|
}
|
||||||
|
if (typeof sessions.list === "function") {
|
||||||
|
for (const session of sessions.list() ?? []) if (session && session.sessionId) out.push({
|
||||||
|
id: session.sessionId,
|
||||||
|
live: session
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 读会话当前的权限预设值(投影不可用时返回 undefined)。
|
||||||
|
* 兼容 DSH 0.2.2 的 `{ currentValue: string }` 投影视图与直接返回字符串的测试桩。
|
||||||
|
*/
|
||||||
|
function currentPreset(live) {
|
||||||
|
try {
|
||||||
|
const snap = live?.projections?.faceOf?.("permissions")?.getSnapshot?.();
|
||||||
|
if (typeof snap === "string") return snap;
|
||||||
|
if (snap && typeof snap === "object" && typeof snap.currentValue === "string") return snap.currentValue;
|
||||||
|
return;
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 判定会话是否允许执行首次默认自动审查切换:
|
||||||
|
* - 已有对话内容的会话(`blank === false`)不改;
|
||||||
|
* - 子代理会话(`origin === 'subagent'`)不改;
|
||||||
|
* - 其余空白新建会话(以及未提供 blank 元数据的轻量测试桩)允许首次切换。
|
||||||
|
*/
|
||||||
|
function isAutoSwitchEligible(id, live, sessions) {
|
||||||
|
try {
|
||||||
|
if (live?.getSnapshot?.()?.blank === false) return false;
|
||||||
|
const summary = sessions?.list?.getSnapshot?.()?.byId?.[id];
|
||||||
|
if (summary?.blank === false) return false;
|
||||||
|
if (summary?.origin === "subagent") return false;
|
||||||
|
} catch {}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
function loadHandledIds(doc) {
|
||||||
|
const set = /* @__PURE__ */ new Set();
|
||||||
|
try {
|
||||||
|
const raw = (doc?.defaultView?.localStorage)?.getItem?.(HANDLED_STORAGE_KEY);
|
||||||
|
if (typeof raw === "string" && raw) {
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
if (Array.isArray(parsed)) {
|
||||||
|
for (const item of parsed) if (typeof item === "string" && item) set.add(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
return set;
|
||||||
|
}
|
||||||
|
function saveHandledIds(doc, set) {
|
||||||
|
try {
|
||||||
|
const storage = doc?.defaultView?.localStorage;
|
||||||
|
if (!storage?.setItem) return;
|
||||||
|
const items = [...set].slice(-500);
|
||||||
|
storage.setItem(HANDLED_STORAGE_KEY, JSON.stringify(items));
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
|
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
|
||||||
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
|
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
|
||||||
|
|
@ -465,17 +572,23 @@ window.__ModuleLoader__.load({
|
||||||
}
|
}
|
||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
/**
|
const defaultTimers = {
|
||||||
* 安装权限 UI 策略:只观察 DOM、摘掉「完全权限」选项。
|
setInterval: (fn, ms) => setInterval(fn, ms),
|
||||||
* 不接收 getSessions,也不启动任何会话轮询。
|
clearInterval: (id) => clearInterval(id),
|
||||||
* @returns 卸载函数
|
|
||||||
*/
|
|
||||||
function installPermissionPolicy(doc, _getSessions, timers = {
|
|
||||||
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
||||||
clearTimeout: (id) => clearTimeout(id)
|
clearTimeout: (id) => clearTimeout(id)
|
||||||
}) {
|
};
|
||||||
|
/**
|
||||||
|
* 安装权限策略:
|
||||||
|
* 1. 观察 DOM、摘掉「完全权限」选项;
|
||||||
|
* 2. 观察/轮询空白新建会话,首次见到时自动切到 `auto`(自动审查)。
|
||||||
|
* @returns 卸载函数
|
||||||
|
*/
|
||||||
|
function installPermissionPolicy(doc, getSessions, timers = defaultTimers) {
|
||||||
let disposed = false;
|
let disposed = false;
|
||||||
let scanTimer = 0;
|
let scanTimer = 0;
|
||||||
|
const setTimerInterval = timers.setInterval ?? defaultTimers.setInterval;
|
||||||
|
const clearTimerInterval = timers.clearInterval ?? defaultTimers.clearInterval;
|
||||||
const scheduleScan = () => {
|
const scheduleScan = () => {
|
||||||
if (disposed || scanTimer) return;
|
if (disposed || scanTimer) return;
|
||||||
scanTimer = timers.setTimeout(() => {
|
scanTimer = timers.setTimeout(() => {
|
||||||
|
|
@ -489,10 +602,91 @@ window.__ModuleLoader__.load({
|
||||||
subtree: true
|
subtree: true
|
||||||
});
|
});
|
||||||
pruneFullAccess(doc);
|
pruneFullAccess(doc);
|
||||||
|
const handled = loadHandledIds(doc);
|
||||||
|
const inFlight = /* @__PURE__ */ new Set();
|
||||||
|
const projectionUnsubs = /* @__PURE__ */ new Map();
|
||||||
|
let listUnsub;
|
||||||
|
const markHandled = (id) => {
|
||||||
|
if (!handled.has(id)) {
|
||||||
|
handled.add(id);
|
||||||
|
saveHandledIds(doc, handled);
|
||||||
|
}
|
||||||
|
const unsub = projectionUnsubs.get(id);
|
||||||
|
if (unsub) {
|
||||||
|
projectionUnsubs.delete(id);
|
||||||
|
try {
|
||||||
|
unsub();
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const watchProjection = (id, live) => {
|
||||||
|
if (projectionUnsubs.has(id) || handled.has(id)) return;
|
||||||
|
const face = live?.projections?.faceOf?.("permissions");
|
||||||
|
if (typeof face?.subscribe !== "function") return;
|
||||||
|
try {
|
||||||
|
const unsub = face.subscribe(() => {
|
||||||
|
if (!disposed) tick();
|
||||||
|
});
|
||||||
|
if (typeof unsub === "function") projectionUnsubs.set(id, unsub);
|
||||||
|
} catch {}
|
||||||
|
};
|
||||||
|
const tick = async () => {
|
||||||
|
if (disposed || typeof getSessions !== "function") return;
|
||||||
|
let sessions;
|
||||||
|
try {
|
||||||
|
sessions = getSessions();
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!listUnsub && typeof sessions?.list?.subscribe === "function") try {
|
||||||
|
listUnsub = sessions.list.subscribe(() => {
|
||||||
|
if (!disposed) tick();
|
||||||
|
});
|
||||||
|
} catch {}
|
||||||
|
for (const { id, live } of liveSessions(sessions)) {
|
||||||
|
if (handled.has(id) || inFlight.has(id)) continue;
|
||||||
|
if (!isAutoSwitchEligible(id, live, sessions)) {
|
||||||
|
markHandled(id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const preset = currentPreset(live);
|
||||||
|
if (!shouldAutoSwitch(preset, handled.has(id))) {
|
||||||
|
if (preset !== void 0 && preset !== null) markHandled(id);
|
||||||
|
else watchProjection(id, live);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
markHandled(id);
|
||||||
|
if (typeof live?.command !== "function") continue;
|
||||||
|
inFlight.add(id);
|
||||||
|
try {
|
||||||
|
const result = await live.command(`/permission ${AUTO_REVIEW_PRESET}`);
|
||||||
|
if (!result?.ok) console.info("[dsh-better-chat] auto review not applied for session", id, result?.error?.code ?? "");
|
||||||
|
} catch {
|
||||||
|
console.info("[dsh-better-chat] auto review switch failed for session", id);
|
||||||
|
} finally {
|
||||||
|
inFlight.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const intervalId = typeof getSessions === "function" ? setTimerInterval(() => {
|
||||||
|
tick();
|
||||||
|
}, 2500) : 0;
|
||||||
|
if (typeof getSessions === "function") tick();
|
||||||
return () => {
|
return () => {
|
||||||
disposed = true;
|
disposed = true;
|
||||||
observer.disconnect();
|
observer.disconnect();
|
||||||
if (scanTimer) timers.clearTimeout(scanTimer);
|
if (scanTimer) timers.clearTimeout(scanTimer);
|
||||||
|
if (intervalId) clearTimerInterval(intervalId);
|
||||||
|
if (listUnsub) {
|
||||||
|
try {
|
||||||
|
listUnsub();
|
||||||
|
} catch {}
|
||||||
|
listUnsub = void 0;
|
||||||
|
}
|
||||||
|
for (const unsub of projectionUnsubs.values()) try {
|
||||||
|
unsub();
|
||||||
|
} catch {}
|
||||||
|
projectionUnsubs.clear();
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// src/client/chat/store-update.ts
|
// src/client/chat/store-update.ts
|
||||||
|
|
@ -53401,7 +53595,7 @@ ${trimmed}
|
||||||
const getBindings = () => currentBindings(chatPrefs);
|
const getBindings = () => currentBindings(chatPrefs);
|
||||||
ctx.effect(() => install(document, getBindings), "dsh-better-chat: approval key routing");
|
ctx.effect(() => install(document, getBindings), "dsh-better-chat: approval key routing");
|
||||||
ctx.effect(() => installKeyHints(document, { getBindings }), "dsh-better-chat: approval key hints");
|
ctx.effect(() => installKeyHints(document, { getBindings }), "dsh-better-chat: approval key hints");
|
||||||
ctx.effect(() => installPermissionPolicy(document), "dsh-better-chat: permission policy (no full access)");
|
ctx.effect(() => installPermissionPolicy(document, () => ctx.sessions), "dsh-better-chat: permission policy (no full access, auto review by default)");
|
||||||
try {
|
try {
|
||||||
ctx.plugin(storeUpdatePlugin);
|
ctx.plugin(storeUpdatePlugin);
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|
|
||||||
File diff suppressed because one or more lines are too long
72
lib/host.js
72
lib/host.js
|
|
@ -341,9 +341,79 @@ function beginRequest(req, res, route) {
|
||||||
});
|
});
|
||||||
return requestId;
|
return requestId;
|
||||||
}
|
}
|
||||||
|
const AUTO_REVIEW_PRESET = "auto";
|
||||||
|
/**
|
||||||
|
* 判断宿主会话是否为「尚未开始对话、且用户未手动改过权限」的新建空白顶层会话。
|
||||||
|
* - 排除子代理会话(`origin === 'subagent'`)与 fork/seed 会话(`isSeeded` / `inheritedEventCount > 0` / `session/end-seed`);
|
||||||
|
* - 排除已开始轮次或已有用户消息的会话(`turn/start` / `user/message`);
|
||||||
|
* - 排除用户已显式执行过 `/permission` 命令的会话(`command/run` 且 `name === 'permission'`)。
|
||||||
|
*/
|
||||||
|
function isFreshAutoEligibleSession(session) {
|
||||||
|
if (!session || typeof session !== "object") return false;
|
||||||
|
const header = session.header;
|
||||||
|
if (header?.origin === "subagent") return false;
|
||||||
|
if (header?.isSeeded === true) return false;
|
||||||
|
if (typeof session.inheritedEventCount === "number" && session.inheritedEventCount > 0) return false;
|
||||||
|
if (typeof session.snapshotEvents === "function") try {
|
||||||
|
const events = session.snapshotEvents();
|
||||||
|
for (const event of events) if (event?.type === "turn/start" || event?.type === "user/message" || event?.type === "session/end-seed" || event?.type === "command/run" && event?.data?.name === "permission") return false;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
function applyHostAutoReview(permissionPresets, session, handled) {
|
||||||
|
if (!permissionPresets || !session) return false;
|
||||||
|
const id = typeof session.id === "string" ? session.id : typeof session.header?.id === "string" ? session.header.id : void 0;
|
||||||
|
if (id && handled.has(id)) return false;
|
||||||
|
if (!isFreshAutoEligibleSession(session)) {
|
||||||
|
if (id) handled.add(id);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const names = permissionPresets.names;
|
||||||
|
if (!Array.isArray(names) || !names.includes(AUTO_REVIEW_PRESET)) return false;
|
||||||
|
if (id) handled.add(id);
|
||||||
|
try {
|
||||||
|
if (permissionPresets.current?.(session) === AUTO_REVIEW_PRESET) return false;
|
||||||
|
permissionPresets.set?.(session, AUTO_REVIEW_PRESET);
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
log.info("auto review preset switch skipped", {
|
||||||
|
sessionId: id ?? "",
|
||||||
|
error: err instanceof Error ? err.message : String(err)
|
||||||
|
});
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function mountAutoReviewListeners(targetCtx) {
|
||||||
|
const handled = /* @__PURE__ */ new Set();
|
||||||
|
const scanAll = () => {
|
||||||
|
const presets = targetCtx.permissionPresets;
|
||||||
|
const list = targetCtx.agents?.list?.() ?? [];
|
||||||
|
for (const agent of list) if (agent?.session) applyHostAutoReview(presets, agent.session, handled);
|
||||||
|
};
|
||||||
|
targetCtx.effect?.(() => {
|
||||||
|
const offCreated = targetCtx.on?.("agent/created", ({ agent }) => {
|
||||||
|
if (agent?.session) applyHostAutoReview(targetCtx.permissionPresets, agent.session, handled);
|
||||||
|
});
|
||||||
|
const offCatalog = targetCtx.on?.("permission-presets/catalog-changed", () => {
|
||||||
|
scanAll();
|
||||||
|
});
|
||||||
|
scanAll();
|
||||||
|
return () => {
|
||||||
|
if (typeof offCreated === "function") offCreated();
|
||||||
|
if (typeof offCatalog === "function") offCatalog();
|
||||||
|
};
|
||||||
|
}, "dsh-better-chat: default auto-review preset for new sessions");
|
||||||
|
}
|
||||||
function apply(ctx, options) {
|
function apply(ctx, options) {
|
||||||
const flags = options?.flags ?? loadFlags();
|
const flags = options?.flags ?? loadFlags();
|
||||||
log.info("[dsh-better-chat] loaded", { readerEnabled: flags.readerEnabled });
|
log.info("[dsh-better-chat] loaded", { readerEnabled: flags.readerEnabled });
|
||||||
|
const anyCtx = ctx;
|
||||||
|
if (anyCtx.permissionPresets && anyCtx.agents) mountAutoReviewListeners(anyCtx);
|
||||||
|
else if (typeof anyCtx.inject === "function") anyCtx.inject(["permissionPresets", "agents"], (childCtx) => {
|
||||||
|
mountAutoReviewListeners(childCtx);
|
||||||
|
});
|
||||||
if (!flags.readerEnabled) {
|
if (!flags.readerEnabled) {
|
||||||
log.info("route registration skipped", { readerEnabled: false });
|
log.info("route registration skipped", { readerEnabled: false });
|
||||||
return;
|
return;
|
||||||
|
|
@ -377,4 +447,4 @@ function apply(ctx, options) {
|
||||||
};
|
};
|
||||||
}, "dsh-better-chat: reveal and metrics routes");
|
}, "dsh-better-chat: reveal and metrics routes");
|
||||||
}
|
}
|
||||||
export { apply, inject, name };
|
export { apply, applyHostAutoReview, inject, isFreshAutoEligibleSession, name };
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "dsh-better-chat",
|
"name": "dsh-better-chat",
|
||||||
"version": "1.0.0",
|
"version": "1.0.1",
|
||||||
"description": "DSH 聊天增强插件:审批回车批准 / Esc 拒绝、权限 UI、插件商店更新,以及 reading view(合并自 dsh-better-display)",
|
"description": "DSH 聊天增强插件:审批回车批准 / Esc 拒绝、权限 UI、插件商店更新,以及 reading view(合并自 dsh-better-display)",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,19 @@
|
||||||
/**
|
/**
|
||||||
* 功能二:权限 UI —— 去掉「完全权限」选项,不改已有会话权限。
|
* 功能二:权限策略 —— 去掉「完全权限」选项,新会话默认「自动审查」。
|
||||||
*
|
*
|
||||||
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
|
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
|
||||||
* 修改)、danger-full-access(完全权限)、auto(自动审查,EXP)。「自动
|
* 修改)、danger-full-access(完全权限)、auto(自动审查,EXP)。「自动
|
||||||
* 审查」由实验层提供,开启后才出现在当前会话的选择器里;通用设置不提供
|
* 审查」由实验层 @deepseek-ai/dsh-experimental-auto-review 提供,开启后才
|
||||||
* auto,新会话默认值里也选不到它。
|
* 出现在当前会话的选择器里;通用设置不提供 auto,新会话默认值里也选不到它。
|
||||||
*
|
*
|
||||||
* 本功能只做一件事:界面移除完全权限。它**不再**在页面加载、刷新或插件
|
* 本模块做两件事:
|
||||||
* 重载时遍历已有会话改权限:默认权限属于宿主的新建会话流程,本插件没有
|
* 1. 界面移除「完全权限」:观察 DOM,把选择器/菜单/设置下拉里标签为「完全
|
||||||
* 可靠的新建扩展点,因此不拿轮询去补偿。
|
* 权限 / Full access」的选项摘掉。只动界面,手动输入命令仍可达。
|
||||||
|
* 2. 新建/空白会话默认「自动审查」:首次见到空白顶层会话且其权限不是 auto
|
||||||
|
* 时,通过宿主命令通道 `/permission auto` 切过去。已处理过的会话 id 会
|
||||||
|
* 持久化在 localStorage(`dsh.better-chat.permission-handled.v1`),且已
|
||||||
|
* 有对话内容的会话(`blank === false`)和子代理会话不会被改写;用户手
|
||||||
|
* 动切回只读/工作区修改后,刷新或重载也不会被覆盖。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** 完全权限的预设机器值。 */
|
/** 完全权限的预设机器值。 */
|
||||||
|
|
@ -17,6 +22,9 @@ export const FULL_ACCESS_PRESET = 'danger-full-access'
|
||||||
export const AUTO_REVIEW_PRESET = 'auto'
|
export const AUTO_REVIEW_PRESET = 'auto'
|
||||||
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
|
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
|
||||||
export const FULL_ACCESS_LABELS = ['完全权限', 'Full access']
|
export const FULL_ACCESS_LABELS = ['完全权限', 'Full access']
|
||||||
|
/** 已处理会话 id 的浏览器持久化键,避免刷新后覆盖用户手动改过的权限。 */
|
||||||
|
export const HANDLED_STORAGE_KEY = 'dsh.better-chat.permission-handled.v1'
|
||||||
|
const MAX_HANDLED_IDS = 500
|
||||||
|
|
||||||
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
|
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
|
||||||
export function isFullAccessLabel(text: unknown): boolean {
|
export function isFullAccessLabel(text: unknown): boolean {
|
||||||
|
|
@ -30,13 +38,16 @@ export function shouldAutoSwitch(preset: string | undefined | null, alreadyHandl
|
||||||
return preset !== undefined && preset !== null && preset !== AUTO_REVIEW_PRESET && !alreadyHandled
|
return preset !== undefined && preset !== null && preset !== AUTO_REVIEW_PRESET && !alreadyHandled
|
||||||
}
|
}
|
||||||
|
|
||||||
interface LiveSession {
|
export interface LiveSession {
|
||||||
id: string
|
id: string
|
||||||
live: unknown
|
live: any
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 防御式枚举宿主的 live 会话:优先 keys()+binding(),退回 list()。
|
* 防御式枚举宿主的 live 会话:
|
||||||
|
* 1. `keys() + binding()`(测试桩或旧形状)
|
||||||
|
* 2. DSH 0.2.2 `ClientSessions`:`scopes` Map 与 `list.getSnapshot()`(`ids` / `byId`)配合 `binding(id)`
|
||||||
|
* 3. `list()` 函数回退
|
||||||
* 服务形状对不上时安静返回空数组,绝不抛错。
|
* 服务形状对不上时安静返回空数组,绝不抛错。
|
||||||
*/
|
*/
|
||||||
export function liveSessions(sessions: any): LiveSession[] {
|
export function liveSessions(sessions: any): LiveSession[] {
|
||||||
|
|
@ -50,6 +61,30 @@ export function liveSessions(sessions: any): LiveSession[] {
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
if (typeof sessions.binding === 'function' || sessions.scopes instanceof Map) {
|
||||||
|
const seen = new Set<string>()
|
||||||
|
const addCandidate = (id: unknown) => {
|
||||||
|
if (typeof id !== 'string' || !id || seen.has(id)) return
|
||||||
|
const live =
|
||||||
|
(typeof sessions.binding === 'function' ? sessions.binding(id)?.session : undefined) ??
|
||||||
|
(sessions.scopes instanceof Map ? sessions.scopes.get(id)?.binding?.session : undefined)
|
||||||
|
if (live) {
|
||||||
|
seen.add(id)
|
||||||
|
out.push({ id, live })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sessions.scopes instanceof Map) {
|
||||||
|
for (const id of sessions.scopes.keys()) addCandidate(id)
|
||||||
|
}
|
||||||
|
const listSnap = typeof sessions.list?.getSnapshot === 'function' ? sessions.list.getSnapshot() : undefined
|
||||||
|
if (Array.isArray(listSnap?.ids)) {
|
||||||
|
for (const id of listSnap.ids) addCandidate(id)
|
||||||
|
}
|
||||||
|
if (listSnap?.byId && typeof listSnap.byId === 'object') {
|
||||||
|
for (const id of Object.keys(listSnap.byId)) addCandidate(id)
|
||||||
|
}
|
||||||
|
if (out.length > 0 || typeof sessions.list !== 'function') return out
|
||||||
|
}
|
||||||
if (typeof sessions.list === 'function') {
|
if (typeof sessions.list === 'function') {
|
||||||
for (const session of (sessions.list() ?? []) as any[]) {
|
for (const session of (sessions.list() ?? []) as any[]) {
|
||||||
if (session && session.sessionId) out.push({ id: session.sessionId, live: session })
|
if (session && session.sessionId) out.push({ id: session.sessionId, live: session })
|
||||||
|
|
@ -61,15 +96,71 @@ export function liveSessions(sessions: any): LiveSession[] {
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 读会话当前的权限预设值(投影不可用时返回 undefined)。 */
|
/**
|
||||||
|
* 读会话当前的权限预设值(投影不可用时返回 undefined)。
|
||||||
|
* 兼容 DSH 0.2.2 的 `{ currentValue: string }` 投影视图与直接返回字符串的测试桩。
|
||||||
|
*/
|
||||||
export function currentPreset(live: any): string | undefined {
|
export function currentPreset(live: any): string | undefined {
|
||||||
try {
|
try {
|
||||||
return live?.projections?.faceOf('permissions')?.getSnapshot?.()
|
const snap = live?.projections?.faceOf?.('permissions')?.getSnapshot?.()
|
||||||
|
if (typeof snap === 'string') return snap
|
||||||
|
if (snap && typeof snap === 'object' && typeof (snap as { currentValue?: unknown }).currentValue === 'string') {
|
||||||
|
return (snap as { currentValue: string }).currentValue
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
} catch {
|
} catch {
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判定会话是否允许执行首次默认自动审查切换:
|
||||||
|
* - 已有对话内容的会话(`blank === false`)不改;
|
||||||
|
* - 子代理会话(`origin === 'subagent'`)不改;
|
||||||
|
* - 其余空白新建会话(以及未提供 blank 元数据的轻量测试桩)允许首次切换。
|
||||||
|
*/
|
||||||
|
export function isAutoSwitchEligible(id: string, live: any, sessions?: any): boolean {
|
||||||
|
try {
|
||||||
|
if (live?.getSnapshot?.()?.blank === false) return false
|
||||||
|
const summary = sessions?.list?.getSnapshot?.()?.byId?.[id]
|
||||||
|
if (summary?.blank === false) return false
|
||||||
|
if (summary?.origin === 'subagent') return false
|
||||||
|
} catch {
|
||||||
|
// 忽略元数据读取异常
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadHandledIds(doc: Document): Set<string> {
|
||||||
|
const set = new Set<string>()
|
||||||
|
try {
|
||||||
|
const storage = (doc as any)?.defaultView?.localStorage
|
||||||
|
const raw = storage?.getItem?.(HANDLED_STORAGE_KEY)
|
||||||
|
if (typeof raw === 'string' && raw) {
|
||||||
|
const parsed = JSON.parse(raw)
|
||||||
|
if (Array.isArray(parsed)) {
|
||||||
|
for (const item of parsed) {
|
||||||
|
if (typeof item === 'string' && item) set.add(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// localStorage 不可用时仅在内存保存
|
||||||
|
}
|
||||||
|
return set
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveHandledIds(doc: Document, set: Set<string>): void {
|
||||||
|
try {
|
||||||
|
const storage = (doc as any)?.defaultView?.localStorage
|
||||||
|
if (!storage?.setItem) return
|
||||||
|
const items = [...set].slice(-MAX_HANDLED_IDS)
|
||||||
|
storage.setItem(HANDLED_STORAGE_KEY, JSON.stringify(items))
|
||||||
|
} catch {
|
||||||
|
// 忽略写入异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
|
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
|
||||||
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
|
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
|
||||||
|
|
@ -93,25 +184,34 @@ export function pruneFullAccess(doc: Document): number {
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PolicyTimers {
|
export interface PolicyTimers {
|
||||||
|
setInterval?: (fn: () => void, ms: number) => number
|
||||||
|
clearInterval?: (id: number) => void
|
||||||
setTimeout: (fn: () => void, ms: number) => number
|
setTimeout: (fn: () => void, ms: number) => number
|
||||||
clearTimeout: (id: number) => void
|
clearTimeout: (id: number) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const defaultTimers: Required<PolicyTimers> = {
|
||||||
|
setInterval: (fn, ms) => setInterval(fn, ms) as unknown as number,
|
||||||
|
clearInterval: (id) => clearInterval(id),
|
||||||
|
setTimeout: (fn, ms) => setTimeout(fn, ms) as unknown as number,
|
||||||
|
clearTimeout: (id) => clearTimeout(id),
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 安装权限 UI 策略:只观察 DOM、摘掉「完全权限」选项。
|
* 安装权限策略:
|
||||||
* 不接收 getSessions,也不启动任何会话轮询。
|
* 1. 观察 DOM、摘掉「完全权限」选项;
|
||||||
|
* 2. 观察/轮询空白新建会话,首次见到时自动切到 `auto`(自动审查)。
|
||||||
* @returns 卸载函数
|
* @returns 卸载函数
|
||||||
*/
|
*/
|
||||||
export function installPermissionPolicy(
|
export function installPermissionPolicy(
|
||||||
doc: Document,
|
doc: Document,
|
||||||
_getSessions?: unknown,
|
getSessions?: () => any,
|
||||||
timers: PolicyTimers = {
|
timers: PolicyTimers = defaultTimers,
|
||||||
setTimeout: (fn, ms) => setTimeout(fn, ms) as unknown as number,
|
|
||||||
clearTimeout: (id) => clearTimeout(id),
|
|
||||||
},
|
|
||||||
): () => void {
|
): () => void {
|
||||||
let disposed = false
|
let disposed = false
|
||||||
let scanTimer = 0
|
let scanTimer = 0
|
||||||
|
const setTimerInterval = timers.setInterval ?? defaultTimers.setInterval
|
||||||
|
const clearTimerInterval = timers.clearInterval ?? defaultTimers.clearInterval
|
||||||
const scheduleScan = (): void => {
|
const scheduleScan = (): void => {
|
||||||
if (disposed || scanTimer) return
|
if (disposed || scanTimer) return
|
||||||
scanTimer = timers.setTimeout(() => {
|
scanTimer = timers.setTimeout(() => {
|
||||||
|
|
@ -123,9 +223,100 @@ export function installPermissionPolicy(
|
||||||
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
|
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
|
||||||
pruneFullAccess(doc)
|
pruneFullAccess(doc)
|
||||||
|
|
||||||
|
const handled = loadHandledIds(doc)
|
||||||
|
const inFlight = new Set<string>()
|
||||||
|
const projectionUnsubs = new Map<string, () => void>()
|
||||||
|
let listUnsub: (() => void) | undefined
|
||||||
|
|
||||||
|
const markHandled = (id: string): void => {
|
||||||
|
if (!handled.has(id)) {
|
||||||
|
handled.add(id)
|
||||||
|
saveHandledIds(doc, handled)
|
||||||
|
}
|
||||||
|
const unsub = projectionUnsubs.get(id)
|
||||||
|
if (unsub) {
|
||||||
|
projectionUnsubs.delete(id)
|
||||||
|
try { unsub() } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const watchProjection = (id: string, live: any): void => {
|
||||||
|
if (projectionUnsubs.has(id) || handled.has(id)) return
|
||||||
|
const face = live?.projections?.faceOf?.('permissions')
|
||||||
|
if (typeof face?.subscribe !== 'function') return
|
||||||
|
try {
|
||||||
|
const unsub = face.subscribe(() => {
|
||||||
|
if (!disposed) void tick()
|
||||||
|
})
|
||||||
|
if (typeof unsub === 'function') projectionUnsubs.set(id, unsub)
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = async (): Promise<void> => {
|
||||||
|
if (disposed || typeof getSessions !== 'function') return
|
||||||
|
let sessions: any
|
||||||
|
try {
|
||||||
|
sessions = getSessions()
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!listUnsub && typeof sessions?.list?.subscribe === 'function') {
|
||||||
|
try {
|
||||||
|
listUnsub = sessions.list.subscribe(() => {
|
||||||
|
if (!disposed) void tick()
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const { id, live } of liveSessions(sessions)) {
|
||||||
|
if (handled.has(id) || inFlight.has(id)) continue
|
||||||
|
if (!isAutoSwitchEligible(id, live, sessions)) {
|
||||||
|
markHandled(id)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const preset = currentPreset(live)
|
||||||
|
if (!shouldAutoSwitch(preset, handled.has(id))) {
|
||||||
|
if (preset !== undefined && preset !== null) {
|
||||||
|
markHandled(id)
|
||||||
|
} else {
|
||||||
|
watchProjection(id, live)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
markHandled(id)
|
||||||
|
if (typeof live?.command !== 'function') continue
|
||||||
|
inFlight.add(id)
|
||||||
|
try {
|
||||||
|
const result = await live.command(`/permission ${AUTO_REVIEW_PRESET}`)
|
||||||
|
if (!result?.ok) {
|
||||||
|
console.info('[dsh-better-chat] auto review not applied for session', id, result?.error?.code ?? '')
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
console.info('[dsh-better-chat] auto review switch failed for session', id)
|
||||||
|
} finally {
|
||||||
|
inFlight.delete(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const intervalId = typeof getSessions === 'function' ? setTimerInterval(() => { void tick() }, 2500) : 0
|
||||||
|
if (typeof getSessions === 'function') void tick()
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
disposed = true
|
disposed = true
|
||||||
observer.disconnect()
|
observer.disconnect()
|
||||||
if (scanTimer) timers.clearTimeout(scanTimer)
|
if (scanTimer) timers.clearTimeout(scanTimer)
|
||||||
|
if (intervalId) clearTimerInterval(intervalId)
|
||||||
|
if (listUnsub) {
|
||||||
|
try { listUnsub() } catch { /* ignore */ }
|
||||||
|
listUnsub = undefined
|
||||||
|
}
|
||||||
|
for (const unsub of projectionUnsubs.values()) {
|
||||||
|
try { unsub() } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
projectionUnsubs.clear()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,8 @@ export function apply(ctx: Context): void {
|
||||||
ctx.effect(() => installApprovalKeys(document, getBindings), 'dsh-better-chat: approval key routing')
|
ctx.effect(() => installApprovalKeys(document, getBindings), 'dsh-better-chat: approval key routing')
|
||||||
ctx.effect(() => installKeyHints(document, { getBindings }), 'dsh-better-chat: approval key hints')
|
ctx.effect(() => installKeyHints(document, { getBindings }), 'dsh-better-chat: approval key hints')
|
||||||
ctx.effect(
|
ctx.effect(
|
||||||
() => installPermissionPolicy(document),
|
() => installPermissionPolicy(document, () => (ctx as { sessions?: unknown }).sessions),
|
||||||
'dsh-better-chat: permission policy (no full access)',
|
'dsh-better-chat: permission policy (no full access, auto review by default)',
|
||||||
)
|
)
|
||||||
try {
|
try {
|
||||||
ctx.plugin(storeUpdatePlugin as any)
|
ctx.plugin(storeUpdatePlugin as any)
|
||||||
|
|
|
||||||
99
src/host.ts
99
src/host.ts
|
|
@ -46,9 +46,108 @@ function beginRequest(req: IncomingMessage, res: ServerResponse, route: string):
|
||||||
return requestId;
|
return requestId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const AUTO_REVIEW_PRESET = 'auto';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断宿主会话是否为「尚未开始对话、且用户未手动改过权限」的新建空白顶层会话。
|
||||||
|
* - 排除子代理会话(`origin === 'subagent'`)与 fork/seed 会话(`isSeeded` / `inheritedEventCount > 0` / `session/end-seed`);
|
||||||
|
* - 排除已开始轮次或已有用户消息的会话(`turn/start` / `user/message`);
|
||||||
|
* - 排除用户已显式执行过 `/permission` 命令的会话(`command/run` 且 `name === 'permission'`)。
|
||||||
|
*/
|
||||||
|
export function isFreshAutoEligibleSession(session: any): boolean {
|
||||||
|
if (!session || typeof session !== 'object') return false;
|
||||||
|
const header = session.header;
|
||||||
|
if (header?.origin === 'subagent') return false;
|
||||||
|
if (header?.isSeeded === true) return false;
|
||||||
|
if (typeof session.inheritedEventCount === 'number' && session.inheritedEventCount > 0) return false;
|
||||||
|
if (typeof session.snapshotEvents === 'function') {
|
||||||
|
try {
|
||||||
|
const events = session.snapshotEvents() as Array<{ type?: string; data?: { name?: string } }>;
|
||||||
|
for (const event of events) {
|
||||||
|
if (
|
||||||
|
event?.type === 'turn/start'
|
||||||
|
|| event?.type === 'user/message'
|
||||||
|
|| event?.type === 'session/end-seed'
|
||||||
|
|| (event?.type === 'command/run' && event?.data?.name === 'permission')
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyHostAutoReview(permissionPresets: any, session: any, handled: Set<string>): boolean {
|
||||||
|
if (!permissionPresets || !session) return false;
|
||||||
|
const id: string | undefined = typeof session.id === 'string'
|
||||||
|
? session.id
|
||||||
|
: typeof session.header?.id === 'string'
|
||||||
|
? session.header.id
|
||||||
|
: undefined;
|
||||||
|
if (id && handled.has(id)) return false;
|
||||||
|
if (!isFreshAutoEligibleSession(session)) {
|
||||||
|
if (id) handled.add(id);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const names: unknown = permissionPresets.names;
|
||||||
|
if (!Array.isArray(names) || !names.includes(AUTO_REVIEW_PRESET)) {
|
||||||
|
// 实验层 auto-review 尚未就绪:暂不记入 handled,待 catalog-changed 时再切。
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (id) handled.add(id);
|
||||||
|
try {
|
||||||
|
if (permissionPresets.current?.(session) === AUTO_REVIEW_PRESET) return false;
|
||||||
|
permissionPresets.set?.(session, AUTO_REVIEW_PRESET);
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
log.info('auto review preset switch skipped', {
|
||||||
|
sessionId: id ?? '',
|
||||||
|
error: err instanceof Error ? err.message : String(err),
|
||||||
|
});
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mountAutoReviewListeners(targetCtx: any): void {
|
||||||
|
const handled = new Set<string>();
|
||||||
|
const scanAll = (): void => {
|
||||||
|
const presets = targetCtx.permissionPresets;
|
||||||
|
const list = targetCtx.agents?.list?.() ?? [];
|
||||||
|
for (const agent of list) {
|
||||||
|
if (agent?.session) applyHostAutoReview(presets, agent.session, handled);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
targetCtx.effect?.(() => {
|
||||||
|
const offCreated = targetCtx.on?.('agent/created', ({ agent }: { agent?: { session?: unknown } }) => {
|
||||||
|
if (agent?.session) applyHostAutoReview(targetCtx.permissionPresets, agent.session, handled);
|
||||||
|
});
|
||||||
|
const offCatalog = targetCtx.on?.('permission-presets/catalog-changed', () => {
|
||||||
|
scanAll();
|
||||||
|
});
|
||||||
|
scanAll();
|
||||||
|
return () => {
|
||||||
|
if (typeof offCreated === 'function') offCreated();
|
||||||
|
if (typeof offCatalog === 'function') offCatalog();
|
||||||
|
};
|
||||||
|
}, 'dsh-better-chat: default auto-review preset for new sessions');
|
||||||
|
}
|
||||||
|
|
||||||
export function apply(ctx: Context, options?: { readonly flags?: Flags }): void {
|
export function apply(ctx: Context, options?: { readonly flags?: Flags }): void {
|
||||||
const flags = options?.flags ?? loadFlags();
|
const flags = options?.flags ?? loadFlags();
|
||||||
log.info('[dsh-better-chat] loaded', { readerEnabled: flags.readerEnabled });
|
log.info('[dsh-better-chat] loaded', { readerEnabled: flags.readerEnabled });
|
||||||
|
|
||||||
|
const anyCtx = ctx as any;
|
||||||
|
if (anyCtx.permissionPresets && anyCtx.agents) {
|
||||||
|
mountAutoReviewListeners(anyCtx);
|
||||||
|
} else if (typeof anyCtx.inject === 'function') {
|
||||||
|
anyCtx.inject(['permissionPresets', 'agents'], (childCtx: any) => {
|
||||||
|
mountAutoReviewListeners(childCtx);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (!flags.readerEnabled) {
|
if (!flags.readerEnabled) {
|
||||||
log.info('route registration skipped', { readerEnabled: false });
|
log.info('route registration skipped', { readerEnabled: false });
|
||||||
return;
|
return;
|
||||||
|
|
|
||||||
|
|
@ -4,13 +4,16 @@ import { test } from 'vitest'
|
||||||
import {
|
import {
|
||||||
AUTO_REVIEW_PRESET,
|
AUTO_REVIEW_PRESET,
|
||||||
FULL_ACCESS_PRESET,
|
FULL_ACCESS_PRESET,
|
||||||
|
HANDLED_STORAGE_KEY,
|
||||||
currentPreset,
|
currentPreset,
|
||||||
installPermissionPolicy,
|
installPermissionPolicy,
|
||||||
|
isAutoSwitchEligible,
|
||||||
isFullAccessLabel,
|
isFullAccessLabel,
|
||||||
liveSessions,
|
liveSessions,
|
||||||
pruneFullAccess,
|
pruneFullAccess,
|
||||||
shouldAutoSwitch,
|
shouldAutoSwitch,
|
||||||
} from '../../src/client/chat/permission-policy.ts'
|
} from '../../src/client/chat/permission-policy.ts'
|
||||||
|
import { apply as applyHost, applyHostAutoReview, isFreshAutoEligibleSession } from '../../src/host.ts'
|
||||||
|
|
||||||
;(globalThis as any).MutationObserver = class { observe() {} disconnect() {} }
|
;(globalThis as any).MutationObserver = class { observe() {} disconnect() {} }
|
||||||
|
|
||||||
|
|
@ -57,10 +60,26 @@ test('pruneFullAccess removes full-access from selects, listboxes and menus', ()
|
||||||
assert.deepEqual(items.map((o) => o.removed), [false, true, true, false])
|
assert.deepEqual(items.map((o) => o.removed), [false, true, true, false])
|
||||||
})
|
})
|
||||||
|
|
||||||
test('liveSessions: keys+binding, list fallback, hostile shapes', () => {
|
test('liveSessions: keys+binding, ClientSessions list.getSnapshot/scopes, list() fallback, hostile shapes', () => {
|
||||||
const live = { sessionId: 's1' }
|
const live = { sessionId: 's1' }
|
||||||
const viaKeys = liveSessions({ keys: () => ['s1', 's2'], binding: (id: string) => (id === 's1' ? { session: live } : undefined) })
|
const viaKeys = liveSessions({ keys: () => ['s1', 's2'], binding: (id: string) => (id === 's1' ? { session: live } : undefined) })
|
||||||
assert.deepEqual(viaKeys.map((x) => x.id), ['s1'])
|
assert.deepEqual(viaKeys.map((x) => x.id), ['s1'])
|
||||||
|
|
||||||
|
const live2 = { sessionId: 's2' }
|
||||||
|
const viaClientSessions = liveSessions({
|
||||||
|
list: { getSnapshot: () => ({ ids: ['s1', 's2'], byId: { s1: { id: 's1' }, s2: { id: 's2' } } }) },
|
||||||
|
binding: (id: string) => (id === 's2' ? { session: live2 } : undefined),
|
||||||
|
})
|
||||||
|
assert.deepEqual(viaClientSessions.map((x) => x.id), ['s2'])
|
||||||
|
|
||||||
|
const scopes = new Map([['s3', { binding: { session: { sessionId: 's3' } } }]])
|
||||||
|
const viaScopes = liveSessions({
|
||||||
|
scopes,
|
||||||
|
list: { getSnapshot: () => ({ ids: [], byId: {} }) },
|
||||||
|
binding: (id: string) => scopes.get(id)?.binding,
|
||||||
|
})
|
||||||
|
assert.deepEqual(viaScopes.map((x) => x.id), ['s3'])
|
||||||
|
|
||||||
const viaList = liveSessions({ list: () => [{ sessionId: 'a' }, { nope: 1 }] })
|
const viaList = liveSessions({ list: () => [{ sessionId: 'a' }, { nope: 1 }] })
|
||||||
assert.deepEqual(viaList.map((x) => x.id), ['a'])
|
assert.deepEqual(viaList.map((x) => x.id), ['a'])
|
||||||
assert.deepEqual(liveSessions({ keys: () => { throw new Error('x') } }), [])
|
assert.deepEqual(liveSessions({ keys: () => { throw new Error('x') } }), [])
|
||||||
|
|
@ -68,9 +87,11 @@ test('liveSessions: keys+binding, list fallback, hostile shapes', () => {
|
||||||
assert.deepEqual(liveSessions(42), [])
|
assert.deepEqual(liveSessions(42), [])
|
||||||
})
|
})
|
||||||
|
|
||||||
test('currentPreset reads the permissions projection defensively', () => {
|
test('currentPreset reads both string and { currentValue } permissions projections defensively', () => {
|
||||||
const live = { projections: { faceOf: (n: string) => (n === 'permissions' ? { getSnapshot: () => 'workspace-write' } : undefined) } }
|
const strLive = { projections: { faceOf: (n: string) => (n === 'permissions' ? { getSnapshot: () => 'workspace-write' } : undefined) } }
|
||||||
assert.equal(currentPreset(live), 'workspace-write')
|
assert.equal(currentPreset(strLive), 'workspace-write')
|
||||||
|
const objLive = { projections: { faceOf: (n: string) => (n === 'permissions' ? { getSnapshot: () => ({ currentValue: 'auto' }) } : undefined) } }
|
||||||
|
assert.equal(currentPreset(objLive), 'auto')
|
||||||
assert.equal(currentPreset({}), undefined)
|
assert.equal(currentPreset({}), undefined)
|
||||||
assert.equal(currentPreset({ projections: { faceOf: () => { throw new Error('x') } } }), undefined)
|
assert.equal(currentPreset({ projections: { faceOf: () => { throw new Error('x') } } }), undefined)
|
||||||
})
|
})
|
||||||
|
|
@ -88,23 +109,168 @@ function fakeTimers() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
test('policy: page load and refresh never change existing session permissions', async () => {
|
function fakeLive(preset: string | { currentValue: string }, fail = false, blank?: boolean) {
|
||||||
const timers = fakeTimers()
|
|
||||||
const calls: string[] = []
|
const calls: string[] = []
|
||||||
const live = { projections: { faceOf: () => ({ getSnapshot: () => 'read-only' }) }, command: async (text: string) => { calls.push(text); return { ok: true } } }
|
return {
|
||||||
const sessions = { keys: () => ['s1'], binding: () => ({ session: live }) }
|
calls,
|
||||||
|
...(blank === undefined ? {} : { getSnapshot: () => ({ blank }) }),
|
||||||
|
projections: { faceOf: () => ({ getSnapshot: () => preset }) },
|
||||||
|
async command(text: string) {
|
||||||
|
calls.push(text)
|
||||||
|
if (fail) return { ok: false, error: { code: 'unavailable' } }
|
||||||
|
return { ok: true, value: { matched: true } }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fakeStorage() {
|
||||||
|
const map = new Map<string, string>()
|
||||||
|
return {
|
||||||
|
getItem: (k: string) => map.get(k) ?? null,
|
||||||
|
setItem: (k: string, v: string) => { map.set(k, v) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test('policy: first sight of a new blank session switches it to auto once', async () => {
|
||||||
|
const timers = fakeTimers()
|
||||||
|
const live = fakeLive({ currentValue: 'workspace-write' }, false, true)
|
||||||
|
const sessions = {
|
||||||
|
list: { getSnapshot: () => ({ ids: ['s1'], byId: { s1: { id: 's1', blank: true } } }) },
|
||||||
|
binding: (id: string) => (id === 's1' ? { session: live } : undefined),
|
||||||
|
}
|
||||||
const doc = { body: {}, querySelectorAll: () => [] }
|
const doc = { body: {}, querySelectorAll: () => [] }
|
||||||
const dispose = installPermissionPolicy(doc as any, () => sessions, timers as any)
|
const dispose = installPermissionPolicy(doc as any, () => sessions, timers as any)
|
||||||
await timers.runIntervals()
|
await timers.runIntervals()
|
||||||
await timers.runIntervals()
|
await timers.runIntervals()
|
||||||
assert.deepEqual(calls, [], '已有只读会话不能被自动切到 auto')
|
assert.deepEqual(live.calls, ['/permission auto'])
|
||||||
dispose()
|
dispose()
|
||||||
assert.equal(timers.size, 0)
|
assert.equal(timers.size, 0)
|
||||||
|
})
|
||||||
|
|
||||||
// A second mount (the page reload path) must not touch it either.
|
test('policy: already-auto sessions are left alone; failures are not retried', async () => {
|
||||||
|
const timers = fakeTimers()
|
||||||
|
const autoLive = fakeLive('auto')
|
||||||
|
const failLive = fakeLive('read-only', true)
|
||||||
|
const sessions = {
|
||||||
|
keys: () => ['a', 'b'],
|
||||||
|
binding: (id: string) => ({ session: id === 'a' ? autoLive : failLive }),
|
||||||
|
}
|
||||||
|
const doc = { body: {}, querySelectorAll: () => [] }
|
||||||
|
const dispose = installPermissionPolicy(doc as any, () => sessions, timers as any)
|
||||||
|
await timers.runIntervals()
|
||||||
|
await timers.runIntervals()
|
||||||
|
assert.deepEqual(autoLive.calls, [])
|
||||||
|
assert.deepEqual(failLive.calls, ['/permission auto'])
|
||||||
|
dispose()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('policy: existing non-blank sessions and refreshed handled sessions are never overwritten', async () => {
|
||||||
|
const localStorage = fakeStorage()
|
||||||
|
const doc = { body: {}, defaultView: { localStorage }, querySelectorAll: () => [] }
|
||||||
|
|
||||||
|
// 1) An existing conversation (blank: false) is never switched on load.
|
||||||
|
const existingLive = fakeLive({ currentValue: 'read-only' }, false, false)
|
||||||
|
// 2) A brand-new blank session is switched once on first sight.
|
||||||
|
let blankPreset = 'workspace-write'
|
||||||
|
const blankCalls: string[] = []
|
||||||
|
const blankLive = {
|
||||||
|
getSnapshot: () => ({ blank: true }),
|
||||||
|
projections: { faceOf: () => ({ getSnapshot: () => ({ currentValue: blankPreset }) }) },
|
||||||
|
async command(text: string) {
|
||||||
|
blankCalls.push(text)
|
||||||
|
blankPreset = 'auto'
|
||||||
|
return { ok: true, value: { matched: true } }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
const sessions = {
|
||||||
|
list: {
|
||||||
|
getSnapshot: () => ({
|
||||||
|
ids: ['existing-1', 'blank-1'],
|
||||||
|
byId: {
|
||||||
|
'existing-1': { id: 'existing-1', blank: false },
|
||||||
|
'blank-1': { id: 'blank-1', blank: true },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
binding: (id: string) => {
|
||||||
|
if (id === 'existing-1') return { session: existingLive }
|
||||||
|
if (id === 'blank-1') return { session: blankLive }
|
||||||
|
return undefined
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
const timers1 = fakeTimers()
|
||||||
|
const dispose1 = installPermissionPolicy(doc as any, () => sessions, timers1 as any)
|
||||||
|
await timers1.runIntervals()
|
||||||
|
assert.deepEqual(existingLive.calls, [], '已有对话(blank=false)不得被自动切到 auto')
|
||||||
|
assert.deepEqual(blankCalls, ['/permission auto'], '新建空白会话首次见到时应切到 auto')
|
||||||
|
dispose1()
|
||||||
|
|
||||||
|
// User manually switches blank-1 to read-only, then reloads the page (second mount).
|
||||||
|
blankPreset = 'read-only'
|
||||||
|
assert.ok(localStorage.getItem(HANDLED_STORAGE_KEY)?.includes('blank-1'))
|
||||||
const timers2 = fakeTimers()
|
const timers2 = fakeTimers()
|
||||||
const dispose2 = installPermissionPolicy(doc as any, () => sessions, timers2 as any)
|
const dispose2 = installPermissionPolicy(doc as any, () => sessions, timers2 as any)
|
||||||
await timers2.runIntervals()
|
await timers2.runIntervals()
|
||||||
assert.deepEqual(calls, [], '刷新后再次挂载也不能改权限')
|
assert.deepEqual(blankCalls, ['/permission auto'], '刷新后不得覆盖用户手动改过的会话权限')
|
||||||
|
assert.equal(isAutoSwitchEligible('sub-1', {}, { list: { getSnapshot: () => ({ byId: { 'sub-1': { origin: 'subagent' } } }) } }), false)
|
||||||
dispose2()
|
dispose2()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('host auto-review default: switches fresh blank sessions and skips used/subagent/manual sessions', () => {
|
||||||
|
assert.equal(isFreshAutoEligibleSession({ header: { id: 's1' }, snapshotEvents: () => [{ type: 'permission/preset', data: { preset: 'workspace-write' } }] }), true)
|
||||||
|
assert.equal(isFreshAutoEligibleSession({ header: { id: 's2', origin: 'subagent' }, snapshotEvents: () => [] }), false)
|
||||||
|
assert.equal(isFreshAutoEligibleSession({ header: { id: 's3', isSeeded: true }, snapshotEvents: () => [] }), false)
|
||||||
|
assert.equal(isFreshAutoEligibleSession({ header: { id: 's4' }, snapshotEvents: () => [{ type: 'turn/start' }] }), false)
|
||||||
|
assert.equal(isFreshAutoEligibleSession({ header: { id: 's5' }, snapshotEvents: () => [{ type: 'command/run', data: { name: 'permission' } }] }), false)
|
||||||
|
|
||||||
|
const setCalls: Array<[string, string]> = []
|
||||||
|
let catalogNames = ['read-only', 'workspace-write']
|
||||||
|
let currentPresetVal = 'workspace-write'
|
||||||
|
const listeners = new Map<string, (payload?: any) => void>()
|
||||||
|
const session1 = {
|
||||||
|
id: 'fresh-1',
|
||||||
|
header: { id: 'fresh-1' },
|
||||||
|
snapshotEvents: () => [{ type: 'permission/preset', data: { preset: 'workspace-write' } }],
|
||||||
|
}
|
||||||
|
const permissionPresets = {
|
||||||
|
get names() { return catalogNames },
|
||||||
|
current: () => currentPresetVal,
|
||||||
|
set: (s: any, name: string) => {
|
||||||
|
setCalls.push([s.id, name])
|
||||||
|
currentPresetVal = name
|
||||||
|
},
|
||||||
|
}
|
||||||
|
const agents = { list: () => [{ session: session1 }] }
|
||||||
|
|
||||||
|
applyHost({
|
||||||
|
permissionPresets,
|
||||||
|
agents,
|
||||||
|
effect(run: () => void) { run() },
|
||||||
|
on(event: string, fn: (payload?: any) => void) {
|
||||||
|
listeners.set(event, fn)
|
||||||
|
return () => { listeners.delete(event) }
|
||||||
|
},
|
||||||
|
} as any, { flags: { readerEnabled: false } })
|
||||||
|
|
||||||
|
// Before 'auto' is registered in permissionPresets.names, nothing is switched yet.
|
||||||
|
assert.deepEqual(setCalls, [])
|
||||||
|
|
||||||
|
// Once auto-review registers 'auto' and emits catalog-changed, fresh-1 is switched to 'auto'.
|
||||||
|
catalogNames = ['read-only', 'workspace-write', 'auto']
|
||||||
|
listeners.get('permission-presets/catalog-changed')?.()
|
||||||
|
assert.deepEqual(setCalls, [['fresh-1', 'auto']])
|
||||||
|
|
||||||
|
// User later switches fresh-1 to read-only; another catalog-changed or agent/created does not overwrite it.
|
||||||
|
currentPresetVal = 'read-only'
|
||||||
|
listeners.get('permission-presets/catalog-changed')?.()
|
||||||
|
assert.deepEqual(setCalls, [['fresh-1', 'auto']])
|
||||||
|
|
||||||
|
// A new agent/created with a fresh session is switched immediately.
|
||||||
|
const session2 = { id: 'fresh-2', header: { id: 'fresh-2' }, snapshotEvents: () => [] }
|
||||||
|
listeners.get('agent/created')?.({ agent: { session: session2 } })
|
||||||
|
assert.deepEqual(setCalls, [['fresh-1', 'auto'], ['fresh-2', 'auto']])
|
||||||
|
|
||||||
|
// Direct helper coverage when already auto.
|
||||||
|
assert.equal(applyHostAutoReview(permissionPresets, session2, new Set()), false)
|
||||||
|
})
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue