bailinghub 0.3.3 → 0.4.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.
Files changed (91) hide show
  1. package/README.en.md +3 -1
  2. package/README.md +4 -0
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/CHANGELOG.en.md +58 -1
  5. package/docs/CHANGELOG.md +26 -1
  6. package/docs/COMPATIBILITY.en.md +25 -0
  7. package/docs/CONTRACT.en.md +91 -8
  8. package/docs/CONTRACT.md +39 -7
  9. package/docs/DEMO.en.md +6 -0
  10. package/docs/DEMO.md +2 -0
  11. package/docs/INDEPENDENT_VALIDATION.en.md +9 -6
  12. package/docs/INDEPENDENT_VALIDATION.md +9 -6
  13. package/docs/QUICKSTART.en.md +20 -0
  14. package/docs/QUICKSTART.md +2 -2
  15. package/docs/README.en.md +4 -0
  16. package/docs/README.md +4 -0
  17. package/docs/RELEASE_NOTES_v0.3.4.en.md +38 -0
  18. package/docs/RELEASE_NOTES_v0.3.4.md +38 -0
  19. package/docs/RELEASE_NOTES_v0.4.0.en.md +39 -0
  20. package/docs/RELEASE_NOTES_v0.4.0.md +39 -0
  21. package/docs/STREAMING.en.md +32 -0
  22. package/docs/STREAMING.md +8 -2
  23. package/docs/WIDGET_RENDERERS.en.md +123 -6
  24. package/docs/WIDGET_RENDERERS.md +75 -6
  25. package/docs/user-guide/concepts.en.md +8 -1
  26. package/docs/user-guide/concepts.md +3 -1
  27. package/docs/user-guide/console-map.en.md +1 -2
  28. package/docs/user-guide/console-map.md +3 -3
  29. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +9 -0
  30. package/package.json +1 -1
  31. package/schemas/config/chat-entry.schema.json +2 -1
  32. package/scripts/check-doc-links.mjs +2 -0
  33. package/scripts/check-image-tags.sh +1 -1
  34. package/scripts/check-release-consistency.test.mjs +5 -5
  35. package/scripts/e2e-console.mjs +38 -10
  36. package/scripts/install.sh +1 -1
  37. package/scripts/publish-images.sh +1 -1
  38. package/scripts/release-audit.mjs +2 -0
  39. package/scripts/verify-github-repo.mjs +2 -0
  40. package/scripts/widget-renderer-test.mjs +244 -16
  41. package/src/core/config/config-models.test.ts +18 -1
  42. package/src/core/config/config-models.ts +25 -3
  43. package/src/core/config/config-schema.test.ts +2 -0
  44. package/src/core/contracts/types.ts +2 -1
  45. package/src/core/platform/chat-form.test.ts +147 -0
  46. package/src/core/platform/chat-form.ts +402 -0
  47. package/src/core/platform/version.ts +1 -1
  48. package/src/core/runtime/execution-runtime.test.ts +73 -4
  49. package/src/core/runtime/execution-runtime.ts +18 -1
  50. package/src/routes/chat-mount.test.ts +9 -1
  51. package/src/routes/chat.test.ts +319 -7
  52. package/src/routes/chat.ts +179 -28
  53. package/web/console/assets/{Accounts-08VltF2i.js → Accounts-DuUY2UJU.js} +1 -1
  54. package/web/console/assets/{Approvals-CqgmsMau.js → Approvals-B11mo1dy.js} +1 -1
  55. package/web/console/assets/{Audit-bPlpSQt3.js → Audit-CQwJRIJT.js} +1 -1
  56. package/web/console/assets/{BrandLockup-DhX07g3G.js → BrandLockup-BIF-h1pi.js} +1 -1
  57. package/web/console/assets/{Channels-BZe0pLgx.js → Channels-BIploUT-.js} +1 -1
  58. package/web/console/assets/ChatEntries-Cpg_WV-o.js +7 -0
  59. package/web/console/assets/ChatEntries-DsYtcXN6.css +1 -0
  60. package/web/console/assets/Clients--D7NQJKk.css +1 -0
  61. package/web/console/assets/{Clients-BVVZfX3r.js → Clients-DS29eUi2.js} +2 -2
  62. package/web/console/assets/{Cost-DANcjr_p.js → Cost-BF52tfU2.js} +1 -1
  63. package/web/console/assets/{Credentials-D_8tP2Xa.js → Credentials-SwfmQAv6.js} +1 -1
  64. package/web/console/assets/{Diagnostics-Bw1WImFe.js → Diagnostics-CJfbI_8p.js} +1 -1
  65. package/web/console/assets/{Executors-fuieN2Sl.js → Executors-CzlZlznA.js} +1 -1
  66. package/web/console/assets/{Kb-BaMi_7xf.js → Kb-CVX22U4k.js} +1 -1
  67. package/web/console/assets/{Login-Cmz2ppY8.js → Login-PoUVsBI-.js} +1 -1
  68. package/web/console/assets/{Projects-D6xIgFB3.js → Projects-DYlbjLQy.js} +1 -1
  69. package/web/console/assets/{Routes-B90i3ZNa.js → Routes-DSEvGujN.js} +1 -1
  70. package/web/console/assets/{Runs-9qpwotOj.js → Runs-B-TsYZEt.js} +1 -1
  71. package/web/console/assets/Setup-D7nxgn-9.css +1 -0
  72. package/web/console/assets/Setup-xiPXit_b.js +1 -0
  73. package/web/console/assets/{Shell-Dm6eFcl1.js → Shell-DNiWZOYB.js} +1 -1
  74. package/web/console/assets/{StorageBuckets-DY8WuJlM.js → StorageBuckets-Bjsc3pLd.js} +1 -1
  75. package/web/console/assets/{SystemSettings-O_NMPzq_.js → SystemSettings-CcKF2lJ9.js} +1 -1
  76. package/web/console/assets/{SystemStatus-Cok3S7S3.js → SystemStatus-Oj1xjxJn.js} +1 -1
  77. package/web/console/assets/{Targets-YWBoxqvy.js → Targets-y1KllVXT.js} +1 -1
  78. package/web/console/assets/{Tools-BgXDw7Mg.js → Tools-DoEP_y9x.js} +1 -1
  79. package/web/console/assets/{index-S_J0I0Zh.js → index-CxPIS6G7.js} +2 -2
  80. package/web/console/assets/{request-FM608Kfz.js → request-CBLNpLth.js} +1 -1
  81. package/web/console/assets/{schema-DWnFqTkB.js → schema-DzwLpuOy.js} +1 -1
  82. package/web/console/index.html +1 -1
  83. package/web/widget/widget.js +493 -14
  84. package/web-admin/src/pages/ChatEntries.vue +46 -23
  85. package/web-admin/src/pages/Clients.vue +2 -2
  86. package/web-admin/src/pages/Setup.vue +12 -8
  87. package/web/console/assets/ChatEntries-BweMx_CU.css +0 -1
  88. package/web/console/assets/ChatEntries-Ca0lcGqn.js +0 -7
  89. package/web/console/assets/Clients-DcTYN-Js.css +0 -1
  90. package/web/console/assets/Setup-BIjCiA2i.js +0 -1
  91. package/web/console/assets/Setup-BuyKFofL.css +0 -1
