@xmanrui/dsh-im 5.2.0 → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/client-integration.md +6 -2
- package/lib/client.js +398 -115
- package/lib/index.js +323 -321
- package/package.json +1 -1
- package/plugin-src/client/connection-error.js +2 -1
- package/plugin-src/client/global-settings.js +2 -1
- package/plugin-src/client/i18n.js +8 -0
- package/plugin-src/client/index.js +38 -18
- package/plugin-src/client/plugin-page.js +36 -9
- package/plugin-src/client/sidebar-settings.js +129 -0
- package/plugin-src/client/styles.js +8 -0
- package/plugin-src/host/channels/dingtalk/rpc.mjs +5 -1
- package/plugin-src/host/channels/feishu/rpc.mjs +5 -1
- package/plugin-src/host/channels/qq/rpc.mjs +5 -1
- package/plugin-src/host/channels/wecom/rpc.mjs +5 -1
- package/plugin-src/host/channels/weixin/rpc.mjs +3 -2
- package/plugin-src/host/channels/whatsapp/rpc.mjs +5 -1
- package/plugin-src/host/index.mjs +7 -0
- package/plugin-src/host/sidebar-settings.mjs +113 -0
- package/src/channels/imessage/imessage-api.mjs +67 -2
- package/src/channels/shared/connection-error.mjs +5 -5
- package/src/channels/shared/diagnostic-details.mjs +15 -1
- package/src/channels/shared/i18n-en/diagnostics.mjs +5 -0
- package/src/channels/shared/qr-encoding-error.mjs +39 -0
- package/src/channels/weixin/connection-error.mjs +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xmanrui/dsh-im",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.3.0",
|
|
4
4
|
"icon": "./assets/logo-plugin-message-link-gradient.webp",
|
|
5
5
|
"description": "把微信、飞书、企微、钉钉、QQ、Telegram、WhatsApp、Slack、Discord、Matrix接入DSH。 Connect Telegram, WhatsApp, Slack, Discord, Matrix, WeChat, Feishu, WeCom, DingTalk, and QQ to DSH.",
|
|
6
6
|
"keywords": [
|
|
@@ -37,7 +37,7 @@ export function formatConnectionDiagnostic(value) {
|
|
|
37
37
|
return [
|
|
38
38
|
localizeText(error.message), details.hint ? localizeText(details.hint) : null,
|
|
39
39
|
localizeText('错误码') + ': ' + error.code,
|
|
40
|
-
...['channel', 'operation', 'stage', 'method', 'transport', 'submissionState', 'attempts', 'lastFailureReason', 'reason', 'reasons', 'host', 'durationMs', 'timeoutMs', 'nodeVersion', 'dshVersion', 'platform', 'dependencies', 'proxyConfigured', 'truncated', 'httpStatus', 'providerCode', 'resource', 'file', 'field', 'issue', 'referenceId', 'occurredAt', 'rollback', 'pluginVersion']
|
|
40
|
+
...['channel', 'operation', 'stage', 'method', 'transport', 'submissionState', 'attempts', 'lastFailureReason', 'reason', 'reasons', 'errorTypes', 'qrEncoder', 'qrRenderer', 'host', 'durationMs', 'timeoutMs', 'nodeVersion', 'dshVersion', 'platform', 'dependencies', 'proxyConfigured', 'truncated', 'httpStatus', 'providerCode', 'resource', 'file', 'field', 'issue', 'referenceId', 'occurredAt', 'rollback', 'pluginVersion']
|
|
41
41
|
.filter(field => details[field] !== undefined)
|
|
42
42
|
.map(field => `${field}: ${typeof details[field] === 'object' ? JSON.stringify(details[field]) : details[field]}`),
|
|
43
43
|
].filter(Boolean).join('\n');
|
|
@@ -61,6 +61,7 @@ export function ConnectionError({ error: value, warning = false, showMessage = t
|
|
|
61
61
|
['RPC 方法', details.method], ['调用方式', details.transport === 'host-api' ? localizeText('宿主 API(进程内)') : details.transport === 'http' ? 'HTTP' : details.transport === 'websocket' ? 'WebSocket' : undefined],
|
|
62
62
|
['消息提交状态', localizeText(SUBMISSION_LABELS[details.submissionState] ?? '')],
|
|
63
63
|
['连接尝试次数', details.attempts],
|
|
64
|
+
['异常类型', details.errorTypes?.join(', ')], ['二维码编码器', details.qrEncoder], ['二维码图片格式', details.qrRenderer],
|
|
64
65
|
['最近一次连接失败', localizeText(STREAM_REASON_LABELS[details.lastFailureReason] ?? details.lastFailureReason ?? '')],
|
|
65
66
|
['底层原因', details.reason === 'unknown' ? localizeText('暂未识别') : details.reason], ['多个原因', details.reasons?.join(', ')], ['服务域名', details.host], ['请求耗时(毫秒)', details.durationMs], ['超时阈值(毫秒)', details.timeoutMs], ['Node 版本', details.nodeVersion], ['DSH 版本', details.dshVersion], ['依赖版本', details.dependencies ? Object.entries(details.dependencies).map(([name, version]) => `${name}: ${version}`).join(', ') : undefined], ['代理已配置', details.proxyConfigured], ['原因链已截断', details.truncated], ['运行平台', details.platform], ['HTTP 状态', details.httpStatus], ['服务返回码', details.providerCode],
|
|
66
67
|
['配置文件', details.file], ['配置字段', details.field],
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { GroupHistorySettings } from './group-history-settings.js';
|
|
2
|
+
import { SidebarSettings } from './sidebar-settings.js';
|
|
2
3
|
import * as React from 'react';
|
|
3
4
|
|
|
4
5
|
import {
|
|
@@ -433,6 +434,6 @@ export function GlobalSettingsPanel({ rpcCall }) {
|
|
|
433
434
|
},
|
|
434
435
|
}, item.label)))),
|
|
435
436
|
tab === 'general' ? h('div', { id: 'dim-general-settings-panel-general', className: 'dim-generalSettingsTabPanel', role: 'tabpanel',
|
|
436
|
-
'aria-labelledby': 'dim-general-settings-tab-general' }, h(GroupHistorySettings, { rpcCall }))
|
|
437
|
+
'aria-labelledby': 'dim-general-settings-tab-general' }, h(SidebarSettings, { rpcCall }), h(GroupHistorySettings, { rpcCall }))
|
|
437
438
|
: h(AttachmentSettingsPanel, { rpcCall }));
|
|
438
439
|
}
|
|
@@ -10,6 +10,14 @@ const EN = Object.freeze({
|
|
|
10
10
|
...diagnostics,
|
|
11
11
|
...imageInput,
|
|
12
12
|
'$locale': 'en',
|
|
13
|
+
'侧边栏入口': 'Sidebar entry',
|
|
14
|
+
'自动模式:未配置渠道时显示,配置至少一个渠道后隐藏。隐藏后仍可从插件详情或设置进入,不影响机器人后台运行。': 'Automatic: show before any channel is configured, then hide. Plugin details and Settings remain available; bots keep running in the background.',
|
|
15
|
+
'自动隐藏': 'Auto-hide',
|
|
16
|
+
'始终显示': 'Always show',
|
|
17
|
+
'始终隐藏': 'Always hide',
|
|
18
|
+
'正在读取侧边栏设置…': 'Loading sidebar settings…',
|
|
19
|
+
'无法读取或保存侧边栏设置,请稍后重试。': 'Unable to read or save sidebar settings. Try again.',
|
|
20
|
+
'侧边栏设置返回了无法识别的响应。': 'Unrecognized sidebar settings response.',
|
|
13
21
|
'保持本页打开,等待权限生效': 'Keep this page open while the permission takes effect',
|
|
14
22
|
"群聊天记录": "Group chat history",
|
|
15
23
|
"群聊天记录保留天数": "Group chat retention (days)",
|
|
@@ -84,6 +84,7 @@ import { UpdatePanel, UPDATE_RPC_CHANNEL } from './update-panel.js';
|
|
|
84
84
|
import { WorkspaceDirectoryPickerContext } from './workspace-editor.js';
|
|
85
85
|
import { IMPanelErrorBoundary } from './panel-error-boundary.js';
|
|
86
86
|
import { installImPluginPage } from './plugin-page.js';
|
|
87
|
+
import { installSidebarVisibilitySync, SIDEBAR_SETTINGS_ENDPOINTS, SIDEBAR_SETTINGS_RPC_CHANNEL } from './sidebar-settings.js';
|
|
87
88
|
|
|
88
89
|
export const name = 'im-settings';
|
|
89
90
|
export const inject = ['slots', 'connection', 'locale', 'workspaces'];
|
|
@@ -492,40 +493,50 @@ export function apply(ctx) {
|
|
|
492
493
|
};
|
|
493
494
|
}, 'im-settings: install combined channel styles');
|
|
494
495
|
|
|
496
|
+
let sidebarSync;
|
|
497
|
+
const managementRpc = async (connection, channel, endpoint, payload, signal) => {
|
|
498
|
+
const result = await callManagementRpc(connection, channel, endpoint, payload, signal);
|
|
499
|
+
if (result?.ok === true) {
|
|
500
|
+
if (endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set) sidebarSync?.apply(result);
|
|
501
|
+
else if (endpoint !== SIDEBAR_SETTINGS_ENDPOINTS.get) sidebarSync?.refresh();
|
|
502
|
+
}
|
|
503
|
+
return result;
|
|
504
|
+
};
|
|
495
505
|
const feishuRpcCall = (endpoint, payload, signal) =>
|
|
496
|
-
|
|
506
|
+
managementRpc(ctx.connection, FEISHU_RPC_CHANNEL, endpoint, payload, signal);
|
|
497
507
|
const weixinRpcCall = (endpoint, payload, signal) =>
|
|
498
|
-
|
|
508
|
+
managementRpc(ctx.connection, WEIXIN_RPC_CHANNEL, endpoint, payload, signal);
|
|
499
509
|
const dingtalkRpcCall = (endpoint, payload, signal) =>
|
|
500
|
-
|
|
510
|
+
managementRpc(ctx.connection, DINGTALK_RPC_CHANNEL, endpoint, payload, signal);
|
|
501
511
|
const qqRpcCall = (endpoint, payload, signal) =>
|
|
502
|
-
|
|
512
|
+
managementRpc(ctx.connection, QQ_RPC_CHANNEL, endpoint, payload, signal);
|
|
503
513
|
const wecomRpcCall = (endpoint, payload, signal) =>
|
|
504
|
-
|
|
514
|
+
managementRpc(ctx.connection, WECOM_RPC_CHANNEL, endpoint, payload, signal);
|
|
505
515
|
const wecomAppRpcCall = (endpoint, payload, signal) =>
|
|
506
|
-
|
|
516
|
+
managementRpc(ctx.connection, WECOM_APP_RPC_CHANNEL, endpoint, payload, signal);
|
|
507
517
|
const telegramRpcCall = (endpoint, payload, signal) =>
|
|
508
|
-
|
|
518
|
+
managementRpc(ctx.connection, TELEGRAM_RPC_CHANNEL, endpoint, payload, signal);
|
|
509
519
|
const discordRpcCall = (endpoint, payload, signal) =>
|
|
510
|
-
|
|
520
|
+
managementRpc(ctx.connection, DISCORD_RPC_CHANNEL, endpoint, payload, signal);
|
|
511
521
|
const whatsappRpcCall = (endpoint, payload, signal) =>
|
|
512
|
-
|
|
522
|
+
managementRpc(ctx.connection, WHATSAPP_RPC_CHANNEL, endpoint, payload, signal);
|
|
513
523
|
const imessageRpcCall = (endpoint, payload, signal) =>
|
|
514
|
-
|
|
524
|
+
managementRpc(ctx.connection, IMESSAGE_RPC_CHANNEL, endpoint, payload, signal);
|
|
515
525
|
const emailRpcCall = (endpoint, payload, signal) =>
|
|
516
|
-
|
|
526
|
+
managementRpc(ctx.connection, EMAIL_RPC_CHANNEL, endpoint, payload, signal);
|
|
517
527
|
const matrixRpcCall = (endpoint, payload, signal) =>
|
|
518
|
-
|
|
528
|
+
managementRpc(ctx.connection, MATRIX_RPC_CHANNEL, endpoint, payload, signal);
|
|
519
529
|
const slackRpcCall = (endpoint, payload, signal) =>
|
|
520
|
-
|
|
530
|
+
managementRpc(ctx.connection, SLACK_RPC_CHANNEL, endpoint, payload, signal);
|
|
521
531
|
const officeRpcCall = (endpoint, payload, signal) =>
|
|
522
|
-
|
|
532
|
+
managementRpc(ctx.connection, OFFICE_RPC_CHANNEL, endpoint, payload, signal);
|
|
523
533
|
const updateRpcCall = (endpoint, payload, signal) =>
|
|
524
|
-
|
|
534
|
+
managementRpc(ctx.connection, UPDATE_RPC_CHANNEL, endpoint, payload, signal);
|
|
525
535
|
const deliveryRpcCall = (endpoint, payload, signal) =>
|
|
526
|
-
|
|
536
|
+
managementRpc(ctx.connection, DELIVERY_RPC_CHANNEL, endpoint, payload, signal);
|
|
527
537
|
const globalSettingsRpcCall = (endpoint, payload, signal) =>
|
|
528
|
-
|
|
538
|
+
managementRpc(ctx.connection, Object.values(SIDEBAR_SETTINGS_ENDPOINTS).includes(endpoint)
|
|
539
|
+
? SIDEBAR_SETTINGS_RPC_CHANNEL : GLOBAL_SETTINGS_RPC_CHANNEL, endpoint, payload, signal);
|
|
529
540
|
const workspaceDirectoryPicker = Object.freeze({
|
|
530
541
|
listDirectory: (path, signal) =>
|
|
531
542
|
callWorkspaceDirectoryApi(ctx, 'listDirectory', path, signal),
|
|
@@ -567,11 +578,20 @@ export function apply(ctx) {
|
|
|
567
578
|
preferredSectionId: props.preferredSectionId,
|
|
568
579
|
});
|
|
569
580
|
|
|
570
|
-
installImPluginPage(ctx, {
|
|
581
|
+
const pluginPage = installImPluginPage(ctx, {
|
|
571
582
|
packageName: manifest.name,
|
|
572
583
|
renderPanel: buildPanelElement,
|
|
573
584
|
});
|
|
574
585
|
|
|
586
|
+
ctx.effect(() => {
|
|
587
|
+
sidebarSync = installSidebarVisibilitySync({
|
|
588
|
+
rpcCall: (endpoint, payload, signal) =>
|
|
589
|
+
callManagementRpc(ctx.connection, SIDEBAR_SETTINGS_RPC_CHANNEL, endpoint, payload, signal),
|
|
590
|
+
setVisible: (visible) => pluginPage.setSidebarVisible(visible),
|
|
591
|
+
});
|
|
592
|
+
return () => { sidebarSync.dispose(); sidebarSync = null; };
|
|
593
|
+
}, 'im-settings: sidebar visibility');
|
|
594
|
+
|
|
575
595
|
ctx.effect(() => {
|
|
576
596
|
let disposed = false;
|
|
577
597
|
let stopSettings = null;
|
|
@@ -34,8 +34,19 @@ function ImSidebarIcon({ size }) {
|
|
|
34
34
|
|
|
35
35
|
// Optional services and slots keep the existing settings entry working on
|
|
36
36
|
// older DSH versions. Reuse the same panel through public navigation APIs.
|
|
37
|
-
export function installImPluginPage(ctx, { packageName, renderPanel }) {
|
|
38
|
-
|
|
37
|
+
export function installImPluginPage(ctx, { packageName, renderPanel, sidebarVisible = false }) {
|
|
38
|
+
// Wait for the Host's saved preference before adding a navigation row. An
|
|
39
|
+
// optimistic show would briefly shift the sidebar on every configured start.
|
|
40
|
+
let visible = sidebarVisible;
|
|
41
|
+
let updateSidebar = null;
|
|
42
|
+
const controller = {
|
|
43
|
+
setSidebarVisible(value) {
|
|
44
|
+
if (typeof value !== 'boolean') throw new TypeError('visible must be a boolean');
|
|
45
|
+
visible = value;
|
|
46
|
+
updateSidebar?.();
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
if (typeof ctx.inject !== 'function') return controller;
|
|
39
50
|
ctx.inject(['layout', 'pluginNavigation'], (pageCtx) =>
|
|
40
51
|
pageCtx.slots.inject('main', () => {
|
|
41
52
|
const unregisterPage = pageCtx.slots.register({
|
|
@@ -45,12 +56,26 @@ export function installImPluginPage(ctx, { packageName, renderPanel }) {
|
|
|
45
56
|
onBack: () => pageCtx.pluginNavigation.openBundle(packageName),
|
|
46
57
|
}),
|
|
47
58
|
}, ImPluginPage);
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
59
|
+
let stopSidebar = null;
|
|
60
|
+
const update = () => {
|
|
61
|
+
if (visible === (stopSidebar !== null)) return;
|
|
62
|
+
if (!visible) {
|
|
63
|
+
const stop = stopSidebar;
|
|
64
|
+
stopSidebar = null;
|
|
65
|
+
stop();
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
// Own the slot subscription, including late declarations, so toggling
|
|
69
|
+
// cannot leave a pending registration or add a duplicate entry.
|
|
70
|
+
stopSidebar = pageCtx.slots.inject('sidebar.panellist', () =>
|
|
71
|
+
pageCtx.slots.register({
|
|
72
|
+
name: 'sidebar.panellist', id: IM_MAIN_PANEL_ID,
|
|
73
|
+
order: 10, label: () => pageCtx.locale.bind(IM_LOCALE_NAMESPACE)('IM机器人'),
|
|
74
|
+
locale: IM_LOCALE_NAMESPACE,
|
|
75
|
+
}, ImSidebarIcon));
|
|
76
|
+
};
|
|
77
|
+
updateSidebar = update;
|
|
78
|
+
update();
|
|
54
79
|
const stopActions = pageCtx.slots.inject('plugins.detail.actions', () =>
|
|
55
80
|
pageCtx.slots.register({
|
|
56
81
|
name: 'plugins.detail.actions', id: 'xmanrui-dsh-im-open',
|
|
@@ -62,8 +87,10 @@ export function installImPluginPage(ctx, { packageName, renderPanel }) {
|
|
|
62
87
|
}, OpenImAction));
|
|
63
88
|
return () => {
|
|
64
89
|
stopActions();
|
|
65
|
-
|
|
90
|
+
updateSidebar = null;
|
|
91
|
+
stopSidebar?.();
|
|
66
92
|
unregisterPage();
|
|
67
93
|
};
|
|
68
94
|
}));
|
|
95
|
+
return controller;
|
|
69
96
|
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
import { h } from './i18n.js';
|
|
3
|
+
|
|
4
|
+
export const SIDEBAR_SETTINGS_RPC_CHANNEL = '/dsh-im-sidebar';
|
|
5
|
+
export const SIDEBAR_SETTINGS_ENDPOINTS = Object.freeze({
|
|
6
|
+
get: 'settings.sidebar-entry.get', set: 'settings.sidebar-entry.set',
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
function settingsResult(result) {
|
|
10
|
+
if (result?.ok === false) throw new Error(result.error?.message || '无法读取或保存侧边栏设置,请稍后重试。');
|
|
11
|
+
const value = result?.ok === true ? result.value : result;
|
|
12
|
+
if (!['auto', 'show', 'hide'].includes(value?.mode) || typeof value.visible !== 'boolean') {
|
|
13
|
+
throw new Error('侧边栏设置返回了无法识别的响应。');
|
|
14
|
+
}
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** One small Host read at startup and after management calls. A slow fallback
|
|
19
|
+
* observes changes made by another client without mounting a management panel. */
|
|
20
|
+
export function installSidebarVisibilitySync({ rpcCall, setVisible,
|
|
21
|
+
setTimeoutFn = globalThis.setTimeout, clearTimeoutFn = globalThis.clearTimeout,
|
|
22
|
+
pollMs = 30_000,
|
|
23
|
+
}) {
|
|
24
|
+
const abort = new AbortController();
|
|
25
|
+
let timer;
|
|
26
|
+
let running = false;
|
|
27
|
+
let pending = false;
|
|
28
|
+
let revision = 0;
|
|
29
|
+
const schedule = (delay) => {
|
|
30
|
+
clearTimeoutFn(timer);
|
|
31
|
+
if (!abort.signal.aborted) timer = setTimeoutFn(refresh, delay);
|
|
32
|
+
};
|
|
33
|
+
const refresh = async () => {
|
|
34
|
+
if (abort.signal.aborted) return;
|
|
35
|
+
if (running) { pending = true; return; }
|
|
36
|
+
running = true;
|
|
37
|
+
pending = false;
|
|
38
|
+
const current = revision;
|
|
39
|
+
try {
|
|
40
|
+
const value = settingsResult(await rpcCall(SIDEBAR_SETTINGS_ENDPOINTS.get, {}, abort.signal));
|
|
41
|
+
if (!abort.signal.aborted && current === revision && !pending) setVisible(value.visible);
|
|
42
|
+
} catch {
|
|
43
|
+
// Retain the last confirmed visibility (initially hidden) on failure.
|
|
44
|
+
// Settings and plugin details remain available independently.
|
|
45
|
+
} finally {
|
|
46
|
+
running = false;
|
|
47
|
+
schedule(pending ? 0 : pollMs);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
void refresh();
|
|
51
|
+
return {
|
|
52
|
+
refresh() {
|
|
53
|
+
revision++;
|
|
54
|
+
if (running) pending = true;
|
|
55
|
+
else schedule(0);
|
|
56
|
+
},
|
|
57
|
+
apply(value) {
|
|
58
|
+
revision++;
|
|
59
|
+
if (!abort.signal.aborted) setVisible(settingsResult(value).visible);
|
|
60
|
+
},
|
|
61
|
+
dispose() { abort.abort(); clearTimeoutFn(timer); },
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function SidebarSettings({ rpcCall }) {
|
|
66
|
+
const [mode, setMode] = React.useState('auto');
|
|
67
|
+
const [phase, setPhase] = React.useState('loading');
|
|
68
|
+
const [error, setError] = React.useState(null);
|
|
69
|
+
const [saved, setSaved] = React.useState(false);
|
|
70
|
+
const mounted = React.useRef(false);
|
|
71
|
+
const busy = React.useRef(false);
|
|
72
|
+
const failedMode = React.useRef(null);
|
|
73
|
+
const id = React.useId();
|
|
74
|
+
const disabled = phase === 'loading' || phase === 'saving';
|
|
75
|
+
const load = React.useCallback(async (signal) => {
|
|
76
|
+
setPhase('loading'); setError(null); setSaved(false);
|
|
77
|
+
failedMode.current = null;
|
|
78
|
+
try {
|
|
79
|
+
const value = settingsResult(await rpcCall(SIDEBAR_SETTINGS_ENDPOINTS.get, {}, signal));
|
|
80
|
+
if (signal?.aborted || !mounted.current) return;
|
|
81
|
+
setMode(value.mode); setPhase('ready');
|
|
82
|
+
} catch (caught) {
|
|
83
|
+
if (signal?.aborted || !mounted.current) return;
|
|
84
|
+
setError(caught.message); setPhase('error');
|
|
85
|
+
}
|
|
86
|
+
}, [rpcCall]);
|
|
87
|
+
React.useEffect(() => {
|
|
88
|
+
mounted.current = true;
|
|
89
|
+
const abort = new AbortController();
|
|
90
|
+
void load(abort.signal);
|
|
91
|
+
return () => { mounted.current = false; abort.abort(); };
|
|
92
|
+
}, [load]);
|
|
93
|
+
const save = async (nextMode) => {
|
|
94
|
+
if (busy.current || disabled) return;
|
|
95
|
+
const previousMode = mode;
|
|
96
|
+
busy.current = true; setPhase('saving'); setError(null); setSaved(false);
|
|
97
|
+
setMode(nextMode);
|
|
98
|
+
failedMode.current = null;
|
|
99
|
+
try {
|
|
100
|
+
const value = settingsResult(await rpcCall(SIDEBAR_SETTINGS_ENDPOINTS.set, { mode: nextMode }));
|
|
101
|
+
if (mounted.current) { setMode(value.mode); setSaved(true); setPhase('ready'); }
|
|
102
|
+
} catch (caught) {
|
|
103
|
+
if (mounted.current) {
|
|
104
|
+
failedMode.current = nextMode;
|
|
105
|
+
setMode(previousMode); setError(caught.message); setPhase('error');
|
|
106
|
+
}
|
|
107
|
+
} finally { busy.current = false; }
|
|
108
|
+
};
|
|
109
|
+
return h('section', { className: 'dim-botGeneralSettings dim-sidebarSettings', 'aria-label': '侧边栏入口', 'aria-busy': disabled },
|
|
110
|
+
h('div', { className: 'dim-botGeneralRow' },
|
|
111
|
+
h('div', { className: 'dim-botGeneralText' },
|
|
112
|
+
h('div', { className: 'dim-sidebarHeading' },
|
|
113
|
+
h('label', { className: 'dim-botGeneralTitle', htmlFor: id }, '侧边栏入口'),
|
|
114
|
+
h('span', { role: 'status', className: 'dim-botGeneralHelp' },
|
|
115
|
+
phase === 'loading' ? '正在读取侧边栏设置…' : phase === 'saving' ? '保存中…' : saved ? '已保存' : '')),
|
|
116
|
+
h('p', { className: 'dim-botGeneralHelp', id: `${id}-help` }, '自动模式:未配置渠道时显示,配置至少一个渠道后隐藏。隐藏后仍可从插件详情或设置进入,不影响机器人后台运行。')),
|
|
117
|
+
h('div', { className: 'dim-botGeneralControl' },
|
|
118
|
+
h('select', { id, className: 'dim-sidebarSelect', value: mode, disabled, 'aria-describedby': `${id}-help`,
|
|
119
|
+
onChange: (event) => save(event.target.value) },
|
|
120
|
+
h('option', { value: 'auto' }, '自动隐藏'),
|
|
121
|
+
h('option', { value: 'show' }, '始终显示'),
|
|
122
|
+
h('option', { value: 'hide' }, '始终隐藏')),
|
|
123
|
+
h('svg', { width: 16, height: 16, viewBox: '0 0 16 16', 'aria-hidden': true },
|
|
124
|
+
h('path', { d: 'm4 6 4 4 4-4', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5 })))),
|
|
125
|
+
error ? h('div', { className: 'dim-sidebarFeedback' },
|
|
126
|
+
h('p', { role: 'alert', className: 'dim-accessFeedback', 'data-tone': 'error' }, error),
|
|
127
|
+
h('button', { type: 'button', className: 'dim-deliveryButton',
|
|
128
|
+
onClick: () => failedMode.current === null ? load() : save(failedMode.current) }, '重试')) : null);
|
|
129
|
+
}
|
|
@@ -646,6 +646,14 @@ const CSS = String.raw`
|
|
|
646
646
|
.dim-botGeneralControl { position: relative; min-width: 0; max-width: 100%; justify-self: end; color: var(--dsw-alias-label-primary, #1f2329); }
|
|
647
647
|
.dim-botGeneralControl select, .dim-groupHistoryInput { display: block; min-width: 104px; max-width: 100%; height: 36px; padding: 0 36px 0 14px; border: 0; border-radius: 10px; color: inherit; background: var(--dsw-alias-bg-module-platform, #f5f6f7); font: inherit; font-size: 14px; line-height: 22px; appearance: none; }
|
|
648
648
|
.dim-botGeneralControl select { cursor: pointer; }
|
|
649
|
+
.dim-sidebarSettings { border-bottom: 1px solid var(--dsw-alias-border-l2, #dfe1e5); }
|
|
650
|
+
.dim-sidebarSettings .dim-botGeneralRow { border-bottom: 0; }
|
|
651
|
+
.dim-sidebarHeading { display: flex; align-items: baseline; flex-wrap: wrap; gap: 8px; }
|
|
652
|
+
.dim-sidebarFeedback { display: flex; align-items: center; gap: 12px; padding-bottom: 16px; }
|
|
653
|
+
.dim-sidebarFeedback .dim-accessFeedback { flex: 1; min-width: 0; }
|
|
654
|
+
/* Native option popups do not inherit the select's painted background on
|
|
655
|
+
Windows. Set both colors so dark Host text never lands on a light popup. */
|
|
656
|
+
.dim-sidebarSelect option { color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-bg-layer-3, #fff); }
|
|
649
657
|
.dim-botGeneralControl select:hover:not(:disabled), .dim-groupHistoryInput:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover, #eef0f3); }
|
|
650
658
|
.dim-botGeneralControl select:focus-visible, .dim-groupHistoryInput:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary, #3370ff); outline-offset: 2px; }
|
|
651
659
|
.dim-botGeneralControl select:disabled, .dim-groupHistoryInput:disabled { opacity: .5; cursor: not-allowed; }
|
|
@@ -4,6 +4,7 @@ import { createConnectionDiagnostics, diagnosticRpcResult } from '../../../../sr
|
|
|
4
4
|
import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
|
|
5
5
|
import { registerManagementRpc } from '../../../management-rpc.mjs';
|
|
6
6
|
import QRCode from 'qrcode';
|
|
7
|
+
import { qrEncodingError } from '../../../../src/channels/shared/qr-encoding-error.mjs';
|
|
7
8
|
import { SET_CONTEXT_ENHANCEMENT_ENDPOINT, validContextEnhancementPayload } from '../shared/context-enhancement-rpc.mjs';
|
|
8
9
|
import { SET_ACCESS_POLICY_ENDPOINT, validAccessPolicyPayload } from '../shared/access-policy-rpc.mjs';
|
|
9
10
|
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
|
@@ -242,7 +243,10 @@ export function createDingtalkRpcHandler(controller, { encodeQr = qrDataUrl } =
|
|
|
242
243
|
let encoded = qrCache.get(url);
|
|
243
244
|
if (!encoded) {
|
|
244
245
|
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
|
|
245
|
-
encoded = Promise.resolve().then(() => encodeQr(url))
|
|
246
|
+
encoded = Promise.resolve().then(() => encodeQr(url)).catch(error => {
|
|
247
|
+
if (qrCache.get(url) === encoded) qrCache.delete(url);
|
|
248
|
+
throw qrEncodingError(error);
|
|
249
|
+
});
|
|
246
250
|
qrCache.set(url, encoded);
|
|
247
251
|
}
|
|
248
252
|
return encoded;
|
|
@@ -5,6 +5,7 @@ import { normalizeBotAlias } from '../../../../src/channels/shared/bot-alias.mjs
|
|
|
5
5
|
import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
|
|
6
6
|
import { registerManagementRpc } from '../../../management-rpc.mjs';
|
|
7
7
|
import QRCode from 'qrcode';
|
|
8
|
+
import { qrEncodingError } from '../../../../src/channels/shared/qr-encoding-error.mjs';
|
|
8
9
|
import {
|
|
9
10
|
normalizeAgentPresetCatalog,
|
|
10
11
|
normalizeAgentPresetId,
|
|
@@ -613,7 +614,10 @@ export function createFeishuRpcHandler(controller, { encodeQr = qrCodeDataUrl }
|
|
|
613
614
|
let encoded = qrCache.get(url);
|
|
614
615
|
if (!encoded) {
|
|
615
616
|
if (qrCache.size >= 32) qrCache.delete(qrCache.keys().next().value);
|
|
616
|
-
encoded = Promise.resolve().then(() => encodeQr(url))
|
|
617
|
+
encoded = Promise.resolve().then(() => encodeQr(url)).catch(error => {
|
|
618
|
+
if (qrCache.get(url) === encoded) qrCache.delete(url);
|
|
619
|
+
throw qrEncodingError(error);
|
|
620
|
+
});
|
|
617
621
|
qrCache.set(url, encoded);
|
|
618
622
|
}
|
|
619
623
|
return encoded;
|
|
@@ -3,6 +3,7 @@ import { createConnectionDiagnostics, diagnosticRpcResult } from '../../../../sr
|
|
|
3
3
|
import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
|
|
4
4
|
import { registerManagementRpc } from '../../../management-rpc.mjs';
|
|
5
5
|
import QRCode from 'qrcode';
|
|
6
|
+
import { qrEncodingError } from '../../../../src/channels/shared/qr-encoding-error.mjs';
|
|
6
7
|
import {
|
|
7
8
|
connectionTestTargetUnavailable,
|
|
8
9
|
publicConnectionTestResult,
|
|
@@ -148,7 +149,10 @@ export function createQqRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
|
|
|
148
149
|
let encoded = qrCache.get(url);
|
|
149
150
|
if (!encoded) {
|
|
150
151
|
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
|
|
151
|
-
encoded = Promise.resolve().then(() => encodeQr(url))
|
|
152
|
+
encoded = Promise.resolve().then(() => encodeQr(url)).catch(error => {
|
|
153
|
+
if (qrCache.get(url) === encoded) qrCache.delete(url);
|
|
154
|
+
throw qrEncodingError(error);
|
|
155
|
+
});
|
|
152
156
|
qrCache.set(url, encoded);
|
|
153
157
|
}
|
|
154
158
|
return encoded;
|
|
@@ -3,6 +3,7 @@ import { createConnectionDiagnostics, diagnosticRpcResult } from '../../../../sr
|
|
|
3
3
|
import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
|
|
4
4
|
import { registerManagementRpc } from '../../../management-rpc.mjs';
|
|
5
5
|
import QRCode from 'qrcode';
|
|
6
|
+
import { qrEncodingError } from '../../../../src/channels/shared/qr-encoding-error.mjs';
|
|
6
7
|
import { SET_CONTEXT_ENHANCEMENT_ENDPOINT, validContextEnhancementPayload } from '../shared/context-enhancement-rpc.mjs';
|
|
7
8
|
import { SET_ACCESS_POLICY_ENDPOINT, validAccessPolicyPayload } from '../shared/access-policy-rpc.mjs';
|
|
8
9
|
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
|
@@ -149,7 +150,10 @@ export function createWecomRpcHandler(controller, { encodeQr = qrDataUrl } = {})
|
|
|
149
150
|
let encoded = qrCache.get(url);
|
|
150
151
|
if (!encoded) {
|
|
151
152
|
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
|
|
152
|
-
encoded = Promise.resolve().then(() => encodeQr(url))
|
|
153
|
+
encoded = Promise.resolve().then(() => encodeQr(url)).catch(error => {
|
|
154
|
+
if (qrCache.get(url) === encoded) qrCache.delete(url);
|
|
155
|
+
throw qrEncodingError(error);
|
|
156
|
+
});
|
|
153
157
|
qrCache.set(url, encoded);
|
|
154
158
|
}
|
|
155
159
|
return encoded;
|
|
@@ -2,6 +2,7 @@ import { SET_MESSAGE_MODE_ENDPOINT, validMessageModePayload } from '../../../../
|
|
|
2
2
|
import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
|
|
3
3
|
import { registerManagementRpc } from '../../../management-rpc.mjs';
|
|
4
4
|
import QRCode from 'qrcode';
|
|
5
|
+
import { qrEncodingError } from '../../../../src/channels/shared/qr-encoding-error.mjs';
|
|
5
6
|
import { createWeixinDiagnostics, weixinStageError } from '../../../../src/channels/weixin/connection-error.mjs';
|
|
6
7
|
import { SET_CONTEXT_ENHANCEMENT_ENDPOINT, validContextEnhancementPayload } from '../shared/context-enhancement-rpc.mjs';
|
|
7
8
|
import { SET_ACCESS_POLICY_ENDPOINT, validAccessPolicyPayload } from '../shared/access-policy-rpc.mjs';
|
|
@@ -170,8 +171,8 @@ export function createWeixinRpcHandler(controller, { encodeQr = qrDataUrl, logge
|
|
|
170
171
|
if (!encoded) {
|
|
171
172
|
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
|
|
172
173
|
encoded = Promise.resolve().then(() => encodeQr(url)).catch(error => {
|
|
173
|
-
qrCache.delete(url);
|
|
174
|
-
throw weixinStageError('qr-encode-failed', error);
|
|
174
|
+
if (qrCache.get(url) === encoded) qrCache.delete(url);
|
|
175
|
+
throw weixinStageError('qr-encode-failed', qrEncodingError(error));
|
|
175
176
|
});
|
|
176
177
|
qrCache.set(url, encoded);
|
|
177
178
|
}
|
|
@@ -3,6 +3,7 @@ import { createConnectionDiagnostics, diagnosticRpcResult } from '../../../../sr
|
|
|
3
3
|
import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
|
|
4
4
|
import { registerManagementRpc } from '../../../management-rpc.mjs';
|
|
5
5
|
import QRCode from 'qrcode';
|
|
6
|
+
import { qrEncodingError } from '../../../../src/channels/shared/qr-encoding-error.mjs';
|
|
6
7
|
|
|
7
8
|
import { publicConnectionTestResult } from '../../../../src/channels/shared/connection-test.mjs';
|
|
8
9
|
import { SET_ACCESS_POLICY_ENDPOINT, validAccessPolicyPayload } from '../shared/access-policy-rpc.mjs';
|
|
@@ -134,7 +135,10 @@ export function createWhatsappRpcHandler(controller, { encodeQr = qrDataUrl } =
|
|
|
134
135
|
let encoded = qrCache.get(value);
|
|
135
136
|
if (!encoded) {
|
|
136
137
|
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
|
|
137
|
-
encoded = Promise.resolve().then(() => encodeQr(value))
|
|
138
|
+
encoded = Promise.resolve().then(() => encodeQr(value)).catch(error => {
|
|
139
|
+
if (qrCache.get(value) === encoded) qrCache.delete(value);
|
|
140
|
+
throw qrEncodingError(error);
|
|
141
|
+
});
|
|
138
142
|
qrCache.set(value, encoded);
|
|
139
143
|
}
|
|
140
144
|
return encoded;
|
|
@@ -20,6 +20,7 @@ import { installDeliveryRpc } from './delivery-rpc.mjs';
|
|
|
20
20
|
import { installDeliveryHttp } from './delivery-http.mjs';
|
|
21
21
|
import { createDeliveryService } from './delivery-service.mjs';
|
|
22
22
|
import { installInboundTtlRpc } from './inbound-ttl-rpc.mjs';
|
|
23
|
+
import { installSidebarSettingsRpc } from './sidebar-settings.mjs';
|
|
23
24
|
import { installInjectedContext } from './injected-context.mjs';
|
|
24
25
|
import { installSessionSyncCoordinator } from './session-sync-coordinator.mjs';
|
|
25
26
|
import { installSessionTitlePrefix } from './session-title-prefix.mjs';
|
|
@@ -45,6 +46,7 @@ export function createImHostPlugin(internals = {}) {
|
|
|
45
46
|
const startHostLanguageRpc = internals.installHostLanguageRpc ?? installHostLanguageRpc;
|
|
46
47
|
const startUpdate = internals.installUpdateRpc ?? installUpdateRpc;
|
|
47
48
|
const startInboundTtl = internals.installInboundTtlRpc ?? installInboundTtlRpc;
|
|
49
|
+
const startSidebarSettings = internals.installSidebarSettingsRpc ?? installSidebarSettingsRpc;
|
|
48
50
|
const startInjectedContext = internals.installInjectedContext ?? installInjectedContext;
|
|
49
51
|
const startDelivery = internals.installDeliveryRpc ?? installDeliveryRpc;
|
|
50
52
|
const startDeliveryHttp = internals.installDeliveryHttp ?? installDeliveryHttp;
|
|
@@ -175,6 +177,11 @@ export function createImHostPlugin(internals = {}) {
|
|
|
175
177
|
} catch (error) {
|
|
176
178
|
logger.error?.('[dsh-im] failed to activate update management; continuing with channels', error);
|
|
177
179
|
}
|
|
180
|
+
try {
|
|
181
|
+
startSidebarSettings(ctx, { config });
|
|
182
|
+
} catch (error) {
|
|
183
|
+
logger.error?.('[dsh-im] failed to activate sidebar settings; continuing with channels', error);
|
|
184
|
+
}
|
|
178
185
|
try {
|
|
179
186
|
startInboundTtl(ctx, { config });
|
|
180
187
|
} catch (error) {
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { registerManagementRpc } from '../management-rpc.mjs';
|
|
6
|
+
|
|
7
|
+
import { PluginConfigStore } from '../../src/channels/feishu/plugin-config-store.mjs';
|
|
8
|
+
import { WeixinConfigStore } from '../../src/channels/weixin/config-store.mjs';
|
|
9
|
+
import { DingtalkConfigStore } from '../../src/channels/dingtalk/config-store.mjs';
|
|
10
|
+
import { WecomConfigStore } from '../../src/channels/wecom/config-store.mjs';
|
|
11
|
+
import { WecomAppConfigStore } from '../../src/channels/wecom-app/config-store.mjs';
|
|
12
|
+
import { QqConfigStore } from '../../src/channels/qq/config-store.mjs';
|
|
13
|
+
import { SlackConfigStore } from '../../src/channels/slack/config-store.mjs';
|
|
14
|
+
import { TelegramConfigStore } from '../../src/channels/telegram/config-store.mjs';
|
|
15
|
+
import { DiscordConfigStore } from '../../src/channels/discord/config-store.mjs';
|
|
16
|
+
import { WhatsappConfigStore } from '../../src/channels/whatsapp/config-store.mjs';
|
|
17
|
+
import { IMessageConfigStore } from '../../src/channels/imessage/config-store.mjs';
|
|
18
|
+
import { EmailConfigStore } from '../../src/channels/email/config-store.mjs';
|
|
19
|
+
import { MatrixConfigStore } from '../../src/channels/matrix/matrix-config-store.mjs';
|
|
20
|
+
import { OfficeConfigStore } from '../../src/channels/office/config-store.mjs';
|
|
21
|
+
|
|
22
|
+
export const SIDEBAR_SETTINGS_RPC_CHANNEL = '/dsh-im-sidebar';
|
|
23
|
+
export const SIDEBAR_SETTINGS_ENDPOINTS = Object.freeze({
|
|
24
|
+
get: 'settings.sidebar-entry.get', set: 'settings.sidebar-entry.set',
|
|
25
|
+
});
|
|
26
|
+
const MODES = new Set(['auto', 'show', 'hide']);
|
|
27
|
+
const CHANNEL_STORES = [
|
|
28
|
+
['feishu', PluginConfigStore], ['weixin', WeixinConfigStore],
|
|
29
|
+
['dingtalk', DingtalkConfigStore], ['wecom', WecomConfigStore],
|
|
30
|
+
['wecomApp', WecomAppConfigStore, 'wecom-app'], ['qq', QqConfigStore],
|
|
31
|
+
['slack', SlackConfigStore], ['telegram', TelegramConfigStore],
|
|
32
|
+
['discord', DiscordConfigStore], ['whatsapp', WhatsappConfigStore],
|
|
33
|
+
['imessage', IMessageConfigStore], ['email', EmailConfigStore],
|
|
34
|
+
['matrix', MatrixConfigStore], ['office', OfficeConfigStore],
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
function dshHome(config) {
|
|
38
|
+
return resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Read saved accounts, not connection state or workspace history. An offline
|
|
42
|
+
* bot still counts; an unfinished QR login does not. Reuse each channel's schema
|
|
43
|
+
* and the same per-channel path overrides as production. */
|
|
44
|
+
export async function hasConfiguredChannel(config = {}) {
|
|
45
|
+
const results = await Promise.allSettled(CHANNEL_STORES.map(async ([key, Store, channel = key]) => {
|
|
46
|
+
const options = { dshHome: dshHome(config), ...config[key] };
|
|
47
|
+
const root = resolve(options.dataDir ?? join(dshHome(options), 'integrations', `dsh-${channel}`));
|
|
48
|
+
const store = await new Store(resolve(options.configPath ?? join(root, 'config.json'))).load();
|
|
49
|
+
return key === 'office' ? store.get() !== null : store.list().length > 0;
|
|
50
|
+
}));
|
|
51
|
+
if (results.some((result) => result.status === 'fulfilled' && result.value)) return true;
|
|
52
|
+
// Unknown configuration must not be mistaken for deleting the last channel.
|
|
53
|
+
const failed = results.find((result) => result.status === 'rejected');
|
|
54
|
+
if (failed) throw failed.reason;
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export class SidebarSettingsStore {
|
|
59
|
+
#path;
|
|
60
|
+
#writes = Promise.resolve();
|
|
61
|
+
constructor(path) { this.#path = path; }
|
|
62
|
+
|
|
63
|
+
async get() {
|
|
64
|
+
let raw;
|
|
65
|
+
try { raw = await readFile(this.#path, 'utf8'); }
|
|
66
|
+
catch (error) { if (error.code === 'ENOENT') return 'auto'; throw error; }
|
|
67
|
+
const value = JSON.parse(raw);
|
|
68
|
+
if (value?.version !== 1 || !MODES.has(value.mode)) throw new Error('Invalid sidebar settings');
|
|
69
|
+
return value.mode;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async set(mode) {
|
|
73
|
+
if (!MODES.has(mode)) throw new TypeError('Invalid sidebar mode');
|
|
74
|
+
const operation = this.#writes.catch(() => {}).then(async () => {
|
|
75
|
+
await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
|
|
76
|
+
const temporary = `${this.#path}.${randomUUID()}.tmp`;
|
|
77
|
+
try {
|
|
78
|
+
await writeFile(temporary, `${JSON.stringify({ version: 1, mode }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
79
|
+
await rename(temporary, this.#path);
|
|
80
|
+
} finally { await rm(temporary, { force: true }); }
|
|
81
|
+
return mode;
|
|
82
|
+
});
|
|
83
|
+
this.#writes = operation;
|
|
84
|
+
return operation;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function createSidebarSettingsRpcHandler({ config = {}, store, configured } = {}) {
|
|
89
|
+
store ??= new SidebarSettingsStore(join(dshHome(config), 'integrations', 'dsh-im', 'sidebar-settings.json'));
|
|
90
|
+
configured ??= () => hasConfiguredChannel(config);
|
|
91
|
+
return async (endpoint, payload, signal) => {
|
|
92
|
+
const valid = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
93
|
+
&& (endpoint === SIDEBAR_SETTINGS_ENDPOINTS.get ? Object.keys(payload).length === 0
|
|
94
|
+
: endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set && Object.keys(payload).length === 1 && MODES.has(payload.mode));
|
|
95
|
+
if (!valid) return { ok: false, error: { code: 'bad-request', message: 'Invalid sidebar settings.' } };
|
|
96
|
+
if (signal?.aborted) return { ok: false, error: { code: 'cancelled', message: 'Request cancelled.' } };
|
|
97
|
+
try {
|
|
98
|
+
const mode = endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set ? payload.mode : await store.get();
|
|
99
|
+
const visible = mode === 'show' || (mode === 'auto' && !await configured());
|
|
100
|
+
if (endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set) await store.set(mode);
|
|
101
|
+
return { ok: true, value: { mode, visible } };
|
|
102
|
+
} catch {
|
|
103
|
+
return { ok: false, error: { code: 'sidebar-settings-unavailable', message: '无法读取或保存侧边栏设置,请稍后重试。' } };
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function installSidebarSettingsRpc(ctx, { config = {} } = {}) {
|
|
109
|
+
// Visibility follows ordinary channel management authority. Keep it separate
|
|
110
|
+
// from the general settings route, whose TTL operations remain loopback-only.
|
|
111
|
+
return registerManagementRpc(ctx, SIDEBAR_SETTINGS_RPC_CHANNEL,
|
|
112
|
+
createSidebarSettingsRpcHandler({ config }), { authority: config.rpcAuthority });
|
|
113
|
+
}
|