Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:wrench: Add iOS keyboard shortcut diagnostics https://github.com/siyuan-note/siyuan/issues/20006

Daniel42948a34dc75
diff --git a/app/src/boot/globalEvent/commonHotkey.ts b/app/src/boot/globalEvent/commonHotkey.ts
index bb0dbb93cc..8b76a0735f 100644
--- a/app/src/boot/globalEvent/commonHotkey.ts
+++ b/app/src/boot/globalEvent/commonHotkey.ts
@@ -11,6 +11,7 @@ import {isMac, isNotCtrl, isOnlyMeta} from "../../protyle/util/compatibility";
import {showPopover} from "../../block/popover";
import {clearDisallowedKeymapItems} from "../../util/hotKeyPolicy";
import {getHostCapabilities} from "../../util/hostCapabilities";
+import {logKeyboardDiagnostic} from "../../util/keyboardDiagnostic";
const matchKeymap = (keymap: Config.IKeys, key1: "general" | "editor", key2?: "general" | "insert" | "heading" | "list" | "table") => {
if (key1 === "general") {
@@ -199,6 +200,8 @@ export const syncAppMenuShortcuts = (suspended = false) => {
export const filterHotkey = (event: KeyboardEvent, app: App) => {
// https://github.com/siyuan-note/siyuan/issues/9848 忘记为什么要阻止了 .av__mask 的情况,测了下没问题就先移除
if (document.getElementById("progress") || document.getElementById("errorLog") || event.isComposing) {
+ logKeyboardDiagnostic("filter-stop", event, document.getElementById("progress") ? "progress" :
+ document.getElementById("errorLog") ? "error-log" : "composing");
return true;
}
const target = event.target as HTMLElement;
@@ -218,6 +221,7 @@ export const filterHotkey = (event: KeyboardEvent, app: App) => {
cardElement = document.querySelector(`.layout__wnd--active div[data-key="${Constants.DIALOG_OPENCARD}"]:not(.fn__none)`);
}
if (cardElement) {
+ logKeyboardDiagnostic("filter-stop", event, "card-key");
event.preventDefault();
cardElement.firstElementChild.dispatchEvent(new CustomEvent("click", {detail: event.key.toLowerCase()}));
return true;
@@ -230,6 +234,7 @@ export const filterHotkey = (event: KeyboardEvent, app: App) => {
Constants.KEYCODELIST[event.keyCode] !== "PageDown" &&
event.key !== "Home" && event.key !== "End" &&
!/^F\d{1,2}$/.test(event.key) && event.key.indexOf("Arrow") === -1 && event.key !== "Enter" && event.key !== "Backspace" && event.key !== "Delete") {
+ logKeyboardDiagnostic("filter-stop", event, "plain-key");
return true;
}
diff --git a/app/src/boot/globalEvent/event.ts b/app/src/boot/globalEvent/event.ts
index f47f641afd..5ce299bdf3 100644
--- a/app/src/boot/globalEvent/event.ts
+++ b/app/src/boot/globalEvent/event.ts
@@ -19,10 +19,12 @@ import {initHarmonyTextSelectionMenu} from "../../util/harmonyTextSelectionMenu"
import {clearDragTipGhost, hideDragTip} from "../../protyle/util/dragTip";
import {formatPainter} from "../../protyle/toolbar/FormatPainter";
import {SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE} from "../../protyle/toolbar/subElementLifecycle";
+import {initKeyboardDiagnostics} from "../../util/keyboardDiagnostic";
const KANBAN_GROUP_DRAG_TYPE = `${Constants.SIYUAN_DROP_GUTTER}NodeAttributeView${Constants.ZWSP}Group${Constants.ZWSP}`.toLowerCase();
export const initWindowEvent = (app: App) => {
+ initKeyboardDiagnostics("desktop");
initHarmonyTextSelectionMenu();
let lastEncryptedNotebookTouch = 0;
const touchEncryptedNotebooks = () => {
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 0738809943..02e90625ec 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -1,4 +1,5 @@
import type {BlockQueryRequestInput} from "../../types/api";
+import {logKeyboardDiagnostic} from "../../util/keyboardDiagnostic";
import {isAbove} from "../../util/zIndex";
import {stripSemanticMarkersFromRangeText} from "../../protyle/util/inlineElementMarker";
import {
@@ -1318,7 +1319,9 @@ const panelTreeKeydown = (app: App, event: KeyboardEvent) => {
let switchDialog: Dialog;
export const windowKeyDown = (app: App, event: KeyboardEvent) => {
+ logKeyboardDiagnostic("window-enter", event);
if (event.defaultPrevented || filterHotkey(event, app)) {
+ logKeyboardDiagnostic("window-stop", event, event.defaultPrevented ? "default-prevented" : "filtered");
return;
}
if (switchDialog &&
@@ -1329,6 +1332,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
}
if (searchKeydown(app, event)) {
+ logKeyboardDiagnostic("window-stop", event, "search-keydown");
event.preventDefault();
event.stopPropagation();
return;
@@ -1336,11 +1340,13 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
const isTabWindow = isWindow();
if (bindMenuKeydown(event)) {
+ logKeyboardDiagnostic("window-stop", event, "menu-keydown");
event.preventDefault();
return;
}
if (bindAVPanelKeydown(event)) {
+ logKeyboardDiagnostic("window-stop", event, "av-panel");
event.preventDefault();
return;
}
@@ -1361,6 +1367,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
// 只读正文无法获得焦点,跨块选区的 Esc 不应按上一次活动面板分派。
if (!readonlyBlockSelection && !shortcutTarget.closest("input, textarea, .b3-menu, .av__panel, .av__mask")) {
if (shortcutTarget.closest(".protyle") && editKeydown(app, event)) {
+ logKeyboardDiagnostic("window-stop", event, "editor-handled");
return;
}
if (!isTabWindow && shortcutTarget.closest(".sy__file") && fileTreeKeydown(app, event)) {
diff --git a/app/src/boot/globalEvent/readonlyKeydown.test.ts b/app/src/boot/globalEvent/readonlyKeydown.test.ts
index 5a612b4cdf..fed9f864c9 100644
--- a/app/src/boot/globalEvent/readonlyKeydown.test.ts
+++ b/app/src/boot/globalEvent/readonlyKeydown.test.ts
@@ -13,7 +13,7 @@ const loadFunction = (path: string, name: string, globals: Record<string, unknow
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
}).outputText;
const exports: any = {};
- runInNewContext(compiled, {exports, ...globals});
+ runInNewContext(compiled, {exports, logKeyboardDiagnostic: (): void => undefined, ...globals});
return exports.subject;
};
diff --git a/app/src/command/executor.ts b/app/src/command/executor.ts
index c7e951363c..f72d1ad9c0 100644
--- a/app/src/command/executor.ts
+++ b/app/src/command/executor.ts
@@ -5,6 +5,7 @@ import {executeLegacyNativeCommand} from "./nativeRuntime";
import {getCommandRegistry} from "./service";
import {ensureContextCommands} from "./contextCommands";
import type {ICommandContextSnapshot, TCommandSource} from "./types";
+import {createKeyboardSearchTrace} from "../util/keyboardDiagnostic";
interface IExecByCommandOptions {
command: string;
@@ -30,6 +31,8 @@ export const executeCommandById = (
) => ensureCommandSystem(app).execute(commandId, context, args);
export const execByCommand = async (options: IExecByCommandOptions) => {
+ const trace = createKeyboardSearchTrace(options.command);
+ trace("command-enter");
const app = options.app || window.siyuan.ws.app;
const context = options.context || captureCommandContext({
app,
@@ -39,9 +42,17 @@ export const execByCommand = async (options: IExecByCommandOptions) => {
fileLiElements: options.fileLiElements,
});
const commandId = getNativeCommandId(options.command);
- if (commandId) {
- return ensureCommandSystem(app).execute(commandId, context);
+ try {
+ if (commandId) {
+ const result = await ensureCommandSystem(app).execute(commandId, context);
+ trace("command-result", result.status);
+ return result;
+ }
+ await executeLegacyNativeCommand(options.command, context);
+ trace("command-result", "executed");
+ return {status: "executed" as const};
+ } catch (error) {
+ trace("command-error", "exception");
+ throw error;
}
- await executeLegacyNativeCommand(options.command, context);
- return {status: "executed" as const};
};
diff --git a/app/src/command/nativeRuntime.ts b/app/src/command/nativeRuntime.ts
index de1bd4743a..c9f6707d0a 100644
--- a/app/src/command/nativeRuntime.ts
+++ b/app/src/command/nativeRuntime.ts
@@ -9,6 +9,7 @@ import {fetchSyncPost} from "../util/fetch";
import {globalCommand} from "../boot/globalEvent/command/global";
import {onlyProtyleCommand} from "../boot/globalEvent/command/protyle";
import type {ICommandContextSnapshot} from "./types";
+import {createKeyboardSearchTrace} from "../util/keyboardDiagnostic";
/// #if MOBILE
import {popSearch} from "../mobile/menu/search";
/// #else
@@ -119,10 +120,17 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
case "search":
if (!isFileFocus) {
/// #if MOBILE
+ const trace = createKeyboardSearchTrace("search");
+ trace("search-enter");
+ trace("path-start");
const response = await fetchSyncPost("/api/filetree/getHPathByPath", {
notebook: protyle.notebookId,
path: protyle.path.endsWith(".sy") ? protyle.path : protyle.path + ".sy",
+ }).catch(error => {
+ trace("path-error", "exception");
+ throw error;
});
+ trace("path-result", typeof response.data === "string" ? "string" : "invalid-data", response.code);
if (response.code !== 0 || typeof response.data !== "string") {
return;
}
@@ -132,6 +140,7 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
hPath: pathPosix().join(getNotebookName(protyle.notebookId), response.data),
idPath: [pathPosix().join(protyle.notebookId, protyle.path)],
});
+ trace("dialog-created", "mobile");
/// #else
openSearch({
app,
diff --git a/app/src/config/tabs/appTab.ts b/app/src/config/tabs/appTab.ts
index d15946e808..4a6c798c8f 100644
--- a/app/src/config/tabs/appTab.ts
+++ b/app/src/config/tabs/appTab.ts
@@ -32,6 +32,7 @@ import {genConfigItemMainHtml, genConfigItemName} from "../render/fragments";
import {sendAppSetting} from "./appRuntime";
import {getHostCapabilities} from "../../util/hostCapabilities";
import {genWorkspaceStorageHtml, mountWorkspaceStorage} from "./workspaceStorage";
+import {flushKeyboardDiagnostics} from "../../util/keyboardDiagnostic";
/// #if MOBILE
const registerAppWorkspaceGroup = (tab: SettingTabBuilder) => {
@@ -582,7 +583,8 @@ const registerAppMaintenanceGroup = (tab: SettingTabBuilder) => {
label: window.siyuan.languages.export,
icon: "iconUpload",
afterMount: (root) => {
- root.querySelector("#exportLog")?.addEventListener("click", () => {
+ root.querySelector("#exportLog")?.addEventListener("click", async () => {
+ await flushKeyboardDiagnostics();
fetchPost("/api/system/exportLog", {}, (response) => {
void saveExportFile(response.data.zip);
});
diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.ts
index b973dc8628..442c29534c 100644
--- a/app/src/mobile/index.ts
+++ b/app/src/mobile/index.ts
@@ -74,6 +74,7 @@ import {initializeEnglishCommandTranslations} from "../command/english";
import {loadLanguages} from "../boot/loadLanguages";
import {scrollInputIntoView} from "./util/visibleViewport";
import {installPluginStorageFetchAppId} from "../util/fetchAppId";
+import {initKeyboardDiagnostics} from "../util/keyboardDiagnostic";
class App {
public plugins: import("../plugin").Plugin[] = [];
@@ -266,6 +267,7 @@ class App {
setWebViewFocusable();
});
// 移动端删除键 https://github.com/siyuan-note/siyuan/issues/9259
+ initKeyboardDiagnostics("mobile");
window.addEventListener("keydown", (event) => {
mobileKeydown(siyuanApp, event);
if (getSelection().rangeCount > 0) {
diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.ts
index 58ff398be8..7447c02f63 100644
--- a/app/src/mobile/menu/search.ts
+++ b/app/src/mobile/menu/search.ts
@@ -4,6 +4,7 @@ import {getAttr} from "../../search/attrs";
import type {APICallbackResponse, APIPOSTRoutes} from "../../types/api";
import {getCurrentEditor, openMobileFileById} from "../editor";
import {Constants} from "../../constants";
+import {createKeyboardSearchTrace} from "../../util/keyboardDiagnostic";
import {fetchPost} from "../../util/fetch";
import {getIconByType} from "../../editor/getIcon";
import {preventScroll} from "../../protyle/scroll/preventScroll";
@@ -767,6 +768,8 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTab
};
export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConfig) => {
+ const trace = createKeyboardSearchTrace(searchConfig ? "search" : "globalSearch");
+ trace("search-enter");
const config: Config.IUILayoutTabSearchConfig = JSON.parse(JSON.stringify(window.siyuan.storage[Constants.LOCAL_SEARCHDATA]));
const currentEditor = getCurrentEditor();
if (currentEditor && isEncryptedBox(currentEditor.protyle.notebookId)) {
@@ -917,6 +920,7 @@ export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConf
updateSearchResult(config, element);
}
});
+ trace("dialog-created", "mobile");
};
const goAsset = () => {
diff --git a/app/src/mobile/util/keydown.ts b/app/src/mobile/util/keydown.ts
index bf9a4b6b15..1525d34159 100644
--- a/app/src/mobile/util/keydown.ts
+++ b/app/src/mobile/util/keydown.ts
@@ -4,10 +4,14 @@ import {matchHotKey} from "../../protyle/util/hotKey";
import {getCurrentEditor} from "../editor";
import {filterHotkey} from "../../boot/globalEvent/commonHotkey";
import {captureShortcutContext, dispatchPluginShortcut} from "../../command/shortcutRuntime";
+import {logKeyboardDiagnostic} from "../../util/keyboardDiagnostic";
export const mobileKeydown = (app: App, event: KeyboardEvent) => {
+ logKeyboardDiagnostic("mobile-enter", event);
// 移动端输入框默认填充无 event.key
if (!event.key || event.defaultPrevented || filterHotkey(event, app)) {
+ logKeyboardDiagnostic("mobile-stop", event, !event.key ? "missing-key" :
+ event.defaultPrevented ? "default-prevented" : "filtered");
return;
}
const matchGeneral = Object.keys(window.siyuan.config.keymap.general).sort().find((key) => {
diff --git a/app/src/mobile/util/tabShortcut.test.ts b/app/src/mobile/util/tabShortcut.test.ts
index f6aca434a4..0471aa5f66 100644
--- a/app/src/mobile/util/tabShortcut.test.ts
+++ b/app/src/mobile/util/tabShortcut.test.ts
@@ -12,6 +12,7 @@ it("does not consume the desktop tab menu binding on mobile", () => {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
}).outputText;
const dependencies: Record<string, object> = {
+ "../../util/keyboardDiagnostic": {logKeyboardDiagnostic: (): void => undefined},
"../../boot/globalEvent/commonHotkey": {filterHotkey: () => false},
"../../protyle/util/hotKey": {matchHotKey: () => true},
"../../command/executor": {execByCommand: () => calls.push("native")},
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index 75b5f460b2..de0f1575ba 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -1,4 +1,5 @@
import type {BlockQueryRequestInput} from "../../types/api";
+import {logKeyboardDiagnostic} from "../../util/keyboardDiagnostic";
import {isProtyleListItemFragment} from "../runtimeCapabilities";
import {toggleListMindmap} from "../render/listMindmap";
import {hideElements} from "../ui/hideElements";
@@ -300,15 +301,18 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
bindVerticalNavigationReset(editorElement);
editorElement.addEventListener("keydown", async (event: KeyboardEvent & { target: HTMLElement }) => {
if (event.target.localName === "protyle-html" || event.target.localName === "input") {
+ logKeyboardDiagnostic("editor-stop", event, "input-target");
event.stopPropagation();
return;
}
if (getAVTemplateInteractiveElement(event.target)) {
+ logKeyboardDiagnostic("editor-stop", event, "av-interactive");
event.stopPropagation();
return;
}
// 组合输入期间保留浏览器的原生选区,避免读取选区时修复光标而打断输入法。
if (event.isComposing) {
+ logKeyboardDiagnostic("editor-stop", event, "composing");
event.stopPropagation();
return;
}
diff --git a/app/src/search/spread.ts b/app/src/search/spread.ts
index 167a561b0a..f02840b0f9 100644
--- a/app/src/search/spread.ts
+++ b/app/src/search/spread.ts
@@ -14,6 +14,7 @@ import {
} from "./config";
import {beginSearchPathRequest} from "./path";
import {isDisabledFeature} from "../protyle/util/compatibility";
+import {createKeyboardSearchTrace} from "../util/keyboardDiagnostic";
let openSearchVersion = 0;
@@ -25,6 +26,9 @@ export const openSearch = async (options: {
notebookIds?: string[],
searchPath?: string
}) => {
+ const trace = createKeyboardSearchTrace(options.hotkey === Constants.DIALOG_SEARCH ? "search" :
+ options.hotkey === Constants.DIALOG_GLOBALSEARCH ? "globalSearch" : "");
+ trace("search-enter");
if (window.siyuan.isPublish && options.hotkey === Constants.DIALOG_REPLACE) {
return;
}
@@ -43,11 +47,17 @@ export const openSearch = async (options: {
hPath = getNotebookName(options.notebookId);
idPath.push(options.notebookId);
if (options.searchPath && options.searchPath !== "/") {
+ trace("path-start");
const response = await fetchSyncPost("/api/filetree/getHPathByPath", {
notebook: options.notebookId,
path: options.searchPath.endsWith(".sy") ? options.searchPath : options.searchPath + ".sy"
+ }).catch(error => {
+ trace("path-error", "exception");
+ throw error;
});
+ trace("path-result", typeof response.data === "string" ? "string" : "invalid-data", response.code);
if (version !== openSearchVersion || (isCurrentPathRequest && !isCurrentPathRequest())) {
+ trace("path-stale");
return;
}
if (response.code !== 0 || typeof response.data !== "string") {
@@ -118,10 +128,16 @@ export const openSearch = async (options: {
} else if (options.hotkey === Constants.DIALOG_SEARCH) {
const toPath = item.editors.edit.protyle.path;
const toNotebook = item.editors.edit.protyle.notebookId;
+ trace("path-start");
+ let received = false;
fetchPost("/api/filetree/getHPathsByPaths", {paths: [toPath]}, (response) => {
+ received = true;
+ trace("path-result", Array.isArray(response.data) && typeof response.data[0] === "string" ?
+ "string-array" : "invalid-data", response.code);
if (version !== openSearchVersion || !item.element.isConnected ||
item.element.getAttribute("data-key") !== Constants.DIALOG_SEARCH ||
(isCurrentPathRequest && !isCurrentPathRequest())) {
+ trace("path-stale");
return;
}
if (!Array.isArray(response.data) || typeof response.data[0] !== "string") {
@@ -139,12 +155,17 @@ export const openSearch = async (options: {
storageConfig: replaceSearchConfigPath(
currentData, window.siyuan.storage[Constants.LOCAL_SEARCHDATA]),
});
+ }).finally(() => {
+ if (!received) {
+ trace("path-error", "exception");
+ }
});
}
return true;
}
});
if (exitDialog) {
+ trace("dialog-reused");
return;
}
let range: Range;
@@ -179,4 +200,5 @@ export const openSearch = async (options: {
dialog.destroy({focus: "false"});
});
dialog.data = config;
+ trace("dialog-created");
};
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 987d319108..104d1513ae 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -2158,6 +2158,14 @@ export type SystemImportConfRequestInput = { "file"?: Array<Blob>; };
export type SystemImportFileRequestInput = { "file"?: Blob; };
+export type SystemKeyboardLogEntryInput = { "command"?: string; "detail"?: string; "environment"?: SystemKeyboardLogEnvironmentInput | null; "event"?: number; "keyboard"?: SystemKeyboardLogEventInput | null; "responseCode"?: number | null; "seq": number; "stage": string; "time": number; };
+
+export type SystemKeyboardLogEnvironmentInput = { "frontend": string; "globalSearch": Array<string>; "platform": string; "search": Array<string>; "userAgent": string; "version": string; };
+
+export type SystemKeyboardLogEventInput = { "alt": boolean; "cancelBubble": boolean; "code": string; "composing": boolean; "ctrl": boolean; "defaultPrevented": boolean; "key": string; "keyCode": number; "matchGlobalSearch": boolean; "matchSearch": boolean; "meta": boolean; "repeat": boolean; "shift": boolean; "target": string; "trusted": boolean; };
+
+export type SystemKeyboardLogRequestInput = { "entries": Array<SystemKeyboardLogEntryInput>; "session": string; };
+
export type SystemLANSync = { "enabled": boolean; "maxConcurrentReqs": number; };
export type SystemLang = { "label": string; "name": string; };
@@ -5417,6 +5425,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "none";
};
+ "/api/system/appendKeyboardLog": {
+ request: SystemKeyboardLogRequestInput;
+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/system/bootProgress": {
request: EmptyRequestInput;
response: { "code": 0; "data": BootProgressData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/src/util/keyboardDiagnostic.test.ts b/app/src/util/keyboardDiagnostic.test.ts
new file mode 100644
index 0000000000..c7c3291686
--- /dev/null
+++ b/app/src/util/keyboardDiagnostic.test.ts
@@ -0,0 +1,148 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const fixture = (os = "ios", publish = false, send?: (payload: any) => Promise<object>, native = true) => {
+ const listeners = new Map<string, (event: any) => void>();
+ const timers = new Map<number, {callback: () => void, delay: number}>();
+ const requests: any[] = [];
+ let timer = 0;
+ class Element {
+ tagName = "DIV";
+ closest() { return this; }
+ }
+ const exports: any = {};
+ const source = transpileModule(readFileSync(join(__dirname, "keyboardDiagnostic.ts"), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const dependencies: Record<string, object> = {
+ "../constants": {Constants: {SIYUAN_VERSION: "test"}},
+ "../protyle/util/compatibility": {isInIOS: () => os === "ios" && native},
+ "../protyle/util/hotKey": {matchHotKey: (binding: string, event: any) =>
+ event.metaKey && binding === (event.keyCode === 70 ? "F" : event.keyCode === 80 ? "P" : "")},
+ "./keymapBindings": {getKeymapBindings: (key: string) => [key]},
+ "./fetch": {fetchSyncPost: async (url: string, payload: object, headers: object, process: boolean) => {
+ assert.equal(url, "/api/system/appendKeyboardLog");
+ assert.equal(process, false);
+ requests.push(JSON.parse(JSON.stringify(payload)));
+ return send ? send(payload) : {code: 0};
+ }},
+ "./fetchTimeout": {withFetchTimeout: (request: () => Promise<object>) => request()},
+ };
+ runInNewContext(source, {
+ exports, require: (name: string) => dependencies[name], HTMLElement: Element, AbortController,
+ clearTimeout: (id: number) => timers.delete(id), queueMicrotask,
+ document: {body: {}}, navigator: {platform: "MacIntel", userAgent: "SiYuan iPad"},
+ window: {
+ siyuan: {isPublish: publish, config: {system: {os}, keymap: {general: {search: "F", globalSearch: "P"}}}},
+ setTimeout: (callback: () => void, delay: number) => { timers.set(++timer, {callback, delay}); return timer; },
+ addEventListener: (type: string, listener: (event: any) => void, capture: boolean) => {
+ assert.equal(capture, true);
+ listeners.set(type, listener);
+ },
+ },
+ });
+ const event = (values: object = {}) => ({type: "keydown", key: "p", code: "KeyP", keyCode: 80,
+ metaKey: true, ctrlKey: false, altKey: false, shiftKey: false, isComposing: false, repeat: false,
+ isTrusted: true, defaultPrevented: false, cancelBubble: false, target: new Element(), ...values});
+ const settle = () => {
+ for (const [id, task] of timers) {
+ if (task.delay === 0) {
+ timers.delete(id);
+ task.callback();
+ }
+ }
+ };
+ return {subject: exports, listeners, requests, event, timers, settle};
+};
+
+test("keyboard diagnostics only initialize once in the iOS app", async () => {
+ for (const [os, publish] of [["windows", false], ["ios", true]] as const) {
+ const value = fixture(os, publish);
+ value.subject.initKeyboardDiagnostics("desktop");
+ await value.subject.flushKeyboardDiagnostics();
+ assert.equal(value.listeners.size, 0);
+ assert.equal(value.requests.length, 0);
+ }
+ const browser = fixture("ios", false, undefined, false);
+ browser.subject.initKeyboardDiagnostics("desktop");
+ assert.equal(browser.listeners.size, 0);
+ const value = fixture();
+ value.subject.initKeyboardDiagnostics("mobile");
+ value.subject.initKeyboardDiagnostics("mobile");
+ await value.subject.flushKeyboardDiagnostics();
+ assert.equal(value.requests[0].entries.length, 1);
+ assert.equal(value.requests[0].entries[0].environment.frontend, "mobile");
+});
+
+test("captures composing and missing-modifier events without recording composition text", async () => {
+ const value = fixture();
+ value.subject.initKeyboardDiagnostics("desktop");
+ const composing = value.event({key: "private-pinyin", code: "Unknown", keyCode: 229,
+ metaKey: false, isComposing: true});
+ value.listeners.get("compositionstart")({data: "private-document"});
+ value.listeners.get("keydown")(composing);
+ value.subject.logKeyboardDiagnostic("editor-stop", composing, "composing");
+ composing.cancelBubble = true;
+ await Promise.resolve();
+ value.settle();
+ const ordinary = value.event({metaKey: false});
+ value.listeners.get("keydown")(ordinary);
+ await Promise.resolve();
+ value.settle();
+ value.listeners.get("compositionend")({data: "private-document"});
+ await value.subject.flushKeyboardDiagnostics();
+ const entries = value.requests.flatMap(item => item.entries);
+ const capture = entries.find(item => item.stage === "capture");
+ const stopped = entries.find(item => item.stage === "editor-stop");
+ const settled = entries.find(item => item.stage === "settled");
+ assert.equal(capture.keyboard.keyCode, 229);
+ assert.equal(capture.keyboard.composing, true);
+ assert.equal(capture.keyboard.key, "Other");
+ assert.equal(stopped.event, capture.event);
+ assert.equal(settled.keyboard.cancelBubble, true);
+ assert.equal(entries.filter(item => item.stage === "capture").length, 2);
+ assert.equal(JSON.stringify(value.requests).includes("private-"), false);
+});
+
+test("retains event correlation across asynchronous search and flushes queued batches", async () => {
+ const value = fixture();
+ value.subject.initKeyboardDiagnostics("desktop");
+ value.listeners.get("keydown")(value.event());
+ const trace = value.subject.createKeyboardSearchTrace("globalSearch");
+ trace("command-enter");
+ await Promise.resolve();
+ const duringDispatch = value.subject.createKeyboardSearchTrace("globalSearch");
+ duringDispatch("command-enter");
+ value.settle();
+ trace("dialog-created");
+ for (let index = 0; index < 60; index++) {
+ value.listeners.get("compositionstart")({data: ""});
+ }
+ await value.subject.flushKeyboardDiagnostics();
+ const entries = value.requests.flatMap(item => item.entries);
+ assert.equal(value.requests.length, 2);
+ assert.ok(value.requests.every(item => item.entries.length <= 50));
+ const capture = entries.find(item => item.stage === "capture");
+ assert.equal(capture.keyboard.matchGlobalSearch, true);
+ assert.ok(entries.filter(item => item.stage === "command-enter").every(item => item.event === capture.event));
+ assert.equal(entries.find(item => item.stage === "dialog-created").event, capture.event);
+ assert.ok(entries.every((item, index) => item.seq === index + 1));
+});
+
+test("bounds memory, total records and failed requests without rejecting the export flush", async () => {
+ const value = fixture("ios", false, async () => { throw new Error("offline"); });
+ value.subject.initKeyboardDiagnostics("desktop");
+ for (let index = 0; index < 1500; index++) {
+ value.listeners.get("compositionstart")({data: ""});
+ }
+ for (let index = 0; index < 4; index++) {
+ await value.subject.flushKeyboardDiagnostics();
+ }
+ assert.equal(value.requests.length, 3);
+ assert.equal(value.requests[0].entries[0].seq, 801);
+ assert.ok(value.requests.every(item => item.entries.every((entry: any) => entry.seq <= 1000)));
+});
diff --git a/app/src/util/keyboardDiagnostic.ts b/app/src/util/keyboardDiagnostic.ts
new file mode 100644
index 0000000000..a9323f1e44
--- /dev/null
+++ b/app/src/util/keyboardDiagnostic.ts
@@ -0,0 +1,161 @@
+import {Constants} from "../constants";
+import {matchHotKey} from "../protyle/util/hotKey";
+import {isInIOS} from "../protyle/util/compatibility";
+import {getKeymapBindings} from "./keymapBindings";
+import {fetchSyncPost} from "./fetch";
+import {withFetchTimeout} from "./fetchTimeout";
+import type {SystemKeyboardLogEntryInput, SystemKeyboardLogEventInput} from "../types/api";
+
+const MAX_RECORDS = 1000;
+const MAX_PENDING = 200;
+const BATCH_SIZE = 50;
+const session = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+const events = new WeakMap<KeyboardEvent, number>();
+let enabled = false;
+let sequence = 0;
+let eventSequence = 0;
+let activeEvent = 0;
+let pending: SystemKeyboardLogEntryInput[] = [];
+let timer: number;
+let sending: Promise<void>;
+let failures = 0;
+
+const record = (entry: Omit<SystemKeyboardLogEntryInput, "seq" | "time">) => {
+ if (!enabled || sequence >= MAX_RECORDS) {
+ return;
+ }
+ pending.push({...entry, seq: ++sequence, time: Date.now()});
+ // 网络不可用时限制内存占用,保留最近的诊断记录。
+ if (pending.length > MAX_PENDING) {
+ pending.shift();
+ }
+ if (!timer && !sending && failures < 3) {
+ timer = window.setTimeout(() => {
+ timer = undefined;
+ void flushKeyboardDiagnostics();
+ }, 200);
+ }
+};
+
+// 将已采集的记录写入系统日志,导出前等待当前批次和后续批次完成。
+export const flushKeyboardDiagnostics = async () => {
+ clearTimeout(timer);
+ timer = undefined;
+ if (sending) {
+ await sending;
+ if (pending.length && failures < 3) {
+ await flushKeyboardDiagnostics();
+ }
+ return;
+ }
+ if (!pending.length || failures >= 3) {
+ return;
+ }
+ sending = (async () => {
+ while (pending.length && failures < 3) {
+ const entries = pending.splice(0, BATCH_SIZE);
+ try {
+ const response = await withFetchTimeout((signal) => fetchSyncPost(
+ "/api/system/appendKeyboardLog", {session, entries}, undefined, false, signal), undefined, 3000);
+ if (response.code !== 0) {
+ throw new Error("keyboard diagnostic rejected");
+ }
+ failures = 0;
+ } catch {
+ failures++;
+ pending = [...entries, ...pending].slice(-MAX_PENDING);
+ break;
+ }
+ }
+ })();
+ await sending;
+ sending = undefined;
+ if (pending.length && failures < 3) {
+ timer = window.setTimeout(() => {
+ timer = undefined;
+ void flushKeyboardDiagnostics();
+ }, 1000);
+ }
+};
+
+const snapshot = (event: KeyboardEvent): SystemKeyboardLogEventInput => {
+ const target = event.target instanceof HTMLElement ? event.target : undefined;
+ return {
+ // 只保留目标快捷键和修饰键分类,不记录任意字符或组合输入内容。
+ key: ["f", "F", "p", "P", "Meta", "Control", "Unidentified", "Process"].includes(event.key) ? event.key : "Other",
+ code: ["KeyF", "KeyP", "MetaLeft", "MetaRight", "ControlLeft", "ControlRight"].includes(event.code) ? event.code : "Other",
+ keyCode: event.keyCode,
+ meta: event.metaKey,
+ ctrl: event.ctrlKey,
+ alt: event.altKey,
+ shift: event.shiftKey,
+ composing: event.isComposing,
+ repeat: event.repeat,
+ trusted: event.isTrusted,
+ defaultPrevented: event.defaultPrevented,
+ cancelBubble: event.cancelBubble,
+ target: target?.tagName === "INPUT" ? "input" : target?.tagName === "TEXTAREA" ? "textarea" :
+ target?.closest(".protyle-wysiwyg") ? "editor" : target === document.body ? "body" : "other",
+ matchSearch: matchHotKey(window.siyuan.config.keymap.general.search, event),
+ matchGlobalSearch: matchHotKey(window.siyuan.config.keymap.general.globalSearch, event),
+ };
+};
+
+export const logKeyboardDiagnostic = (stage: string, event: KeyboardEvent, detail = "") => {
+ const id = events.get(event);
+ if (id) {
+ record({stage, event: id, detail, keyboard: snapshot(event)});
+ }
+};
+
+// 在同步分发时保存按键编号,使异步接口返回仍能关联原始按键。
+export const createKeyboardSearchTrace = (command: string) => {
+ const event = activeEvent;
+ const tracked = enabled && ["search", "globalSearch"].includes(command);
+ return (stage: string, detail = "", responseCode?: number) => {
+ if (tracked) {
+ record({stage, event, command, detail, ...(responseCode === undefined ? {} : {responseCode})});
+ }
+ };
+};
+
+export const initKeyboardDiagnostics = (frontend: "desktop" | "mobile") => {
+ if (enabled || window.siyuan.isPublish || !isInIOS()) {
+ return;
+ }
+ enabled = true;
+ record({stage: "environment", environment: {
+ version: Constants.SIYUAN_VERSION,
+ userAgent: navigator.userAgent.slice(0, 512),
+ platform: navigator.platform.slice(0, 64),
+ frontend,
+ search: getKeymapBindings(window.siyuan.config.keymap.general.search).slice(0, 8).map(key => key.slice(0, 20)),
+ globalSearch: getKeymapBindings(window.siyuan.config.keymap.general.globalSearch).slice(0, 8).map(key => key.slice(0, 20)),
+ }});
+ const capture = (event: KeyboardEvent) => {
+ if (sequence >= MAX_RECORDS || !(event.metaKey || event.ctrlKey || event.keyCode === 229 ||
+ [70, 80, 91, 93].includes(event.keyCode) || ["KeyF", "KeyP"].includes(event.code) ||
+ ["f", "F", "p", "P", "Meta", "Control"].includes(event.key))) {
+ return;
+ }
+ const id = ++eventSequence;
+ events.set(event, id);
+ if (event.type === "keydown") {
+ activeEvent = id;
+ }
+ logKeyboardDiagnostic("capture", event, event.type);
+ // 等待整个事件分发结束后记录最终状态,保留各处理器使用的按键编号。
+ window.setTimeout(() => {
+ logKeyboardDiagnostic("settled", event, event.type);
+ if (activeEvent === id) {
+ activeEvent = 0;
+ }
+ }, 0);
+ };
+ // 捕获阶段先于编辑器,阻止冒泡的按键仍留下原始状态。
+ window.addEventListener("keydown", capture, true);
+ window.addEventListener("keyup", capture, true);
+ ["compositionstart", "compositionend"].forEach(stage => {
+ window.addEventListener(stage, () => record({stage, event: activeEvent}), true);
+ });
+};
diff --git a/kernel/api/keyboard_diagnostic.go b/kernel/api/keyboard_diagnostic.go
new file mode 100644
index 0000000000..a17036e8b8
--- /dev/null
+++ b/kernel/api/keyboard_diagnostic.go
@@ -0,0 +1,72 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "slices"
+ "strings"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+)
+
+var appendKeyboardLog = contractHandler(apicontract.SystemAppendKeyboardLog,
+ func(c *gin.Context, request apicontract.SystemKeyboardLogRequest) apicontract.Response[apicontract.Null] {
+ if !validKeyboardLog(request) {
+ return apicontract.Failure[apicontract.Null](-1, "invalid keyboard diagnostic records")
+ }
+ data, err := json.Marshal(request)
+ if err != nil {
+ return apicontract.Failure[apicontract.Null](-1, "encode keyboard diagnostic records failed")
+ }
+ logging.LogInfof("keyboard diagnostic [issue=20006] %s", data)
+ return apicontract.Success(apicontract.Null{})
+ }, func(c *gin.Context) *apicontract.Response[apicontract.Null] {
+ // 限制读取大小,避免诊断接口接收无界请求。
+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64*1024)
+ return nil
+ })
+
+func validKeyboardLog(request apicontract.SystemKeyboardLogRequest) bool {
+ if len(request.Session) == 0 || len(request.Session) > 64 ||
+ strings.IndexFunc(request.Session, func(r rune) bool {
+ return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-')
+ }) >= 0 || len(request.Entries) == 0 || len(request.Entries) > 50 {
+ return false
+ }
+ for _, entry := range request.Entries {
+ if entry.Seq < 1 || entry.Time < 1 || entry.Event < 0 ||
+ !slices.Contains([]string{"", "keydown", "keyup", "input-target", "av-interactive", "composing", "progress",
+ "error-log", "card-key", "plain-key", "default-prevented", "filtered", "search-keydown", "menu-keydown",
+ "av-panel", "editor-handled", "missing-key", "executed", "notFound", "unavailable", "disabled",
+ "exception", "string", "string-array", "invalid-data", "mobile"}, entry.Detail) ||
+ !slices.Contains([]string{"environment", "capture", "settled", "compositionstart", "compositionend",
+ "window-enter", "window-stop", "mobile-enter", "mobile-stop", "filter-stop", "editor-stop",
+ "command-enter", "command-result", "command-error", "search-enter", "path-start", "path-error", "path-result", "path-stale",
+ "dialog-created", "dialog-reused"}, entry.Stage) ||
+ !slices.Contains([]string{"", "search", "globalSearch"}, entry.Command) {
+ return false
+ }
+ if event := entry.Keyboard; event != nil {
+ if !slices.Contains([]string{"f", "F", "p", "P", "Meta", "Control", "Unidentified", "Process", "Other"}, event.Key) ||
+ !slices.Contains([]string{"KeyF", "KeyP", "MetaLeft", "MetaRight", "ControlLeft", "ControlRight", "Other"}, event.Code) ||
+ !slices.Contains([]string{"input", "textarea", "editor", "body", "other"}, event.Target) ||
+ event.KeyCode < 0 || event.KeyCode > 255 {
+ return false
+ }
+ }
+ if env := entry.Environment; env != nil {
+ if len(env.Version) > 64 || len(env.UserAgent) > 512 || len(env.Platform) > 64 ||
+ !slices.Contains([]string{"desktop", "mobile"}, env.Frontend) || len(env.Search) > 8 || len(env.GlobalSearch) > 8 {
+ return false
+ }
+ for _, binding := range append(append([]string{}, env.Search...), env.GlobalSearch...) {
+ if len(binding) > 64 {
+ return false
+ }
+ }
+ }
+ }
+ return true
+}
diff --git a/kernel/api/keyboard_diagnostic_test.go b/kernel/api/keyboard_diagnostic_test.go
new file mode 100644
index 0000000000..f9d969aa3e
--- /dev/null
+++ b/kernel/api/keyboard_diagnostic_test.go
@@ -0,0 +1,123 @@
+package api
+
+import (
+ archiveZip "archive/zip"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractKeyboardDiagnostic(t *testing.T) {
+ oldConf, oldTemp, oldHome, oldLog, oldBypass := model.Conf, util.TempDir, util.HomeDir, logging.LogPath, util.SiYuanAccessAuthCodeBypass
+ oldReadonly := util.ReadOnly
+ model.Conf = model.NewAppConf()
+ model.Conf.ReadOnly = true
+ util.ReadOnly = true
+ util.TempDir, util.HomeDir = t.TempDir(), t.TempDir()
+ logging.SetLogPath(filepath.Join(util.TempDir, "siyuan.log"))
+ util.SiYuanAccessAuthCodeBypass = false
+ t.Cleanup(func() {
+ model.Conf, util.TempDir, util.HomeDir = oldConf, oldTemp, oldHome
+ logging.SetLogPath(oldLog)
+ util.SiYuanAccessAuthCodeBypass = oldBypass
+ util.ReadOnly = oldReadonly
+ })
+ request := func(role model.Role, body string) *httptest.ResponseRecorder {
+ t.Helper()
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, role); c.Next() })
+ ServeAPI(engine)
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/system/appendKeyboardLog", strings.NewReader(body)))
+ if recorder.Code == http.StatusOK {
+ requireAPIContract(t, "POST", "/api/system/appendKeyboardLog", recorder)
+ }
+ return recorder
+ }
+ valid := `{"session":"test-20006","entries":[{"seq":1,"time":1,"stage":"command-enter","event":1,"command":"search"}]}`
+ for _, role := range []model.Role{model.RoleReader, model.RoleEditor} {
+ if response := request(role, valid); response.Code != http.StatusForbidden {
+ t.Fatalf("non-admin admitted: %s", response.Body)
+ }
+ }
+ if response := request(model.RoleVisitor, valid); response.Code != http.StatusUnauthorized {
+ t.Fatalf("unauthenticated request admitted: %s", response.Body)
+ }
+ if response := request(model.RoleAdministrator, valid); !strings.Contains(response.Body.String(), `"code":0`) {
+ t.Fatalf("read-only diagnostic write failed: %s", response.Body)
+ }
+ for _, body := range []string{
+ `{}`, `{"session":"test","entries":[]}`, strings.Replace(valid, `"seq":1`, `"seq":"1"`, 1),
+ strings.Replace(valid, `"stage":"command-enter"`, `"stage":"unknown"`, 1),
+ strings.Replace(valid, `"command":"search"`, `"command":"private-document"`, 1),
+ strings.Replace(valid, `"command":"search"`, `"detail":"private-pinyin"`, 1),
+ strings.TrimSuffix(valid, "}") + `,"padding":"` + strings.Repeat("x", 65536) + `"}`,
+ } {
+ response := request(model.RoleAdministrator, body)
+ var result struct {
+ Code int `json:"code"`
+ }
+ if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil || result.Code >= 0 {
+ t.Fatalf("invalid diagnostic accepted: %s", response.Body)
+ }
+ }
+ data, err := os.ReadFile(logging.LogPath)
+ if err != nil || !strings.Contains(string(data), "keyboard diagnostic [issue=20006]") || strings.Contains(string(data), "private-") {
+ t.Fatalf("diagnostic log missing or contains rejected text: %s %v", data, err)
+ }
+ if path := model.ExportSystemLog(); path == "" {
+ t.Fatal("system log export failed")
+ }
+ archive, err := archiveZip.OpenReader(filepath.Join(util.TempDir, "export", "system-log.zip"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer archive.Close()
+ for _, file := range archive.File {
+ if strings.HasSuffix(file.Name, "/siyuan.log") {
+ input, err := file.Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ exported, err := io.ReadAll(input)
+ input.Close()
+ if err != nil || !strings.Contains(string(exported), "test-20006") {
+ t.Fatalf("export dropped keyboard diagnostics: %s %v", exported, err)
+ }
+ return
+ }
+ }
+ t.Fatal("system log archive lacks siyuan.log")
+}
+
+func TestAPIContractKeyboardDiagnosticLimits(t *testing.T) {
+ request := apicontract.SystemKeyboardLogRequest{Session: "test", Entries: []apicontract.SystemKeyboardLogEntry{{Seq: 1, Time: 1, Stage: "capture"}}}
+ if !validKeyboardLog(request) {
+ t.Fatal("valid diagnostic rejected")
+ }
+ request.Entries[0].Keyboard = &apicontract.SystemKeyboardLogEvent{Key: "private-pinyin", Code: "Other", Target: "editor"}
+ if validKeyboardLog(request) {
+ t.Fatal("arbitrary keyboard text accepted")
+ }
+ request.Entries[0].Keyboard.Key = "Other"
+ if !validKeyboardLog(request) {
+ t.Fatal("redacted keyboard event rejected")
+ }
+ for len(request.Entries) < 51 {
+ request.Entries = append(request.Entries, request.Entries[0])
+ }
+ if validKeyboardLog(request) {
+ t.Fatal("oversized batch accepted")
+ }
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index b8dcd8a0b0..013a4c7a8f 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -100,6 +100,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/system/dismissOnboarding", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, dismissOnboarding)
ginServer.Handle("POST", "/api/system/checkUpdate", model.CheckAuth, model.CheckAdminRole, checkUpdate)
ginServer.Handle("POST", "/api/system/exportLog", model.CheckAuth, model.CheckAdminRole, exportLog)
+ ginServer.Handle("POST", "/api/system/appendKeyboardLog", model.CheckAuth, model.CheckAdminRole, appendKeyboardLog)
ginServer.Handle("POST", "/api/system/getChangelog", model.CheckAuth, getChangelog)
ginServer.Handle("POST", "/api/system/getNetwork", model.CheckAuth, model.CheckAdminRole, getNetwork)
ginServer.Handle("POST", "/api/system/exportConf", model.CheckAuth, model.CheckAdminRole, exportConf)
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index bc645ca147..f4c32e3beb 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1026,6 +1026,7 @@ var SystemEnsureOnboarding = define[EmptyRequest, *SystemOnboarding]("ensureOnbo
var SystemExit = define[SystemExitRequest, SystemExitData]("exit", "/api/system/exit", JSONBody, ResponseOptions{AdditionalCodes: []int{1, 2}, DataOnError: true}, "POST")
var SystemExportConf = define[EmptyRequest, SystemExportConfData]("exportConf", "/api/system/exportConf", NoBody, ResponseOptions{}, "POST")
var SystemExportLog = define[EmptyRequest, SystemZipData]("exportLog", "/api/system/exportLog", NoBody, ResponseOptions{}, "POST")
+var SystemAppendKeyboardLog = define[SystemKeyboardLogRequest, Null]("appendKeyboardLog", "/api/system/appendKeyboardLog", JSONBody, ResponseOptions{}, "POST")
var SystemExportTLSCABundle = define[EmptyRequest, SystemPathData]("exportTLSCABundle", "/api/system/exportTLSCABundle", NoBody, ResponseOptions{}, "POST")
var SystemExportTLSCACert = define[EmptyRequest, SystemPathData]("exportTLSCACert", "/api/system/exportTLSCACert", NoBody, ResponseOptions{}, "POST")
var SystemGetChangelog = define[SystemChangelogRequest, SystemChangelogData]("getChangelog", "/api/system/getChangelog", LegacyOptionalBody, ResponseOptions{}, "POST")
diff --git a/kernel/apicontract/keyboard_diagnostic.go b/kernel/apicontract/keyboard_diagnostic.go
new file mode 100644
index 0000000000..46615720fb
--- /dev/null
+++ b/kernel/apicontract/keyboard_diagnostic.go
@@ -0,0 +1,49 @@
+package apicontract
+
+// SystemKeyboardLogRequest 接收 iOS 快捷键诊断,每批 1 至 50 条,整个请求最多 64 KiB。
+// 仅管理员可写入,支持只读模式;记录不包含正文、组合输入文本、文档路径或设备标识。
+// session 是页面随机会话编号,seq 是会话内递增编号,event 关联同一次按键的处理阶段。
+// 文本字段限制长度,按键和目标只允许诊断用的固定分类;成功返回 null,非法记录返回 -1。
+type SystemKeyboardLogRequest struct {
+ Session string `json:"session"`
+ Entries []SystemKeyboardLogEntry `json:"entries"`
+}
+
+type SystemKeyboardLogEntry struct {
+ Seq int `json:"seq"`
+ Time int64 `json:"time"`
+ Stage string `json:"stage"`
+ Event int `json:"event" api:"optional"`
+ Detail string `json:"detail" api:"optional"`
+ Command string `json:"command" api:"optional"`
+ ResponseCode *int `json:"responseCode,omitempty" api:"optional"`
+ Keyboard *SystemKeyboardLogEvent `json:"keyboard,omitempty" api:"optional"`
+ Environment *SystemKeyboardLogEnvironment `json:"environment,omitempty" api:"optional"`
+}
+
+type SystemKeyboardLogEvent struct {
+ Key string `json:"key"`
+ Code string `json:"code"`
+ KeyCode int `json:"keyCode"`
+ Meta bool `json:"meta"`
+ Ctrl bool `json:"ctrl"`
+ Alt bool `json:"alt"`
+ Shift bool `json:"shift"`
+ Composing bool `json:"composing"`
+ Repeat bool `json:"repeat"`
+ Trusted bool `json:"trusted"`
+ DefaultPrevented bool `json:"defaultPrevented"`
+ CancelBubble bool `json:"cancelBubble"`
+ Target string `json:"target"`
+ MatchSearch bool `json:"matchSearch"`
+ MatchGlobalSearch bool `json:"matchGlobalSearch"`
+}
+
+type SystemKeyboardLogEnvironment struct {
+ Version string `json:"version"`
+ UserAgent string `json:"userAgent"`
+ Platform string `json:"platform"`
+ Frontend string `json:"frontend"`
+ Search []string `json:"search"`
+ GlobalSearch []string `json:"globalSearch"`
+}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index ea8504581b..c3355ee364 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -49201,6 +49201,190 @@
},
"additionalProperties": false
},
+ "SystemKeyboardLogEntryInput": {
+ "type": "object",
+ "properties": {
+ "command": {
+ "type": "string"
+ },
+ "detail": {
+ "type": "string"
+ },
+ "environment": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SystemKeyboardLogEnvironmentInput"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "event": {
+ "type": "integer"
+ },
+ "keyboard": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SystemKeyboardLogEventInput"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "responseCode": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "seq": {
+ "type": "integer"
+ },
+ "stage": {
+ "type": "string"
+ },
+ "time": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "seq",
+ "stage",
+ "time"
+ ],
+ "additionalProperties": false
+ },
+ "SystemKeyboardLogEnvironmentInput": {
+ "type": "object",
+ "properties": {
+ "frontend": {
+ "type": "string"
+ },
+ "globalSearch": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "platform": {
+ "type": "string"
+ },
+ "search": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "userAgent": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "frontend",
+ "globalSearch",
+ "platform",
+ "search",
+ "userAgent",
+ "version"
+ ],
+ "additionalProperties": false
+ },
+ "SystemKeyboardLogEventInput": {
+ "type": "object",
+ "properties": {
+ "alt": {
+ "type": "boolean"
+ },
+ "cancelBubble": {
+ "type": "boolean"
+ },
+ "code": {
+ "type": "string"
+ },
+ "composing": {
+ "type": "boolean"
+ },
+ "ctrl": {
+ "type": "boolean"
+ },
+ "defaultPrevented": {
+ "type": "boolean"
+ },
+ "key": {
+ "type": "string"
+ },
+ "keyCode": {
+ "type": "integer"
+ },
+ "matchGlobalSearch": {
+ "type": "boolean"
+ },
+ "matchSearch": {
+ "type": "boolean"
+ },
+ "meta": {
+ "type": "boolean"
+ },
+ "repeat": {
+ "type": "boolean"
+ },
+ "shift": {
+ "type": "boolean"
+ },
+ "target": {
+ "type": "string"
+ },
+ "trusted": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "alt",
+ "cancelBubble",
+ "code",
+ "composing",
+ "ctrl",
+ "defaultPrevented",
+ "key",
+ "keyCode",
+ "matchGlobalSearch",
+ "matchSearch",
+ "meta",
+ "repeat",
+ "shift",
+ "target",
+ "trusted"
+ ],
+ "additionalProperties": false
+ },
+ "SystemKeyboardLogRequestInput": {
+ "type": "object",
+ "properties": {
+ "entries": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/SystemKeyboardLogEntryInput"
+ }
+ },
+ "session": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "entries",
+ "session"
+ ],
+ "additionalProperties": false
+ },
"SystemLANSync": {
"type": "object",
"properties": {
@@ -159972,6 +160156,81 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/system/appendKeyboardLog",
+ "handler": "appendKeyboardLog",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/SystemKeyboardLogRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "null"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/system/bootProgress",