@@ -2,7 +2,7 @@
2
2
  * 用法:<script src="https://你的中枢/widget.js" data-entry="pub_xxx" async></script>
3
3
  * 可选:data-open="1" 加载即展开(演示页用);
4
4
  * data-ticket="v1.xxx.yyy" 签名访客票据(业务后端在登录态里签发后输出到页面,让登录用户带可信身份;游客不带照常匿名聊)。
5
- * 标题/开场白/主色在控制台「聊天入口」配置,改完即生效(组件每次加载拉取 /chat/:entry/config)。
5
+ * 标题/开场白/主色/默认展开在控制台「聊天入口」配置,改完即生效(组件每次加载拉取 /chat/:entry/config)。
6
6
  * 安全边界:entry_key 可公开;消息走 POST /chat/:entry(Origin 白名单+IP 限速在中枢侧);
7
7
  * 组件只持有 visitor_id(会话连续性用的随机串)与服务端签好的票据,自己造不出任何业务身份。
8
8
  *
@@ -21,6 +21,7 @@
21
21
  const RENDERER_TYPE_RE = /^[a-z][a-z0-9._+-]{0,63}$/;
22
22
  const DEFAULT_RENDERER_PAYLOAD_BYTES = 64 * 1024;
23
23
  const MAX_RENDERER_PAYLOAD_BYTES = 256 * 1024;
24
+ const FORM_RENDERER_TYPE = 'bailing-form';
24
25
  const script = document.currentScript;
25
26
  if (!script) return;
26
27
  const ENTRY = script.dataset.entry;
@@ -28,7 +29,7 @@
28
29
  const scriptUrl = new URL(script.src);
29
30
  const HUB = scriptUrl.origin + scriptUrl.pathname.replace(/\/widget\.js$/, '');
30
31
  const hubAsset = (value) => typeof value === 'string' && value.startsWith('/') ? HUB + value : value;
31
- const AUTO_OPEN = script.dataset.open === '1';
32
+ const SCRIPT_AUTO_OPEN = script.dataset.open === '1';
32
33
  const TICKET = script.dataset.ticket || '';
33
34
  const LS_VISITOR = `bailing_visitor_${ENTRY}`;
34
35
  const LS_HISTORY = `bailing_chat_${ENTRY}`;
@@ -76,6 +77,16 @@
76
77
  bailingChatApi.rendererApiVersion = RENDERER_API;
77
78
  bailingChatApi.registerRenderer = registerRenderer;
78
79
  bailingChatApi.setContext = (o) => { try { bailingChatApi._ctx = (o && typeof o === 'object') ? o : null; } catch { /* 忽略 */ } };
