@michengai/dsh-im-connect 1.0.12 → 1.0.13

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/lib/client.js CHANGED
@@ -1,4 +1,57 @@
1
1
  window.__ModuleLoader__.load({ id: "@michengai/dsh-im-connect", factory: (require) => {
2
+ /**
3
+ * API 基址解析:把插件自己的根绝对路径端点解析到页面实际所在的 base 之下。
4
+ *
5
+ * 为什么需要:DSH 可能被挂在带路径前缀的反向代理后面(例如 https://host/app/dsh/,
6
+ * 网关转发前剥掉前缀)。此时浏览器把根绝对路径 "/api/..." 解析到站点根,前缀丢失,
7
+ * 网关返回自己的 HTML 404,面板就报「服务端返回非 JSON 响应(HTTP 404)」。
8
+ *
9
+ * 为什么这么解析:宿主前端同样以页面 base 解析 API 路径(参见 dsh-client-connection 的
10
+ * openConnectionWebSocket 与 dsh-client-file-upload 的 new URL(path, document.baseURI)),
11
+ * 这里沿用同一约定——先去掉前导 "/",再用 new URL 相对解析;若直接 new URL("/api/x", base)
12
+ * 会丢弃 base 的路径段,前缀就没了。
13
+ */
14
+ /** 页面基准地址;末尾补斜杠,避免 /app/dsh 这类无斜杠页面把前缀解析掉一级。 */
15
+ function pageBaseHref() {
16
+ const doc = globalThis.document;
17
+ if (typeof doc === 'undefined' || doc === null)
18
+ return undefined;
19
+ const raw = doc.baseURI;
20
+ if (typeof raw !== 'string' || raw === '')
21
+ return undefined;
22
+ try {
23
+ const url = new URL(raw);
24
+ if (!url.pathname.endsWith('/'))
25
+ url.pathname += '/';
26
+ return url.href;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ /**
33
+ * 解析插件端点 URL。
34
+ *
35
+ * @param path 端点路径,通常是 "/api/dsh-im-connect/xxx" 这类根绝对路径。
36
+ * @returns 基于页面 base 的绝对 URL;相对路径、完整 URL、协议相对 URL、无 document
37
+ * 或 base 非法时原样返回,保证非浏览器环境与测试夹具行为不变。
38
+ */
39
+ function resolveApiUrl(path) {
40
+ if (typeof path !== 'string' || path.charAt(0) !== '/' || path.charAt(1) === '/')
41
+ return path;
42
+ const base = pageBaseHref();
43
+ if (base === undefined)
44
+ return path;
45
+ try {
46
+ return new URL(path.slice(1), base).href;
47
+ }
48
+ catch {
49
+ return path;
50
+ }
51
+ }
52
+
53
+
54
+
2
55
  const UPDATE_HEADER = "x-michengai-plugin-update";
3
56
  const STYLE_ID = "michengai-plugin-update-ui";
4
57
  const updatePrimitives = (typeof require === "function" ? (function () { try { return require("@deepseek-ai/dsh-client-ui-primitives"); } catch { return {}; } })() : {});
@@ -149,6 +202,7 @@ function ensurePluginUpdateStyle() {
149
202
  style.setAttribute("data-plugin", "@michengai/dsh-im-connect");
150
203
  (document.head ?? document.documentElement).append(style);
151
204
  }
205
+
152
206
  function validPayload(value) {
153
207
  if (value === null || typeof value !== "object") return false;
154
208
  const item = value;
@@ -234,6 +288,7 @@ function UpdateDialog(props) {
234
288
  }
235
289
  function observePluginUpdate(options) {
236
290
  if (typeof document === "undefined" || document.body === null) return () => {};
291
+ const endpoint = resolveApiUrl(options.endpoint);
237
292
  ensurePluginUpdateStyle();
238
293
  const createRoot = ReactDOM.createRoot || function createRootFallback(host) {
239
294
  return {
@@ -268,7 +323,7 @@ function observePluginUpdate(options) {
268
323
  const root = createRoot(host);
269
324
  dialogRoot = root;
270
325
  root.render(React.createElement(UpdateDialog, {
271
- flow: createUpdateFlow((method) => requestStatus(options.endpoint, method, controller.signal), payload, (next) => { payload = next; applyControls(); }),
326
+ flow: createUpdateFlow((method) => requestStatus(endpoint, method, controller.signal), payload, (next) => { payload = next; applyControls(); }),
272
327
  packageName: options.packageName, zhName: options.zhName, enName: options.enName, onClose: closeDialog,
273
328
  }));
274
329
  }
@@ -276,6 +331,26 @@ function observePluginUpdate(options) {
276
331
  const row = document.querySelector(options.titleRowSelector);
277
332
  if (row === null) return;
278
333
  const heading = row.querySelector("h1,h2");
334
+ const links = row.querySelector(options.linksSelector);
335
+
336
+ if (options.isEnabled && !options.isEnabled()) {
337
+ if (dialogHost !== undefined) closeDialog();
338
+ if (links !== null) {
339
+ const existing = links.querySelector(`[data-mpi-check="${options.packageName}"]`);
340
+ if (existing !== null) {
341
+ unmountCheck();
342
+ existing.remove();
343
+ }
344
+ }
345
+ if (heading !== null) {
346
+ const version = heading.querySelector(`.mpi-version[data-package="${options.packageName}"]`);
347
+ if (version !== null) {
348
+ version.remove();
349
+ }
350
+ }
351
+ return;
352
+ }
353
+
279
354
  if (heading !== null && payload !== undefined) {
280
355
  let version = heading.querySelector(`.mpi-version[data-package="${options.packageName}"]`);
281
356
  if (version === null) {
@@ -288,7 +363,6 @@ function observePluginUpdate(options) {
288
363
  if (version.textContent !== versionLabel) version.textContent = versionLabel;
289
364
  }
290
365
  if (buttonHost !== undefined && !buttonHost.isConnected) unmountCheck();
291
- const links = row.querySelector(options.linksSelector);
292
366
  if (links === null) return;
293
367
  const existing = links.querySelector(`[data-mpi-check="${options.packageName}"]`);
294
368
  if (existing !== null) {
@@ -305,7 +379,7 @@ function observePluginUpdate(options) {
305
379
  renderCheck();
306
380
  };
307
381
  const load = async () => {
308
- payload = await requestStatus(options.endpoint, "GET", controller.signal);
382
+ payload = await requestStatus(endpoint, "GET", controller.signal);
309
383
  applyControls();
310
384
  return payload;
311
385
  };
@@ -314,9 +388,15 @@ function observePluginUpdate(options) {
314
388
  frame = window.requestAnimationFrame(() => { frame = undefined; applyControls(); });
315
389
  });
316
390
  observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ["lang"] });
391
+ const onToggle = () => {
392
+ applyControls();
393
+ if (!options.isEnabled || options.isEnabled()) void load().catch(() => {});
394
+ };
395
+ if (typeof window !== "undefined") window.addEventListener("ima-update-toggle", onToggle);
317
396
  applyControls();
318
397
  void load().catch(() => {});
319
- return () => {
398
+ const cleanup = () => {
399
+ if (typeof window !== "undefined") window.removeEventListener("ima-update-toggle", onToggle);
320
400
  controller.abort();
321
401
  observer.disconnect();
322
402
  closeDialog();
@@ -324,6 +404,7 @@ function observePluginUpdate(options) {
324
404
  if (frame !== undefined) window.cancelAnimationFrame(frame);
325
405
  document.querySelectorAll(`[data-mpi-check="${options.packageName}"],.mpi-version[data-package="${options.packageName}"]`).forEach((node) => node.remove());
326
406
  };
407
+ return cleanup;
327
408
  }
328
409
  var module = { exports: {} };
329
410
  var exports = module.exports;
@@ -335,6 +416,7 @@ function observePluginUpdate(options) {
335
416
  const HostMenu = primitives.Menu;
336
417
  const HostModal = primitives.Modal;
337
418
  const HostSegmentedTabs = primitives.SegmentedTabs;
419
+ const PrimitiveSwitch = primitives.Switch;
338
420
  // 宿主 Button 由 forwardRef 包成对象,typeof 是 object,不是 function。
339
421
  function isHostComponent(component) {
340
422
  return typeof component === "function" || (!!component && typeof component === "object" && typeof component.render === "function");
@@ -930,6 +1012,8 @@ function observePluginUpdate(options) {
930
1012
  "connection.title": "本次状态检查", "connection.scope": "仅检查本机渠道运行状态,未验证平台凭据或消息收发。", "connection.checkedAt": "检查时间", "connection.receiveOn": "接收开关已开启", "connection.receiveOff": "接收开关已关闭;请在账号列表开启后再发送消息。", "connection.checking": "检查中…",
931
1013
  "connection.next.connected": "可在原聊天发送消息验证收发;私聊仍需符合准入设置。", "connection.next.connecting": "请稍后再次检查;等待扫码时请完成手机确认。", "connection.next.reconnecting": "渠道正在尝试恢复,请稍后再次检查。", "connection.next.disconnected": "请重新连接;需要扫码的渠道可重新添加绑定。", "connection.next.stopped": "请点击重新连接以启动账号。", "connection.next.error": "请尝试重新连接;仍有异常时查看本机日志。", "connection.next.unknown": "暂时无法确认状态,请稍后再检查或查看本机日志。",
932
1014
  "settings.label": "IM助理", "settings.title": "IM助理", "settings.description": "管理各渠道账号。每个账号独立选择工作区、模型和权限,配置仅保存在本机。", "settings.viewProject": "GitHub", "settings.feedback": "问题反馈",
1015
+ "sidebar.entry.title": "侧边栏入口", "sidebar.entry.desc": "在侧栏显示即时通讯管理入口。设置里的入口不变。", "sidebar.entry.toggle": "切换侧边栏入口",
1016
+ "update.entry.title": "在线更新", "update.entry.desc": "允许检查并在线安装即时通讯插件的新版本。关闭后隐藏更新入口。", "update.entry.toggle": "切换在线更新", "error.update.disabled": "在线更新已被禁用",
933
1017
  "settings.aria": "IM助理", "settings.publicChatNotice": "未批准用户可以发起聊天,但不能批准工具调用。", "pending.notice": "有访问请求。批准后该用户才能驱动本机助手。", "action.approve": "批准", "action.deny": "拒绝", "loading": "加载中…",
934
1018
  "account.presetUnavailable": "预设不可用", "account.presetNote": "更改后使用新会话,旧会话保留。", "action.settings": "设置", "command.dm": "私聊命令", "command.group": "群聊命令", "command.enabled": "可以执行命令", "command.disabled": "仅正常对话",
935
1019
  "account.workspace": "工作区", "account.currentWorkspace": "当前工作区", "account.selectWorkspace": "请选择工作区", "account.selectModel": "请选择模型", "account.selectPermission": "请选择权限", "account.privateAccess": "私聊准入", "account.privateApproved": "仅已批准用户", "account.privateAll": "允许所有私聊用户", "account.sendMode": "发送方式", "account.sendQueue": "排队发送", "account.sendSteer": "插话发送", "account.sendSteerNote": "插话发送会把消息作为补充指令立即交给运行中的任务;任务空闲时与排队发送相同。", "account.autoNameNote": "绑定成功后会自动生成账号名,无需手动填写。需要区分使用者时,可在账号行填写备注。", "account.proxyMode": "网络代理", "account.proxyInherit": "跟随宿主", "account.proxyDirect": "直接连接", "account.proxyCustom": "手动配置", "account.proxyUrl": "代理地址", "account.proxyNote": "仅影响当前账号;保存后自动重连生效。", "account.proxySaved": "代理地址已保存;留空保存可保留当前地址。", "account.defaultName": "{channel}账号 {count}",
@@ -959,6 +1043,8 @@ function observePluginUpdate(options) {
959
1043
  "connection.title": "Status check result", "connection.scope": "Checks local channel runtime only. Platform credentials and message delivery have not been verified.", "connection.checkedAt": "Checked at", "connection.receiveOn": "Receiving is enabled", "connection.receiveOff": "Receiving is disabled. Enable it in the account list before sending messages.", "connection.checking": "Checking…",
960
1044
  "connection.next.connected": "Send a message in the original chat to verify delivery. Private chats still follow access settings.", "connection.next.connecting": "Check again shortly. Complete confirmation on your phone if a QR scan is pending.", "connection.next.reconnecting": "The channel is attempting to recover. Check again shortly.", "connection.next.disconnected": "Reconnect the account. QR channels may need to be added again.", "connection.next.stopped": "Select Reconnect to start the account.", "connection.next.error": "Try reconnecting. If the issue persists, check the local logs.", "connection.next.unknown": "The current state could not be confirmed. Check again later or inspect the local logs.",
961
1045
  "settings.label": "IM Assistant", "settings.title": "IM Assistant", "settings.description": "Manage accounts across channels. Each account has its own workspace, model, and permission settings, stored only on this machine.", "settings.viewProject": "GitHub", "settings.feedback": "Issues",
1046
+ "sidebar.entry.title": "Sidebar entry", "sidebar.entry.desc": "Show IM Connect in the sidebar. The Settings entry stays either way.", "sidebar.entry.toggle": "Toggle sidebar entry",
1047
+ "update.entry.title": "Online updates", "update.entry.desc": "Allow checking and installing new versions online. Hides the update entry when disabled.", "update.entry.toggle": "Toggle online updates", "error.update.disabled": "Online updates are disabled",
962
1048
  "settings.aria": "IM Assistant", "settings.publicChatNotice": "Unapproved users can start chats, but they cannot approve tool calls.", "pending.notice": "There are access requests. Approve a user before they can control the local assistant.", "action.approve": "Approve", "action.deny": "Deny", "loading": "Loading…",
963
1049
  "account.presetUnavailable": "Preset unavailable", "account.presetNote": "Changes start a new session; previous sessions are kept.", "action.settings": "Settings", "command.dm": "DM commands", "command.group": "Group commands", "command.enabled": "Commands enabled", "command.disabled": "Conversation only",
964
1050
  "account.workspace": "Workspace", "account.currentWorkspace": "Current workspace", "account.selectWorkspace": "Select a workspace", "account.selectModel": "Select a model", "account.selectPermission": "Select a permission", "account.privateAccess": "Private chat access", "account.privateApproved": "Approved users only", "account.privateAll": "Allow all DM users", "account.sendMode": "Send mode", "account.sendQueue": "Queue", "account.sendSteer": "Steer", "account.sendSteerNote": "Steer hands the message to the running task as additional instructions at its next step; when the task is idle it behaves like Queue.", "account.autoNameNote": "The account name is generated automatically after setup. Add a remark on the account row if you need to tell users apart.", "account.proxyMode": "Network proxy", "account.proxyInherit": "Follow Host", "account.proxyDirect": "Connect directly", "account.proxyCustom": "Configure manually", "account.proxyUrl": "Proxy address", "account.proxyNote": "Affects only this account. The channel reconnects automatically after saving.", "account.proxySaved": "A proxy address is saved. Leave the field blank to keep it.", "account.defaultName": "{channel} account {count}",
@@ -1165,7 +1251,7 @@ function observePluginUpdate(options) {
1165
1251
  .ima-btn-danger:hover:not(:disabled){color:var(--dsw-alias-state-error-primary,var(--ima-danger))!important;border-color:var(--dsw-alias-state-error-primary,var(--ima-danger))!important;background:rgba(239,68,68,.12)!important}
1166
1252
  .ima-btn-danger-primary,.ima-btn-danger.ima-btn-danger-primary{background:var(--dsw-alias-state-error-primary,var(--ima-danger))!important;border-color:var(--dsw-alias-state-error-primary,var(--ima-danger))!important;color:#fff!important}
1167
1253
  @container (max-width:480px){.ima-account-row{grid-template-columns:minmax(0,1fr) auto auto;gap:8px;padding:10px}.ima-account-receive>span{display:none}.ima-platform-head{padding:10px 12px}.ima-account-list{padding:0 12px 12px}}
1168
-
1254
+ .ima-main-panel{box-sizing:border-box;height:100%;min-height:0;overflow-y:auto;display:flex;flex-direction:column;align-items:center;padding:28px clamp(24px,4vw,48px) 48px}.ima-main-panel>*{width:100%;max-width:960px}.ima-bundle-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:12px 0;border-bottom:0.5px solid var(--dsw-alias-border-l2)}.ima-bundle-label-box{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1;text-align:left}.ima-bundle-title{font-size:13px;font-weight:500;line-height:20px;color:var(--dsw-alias-label-primary)}.ima-bundle-desc{font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
1169
1255
  `;
1170
1256
 
1171
1257
  const TITLE_LINK_CSS = "@media(max-width:720px){.ima-title-row{flex-wrap:wrap}}";
@@ -1266,7 +1352,8 @@ function observePluginUpdate(options) {
1266
1352
  request.headers = Object.assign({ "content-type": "application/json" }, request.headers || {}, { "x-dsh-im-connect-client": "1" });
1267
1353
  if (request.body === undefined) request.body = "{}";
1268
1354
  }
1269
- return fetch(API_BASE + path, request).then((r) => r.json()).then((data) => {
1355
+ const targetUrl = typeof resolveApiUrl === "function" ? resolveApiUrl(API_BASE + path) : API_BASE + path;
1356
+ return fetch(targetUrl, request).then((r) => r.json()).then((data) => {
1270
1357
  if (!request.signal?.aborted && data.ok && Array.isArray(data.groups)) updateChannelMembership(data.groups);
1271
1358
  return data;
1272
1359
  });
@@ -2056,8 +2143,12 @@ function observePluginUpdate(options) {
2056
2143
  if (!next) { setHint(t("error.chooseWorkspace")); return Promise.resolve(); }
2057
2144
  if (typeof props.createWorkspace !== "function") { setHint(t("error.workspaceUnavailable")); return Promise.resolve(); }
2058
2145
  setAddBusy(true);
2059
- return Promise.resolve(props.createWorkspace({ path: next })).then((created) => {
2060
- const cwdPath = (created && (created.path || created.cwd)) || next;
2146
+ return Promise.resolve().then(() => props.createWorkspace({ path: next })).then((created) => {
2147
+ const cwdPath = created && (created.path || created.cwd);
2148
+ if (typeof cwdPath !== "string" || !cwdPath.trim()) {
2149
+ setHint(t("error.addWorkspace"));
2150
+ return;
2151
+ }
2061
2152
  update({ cwd: cwdPath });
2062
2153
  }).catch((error) => setHint((error && error.message) || t("error.addWorkspace")))
2063
2154
  .finally(() => setAddBusy(false));
@@ -3621,19 +3712,33 @@ function observePluginUpdate(options) {
3621
3712
  }
3622
3713
  openListed(id);
3623
3714
  };
3715
+ const safeExpandSidebar = useCallback(() => {}, []);
3716
+ const rawUseWorkspaceShortcuts = typeof props.useWorkspaceShortcuts === "function" ? props.useWorkspaceShortcuts : undefined;
3717
+ const useIsolatedWorkspaceShortcuts = useCallback((select, equals) => {
3718
+ if (typeof rawUseWorkspaceShortcuts !== "function") return select({ searchRequest: 0, addRequested: false, directoryBusy: false, renameTarget: null });
3719
+ return rawUseWorkspaceShortcuts((state) => select(Object.assign({}, state, { searchRequest: 0 })), equals);
3720
+ }, [rawUseWorkspaceShortcuts]);
3721
+ const guardedHostProps = Object.assign({}, props, {
3722
+ expandSidebar: safeExpandSidebar,
3723
+ useWorkspaceShortcuts: useIsolatedWorkspaceShortcuts,
3724
+ });
3624
3725
  const officialProps = Object.assign({}, props, { useSessions: useTaskSessions, t: officialT, openSession, open: openSession });
3726
+ const guardedOfficialProps = Object.assign({}, officialProps, {
3727
+ expandSidebar: safeExpandSidebar,
3728
+ useWorkspaceShortcuts: useIsolatedWorkspaceShortcuts,
3729
+ });
3625
3730
  const channelView = h(ChannelOfficialView, {
3626
3731
  officialTree: Official,
3627
- hostProps: props,
3732
+ hostProps: guardedHostProps,
3628
3733
  hostT: officialT,
3629
3734
  t,
3630
3735
  openSession,
3631
3736
  openChannelSettings: props.openChannelSettings,
3632
3737
  openImSettings: props.openImSettings,
3633
3738
  });
3634
- if (props.wide === false) return Official ? h(Official, officialProps) : null;
3739
+ if (props.wide === false) return Official ? h(Official, guardedOfficialProps) : null;
3635
3740
  const officialTree = Official
3636
- ? h("div", { className: "ima-official-tree" }, h(Official, officialProps))
3741
+ ? h("div", { className: "ima-official-tree" }, h(Official, guardedOfficialProps))
3637
3742
  : null;
3638
3743
  const visibleTab = resolveSidebarTab(tab, extraTabs);
3639
3744
  const extra = extraTabs.find((item) => item.id === visibleTab);
@@ -3784,6 +3889,330 @@ function observePluginUpdate(options) {
3784
3889
  || component.__dshAutomationOriginal !== undefined);
3785
3890
  }
3786
3891
 
3892
+ const BUNDLE_KEY = "@michengai/dsh-im-connect";
3893
+ const SIDEBAR_PANEL_ID = "im-connect";
3894
+ const SIDEBAR_PANEL_ORDER = 3;
3895
+
3896
+ function ImSidebarIcon(props) {
3897
+ const size = props && typeof props.size === "number" ? props.size : 16;
3898
+ return h(IconQueueOutline, { size });
3899
+ }
3900
+
3901
+ function ImBundleConfigCard(props) {
3902
+ const {
3903
+ t,
3904
+ enabled,
3905
+ onToggle,
3906
+ disabled,
3907
+ onlineUpdateEnabled = true,
3908
+ onToggleOnlineUpdate,
3909
+ onlineUpdateDisabled,
3910
+ onlineUpdateLocked = false,
3911
+ } = props;
3912
+
3913
+ const SwitchComponent = PrimitiveSwitch || Switch;
3914
+ const rows = [
3915
+ h("div", { key: "sidebar-entry", className: "ima-bundle-row" },
3916
+ h("div", { className: "ima-bundle-label-box" },
3917
+ h("span", { className: "ima-bundle-title" }, t("sidebar.entry.title")),
3918
+ h("span", { className: "ima-bundle-desc" }, t("sidebar.entry.desc"))
3919
+ ),
3920
+ h(SwitchComponent, {
3921
+ checked: enabled,
3922
+ onChange: onToggle,
3923
+ label: t("sidebar.entry.toggle"),
3924
+ disabled: disabled,
3925
+ })
3926
+ ),
3927
+ ];
3928
+
3929
+ if (typeof onToggleOnlineUpdate === "function") {
3930
+ const updateDesc = onlineUpdateLocked
3931
+ ? `${t("update.entry.desc")} (${t("error.update.disabled")})`
3932
+ : t("update.entry.desc");
3933
+ rows.push(
3934
+ h("div", { key: "online-update", className: "ima-bundle-row" },
3935
+ h("div", { className: "ima-bundle-label-box" },
3936
+ h("span", { className: "ima-bundle-title" }, t("update.entry.title")),
3937
+ h("span", { className: "ima-bundle-desc" }, updateDesc)
3938
+ ),
3939
+ h(SwitchComponent, {
3940
+ checked: onlineUpdateEnabled,
3941
+ onChange: onToggleOnlineUpdate,
3942
+ label: t("update.entry.toggle"),
3943
+ disabled: onlineUpdateDisabled || onlineUpdateLocked,
3944
+ })
3945
+ )
3946
+ );
3947
+ }
3948
+
3949
+ return h(React.Fragment, null, rows);
3950
+ }
3951
+
3952
+ function ImBundleConfigCardWrapper(props) {
3953
+ const [enabled, setEnabled] = useState(props.getEnabled);
3954
+ const [onlineUpdateEnabled, setOnlineUpdateEnabled] = useState(props.getOnlineUpdateEnabled ? props.getOnlineUpdateEnabled : () => true);
3955
+ const [onlineUpdateLocked, setOnlineUpdateLocked] = useState(props.getOnlineUpdateLocked ? props.getOnlineUpdateLocked : () => false);
3956
+ const [savingSidebar, setSavingSidebar] = useState(false);
3957
+ const [savingUpdate, setSavingUpdate] = useState(false);
3958
+
3959
+ useEffect(() => {
3960
+ setEnabled(props.getEnabled());
3961
+ if (props.getOnlineUpdateEnabled) {
3962
+ setOnlineUpdateEnabled(props.getOnlineUpdateEnabled());
3963
+ }
3964
+ if (props.getOnlineUpdateLocked) {
3965
+ setOnlineUpdateLocked(props.getOnlineUpdateLocked());
3966
+ }
3967
+ return props.subscribe(() => {
3968
+ setEnabled(props.getEnabled());
3969
+ if (props.getOnlineUpdateEnabled) {
3970
+ setOnlineUpdateEnabled(props.getOnlineUpdateEnabled());
3971
+ }
3972
+ if (props.getOnlineUpdateLocked) {
3973
+ setOnlineUpdateLocked(props.getOnlineUpdateLocked());
3974
+ }
3975
+ });
3976
+ }, [props]);
3977
+
3978
+ const onToggleSidebar = (next) => {
3979
+ setSavingSidebar(true);
3980
+ setEnabled(next);
3981
+ props.setSidebar(next).catch(() => {
3982
+ setEnabled(props.getEnabled());
3983
+ }).finally(() => {
3984
+ setSavingSidebar(false);
3985
+ });
3986
+ };
3987
+
3988
+ const onToggleOnlineUpdate = props.setOnlineUpdate ? (next) => {
3989
+ if (onlineUpdateLocked) return;
3990
+ setSavingUpdate(true);
3991
+ setOnlineUpdateEnabled(next);
3992
+ props.setOnlineUpdate(next).catch(() => {
3993
+ if (props.getOnlineUpdateEnabled) {
3994
+ setOnlineUpdateEnabled(props.getOnlineUpdateEnabled());
3995
+ }
3996
+ }).finally(() => {
3997
+ setSavingUpdate(false);
3998
+ });
3999
+ } : undefined;
4000
+
4001
+ return h(ImBundleConfigCard, {
4002
+ t: props.t,
4003
+ enabled,
4004
+ disabled: savingSidebar,
4005
+ onToggle: onToggleSidebar,
4006
+ onlineUpdateEnabled,
4007
+ onlineUpdateDisabled: savingUpdate,
4008
+ onlineUpdateLocked,
4009
+ onToggleOnlineUpdate,
4010
+ });
4011
+ }
4012
+
4013
+ function setupSidebarEntry(ctx, options) {
4014
+ if (!ctx.locale) {
4015
+ return {
4016
+ isEnabled: () => false,
4017
+ isSupported: () => false,
4018
+ setEnabled: async () => false,
4019
+ isOnlineUpdateEnabled: () => true,
4020
+ setOnlineUpdate: async () => false,
4021
+ destroy: () => {},
4022
+ };
4023
+ }
4024
+ const { callApi, renderPanel, ns } = options;
4025
+ let sidebarEntryEnabled = false;
4026
+ let sidebarSupported = false;
4027
+ let offPanel = null;
4028
+ let offRow = null;
4029
+ let epoch = 0;
4030
+ let layoutService;
4031
+ const listeners = new Set();
4032
+
4033
+ const notify = () => {
4034
+ for (const listener of listeners) {
4035
+ try { listener(); } catch {}
4036
+ }
4037
+ };
4038
+
4039
+ const sync = () => {
4040
+ if (sidebarSupported && sidebarEntryEnabled) {
4041
+ if (!offPanel) {
4042
+ const res = ctx.slots.register({
4043
+ name: "main",
4044
+ key: SIDEBAR_PANEL_ID,
4045
+ locale: ns,
4046
+ inject: () => {
4047
+ const extra = typeof options.injectProps === "function" ? options.injectProps() : options.injectProps;
4048
+ return Object.assign({ t: ctx.locale?.bind ? ctx.locale.bind(ns) : undefined }, extra);
4049
+ },
4050
+ }, (ownerProps) => h("div", { className: "ima-main-panel" }, renderPanel(ownerProps)));
4051
+ offPanel = typeof res === "function" ? res : () => {};
4052
+ }
4053
+ if (!offRow) {
4054
+ const res = ctx.slots.register({
4055
+ name: "sidebar.panellist",
4056
+ id: SIDEBAR_PANEL_ID,
4057
+ order: SIDEBAR_PANEL_ORDER,
4058
+ label: () => ctx.locale.bind(ns)("settings.title"),
4059
+ locale: ns,
4060
+ }, (ownerProps) => h(ImSidebarIcon, ownerProps));
4061
+ offRow = typeof res === "function" ? res : () => {};
4062
+ }
4063
+ } else {
4064
+ if (layoutService?.panelInfo && typeof layoutService.selectPanel === "function") {
4065
+ try {
4066
+ if (layoutService.panelInfo.getSnapshot().activePanelId === SIDEBAR_PANEL_ID) {
4067
+ layoutService.selectPanel(null);
4068
+ }
4069
+ } catch {}
4070
+ }
4071
+ if (offRow) {
4072
+ try { offRow(); } catch {}
4073
+ offRow = null;
4074
+ }
4075
+ if (offPanel) {
4076
+ try { offPanel(); } catch {}
4077
+ offPanel = null;
4078
+ }
4079
+ }
4080
+ };
4081
+
4082
+ const setEnabled = async (next) => {
4083
+ const currentEpoch = ++epoch;
4084
+ sidebarEntryEnabled = next;
4085
+ sync();
4086
+ notify();
4087
+ try {
4088
+ await callApi("/sidebar-entry", {
4089
+ method: "POST",
4090
+ body: JSON.stringify({ enabled: next }),
4091
+ });
4092
+ return next;
4093
+ } catch (err) {
4094
+ if (currentEpoch === epoch) {
4095
+ sidebarEntryEnabled = !next;
4096
+ sync();
4097
+ notify();
4098
+ }
4099
+ throw err;
4100
+ }
4101
+ };
4102
+
4103
+ let onlineUpdateEnabled = true;
4104
+ let onlineUpdateLocked = false;
4105
+ let updateEpoch = 0;
4106
+
4107
+ const setOnlineUpdate = async (next) => {
4108
+ if (onlineUpdateLocked) return onlineUpdateEnabled;
4109
+ const currentEpoch = ++updateEpoch;
4110
+ onlineUpdateEnabled = next;
4111
+ notify();
4112
+ if (typeof options.onOnlineUpdateChange === "function") {
4113
+ try { options.onOnlineUpdateChange(next); } catch {}
4114
+ }
4115
+ try {
4116
+ await callApi("/online-update", {
4117
+ method: "POST",
4118
+ body: JSON.stringify({ enabled: next }),
4119
+ });
4120
+ // 乐观通知可能早于服务端开启;保存完成后再通知更新器重读版本。
4121
+ if (currentEpoch === updateEpoch && typeof options.onOnlineUpdateChange === "function") {
4122
+ options.onOnlineUpdateChange(next);
4123
+ }
4124
+ return next;
4125
+ } catch (err) {
4126
+ if (currentEpoch === updateEpoch) {
4127
+ onlineUpdateEnabled = !next;
4128
+ notify();
4129
+ if (typeof options.onOnlineUpdateChange === "function") {
4130
+ try { options.onOnlineUpdateChange(!next); } catch {}
4131
+ }
4132
+ }
4133
+ throw err;
4134
+ }
4135
+ };
4136
+
4137
+ const loadEpoch = epoch;
4138
+ callApi("/sidebar-entry")
4139
+ .then((res) => {
4140
+ if (epoch === loadEpoch && res && typeof res.enabled === "boolean") {
4141
+ sidebarEntryEnabled = res.enabled;
4142
+ sync();
4143
+ notify();
4144
+ }
4145
+ })
4146
+ .catch(() => {});
4147
+
4148
+ const loadUpdateEpoch = updateEpoch;
4149
+ callApi("/online-update")
4150
+ .then((res) => {
4151
+ if (updateEpoch === loadUpdateEpoch && res) {
4152
+ if (typeof res.enabled === "boolean") onlineUpdateEnabled = res.enabled;
4153
+ if (typeof res.locked === "boolean") onlineUpdateLocked = res.locked;
4154
+ notify();
4155
+ if (typeof options.onOnlineUpdateChange === "function") {
4156
+ try { options.onOnlineUpdateChange(onlineUpdateEnabled); } catch {}
4157
+ }
4158
+ }
4159
+ })
4160
+ .catch(() => {});
4161
+
4162
+ if (typeof ctx.inject === "function") {
4163
+ ctx.inject(["layout"], (scoped) => {
4164
+ layoutService = scoped.layout;
4165
+ });
4166
+ }
4167
+
4168
+ ctx.slots.inject("sidebar.panellist", () => {
4169
+ sidebarSupported = true;
4170
+ sync();
4171
+ });
4172
+
4173
+ ctx.slots.inject("plugins.bundle.config", () => {
4174
+ return ctx.slots.register({
4175
+ name: "plugins.bundle.config",
4176
+ key: BUNDLE_KEY,
4177
+ locale: ns,
4178
+ }, (ownerProps) => {
4179
+ if (ownerProps && ownerProps.view === "summary") return null;
4180
+ return h(ImBundleConfigCardWrapper, {
4181
+ t: ctx.locale.bind(ns),
4182
+ getEnabled: () => sidebarEntryEnabled,
4183
+ setSidebar: setEnabled,
4184
+ getOnlineUpdateEnabled: () => onlineUpdateEnabled,
4185
+ getOnlineUpdateLocked: () => onlineUpdateLocked,
4186
+ setOnlineUpdate: setOnlineUpdate,
4187
+ subscribe: (fn) => {
4188
+ listeners.add(fn);
4189
+ return () => { listeners.delete(fn); };
4190
+ },
4191
+ });
4192
+ });
4193
+ });
4194
+
4195
+ return {
4196
+ isEnabled: () => sidebarEntryEnabled,
4197
+ isSupported: () => sidebarSupported,
4198
+ setEnabled,
4199
+ isOnlineUpdateEnabled: () => onlineUpdateEnabled,
4200
+ isOnlineUpdateLocked: () => onlineUpdateLocked,
4201
+ setOnlineUpdate,
4202
+ destroy: () => {
4203
+ listeners.clear();
4204
+ if (offRow) {
4205
+ try { offRow(); } catch {}
4206
+ offRow = null;
4207
+ }
4208
+ if (offPanel) {
4209
+ try { offPanel(); } catch {}
4210
+ offPanel = null;
4211
+ }
4212
+ },
4213
+ };
4214
+ }
4215
+
3787
4216
  function apply(ctx) {
3788
4217
  ensureStyle();
3789
4218
  ctx.effect(() => {
@@ -3816,6 +4245,25 @@ function observePluginUpdate(options) {
3816
4245
  }), "im-connect: channel membership");
3817
4246
  ctx.effect(() => ctx.locale.register(IM_LOCALE_NS, IM_LOCALES), "im-connect: dictionaries");
3818
4247
  const t = ctx.locale.bind(IM_LOCALE_NS);
4248
+ const permissionT = ctx.locale.bind("permission.access");
4249
+ const modelT = ctx.locale.bind("model");
4250
+ const presetT = ctx.locale.bind("settings.agentPreset");
4251
+ const sidebarController = setupSidebarEntry(ctx, {
4252
+ callApi: api,
4253
+ renderPanel: (ownerProps) => h(LocalizedSettingsPage, ownerProps),
4254
+ ns: IM_LOCALE_NS,
4255
+ injectProps: () => ({
4256
+ createWorkspace: typeof ctx.workspaces?.create === "function" ? (input) => ctx.workspaces.create(input) : undefined,
4257
+ pickDirectory: () => pickHostDirectory(ctx),
4258
+ permissionT,
4259
+ modelT,
4260
+ presetT,
4261
+ }),
4262
+ onOnlineUpdateChange: () => {
4263
+ if (typeof window !== "undefined") window.dispatchEvent(new CustomEvent("ima-update-toggle"));
4264
+ },
4265
+ });
4266
+ ctx.effect(() => () => sidebarController.destroy(), "im-connect: sidebar entry");
3819
4267
  ctx.effect(() => observePluginUpdate({
3820
4268
  endpoint: "/api/michengai/dsh-im-connect/update",
3821
4269
  packageName: "@michengai/dsh-im-connect",
@@ -3824,10 +4272,8 @@ function observePluginUpdate(options) {
3824
4272
  zhName: t("settings.title"),
3825
4273
  enName: t("settings.title"),
3826
4274
  createIcon: createPluginUpdateIcon,
4275
+ isEnabled: () => sidebarController.isOnlineUpdateEnabled(),
3827
4276
  }), "im-connect: plugin update ui");
3828
- const permissionT = ctx.locale.bind("permission.access");
3829
- const modelT = ctx.locale.bind("model");
3830
- const presetT = ctx.locale.bind("settings.agentPreset");
3831
4277
  const subscribeLocale = (listener) => ctx.locale.subscribe(listener);
3832
4278
  const localeSnapshot = () => ctx.locale.getSnapshot();
3833
4279
  const openChannelSettings = (request) => {
@@ -3951,7 +4397,7 @@ function observePluginUpdate(options) {
3951
4397
  icon: "chat",
3952
4398
  locale: IM_LOCALE_NS,
3953
4399
  inject: () => ({
3954
- createWorkspace: (input) => ctx.workspaces.create(input),
4400
+ createWorkspace: typeof ctx.workspaces?.create === "function" ? (input) => ctx.workspaces.create(input) : undefined,
3955
4401
  pickDirectory: () => pickHostDirectory(ctx),
3956
4402
  permissionT,
3957
4403
  modelT,
@@ -4135,5 +4581,7 @@ function observePluginUpdate(options) {
4135
4581
 
4136
4582
  exports.apply = apply;
4137
4583
  exports.inject = inject;
4584
+ exports.resolveApiUrl = resolveApiUrl;
4585
+ exports.setupSidebarEntry = setupSidebarEntry;
4138
4586
  return module.exports;
4139
4587
  } });
package/lib/index.d.ts CHANGED
@@ -14,6 +14,8 @@ export interface PluginConfig {
14
14
  agentPreset: string;
15
15
  mergeTimeoutSecs: number;
16
16
  topicNaming: TopicMode;
17
+ updater?: boolean;
18
+ onlineUpdate?: boolean;
17
19
  }
18
20
  export declare const Config: Schema<PluginConfig>;
19
21
  export declare function apply(ctx: Context, config: PluginConfig): void;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,MAAM,MAAM,0BAA0B,CAAA;AAM7C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAA;AAIxD,eAAO,MAAM,IAAI,mBAAmB,CAAA;AACpC,eAAO,MAAM,MAAM,UAQlB,CAAA;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAA;IAChB,GAAG,EAAE,MAAM,CAAA;IACX,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,WAAW,EAAE,MAAM,CAAA;IACnB,gBAAgB,EAAE,MAAM,CAAA;IACxB,WAAW,EAAE,SAAS,CAAA;CACvB;AAED,eAAO,MAAM,MAAM,EAAE,MAAM,CAAC,YAAY,CAQtC,CAAA;AAEF,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,GAAG,IAAI,CAyC9D;AAED,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACjF,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,EACV,aAAa,EACb,aAAa,EACb,YAAY,GACb,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,MAAM,MAAM,0BAA0B,CAAA;AAM7C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAA;AAIxD,eAAO,MAAM,IAAI,mBAAmB,CAAA;AACpC,eAAO,MAAM,MAAM,UAQlB,CAAA;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAA;IAChB,GAAG,EAAE,MAAM,CAAA;IACX,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,WAAW,EAAE,MAAM,CAAA;IACnB,gBAAgB,EAAE,MAAM,CAAA;IACxB,WAAW,EAAE,SAAS,CAAA;IACtB,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,YAAY,CAAC,EAAE,OAAO,CAAA;CACvB;AAED,eAAO,MAAM,MAAM,EAAE,MAAM,CAAC,YAAY,CAUtC,CAAA;AAEF,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,GAAG,IAAI,CA2C9D;AAED,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACjF,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,EACV,aAAa,EACb,aAAa,EACb,YAAY,GACb,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA"}