80
+ // 官方表单也通过同一个可扩展 registry 工作:先注册零依赖内置实现,再装载宿主预注册项。
81
+ // 因此同名的宿主 renderer 会明确覆盖内置实现;它仍只拿到受限 mount context,拿不到 ticket/visitor。
82
+ registerRenderer({
83
+ type: FORM_RENDERER_TYPE,
84
+ version: 1,
85
+ label: '交互表单',
86
+ contentType: 'application/json',
87
+ maxPayloadBytes: 32 * 1024,
88
+ mount: mountBailingForm,
89
+ });
79
90
  for (const definition of preloadedRenderers) {
80
91
  try { registerRenderer(definition); }
81
92
  catch (e) { console.warn('[百灵聊天组件] 忽略不合法的预注册渲染器', e); }
@@ -119,13 +130,34 @@
119
130
  if (!Array.isArray(history)) history = [];
120
131
  let pending = false;
121
132
  let pendingAtt = null; // 待发送的媒体附件 {type,url,name,uploading?,error?}(单个,再选/录会替换)
122
- let cfg = { enabled: true, title: '在线咨询', greeting: '', color: '#7a5b3a', brand: '',
133
+ let cfg = { enabled: true, title: '在线咨询', greeting: '', color: '#7a5b3a', brand: '', default_open: false,
123
134
  width: 400, height: 600, title_align: 'center', position: 'right', offset_x: 24, offset_y: 24, avatar: '', launcher_icon: '', resizable: false, ai_notice: true,
124
135
  powered_by_visible: true, powered_by_text: '' };
125
136
 
126
137
  function saveHistory() {
127
138
  try { localStorage.setItem(LS_HISTORY, JSON.stringify(history.slice(-50))); } catch { /* 容量/隐私模式 */ }
128
139
  }
140
+ function normalizeInteractionMeta(value) {
141
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
142
+ const type = String(value.type || '').trim().toLowerCase();
143
+ const sourceJobId = String(value.source_job_id || '').trim();
144
+ const formId = String(value.form_id || '').trim();
145
+ const submissionId = String(value.submission_id || '').trim();
146
+ const action = String(value.action || '').trim().toLowerCase();
147
+ if (type !== FORM_RENDERER_TYPE || Number(value.version) !== 1 || !sourceJobId || !formId || !submissionId) return null;
148
+ if (action !== 'submit' && action !== 'cancel') return null;
149
+ return Object.freeze({ type, version: 1, source_job_id: sourceJobId, form_id: formId, submission_id: submissionId, action });
150
+ }
151
+ function formResponsesForJob(jobId) {
152
+ const sourceJobId = String(jobId || '');
153
+ if (!sourceJobId) return Object.freeze([]);
154
+ const responses = [];
155
+ for (const item of history) {
156
+ const interaction = normalizeInteractionMeta(item && (item.i || item.interaction));
157
+ if (interaction && interaction.source_job_id === sourceJobId) responses.push(interaction);
158
+ }
159
+ return Object.freeze(responses);
160
+ }
129
161
  // 生成新会话线程 id([a-z0-9],≤32,与后端清洗规则一致);crypto 不可用时退回时间戳+随机
130
162
  function newThreadId() {
131
163
  let r = '';
@@ -306,6 +338,34 @@
306
338
  .attchip button { background: none; border: none; color: #b8b0a4; cursor: pointer; font-size: 15px;
307
339
  line-height: 1; padding: 0 2px; }
308
340
  .attchip button:hover { color: #b3554a; }
341
+ .bailing-form { display: flex; flex-direction: column; gap: 12px; min-width: min(420px, 100%); color: #3d372f; }
342
+ .bailing-form .bf-head { display: flex; flex-direction: column; gap: 3px; }
343
+ .bailing-form .bf-title { font-size: 16px; line-height: 1.45; font-weight: 700; }
344
+ .bailing-form .bf-description { color: #756e63; font-size: 12px; line-height: 1.55; white-space: pre-wrap; }
345
+ .bailing-form .bf-fields { display: flex; flex-direction: column; gap: 11px; border: 0; min-width: 0; }
346
+ .bailing-form .bf-field { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
347
+ .bailing-form .bf-label { color: #4a443c; font-size: 13px; line-height: 1.45; font-weight: 600; }
348
+ .bailing-form .bf-required { color: #b3554a; margin-left: 3px; }
349
+ .bailing-form .bf-help { color: #8f877b; font-size: 11px; line-height: 1.45; white-space: pre-wrap; }
350
+ .bailing-form input[type="text"], .bailing-form input[type="number"], .bailing-form input[type="date"],
351
+ .bailing-form textarea, .bailing-form select { width: 100%; min-width: 0; border: 1px solid #ddd7cd; border-radius: 8px;
352
+ background: #fff; color: #3d372f; padding: 8px 10px; font-size: 13px; line-height: 1.45; outline: none; }
353
+ .bailing-form textarea { min-height: 76px; resize: vertical; }
354
+ .bailing-form input:focus, .bailing-form textarea:focus, .bailing-form select:focus { border-color: var(--accent); }
355
+ .bailing-form .bf-choices { display: flex; flex-wrap: wrap; gap: 7px 14px; }
356
+ .bailing-form .bf-choice { display: inline-flex; align-items: center; gap: 6px; color: #514b42; font-size: 13px; line-height: 1.45; }
357
+ .bailing-form .bf-choice input { accent-color: var(--accent); }
358
+ .bailing-form .bf-field-error { display: none; color: #b3554a; font-size: 11px; line-height: 1.4; }
359
+ .bailing-form .bf-field-error.on { display: block; }
360
+ .bailing-form .bf-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
361
+ .bailing-form .bf-actions button { border: 1px solid #ddd7cd; border-radius: 8px; background: #fff; color: #6f685c;
362
+ padding: 7px 14px; font-size: 12px; line-height: 1.4; cursor: pointer; }
363
+ .bailing-form .bf-actions button.primary { border-color: var(--accent); background: var(--accent); color: #fff; }
364
+ .bailing-form .bf-actions button:disabled { opacity: .55; cursor: default; }
365
+ .bailing-form .bf-status { min-height: 17px; color: #7b7368; font-size: 12px; line-height: 1.45; }
366
+ .bailing-form .bf-status.error { color: #b3554a; }
367
+ .bailing-form .bf-status.receipt { border: 1px solid #dde8dc; border-radius: 8px; background: #f4f8f3; color: #537052; padding: 8px 10px; }
368
+ .bailing-form.is-complete .bf-fields { opacity: .72; }
309
369
  /* 移动端自适应:小屏面板接近全屏,沟通不憋屈(!important 压过位置/尺寸变量与 .pos-left 高优先级规则)*/
310
370
  @media (max-width: 480px) {
311
371
  .panel { width: calc(100vw - 16px) !important; height: calc(100dvh - 92px) !important;
@@ -495,6 +555,287 @@
495
555
  pre.appendChild(code);
496
556
  return pre;
497
557
  }
558
+ const FORM_ID_RE = /^[a-z][a-z0-9_-]{0,63}$/;
559
+ const FORM_FIELD_RE = /^[a-z][a-z0-9_-]{0,63}$/;
560
+ const FORM_SENSITIVE_RE = /(?:password|passwd|\bpwd\b|secret|token|api[ _-]?key|access[ _-]?key|private[ _-]?key|credit[ _-]?card|card[ _-]?(?:number|no)|\bcvv\b|\bcvc\b|密码|口令|密钥|私钥|令牌|银行卡|信用卡|卡号)/i;
561
+ const FORM_TEXT_CONTROL_RE = /[\u0000-\u001f\u007f]/;
562
+ const FORM_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
563
+ const FORM_FIELD_TYPES = new Set(['text', 'textarea', 'number', 'date', 'boolean', 'single_select', 'multi_select']);
564
+ const FORM_TOP_KEYS = new Set(['version', 'form_id', 'title', 'description', 'schema', 'submit_label', 'cancel_label']);
565
+ const FORM_COMMON_FIELD_KEYS = ['type', 'label', 'description', 'placeholder', 'required'];
566
+ const FORM_FIELD_KEYS = {
567
+ text: new Set([...FORM_COMMON_FIELD_KEYS, 'minLength', 'maxLength']),
568
+ textarea: new Set([...FORM_COMMON_FIELD_KEYS, 'minLength', 'maxLength']),
569
+ number: new Set([...FORM_COMMON_FIELD_KEYS, 'min', 'max']),
570
+ date: new Set([...FORM_COMMON_FIELD_KEYS, 'min', 'max']),
571
+ boolean: new Set(FORM_COMMON_FIELD_KEYS),
572
+ single_select: new Set([...FORM_COMMON_FIELD_KEYS, 'options']),
573
+ multi_select: new Set([...FORM_COMMON_FIELD_KEYS, 'options']),
574
+ };
575
+ let formControlSeq = 0;
576
+ function isPlainRecord(value) {
577
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
578
+ const proto = Object.getPrototypeOf(value);
579
+ return proto === Object.prototype || proto === null;
580
+ }
581
+ function strictFormText(value, max, required) {
582
+ if (value === undefined && !required) return undefined;
583
+ if (typeof value !== 'string') throw new TypeError('invalid bailing-form text');
584
+ const text = value.trim();
585
+ if (!text || text.length > max || FORM_TEXT_CONTROL_RE.test(text) || text.includes('```')) throw new TypeError('invalid bailing-form text');
586
+ return text;
587
+ }
588
+ function rejectFormUnknownKeys(value, allowed) {
589
+ if (Object.keys(value).some((key) => !allowed.has(key))) throw new TypeError('unknown bailing-form property');
590
+ }
591
+ function isRealFormDate(value) {
592
+ if (typeof value !== 'string' || !FORM_DATE_RE.test(value)) return false;
593
+ const parts = value.split('-').map(Number);
594
+ const date = new Date(Date.UTC(parts[0], parts[1] - 1, parts[2]));
595
+ return date.getUTCFullYear() === parts[0] && date.getUTCMonth() === parts[1] - 1 && date.getUTCDate() === parts[2];
596
+ }
597
+ function normalizeFormPayload(payload) {
598
+ if (!isPlainRecord(payload) || payload.version !== 1) throw new TypeError('unsupported bailing-form version');
599
+ rejectFormUnknownKeys(payload, FORM_TOP_KEYS);
600
+ const formId = strictFormText(payload.form_id, 64, true);
601
+ const title = strictFormText(payload.title, 80, true);
602
+ const description = strictFormText(payload.description, 300, false);
603
+ const submitLabel = strictFormText(payload.submit_label, 32, false) || '提交';
604
+ const cancelLabel = strictFormText(payload.cancel_label, 32, false) || '取消';
605
+ if (!FORM_ID_RE.test(formId) || !isPlainRecord(payload.schema) || FORM_SENSITIVE_RE.test([formId, title, description || ''].join(' '))) {
606
+ throw new TypeError('invalid bailing-form payload');
607
+ }
608
+ const entries = Object.entries(payload.schema);
609
+ if (!entries.length || entries.length > 12) throw new TypeError('invalid bailing-form field count');
610
+ const fields = entries.map(([name, raw]) => {
611
+ if (!FORM_FIELD_RE.test(name) || !isPlainRecord(raw)) throw new TypeError('invalid bailing-form field');
612
+ const type = raw.type;
613
+ if (typeof type !== 'string' || !FORM_FIELD_TYPES.has(type)) throw new TypeError('invalid bailing-form field');
614
+ rejectFormUnknownKeys(raw, FORM_FIELD_KEYS[type]);
615
+ const label = strictFormText(raw.label, 80, true);
616
+ const help = strictFormText(raw.description, 200, false);
617
+ const placeholder = strictFormText(raw.placeholder, 120, false);
618
+ if (raw.required !== undefined && typeof raw.required !== 'boolean') throw new TypeError('invalid bailing-form required');
619
+ if (FORM_SENSITIVE_RE.test([name, label, help || '', placeholder || ''].join(' '))) throw new TypeError('invalid bailing-form field');
620
+ const field = { name, type, label, help, placeholder, required: raw.required === true };
621
+ if (type === 'text' || type === 'textarea') {
622
+ const cap = type === 'textarea' ? 2000 : 500;
623
+ const minLength = raw.minLength === undefined ? 0 : raw.minLength;
624
+ const maxLength = raw.maxLength === undefined ? cap : raw.maxLength;
625
+ if (!Number.isInteger(minLength) || !Number.isInteger(maxLength) || minLength < 0 || maxLength < 1 || maxLength > cap || minLength > maxLength) {
626
+ throw new TypeError('invalid bailing-form text limits');
627
+ }
628
+ field.minLength = minLength;
629
+ field.maxLength = maxLength;
630
+ }
631
+ if (type === 'number') {
632
+ const min = raw.min === undefined ? null : raw.min;
633
+ const max = raw.max === undefined ? null : raw.max;
634
+ if ((min !== null && (typeof min !== 'number' || !Number.isFinite(min))) || (max !== null && (typeof max !== 'number' || !Number.isFinite(max))) || (min !== null && max !== null && min > max)) {
635
+ throw new TypeError('invalid bailing-form number limits');
636
+ }
637
+ field.min = min;
638
+ field.max = max;
639
+ }
640
+ if (type === 'date') {
641
+ const min = raw.min === undefined ? null : raw.min;
642
+ const max = raw.max === undefined ? null : raw.max;
643
+ if ((min !== null && !isRealFormDate(min)) || (max !== null && !isRealFormDate(max)) || (min !== null && max !== null && min > max)) {
644
+ throw new TypeError('invalid bailing-form date limits');
645
+ }
646
+ field.min = min;
647
+ field.max = max;
648
+ }
649
+ if (type === 'single_select' || type === 'multi_select') {
650
+ if (!Array.isArray(raw.options) || !raw.options.length || raw.options.length > 50) throw new TypeError('invalid bailing-form options');
651
+ const seen = new Set();
652
+ field.options = raw.options.map((option) => {
653
+ if (!isPlainRecord(option)) throw new TypeError('invalid bailing-form option');
654
+ rejectFormUnknownKeys(option, new Set(['label', 'value']));
655
+ const optionLabel = strictFormText(option.label, 80, true);
656
+ const optionValue = strictFormText(option.value, 120, true);
657
+ if (seen.has(optionValue)) throw new TypeError('invalid bailing-form option');
658
+ seen.add(optionValue);
659
+ return Object.freeze({ label: optionLabel, value: optionValue });
660
+ });
661
+ }
662
+ return Object.freeze(field);
663
+ });
664
+ return Object.freeze({ version: 1, form_id: formId, title, description, submit_label: submitLabel, cancel_label: cancelLabel, fields: Object.freeze(fields) });
665
+ }
666
+ function newSubmissionId() {
667
+ let random = '';
668
+ try { random = (crypto.randomUUID && crypto.randomUUID().replace(/-/g, '')) || ''; } catch { /* 非安全上下文 */ }
669
+ if (!random) random = Date.now().toString(36) + Math.random().toString(36).slice(2, 14);
670
+ return ('sub_' + random).slice(0, 64);
671
+ }
672
+ function formDisplayText(form, action, rows) {
673
+ if (action === 'cancel') return `已取消填写:${form.title}`;
674
+ const lines = [`已提交:${form.title}`];
675
+ for (const row of rows) lines.push(`${row.label}:${row.text}`);
676
+ return lines.join('\n').slice(0, 4000);
677
+ }
678
+ function mountBailingForm({ container, payload, message, respond, signal }) {
679
+ const formSpec = normalizeFormPayload(payload);
680
+ if (typeof respond !== 'function') throw new TypeError('bailing-form respond unavailable');
681
+ if (!message || !message.jobId || message.jobId.length > 128 || !/^[a-zA-Z0-9_-]+$/.test(message.jobId)) {
682
+ throw new TypeError('bailing-form requires an authoritative source job');
683
+ }
684
+ container.replaceChildren();
685
+ container.dataset.formId = formSpec.form_id;
686
+ const form = document.createElement('form');
687
+ form.className = 'bailing-form';
688
+ const head = document.createElement('div'); head.className = 'bf-head';
689
+ const title = document.createElement('div'); title.className = 'bf-title'; title.textContent = formSpec.title;
690
+ head.appendChild(title);
691
+ if (formSpec.description) { const desc = document.createElement('div'); desc.className = 'bf-description'; desc.textContent = formSpec.description; head.appendChild(desc); }
692
+ const fieldsEl = document.createElement('fieldset'); fieldsEl.className = 'bf-fields';
693
+ const controls = [];
694
+ for (const field of formSpec.fields) {
695
+ const row = document.createElement('div'); row.className = 'bf-field';
696
+ const controlId = `bf-${++formControlSeq}`;
697
+ const label = document.createElement('label'); label.className = 'bf-label'; label.textContent = field.label;
698
+ if (field.required) { const required = document.createElement('span'); required.className = 'bf-required'; required.textContent = '*'; label.appendChild(required); }
699
+ const error = document.createElement('div'); error.className = 'bf-field-error';
700
+ let focusNode = null;
701
+ let nodes = [];
702
+ let readValue;
703
+ if (field.type === 'text' || field.type === 'textarea' || field.type === 'number' || field.type === 'date') {
704
+ const input = document.createElement(field.type === 'textarea' ? 'textarea' : 'input');
705
+ if (field.type !== 'textarea') input.type = field.type;
706
+ input.id = controlId; input.name = field.name; input.required = field.required;
707
+ if (field.placeholder) input.placeholder = field.placeholder;
708
+ if (field.type === 'text' || field.type === 'textarea') {
709
+ input.minLength = field.minLength; input.maxLength = field.maxLength;
710
+ }
711
+ if (field.type === 'number') {
712
+ input.step = 'any';
713
+ if (field.min !== null) input.min = String(field.min);
714
+ if (field.max !== null) input.max = String(field.max);
715
+ }
716
+ if (field.type === 'date') {
717
+ if (field.min !== null) input.min = field.min;
718
+ if (field.max !== null) input.max = field.max;
719
+ }
720
+ label.htmlFor = controlId; row.append(label, input); focusNode = input; nodes = [input];
721
+ readValue = () => {
722
+ const raw = input.value.trim();
723
+ if (!raw) return { omitted: !field.required, value: '', text: '(未填写)' };
724
+ if ((field.type === 'text' || field.type === 'textarea') && raw.length < field.minLength) return { error: `至少输入 ${field.minLength} 个字符` };
725
+ if ((field.type === 'text' || field.type === 'textarea') && raw.length > field.maxLength) return { error: `不能超过 ${field.maxLength} 个字符` };
726
+ if (field.type === 'number') {
727
+ const number = Number(raw);
728
+ if (!Number.isFinite(number)) return { error: '请输入有效数字' };
729
+ if (field.min !== null && number < field.min) return { error: `不能小于 ${field.min}` };
730
+ if (field.max !== null && number > field.max) return { error: `不能大于 ${field.max}` };
731
+ return { value: number, text: String(number) };
732
+ }
733
+ if (field.type === 'date') {
734
+ if (!isRealFormDate(raw)) return { error: '请输入有效日期' };
735
+ if (field.min !== null && raw < field.min) return { error: `不能早于 ${field.min}` };
736
+ if (field.max !== null && raw > field.max) return { error: `不能晚于 ${field.max}` };
737
+ }
738
+ return { value: raw, text: raw };
739
+ };
740
+ } else if (field.type === 'boolean') {
741
+ const choice = document.createElement('label'); choice.className = 'bf-choice'; choice.htmlFor = controlId;
742
+ const input = document.createElement('input'); input.type = 'checkbox'; input.id = controlId; input.name = field.name;
743
+ const copy = document.createElement('span'); copy.textContent = field.label;
744
+ if (field.required) { const required = document.createElement('span'); required.className = 'bf-required'; required.textContent = '*'; copy.appendChild(required); }
745
+ choice.append(input, copy); row.appendChild(choice); focusNode = input; nodes = [input];
746
+ readValue = () => ({ value: input.checked, text: input.checked ? '是' : '否' });
747
+ } else if (field.type === 'single_select') {
748
+ const select = document.createElement('select'); select.id = controlId; select.name = field.name; select.required = field.required;
749
+ const empty = document.createElement('option'); empty.value = ''; empty.textContent = field.placeholder || '请选择'; select.appendChild(empty);
750
+ for (const option of field.options) { const el = document.createElement('option'); el.value = option.value; el.textContent = option.label; select.appendChild(el); }
751
+ label.htmlFor = controlId; row.append(label, select); focusNode = select; nodes = [select];
752
+ readValue = () => {
753
+ if (!select.value) return { omitted: !field.required, value: '', text: '(未选择)' };
754
+ const option = field.options.find((item) => item.value === select.value);
755
+ return { value: select.value, text: option ? option.label : select.value };
756
+ };
757
+ } else {
758
+ row.appendChild(label);
759
+ const choices = document.createElement('div'); choices.className = 'bf-choices'; choices.setAttribute('role', 'group'); choices.setAttribute('aria-label', field.label);
760
+ nodes = field.options.map((option, optionIndex) => {
761
+ const choice = document.createElement('label'); choice.className = 'bf-choice';
762
+ const input = document.createElement('input'); input.type = 'checkbox'; input.name = field.name; input.value = option.value; input.id = `${controlId}-${optionIndex}`;
763
+ const copy = document.createElement('span'); copy.textContent = option.label;
764
+ choice.htmlFor = input.id; choice.append(input, copy); choices.appendChild(choice);
765
+ return input;
766
+ });
767
+ row.appendChild(choices); focusNode = nodes[0];
768
+ readValue = () => {
769
+ const selected = nodes.filter((node) => node.checked).map((node) => node.value);
770
+ if (field.required && !selected.length) return { error: '请至少选择一项' };
771
+ if (!field.required && !selected.length) return { omitted: true, value: [], text: '(未选择)' };
772
+ return { value: selected, text: selected.map((value) => field.options.find((option) => option.value === value)?.label || value).join('、') || '(未选择)' };
773
+ };
774
+ }
775
+ if (field.help) { const help = document.createElement('div'); help.className = 'bf-help'; help.textContent = field.help; row.appendChild(help); }
776
+ row.appendChild(error); fieldsEl.appendChild(row);
777
+ controls.push({ field, nodes, focusNode, error, readValue });
778
+ }
779
+ const actions = document.createElement('div'); actions.className = 'bf-actions';
780
+ const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = formSpec.cancel_label;
781
+ const submit = document.createElement('button'); submit.type = 'submit'; submit.className = 'primary'; submit.textContent = formSpec.submit_label;
782
+ actions.append(cancel, submit);
783
+ const status = document.createElement('div'); status.className = 'bf-status'; status.setAttribute('aria-live', 'polite');
784
+ form.append(head, fieldsEl, actions, status); container.appendChild(form);
785
+ let destroyed = false;
786
+ let processing = false;
787
+ const submissionId = newSubmissionId();
788
+ const setDisabled = (disabled) => {
789
+ for (const control of controls) for (const node of control.nodes) node.disabled = disabled;
790
+ submit.disabled = disabled; cancel.disabled = disabled;
791
+ };
792
+ const showReceipt = (action) => {
793
+ processing = false; setDisabled(true); form.classList.add('is-complete');
794
+ status.className = 'bf-status receipt';
795
+ status.textContent = action === 'cancel' ? '已取消,表单不会再提交。' : '已提交,内容已作为新一轮消息发送。';
796
+ };
797
+ const clearErrors = () => {
798
+ for (const control of controls) { control.error.textContent = ''; control.error.classList.remove('on'); }
799
+ status.className = 'bf-status'; status.textContent = '';
800
+ };
801
+ const submitAction = async (action) => {
802
+ if (destroyed || processing || form.classList.contains('is-complete')) return;
803
+ clearErrors();
804
+ const values = {};
805
+ const rows = [];
806
+ if (action === 'submit') {
807
+ if (!form.reportValidity()) return;
808
+ for (const control of controls) {
809
+ const result = control.readValue();
810
+ if (result.error) {
811
+ control.error.textContent = result.error; control.error.classList.add('on');
812
+ if (control.focusNode) control.focusNode.focus();
813
+ return;
814
+ }
815
+ if (!result.omitted) values[control.field.name] = result.value;
816
+ if (!result.omitted) rows.push({ label: control.field.label, text: result.text });
817
+ }
818
+ }
819
+ processing = true; setDisabled(true); status.textContent = '正在提交…';
820
+ try {
821
+ await respond({ form_id: formSpec.form_id, submission_id: submissionId, action, values }, { displayText: formDisplayText(formSpec, action, rows) });
822
+ if (!destroyed && !(signal && signal.aborted)) showReceipt(action);
823
+ } catch (error) {
824
+ if (destroyed || (signal && signal.aborted)) return;
825
+ processing = false; setDisabled(false); status.className = 'bf-status error';
826
+ status.textContent = (error && error.message) || '提交失败,请重试。';
827
+ }
828
+ };
829
+ form.addEventListener('submit', (event) => { event.preventDefault(); void submitAction('submit'); });
830
+ cancel.addEventListener('click', () => { void submitAction('cancel'); });
831
+ const previous = Array.isArray(message && message.responses)
832
+ ? message.responses.find((item) => item && item.form_id === formSpec.form_id)
833
+ : null;
834
+ if (previous) showReceipt(previous.action);
835
+ const onAbort = () => { destroyed = true; setDisabled(true); };
836
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
837
+ return () => { destroyed = true; if (signal) signal.removeEventListener('abort', onAbort); };
838
+ }
498
839
  function cleanupHandle(handle) {
499
840
  if (typeof handle === 'function') return handle;
500
841
  if (handle && typeof handle.destroy === 'function') return () => handle.destroy();
@@ -516,7 +857,7 @@
516
857
  disposeRichContent(el);
517
858
  el.replaceChildren();
518
859
  }
519
- function renderRegisteredBlock(el, type, source) {
860
+ function renderRegisteredBlock(el, type, source, options = {}) {
520
861
  const definition = rendererRegistry.get(type);
521
862
  if (!definition || payloadByteLength(source) > definition.maxPayloadBytes) return false;
522
863
  let payload = source;
@@ -550,6 +891,10 @@
550
891
 
551
892
  let result;
552
893
  try {
894
+ const messageJobId = String(options.messageJobId || '');
895
+ const message = Object.freeze({ jobId: messageJobId, responses: formResponsesForJob(messageJobId) });
896
+ // source_job_id/type/version 由组件闭包强制,renderer 无法冒用其他消息;认证信息也不进入 mount context。
897
+ const respond = (response, presentation) => respondToRenderer(definition, message, response, presentation);
553
898
  result = definition.mount(Object.freeze({
554
899
  container,
555
900
  payload,
@@ -558,6 +903,8 @@
558
903
  version: definition.version,
559
904
  theme: Object.freeze({ accent: String(cfg.color || '#7a5b3a') }),
560
905
  signal: state.controller.signal,
906
+ message,
907
+ respond,
561
908
  }));
562
909
  } catch (e) {
563
910
  console.warn('[百灵聊天组件] 富内容渲染失败,已降级为代码块', e);
@@ -593,7 +940,7 @@
593
940
  const closed = i < lines.length;
594
941
  if (closed) i++;
595
942
  const source = buf.join('\n');
596
- if (!(closed && allowRich && language && renderRegisteredBlock(el, language, source))) {
943
+ if (!(closed && allowRich && language && renderRegisteredBlock(el, language, source, options))) {
597
944
  el.appendChild(createCodeBlock(source, language));
598
945
  }
599
946
  continue;
@@ -628,7 +975,7 @@
628
975
 
629
976
  // 打字机逐字显示(仅新到的 AI 回复):按当前子串重渲 markdown(短文重渲成本可忽略),完成后回调追加来源/评价。
630
977
  // 历史回灌、服务端总账、错误气泡都走即时渲染——只有 send() 里刚到的回复带 typing 标志。
631
- function typeReply(el, text, onDone) {
978
+ function typeReply(el, text, onDone, renderOptions = {}) {
632
979
  el.classList.add('md');
633
980
  const full = String(text || ''), total = full.length;
634
981
  if (!total) { if (onDone) onDone(); return; }
@@ -639,7 +986,7 @@
639
986
  const timer = setInterval(() => {
640
987
  i = Math.min(total, i + step);
641
988
  clearRenderedReply(el);
642
- renderReply(el, full.slice(0, i), { allowRich: i >= total });
989
+ renderReply(el, full.slice(0, i), { ...renderOptions, allowRich: i >= total });
643
990
  msgsEl.scrollTop = msgsEl.scrollHeight;
644
991
  if (i >= total) { clearInterval(timer); if (onDone) onDone(); }
645
992
  }, 24);
@@ -710,8 +1057,11 @@
710
1057
  msgsEl.appendChild(el);
711
1058
  if (role === 'a' && !isErr) {
712
1059
  // 新到的回复打字机逐字铺开,铺完再追加来源/评价;其余(历史/错误)即时渲染
713
- if (extra && extra.typing) { typeReply(el, disp, () => appendExtras(role, isErr, { ...extra, copyText: disp }, el)); return el; }
714
- renderReply(el, disp);
1060
+ if (extra && extra.typing) {
1061
+ typeReply(el, disp, () => appendExtras(role, isErr, { ...extra, copyText: disp }, el), { messageJobId: extra.jobId });
1062
+ return el;
1063
+ }
1064
+ renderReply(el, disp, { messageJobId: extra && extra.jobId });
715
1065
  } else { el.textContent = disp; }
716
1066
  }
717
1067
  appendExtras(role, isErr, extra ? { ...extra, copyText: disp } : extra, el);
@@ -875,7 +1225,7 @@
875
1225
  msgsEl.replaceChildren();
876
1226
  typingEl = null;
877
1227
  if (!history.length && cfg.greeting) addMsg('a', cfg.greeting);
878
- for (const m of history) addMsg(m.r, m.t, m.e, { refs: m.refs, jobId: m.j, voted: m.v, comment: m.c, atts: m.atts });
1228
+ for (const m of history) addMsg(m.r, m.t, m.e, { refs: m.refs, jobId: m.j, voted: m.v, comment: m.c, atts: m.atts, interaction: m.i || m.interaction });
879
1229
  }
880
1230
 
881
1231
  async function api(path, opts) {
@@ -912,9 +1262,15 @@
912
1262
  function mergeServerMessages(msgs) {
913
1263
  const byJob = {};
914
1264
  for (const m of history) { if (m.j) byJob[m.j] = { v: m.v, c: m.c, refs: m.refs }; }
1265
+ const localInteractions = {};
1266
+ for (const m of history) {
1267
+ const interaction = normalizeInteractionMeta(m && (m.i || m.interaction));
1268
+ if (m && m.j && interaction) localInteractions[m.j] = interaction;
1269
+ }
915
1270
  history = msgs.map((m) => ({
916
1271
  r: m.r, t: m.t, e: false, j: m.j || undefined, atts: m.atts,
917
1272
  ...(m.j && byJob[m.j] ? { v: byJob[m.j].v, c: byJob[m.j].c, refs: byJob[m.j].refs } : {}),
1273
+ ...((normalizeInteractionMeta(m.interaction) || (m.j && localInteractions[m.j])) ? { i: normalizeInteractionMeta(m.interaction) || localInteractions[m.j] } : {}),
918
1274
  }));
919
1275
  saveHistory();
920
1276
  renderHistory();
@@ -946,11 +1302,11 @@
946
1302
  let progressCopyEl = null;
947
1303
  let progressStatusEl = null;
948
1304
 
949
- function flush(allowRich = false) {
1305
+ function flush(allowRich = false, messageJobId = '') {
950
1306
  if (renderTimer) { clearTimeout(renderTimer); renderTimer = null; }
951
1307
  if (!bubble) return;
952
1308
  clearRenderedReply(bubble);
953
- renderReply(bubble, text, { allowRich });
1309
+ renderReply(bubble, text, { allowRich, messageJobId });
954
1310
  msgsEl.scrollTop = msgsEl.scrollHeight;
955
1311
  }
956
1312
  function scheduleRender() {
@@ -1066,7 +1422,7 @@
1066
1422
  removeProgress();
1067
1423
  if (!bubble) return false;
1068
1424
  text = String(resp.reply || '(无内容)');
1069
- flush(true);
1425
+ flush(true, resp.job_id);
1070
1426
  const refs = Array.isArray(resp.references) ? resp.references : undefined;
1071
1427
  const atts = Array.isArray(resp.attachments) ? resp.attachments : undefined;
1072
1428
  appendExtras('a', false, { refs, jobId: resp.job_id, atts, copyText: text }, bubble);
@@ -1288,6 +1644,129 @@
1288
1644
  }
1289
1645
  }
1290
1646
 
1647
+ function normalizeRendererResponse(definition, message, response) {
1648
+ if (definition.type !== FORM_RENDERER_TYPE || definition.version !== 1) throw new Error('当前交互提交仅支持 bailing-form v1。');
1649
+ if (!message.jobId || message.jobId.length > 128 || !/^[a-zA-Z0-9_-]+$/.test(message.jobId)) throw new Error('当前表单缺少有效来源消息,无法提交。');
1650
+ if (!isPlainRecord(response)) throw new Error('表单提交内容不合法。');
1651
+ rejectFormUnknownKeys(response, new Set(['form_id', 'submission_id', 'action', 'values']));
1652
+ const formId = strictFormText(response.form_id, 64, true);
1653
+ const submissionId = strictFormText(response.submission_id, 64, true);
1654
+ const action = String(response.action || '').trim().toLowerCase();
1655
+ if (!FORM_ID_RE.test(formId) || !/^[a-zA-Z0-9_-]{8,64}$/.test(submissionId)) throw new Error('表单提交标识不合法。');
1656
+ if (action !== 'submit' && action !== 'cancel') throw new Error('表单操作不合法。');
1657
+ const rawValues = action === 'cancel' ? {} : response.values;
1658
+ if (!isPlainRecord(rawValues) || Object.keys(rawValues).length > 12) throw new Error('表单提交值不合法。');
1659
+ const values = {};
1660
+ for (const [key, value] of Object.entries(rawValues)) {
1661
+ if (!FORM_FIELD_RE.test(key)) throw new Error('表单字段不合法。');
1662
+ if (typeof value === 'string') values[key] = value;
1663
+ else if (typeof value === 'number' && Number.isFinite(value)) values[key] = value;
1664
+ else if (typeof value === 'boolean') values[key] = value;
1665
+ else if (Array.isArray(value) && value.length <= 50 && value.every((item) => typeof item === 'string')) values[key] = [...value];
1666
+ else throw new Error('表单字段值不合法。');
1667
+ }
1668
+ let valuesJson = '';
1669
+ try { valuesJson = JSON.stringify(values); } catch { throw new Error('表单提交值无法序列化。'); }
1670
+ if (payloadByteLength(valuesJson) > 32 * 1024) throw new Error('表单提交值过大。');
1671
+ return Object.freeze({
1672
+ type: definition.type,
1673
+ version: definition.version,
1674
+ source_job_id: message.jobId,
1675
+ form_id: formId,
1676
+ submission_id: submissionId,
1677
+ action,
1678
+ values: Object.freeze(values),
1679
+ });
1680
+ }
1681
+ function respondToRenderer(definition, message, response, presentation) {
1682
+ const interaction = normalizeRendererResponse(definition, message, response);
1683
+ const displayText = String((presentation && presentation.displayText) || (interaction.action === 'cancel' ? '已取消填写表单。' : '已提交表单。')).slice(0, 4000);
1684
+ return submitInteractionResponse(interaction, displayText);
1685
+ }
1686
+ function submitInteractionResponse(interaction, displayText) {
1687
+ if (pending) return Promise.reject(new Error('当前还有一条消息正在处理,请稍后再提交。'));
1688
+ pending = true; sendBtn.disabled = true;
1689
+ if (attachBtn) attachBtn.disabled = true;
1690
+ if (voiceBtn) voiceBtn.disabled = true;
1691
+ const temporaryUser = addMsg('u', displayText, false);
1692
+ setTyping(true);
1693
+ const live = createLiveAssistant();
1694
+ const beforeAssistantCount = history.filter((item) => item.r === 'a').length;
1695
+ let resolveAccepted;
1696
+ let rejectAccepted;
1697
+ let acknowledgementSettled = false;
1698
+ const acceptedPromise = new Promise((resolve, reject) => { resolveAccepted = resolve; rejectAccepted = reject; });
1699
+ const acknowledge = (value) => {
1700
+ if (acknowledgementSettled) return;
1701
+ acknowledgementSettled = true;
1702
+ resolveAccepted(value);
1703
+ };
1704
+ const rejectAcknowledgement = (error) => {
1705
+ if (acknowledgementSettled) return;
1706
+ acknowledgementSettled = true;
1707
+ rejectAccepted(error);
1708
+ };
1709
+ // respond() 只等到 POST 被权威服务端接受,便立即让表单显示只读回执;
1710
+ // 后续 SSE/断线恢复在受控后台链路收口,全局 pending 仍保持到下一轮回答完成。
1711
+ void (async () => {
1712
+ let accepted = false;
1713
+ try {
1714
+ const clientCapabilities = collectClientCapabilities();
1715
+ let resp = await api(`/chat/${ENTRY}`, {
1716
+ method: 'POST', headers: { 'content-type': 'application/json' },
1717
+ body: JSON.stringify({
1718
+ interaction_response: interaction,
1719
+ visitor_id: visitorId,
1720
+ context: collectPageContext(),
1721
+ ...(clientCapabilities ? { client_capabilities: clientCapabilities } : {}),
1722
+ ...(threadId ? { thread_id: threadId } : {}),
1723
+ ...(TICKET ? { ticket: TICKET } : {}),
1724
+ }),
1725
+ });
1726
+ accepted = true;
1727
+ if (resp.visitor_id && resp.visitor_id !== visitorId) {
1728
+ visitorId = resp.visitor_id;
1729
+ try { localStorage.setItem(LS_VISITOR, visitorId); } catch { /* 忽略 */ }
1730
+ }
1731
+ history.push({ r: 'u', t: displayText, j: resp.job_id || undefined, i: normalizeInteractionMeta(interaction) }); saveHistory();
1732
+ acknowledge({ accepted: true, job_id: resp.job_id || '' });
1733
+ const deadline = Date.now() + 5 * 60 * 1000;
1734
+ if (!resp.done && resp.job_id) {
1735
+ const streamed = await waitForEventStream(resp.job_id, deadline, live);
1736
+ if (streamed) resp = streamed;
1737
+ }
1738
+ setTyping(false);
1739
+ if (!resp.done) live.discard('任务仍在后台处理中');
1740
+ appendAssistantResponse(resp, live);
1741
+ } catch (error) {
1742
+ setTyping(false);
1743
+ live.discard('处理未完成', true);
1744
+ if (isNetworkError(error) && await recoverFromServerHistory(beforeAssistantCount)) {
1745
+ acknowledge({ accepted: true, recovered: true });
1746
+ return;
1747
+ }
1748
+ if (accepted) {
1749
+ const messageText = publicErrorMessage(error);
1750
+ addMsg('a', messageText, true);
1751
+ history.push({ r: 'a', t: messageText, e: true }); saveHistory();
1752
+ // POST 已被服务端接受时不再开放重复提交;后续可由 thread 历史补齐回答。
1753
+ acknowledge({ accepted: true, pending_reply: true });
1754
+ } else {
1755
+ if (temporaryUser && temporaryUser.isConnected) temporaryUser.remove();
1756
+ rejectAcknowledgement(new Error(publicErrorMessage(error)));
1757
+ }
1758
+ } finally {
1759
+ pending = false; sendBtn.disabled = false;
1760
+ if (attachBtn && cfg.upload) attachBtn.disabled = false;
1761
+ if (voiceBtn && cfg.upload && canRecordAudio()) voiceBtn.disabled = false;
1762
+ }
1763
+ })().catch((error) => {
1764
+ console.warn('[百灵聊天组件] 表单后续链路异常', error);
1765
+ rejectAcknowledgement(new Error(publicErrorMessage(error)));
1766
+ });
1767
+ return acceptedPromise;
1768
+ }
1769
+
1291
1770
  async function send() {
1292
1771
  const text = inputEl.value.trim();
1293
1772
  const att = (pendingAtt && pendingAtt.url) ? pendingAtt : null; // 只有上传成功(有 url)的才随消息发出
@@ -1485,6 +1964,6 @@
1485
1964
  renderHistory();
1486
1965
  void syncServerHistory(); // 本地先即时上屏,再用服务端总账补齐迟到(审批后等)的回复
1487
1966
  host.style.visibility = 'visible';
1488
- if (AUTO_OPEN) { panel.classList.add('open'); inputEl.focus(); }
1967
+ if (SCRIPT_AUTO_OPEN || cfg.default_open === true) { panel.classList.add('open'); inputEl.focus(); }
1489
1968
  })();
1490
1969
  })();