bailinghub 0.3.4 → 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.
- package/README.en.md +3 -1
- package/README.md +3 -0
- package/docker-compose.images.yml +2 -2
- package/docs/CHANGELOG.en.md +46 -1
- package/docs/CHANGELOG.md +14 -1
- package/docs/COMPATIBILITY.en.md +25 -0
- package/docs/CONTRACT.en.md +79 -8
- package/docs/CONTRACT.md +36 -6
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/QUICKSTART.en.md +6 -0
- package/docs/QUICKSTART.md +1 -1
- package/docs/README.en.md +2 -0
- package/docs/README.md +2 -0
- package/docs/RELEASE_NOTES_v0.4.0.en.md +39 -0
- package/docs/RELEASE_NOTES_v0.4.0.md +39 -0
- package/docs/STREAMING.en.md +32 -0
- package/docs/STREAMING.md +8 -2
- package/docs/WIDGET_RENDERERS.en.md +123 -6
- package/docs/WIDGET_RENDERERS.md +75 -6
- package/docs/user-guide/console-map.en.md +1 -2
- package/docs/user-guide/console-map.md +2 -2
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +9 -0
- package/package.json +1 -1
- package/schemas/config/chat-entry.schema.json +2 -1
- package/scripts/check-doc-links.mjs +1 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +5 -5
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +1 -0
- package/scripts/verify-github-repo.mjs +1 -0
- package/scripts/widget-renderer-test.mjs +244 -16
- package/src/core/config/config-models.test.ts +18 -1
- package/src/core/config/config-models.ts +25 -3
- package/src/core/config/config-schema.test.ts +2 -0
- package/src/core/contracts/types.ts +2 -1
- package/src/core/platform/chat-form.test.ts +147 -0
- package/src/core/platform/chat-form.ts +402 -0
- package/src/core/platform/version.ts +1 -1
- package/src/core/runtime/execution-runtime.test.ts +61 -0
- package/src/core/runtime/execution-runtime.ts +17 -0
- package/src/routes/chat.test.ts +319 -7
- package/src/routes/chat.ts +166 -21
- package/web/console/assets/{Accounts-CAwrtBiS.js → Accounts-DuUY2UJU.js} +1 -1
- package/web/console/assets/{Approvals-C2BZ86T3.js → Approvals-B11mo1dy.js} +1 -1
- package/web/console/assets/{Audit-B-E4Y_Up.js → Audit-CQwJRIJT.js} +1 -1
- package/web/console/assets/{BrandLockup-C18u8Lx5.js → BrandLockup-BIF-h1pi.js} +1 -1
- package/web/console/assets/{Channels-DTy8ylH-.js → Channels-BIploUT-.js} +1 -1
- package/web/console/assets/ChatEntries-Cpg_WV-o.js +7 -0
- package/web/console/assets/ChatEntries-DsYtcXN6.css +1 -0
- package/web/console/assets/{Clients-DWs9JFr0.js → Clients-DS29eUi2.js} +1 -1
- package/web/console/assets/{Cost-2SSYs1AT.js → Cost-BF52tfU2.js} +1 -1
- package/web/console/assets/{Credentials-B79LtxCE.js → Credentials-SwfmQAv6.js} +1 -1
- package/web/console/assets/{Diagnostics-BakcRYvb.js → Diagnostics-CJfbI_8p.js} +1 -1
- package/web/console/assets/{Executors-BXoyo28u.js → Executors-CzlZlznA.js} +1 -1
- package/web/console/assets/{Kb-ISbzquab.js → Kb-CVX22U4k.js} +1 -1
- package/web/console/assets/{Login-Dlu6Wgcf.js → Login-PoUVsBI-.js} +1 -1
- package/web/console/assets/{Projects-DFzmtnqg.js → Projects-DYlbjLQy.js} +1 -1
- package/web/console/assets/{Routes-B-hm9HGY.js → Routes-DSEvGujN.js} +1 -1
- package/web/console/assets/{Runs-hMRu1im3.js → Runs-B-TsYZEt.js} +1 -1
- package/web/console/assets/{Setup-CrBAV-b9.js → Setup-xiPXit_b.js} +1 -1
- package/web/console/assets/{Shell-B1a8DvXQ.js → Shell-DNiWZOYB.js} +1 -1
- package/web/console/assets/{StorageBuckets-BRfL_eHb.js → StorageBuckets-Bjsc3pLd.js} +1 -1
- package/web/console/assets/{SystemSettings-CyirVLbq.js → SystemSettings-CcKF2lJ9.js} +1 -1
- package/web/console/assets/{SystemStatus-DZ_OR7sk.js → SystemStatus-Oj1xjxJn.js} +1 -1
- package/web/console/assets/{Targets-CtIMa66c.js → Targets-y1KllVXT.js} +1 -1
- package/web/console/assets/{Tools-BfDZHt01.js → Tools-DoEP_y9x.js} +1 -1
- package/web/console/assets/{index-DBiByFiO.js → index-CxPIS6G7.js} +2 -2
- package/web/console/assets/{request-DY2cxQqZ.js → request-CBLNpLth.js} +1 -1
- package/web/console/assets/{schema-6mCQ7rR5.js → schema-DzwLpuOy.js} +1 -1
- package/web/console/index.html +1 -1
- package/web/widget/widget.js +493 -14
- package/web-admin/src/pages/ChatEntries.vue +18 -6
- package/web/console/assets/ChatEntries-9xbRiQov.css +0 -1
- package/web/console/assets/ChatEntries-DvD-4IeE.js +0 -7
package/src/routes/chat.test.ts
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import test from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
3
|
import { EventEmitter } from 'node:events';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
4
5
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
6
|
import type { AppConfig } from '../core/config/config';
|
|
6
|
-
import type { ChatEntry, Job } from '../core/contracts/types';
|
|
7
|
+
import type { ChatEntry, Job, Route } from '../core/contracts/types';
|
|
7
8
|
import type { RuntimeContext } from '../core/edition';
|
|
8
9
|
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
9
10
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
10
11
|
import { CHAT_STREAM_PROTOCOL, InMemoryJobStreamBroker } from '../core/runtime/job-stream';
|
|
11
|
-
import { handleChatConfigFor, handleChatEventsFor, normalizePresentationCapabilities, type ChatApiDeps } from './chat';
|
|
12
|
+
import { handleChatConfigFor, handleChatEventsFor, handleChatFor, handleChatThreadFor, normalizePresentationCapabilities, type ChatApiDeps } from './chat';
|
|
12
13
|
|
|
13
14
|
class FakeResponse {
|
|
14
15
|
statusCode = 0;
|
|
@@ -39,8 +40,19 @@ class FakeResponse {
|
|
|
39
40
|
}
|
|
40
41
|
}
|
|
41
42
|
|
|
42
|
-
function request(origin = 'https://shop.example.com', headers: Record<string, string> = {}): IncomingMessage {
|
|
43
|
-
return Object.assign(new EventEmitter(), { headers: { origin, ...headers } }) as IncomingMessage;
|
|
43
|
+
function request(origin: string | null = 'https://shop.example.com', headers: Record<string, string> = {}): IncomingMessage {
|
|
44
|
+
return Object.assign(new EventEmitter(), { headers: { ...(origin === null ? {} : { origin }), ...headers } }) as IncomingMessage;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function jsonRequest(body: Record<string, unknown>, origin = 'https://shop.example.com'): IncomingMessage {
|
|
48
|
+
const stream = Readable.from([Buffer.from(JSON.stringify(body))]) as unknown as IncomingMessage;
|
|
49
|
+
stream.method = 'POST';
|
|
50
|
+
stream.headers = { origin, 'x-forwarded-for': '127.0.0.1' };
|
|
51
|
+
return stream;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function responseJson(res: FakeResponse): Record<string, unknown> {
|
|
55
|
+
return JSON.parse(Buffer.from(res.body).toString('utf8')) as Record<string, unknown>;
|
|
44
56
|
}
|
|
45
57
|
|
|
46
58
|
function entry(overrides: Partial<ChatEntry> = {}): ChatEntry {
|
|
@@ -114,9 +126,9 @@ function streamDeps(job: Job, broker: InMemoryJobStreamBroker): ChatApiDeps {
|
|
|
114
126
|
};
|
|
115
127
|
}
|
|
116
128
|
|
|
117
|
-
async function configBody(value: ChatEntry | null): Promise<{ status: number; body: Record<string, unknown> }> {
|
|
129
|
+
async function configBody(value: ChatEntry | null, origin: string | null = 'https://shop.example.com'): Promise<{ status: number; body: Record<string, unknown> }> {
|
|
118
130
|
const res = new FakeResponse();
|
|
119
|
-
await handleChatConfigFor(deps(value), request(), res as unknown as ServerResponse, 'pub_demo1234');
|
|
131
|
+
await handleChatConfigFor(deps(value), request(origin), res as unknown as ServerResponse, 'pub_demo1234');
|
|
120
132
|
return {
|
|
121
133
|
status: res.statusCode,
|
|
122
134
|
body: JSON.parse(Buffer.from(res.body).toString('utf8')) as Record<string, unknown>,
|
|
@@ -125,12 +137,13 @@ async function configBody(value: ChatEntry | null): Promise<{ status: number; bo
|
|
|
125
137
|
|
|
126
138
|
test('chat config: 启用入口下发品牌控制且保留部署品牌兼容字段', async () => {
|
|
127
139
|
const result = await configBody(entry({
|
|
128
|
-
appearance: { powered_by_visible: true, powered_by_text: '由示例业务驱动' },
|
|
140
|
+
appearance: { default_open: true, powered_by_visible: true, powered_by_text: '由示例业务驱动' },
|
|
129
141
|
}));
|
|
130
142
|
|
|
131
143
|
assert.equal(result.status, 200);
|
|
132
144
|
assert.equal(result.body.enabled, true);
|
|
133
145
|
assert.equal(result.body.brand, '百灵中枢');
|
|
146
|
+
assert.equal(result.body.default_open, true);
|
|
134
147
|
assert.equal(result.body.powered_by_visible, true);
|
|
135
148
|
assert.equal(result.body.powered_by_text, '由示例业务驱动');
|
|
136
149
|
});
|
|
@@ -139,6 +152,7 @@ test('chat config: 老入口生成默认品牌文案', async () => {
|
|
|
139
152
|
const result = await configBody(entry());
|
|
140
153
|
|
|
141
154
|
assert.equal(result.status, 200);
|
|
155
|
+
assert.equal(result.body.default_open, false);
|
|
142
156
|
assert.equal(result.body.powered_by_visible, true);
|
|
143
157
|
assert.equal(result.body.powered_by_text, '由 百灵中枢 驱动');
|
|
144
158
|
});
|
|
@@ -153,6 +167,32 @@ test('chat config: 停用入口返回静默隐藏状态,不存在入口仍返
|
|
|
153
167
|
assert.deepEqual(missing.body, { error: '聊天入口不存在' });
|
|
154
168
|
});
|
|
155
169
|
|
|
170
|
+
test('chat Origin 白名单: 浏览器来源规范化后精确匹配,错误来源在业务逻辑前拒绝', async () => {
|
|
171
|
+
const normalized = await configBody(entry(), 'https://SHOP.example.com:443/');
|
|
172
|
+
assert.equal(normalized.status, 200);
|
|
173
|
+
|
|
174
|
+
for (const deniedOrigin of ['https://other.example.com', 'https://shop.example.com/path', 'null']) {
|
|
175
|
+
const denied = await configBody(entry(), deniedOrigin);
|
|
176
|
+
assert.equal(denied.status, 403, deniedOrigin);
|
|
177
|
+
assert.deepEqual(denied.body, { error: '该站点未被允许嵌入此聊天入口' });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const unrestricted = await configBody(entry({ allowed_origins: [] }), 'https://other.example.com');
|
|
181
|
+
assert.equal(unrestricted.status, 200);
|
|
182
|
+
|
|
183
|
+
const noBrowserOrigin = await configBody(entry(), null);
|
|
184
|
+
assert.equal(noBrowserOrigin.status, 200);
|
|
185
|
+
|
|
186
|
+
const deniedMessage = new FakeResponse();
|
|
187
|
+
await handleChatFor(
|
|
188
|
+
deps(entry()),
|
|
189
|
+
jsonRequest({ message: '不应进入任务链路', visitor_id: 'visitor-12345678' }, 'https://other.example.com'),
|
|
190
|
+
deniedMessage as unknown as ServerResponse,
|
|
191
|
+
'pub_demo1234',
|
|
192
|
+
);
|
|
193
|
+
assert.equal(deniedMessage.statusCode, 403);
|
|
194
|
+
});
|
|
195
|
+
|
|
156
196
|
test('chat events: 增量事件可回放,done 仍以任务库最终结果为权威值', async () => {
|
|
157
197
|
const broker = new InMemoryJobStreamBroker();
|
|
158
198
|
const job = finishedJob();
|
|
@@ -220,3 +260,275 @@ test('chat events: Last-Event-ID 跳过已收到事件,回放窗口丢失时
|
|
|
220
260
|
assert.doesNotMatch(gapBody, /DROPPED_CHUNK/);
|
|
221
261
|
assert.match(gapBody, /LATEST_CHUNK/);
|
|
222
262
|
});
|
|
263
|
+
|
|
264
|
+
const chatRoute: Route = {
|
|
265
|
+
route_key: 'chat.main',
|
|
266
|
+
name: '聊天路由',
|
|
267
|
+
enabled: true,
|
|
268
|
+
target: 'llm',
|
|
269
|
+
target_config: {},
|
|
270
|
+
profile: 'general',
|
|
271
|
+
session_policy: 'per_key',
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
function formReply(): string {
|
|
275
|
+
return '请补充信息:\n```bailing-form\n' + JSON.stringify({
|
|
276
|
+
version: 1,
|
|
277
|
+
form_id: 'refund_info',
|
|
278
|
+
title: '退款信息',
|
|
279
|
+
schema: {
|
|
280
|
+
reason: { type: 'textarea', label: '退款原因', required: true, maxLength: 200 },
|
|
281
|
+
method: {
|
|
282
|
+
type: 'single_select',
|
|
283
|
+
label: '退款方式',
|
|
284
|
+
required: true,
|
|
285
|
+
options: [{ label: '原路退回', value: 'original' }, { label: '余额', value: 'balance' }],
|
|
286
|
+
},
|
|
287
|
+
},
|
|
288
|
+
}) + '\n```';
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function interactionBody(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
|
292
|
+
return {
|
|
293
|
+
visitor_id: 'visitor-12345678',
|
|
294
|
+
thread_id: 'case-1',
|
|
295
|
+
interaction_response: {
|
|
296
|
+
type: 'bailing-form',
|
|
297
|
+
version: 1,
|
|
298
|
+
source_job_id: 'source-job-123',
|
|
299
|
+
form_id: 'refund_info',
|
|
300
|
+
submission_id: 'submission-123',
|
|
301
|
+
action: 'submit',
|
|
302
|
+
values: { reason: '商品损坏', method: 'original' },
|
|
303
|
+
...overrides,
|
|
304
|
+
},
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function sourceFormJob(overrides: Partial<Job> = {}): Job {
|
|
309
|
+
return finishedJob({
|
|
310
|
+
job_id: 'source-job-123',
|
|
311
|
+
request_id: 'source-request-123',
|
|
312
|
+
source: 'chat:pub_demo1234',
|
|
313
|
+
result: { text: formReply() },
|
|
314
|
+
metadata: { chat_entry: 'pub_demo1234', visitor_id: 'visitor-12345678', thread_id: 'case-1' },
|
|
315
|
+
...overrides,
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function chatFixture(source: Job = sourceFormJob(), throwAfterCreate = false): {
|
|
320
|
+
deps: ChatApiDeps;
|
|
321
|
+
jobs: Map<string, Job>;
|
|
322
|
+
launches: Array<Record<string, unknown>>;
|
|
323
|
+
} {
|
|
324
|
+
const jobs = new Map<string, Job>([[source.job_id, source]]);
|
|
325
|
+
const launches: Array<Record<string, unknown>> = [];
|
|
326
|
+
const config = {
|
|
327
|
+
chatEntries: {
|
|
328
|
+
get: async () => entry(),
|
|
329
|
+
listPageContexts: async () => [],
|
|
330
|
+
},
|
|
331
|
+
rateLimits: { consume: async () => false },
|
|
332
|
+
routes: { get: async () => chatRoute },
|
|
333
|
+
targets: { list: async () => [] },
|
|
334
|
+
conversations: {
|
|
335
|
+
sessionForScope: async () => ({ sessionId: 'session-1', isContinue: true, scopeKey: 'scope-1' }),
|
|
336
|
+
},
|
|
337
|
+
} as unknown as ConfigStoreContract;
|
|
338
|
+
const state = {
|
|
339
|
+
getJob: async (jobId: string) => jobs.get(jobId) ?? null,
|
|
340
|
+
findByRequestId: async (requestId: string) => [...jobs.values()].find((item) => item.request_id === requestId) ?? null,
|
|
341
|
+
} as unknown as RuntimeStateStore;
|
|
342
|
+
const fixtureDeps: ChatApiDeps = {
|
|
343
|
+
cfg: { brand: { name: '百灵中枢' } } as AppConfig,
|
|
344
|
+
isPaused: () => false,
|
|
345
|
+
runtimeContextFor: async () => ({} as RuntimeContext),
|
|
346
|
+
runtimeStoresFor: () => ({ state, config }),
|
|
347
|
+
resolveProjectPathFor: async () => null,
|
|
348
|
+
now: () => new Date(0).toISOString(),
|
|
349
|
+
engineForContext: () => ({
|
|
350
|
+
launchJob: async (spec) => {
|
|
351
|
+
launches.push(spec as unknown as Record<string, unknown>);
|
|
352
|
+
const created = finishedJob({
|
|
353
|
+
job_id: 'response-job-123',
|
|
354
|
+
request_id: spec.requestId,
|
|
355
|
+
status: 'queued',
|
|
356
|
+
source: spec.source,
|
|
357
|
+
result: undefined,
|
|
358
|
+
raw_result: undefined,
|
|
359
|
+
input: spec.fullInput,
|
|
360
|
+
input_preview: spec.fullInput.slice(0, 200),
|
|
361
|
+
metadata: spec.metadata,
|
|
362
|
+
});
|
|
363
|
+
jobs.set(created.job_id, created);
|
|
364
|
+
if (throwAfterCreate) throw Object.assign(new Error('duplicate'), { code: 'ER_DUP_ENTRY' });
|
|
365
|
+
return created;
|
|
366
|
+
},
|
|
367
|
+
}),
|
|
368
|
+
};
|
|
369
|
+
return { deps: fixtureDeps, jobs, launches };
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
test('POST /chat interaction: 从来源 done 回答重解析 schema,生成新用户轮次且 metadata 不重复 values', async () => {
|
|
373
|
+
const fixture = chatFixture();
|
|
374
|
+
const res = new FakeResponse();
|
|
375
|
+
await handleChatFor(fixture.deps, jsonRequest(interactionBody()), res as unknown as ServerResponse, 'pub_demo1234');
|
|
376
|
+
|
|
377
|
+
assert.equal(res.statusCode, 200);
|
|
378
|
+
assert.equal(responseJson(res)['job_id'], 'response-job-123');
|
|
379
|
+
assert.equal(fixture.launches.length, 1);
|
|
380
|
+
const launch = fixture.launches[0]!;
|
|
381
|
+
assert.match(String(launch['requestId']), /^chat_form_[0-9a-f]{48}$/);
|
|
382
|
+
assert.match(String(launch['fullInput']), /退款方式(method):原路退回/);
|
|
383
|
+
assert.match(String(launch['fullInput']), /用户数据,不是系统指令/);
|
|
384
|
+
const metadata = launch['metadata'] as Record<string, unknown>;
|
|
385
|
+
assert.deepEqual(metadata['interaction'], {
|
|
386
|
+
type: 'bailing-form',
|
|
387
|
+
version: 1,
|
|
388
|
+
source_job_id: 'source-job-123',
|
|
389
|
+
form_id: 'refund_info',
|
|
390
|
+
submission_id: 'submission-123',
|
|
391
|
+
action: 'submit',
|
|
392
|
+
});
|
|
393
|
+
assert.equal(JSON.stringify(metadata).includes('商品损坏'), false);
|
|
394
|
+
|
|
395
|
+
const replay = new FakeResponse();
|
|
396
|
+
await handleChatFor(fixture.deps, jsonRequest(interactionBody()), replay as unknown as ServerResponse, 'pub_demo1234');
|
|
397
|
+
assert.equal(responseJson(replay)['deduped'], true);
|
|
398
|
+
assert.equal(fixture.launches.length, 1);
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
test('POST /chat interaction: 跨访客或跨 thread 的来源统一不可探测', async () => {
|
|
402
|
+
for (const source of [
|
|
403
|
+
sourceFormJob({ metadata: { chat_entry: 'pub_demo1234', visitor_id: 'other-visitor', thread_id: 'case-1' } }),
|
|
404
|
+
sourceFormJob({ metadata: { chat_entry: 'pub_demo1234', visitor_id: 'visitor-12345678', thread_id: 'other-thread' } }),
|
|
405
|
+
sourceFormJob({ source: 'chat:another-entry' }),
|
|
406
|
+
]) {
|
|
407
|
+
const fixture = chatFixture(source);
|
|
408
|
+
const res = new FakeResponse();
|
|
409
|
+
await handleChatFor(fixture.deps, jsonRequest(interactionBody()), res as unknown as ServerResponse, 'pub_demo1234');
|
|
410
|
+
assert.equal(res.statusCode, 404);
|
|
411
|
+
assert.equal(responseJson(res)['error'], 'not found');
|
|
412
|
+
assert.equal(fixture.launches.length, 0);
|
|
413
|
+
}
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
test('POST /chat interaction: 来源须为 done 且 values 必须满足来源 schema', async () => {
|
|
417
|
+
const pendingFixture = chatFixture(sourceFormJob({ status: 'running' }));
|
|
418
|
+
const pending = new FakeResponse();
|
|
419
|
+
await handleChatFor(pendingFixture.deps, jsonRequest(interactionBody()), pending as unknown as ServerResponse, 'pub_demo1234');
|
|
420
|
+
assert.equal(pending.statusCode, 409);
|
|
421
|
+
|
|
422
|
+
const invalidFixture = chatFixture();
|
|
423
|
+
const invalid = new FakeResponse();
|
|
424
|
+
await handleChatFor(
|
|
425
|
+
invalidFixture.deps,
|
|
426
|
+
jsonRequest(interactionBody({ values: { reason: '损坏', method: 'not-allowed' } })),
|
|
427
|
+
invalid as unknown as ServerResponse,
|
|
428
|
+
'pub_demo1234',
|
|
429
|
+
);
|
|
430
|
+
assert.equal(invalid.statusCode, 400);
|
|
431
|
+
assert.match(String(responseJson(invalid)['error']), /允许的选项/);
|
|
432
|
+
assert.equal(invalidFixture.launches.length, 0);
|
|
433
|
+
|
|
434
|
+
const absentFixture = chatFixture(sourceFormJob({ result: { text: '这里只有普通文字,没有表单。' } }));
|
|
435
|
+
const absent = new FakeResponse();
|
|
436
|
+
await handleChatFor(absentFixture.deps, jsonRequest(interactionBody()), absent as unknown as ServerResponse, 'pub_demo1234');
|
|
437
|
+
assert.equal(absent.statusCode, 400);
|
|
438
|
+
assert.match(String(responseJson(absent)['error']), /没有可提交/);
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
test('POST /chat interaction: canonical 用户消息超过 4000 字时明确拒绝而非截断', async () => {
|
|
442
|
+
const longReply = '```bailing-form\n' + JSON.stringify({
|
|
443
|
+
version: 1,
|
|
444
|
+
form_id: 'refund_info',
|
|
445
|
+
title: '长表单',
|
|
446
|
+
schema: {
|
|
447
|
+
first: { type: 'textarea', label: '第一段', required: true, maxLength: 2000 },
|
|
448
|
+
second: { type: 'textarea', label: '第二段', required: true, maxLength: 2000 },
|
|
449
|
+
},
|
|
450
|
+
}) + '\n```';
|
|
451
|
+
const fixture = chatFixture(sourceFormJob({ result: { text: longReply } }));
|
|
452
|
+
const res = new FakeResponse();
|
|
453
|
+
await handleChatFor(
|
|
454
|
+
fixture.deps,
|
|
455
|
+
jsonRequest(interactionBody({ values: { first: '甲'.repeat(2000), second: '乙'.repeat(2000) } })),
|
|
456
|
+
res as unknown as ServerResponse,
|
|
457
|
+
'pub_demo1234',
|
|
458
|
+
);
|
|
459
|
+
assert.equal(res.statusCode, 400);
|
|
460
|
+
assert.match(String(responseJson(res)['error']), /超过 4000 字上限/);
|
|
461
|
+
assert.equal(fixture.launches.length, 0);
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
test('POST /chat interaction: createJob 并发唯一键失败后回查赢家并返回幂等结果', async () => {
|
|
465
|
+
const fixture = chatFixture(sourceFormJob(), true);
|
|
466
|
+
const res = new FakeResponse();
|
|
467
|
+
await handleChatFor(fixture.deps, jsonRequest(interactionBody()), res as unknown as ServerResponse, 'pub_demo1234');
|
|
468
|
+
|
|
469
|
+
assert.equal(res.statusCode, 200);
|
|
470
|
+
assert.equal(responseJson(res)['job_id'], 'response-job-123');
|
|
471
|
+
assert.equal(responseJson(res)['deduped'], true);
|
|
472
|
+
assert.equal(fixture.launches.length, 1);
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
test('GET /chat thread: 入站表单提交从 job metadata 回灌简化 interaction,不回传 values', async () => {
|
|
476
|
+
const submitted = finishedJob({
|
|
477
|
+
job_id: 'response-job-123',
|
|
478
|
+
thread_id: 7,
|
|
479
|
+
source: 'chat:pub_demo1234',
|
|
480
|
+
metadata: {
|
|
481
|
+
chat_entry: 'pub_demo1234',
|
|
482
|
+
visitor_id: 'visitor-12345678',
|
|
483
|
+
thread_id: 'case-1',
|
|
484
|
+
interaction: {
|
|
485
|
+
type: 'bailing-form',
|
|
486
|
+
version: 1,
|
|
487
|
+
source_job_id: 'source-job-123',
|
|
488
|
+
form_id: 'refund_info',
|
|
489
|
+
submission_id: 'submission-123',
|
|
490
|
+
action: 'submit',
|
|
491
|
+
},
|
|
492
|
+
},
|
|
493
|
+
});
|
|
494
|
+
const state = { getJob: async () => submitted } as unknown as RuntimeStateStore;
|
|
495
|
+
const config = {
|
|
496
|
+
chatEntries: { get: async () => entry() },
|
|
497
|
+
conversations: {
|
|
498
|
+
findThread: async () => 7,
|
|
499
|
+
threadMessages: async () => [{
|
|
500
|
+
direction: 'in',
|
|
501
|
+
content: '用户提交了上一条回答中的结构化表单。',
|
|
502
|
+
job_id: 'response-job-123',
|
|
503
|
+
created_at: new Date(0).toISOString(),
|
|
504
|
+
}],
|
|
505
|
+
},
|
|
506
|
+
} as unknown as ConfigStoreContract;
|
|
507
|
+
const historyDeps: ChatApiDeps = {
|
|
508
|
+
cfg: { brand: { name: '百灵中枢' } } as AppConfig,
|
|
509
|
+
isPaused: () => false,
|
|
510
|
+
runtimeContextFor: async () => ({} as RuntimeContext),
|
|
511
|
+
runtimeStoresFor: () => ({ state, config }),
|
|
512
|
+
resolveProjectPathFor: async () => null,
|
|
513
|
+
now: () => new Date(0).toISOString(),
|
|
514
|
+
engineForContext: () => ({ launchJob: async () => { throw new Error('not used'); } }),
|
|
515
|
+
};
|
|
516
|
+
const res = new FakeResponse();
|
|
517
|
+
await handleChatThreadFor(
|
|
518
|
+
historyDeps,
|
|
519
|
+
request(),
|
|
520
|
+
res as unknown as ServerResponse,
|
|
521
|
+
'pub_demo1234',
|
|
522
|
+
new URL('https://hub.example.com/chat/pub_demo1234/thread?visitor_id=visitor-12345678&thread_id=case-1'),
|
|
523
|
+
);
|
|
524
|
+
const messages = responseJson(res)['messages'] as Array<Record<string, unknown>>;
|
|
525
|
+
assert.deepEqual(messages[0]?.['interaction'], {
|
|
526
|
+
type: 'bailing-form',
|
|
527
|
+
version: 1,
|
|
528
|
+
source_job_id: 'source-job-123',
|
|
529
|
+
form_id: 'refund_info',
|
|
530
|
+
submission_id: 'submission-123',
|
|
531
|
+
action: 'submit',
|
|
532
|
+
});
|
|
533
|
+
assert.equal(JSON.stringify(messages).includes('values'), false);
|
|
534
|
+
});
|
package/src/routes/chat.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// 聊天入口(公开面):网页组件 → POST /chat/:entry → 同一条路由/总账/知识/工具链路。
|
|
2
2
|
// entry_key 可公开;防滥用 = Origin 白名单 + 按 IP 限速 + 可停用。访客=匿名主体;签名访客票据(verifyVisitorTicket)验签后写 metadata.visitor_uid。
|
|
3
3
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
|
-
import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
4
|
+
import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
5
5
|
import { ipOf, normalizeHttpMountPath, readBody, readBodyCapped, send } from '../app/http';
|
|
6
6
|
import type { EngineRuntime } from '../app/engine';
|
|
7
7
|
import { resolveTargetDef } from '../core/targets/resolve';
|
|
@@ -16,6 +16,16 @@ import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
|
16
16
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
17
17
|
import { CHAT_STREAM_PROTOCOL, type JobStreamBroker } from '../core/runtime/job-stream';
|
|
18
18
|
import type { TargetRegistry } from '../core/targets/registry';
|
|
19
|
+
import {
|
|
20
|
+
BailingFormValidationError,
|
|
21
|
+
bailingFormHistoryInteraction,
|
|
22
|
+
buildBailingFormCanonicalInput,
|
|
23
|
+
findBailingFormDefinition,
|
|
24
|
+
parseBailingFormInteraction,
|
|
25
|
+
validateBailingFormValues,
|
|
26
|
+
type BailingFormHistoryInteraction,
|
|
27
|
+
type BailingFormInteraction,
|
|
28
|
+
} from '../core/platform/chat-form';
|
|
19
29
|
|
|
20
30
|
// ---- 聊天入口(公开面):网页组件 → POST /chat/:entry → 同一条路由/总账/知识/工具链路 ----
|
|
21
31
|
// entry_key 设计为可公开(页面源码可见);防滥用 = Origin 白名单 + 按 IP 限速 + 可停用/删除。
|
|
@@ -74,11 +84,26 @@ interface RuntimeContextInput {
|
|
|
74
84
|
actor?: RuntimeActor;
|
|
75
85
|
}
|
|
76
86
|
|
|
87
|
+
function canonicalHttpOrigin(value: unknown): string | undefined {
|
|
88
|
+
const raw = String(value ?? '').trim();
|
|
89
|
+
if (!raw) return undefined;
|
|
90
|
+
try {
|
|
91
|
+
const url = new URL(raw);
|
|
92
|
+
if (raw.includes('?') || raw.includes('#')
|
|
93
|
+
|| (url.protocol !== 'http:' && url.protocol !== 'https:')
|
|
94
|
+
|| url.username || url.password || url.search || url.hash
|
|
95
|
+
|| url.pathname !== '/' || url.origin === 'null') return undefined;
|
|
96
|
+
return url.origin;
|
|
97
|
+
} catch { return undefined; }
|
|
98
|
+
}
|
|
99
|
+
|
|
77
100
|
function chatOriginAllowed(entry: ChatEntry, req: IncomingMessage): boolean {
|
|
78
101
|
if (!entry.allowed_origins.length) return true; // 未配=不限,控制台建议上线前配白名单
|
|
79
|
-
const
|
|
80
|
-
if (!
|
|
81
|
-
|
|
102
|
+
const rawOrigin = (req.headers['origin'] ?? '').toString().trim();
|
|
103
|
+
if (!rawOrigin) return true; // 无 Origin = 非浏览器调用(curl 等),白名单管不到也不必管——它防的是别家网页盗嵌
|
|
104
|
+
const origin = canonicalHttpOrigin(rawOrigin);
|
|
105
|
+
if (!origin) return false;
|
|
106
|
+
return entry.allowed_origins.some((allowed) => canonicalHttpOrigin(allowed) === origin);
|
|
82
107
|
}
|
|
83
108
|
|
|
84
109
|
async function chatRateLimited(config: ConfigStoreContract | null, entry: ChatEntry, ip: string): Promise<boolean> {
|
|
@@ -109,6 +134,58 @@ export function normalizePresentationCapabilities(value: unknown): { renderers:
|
|
|
109
134
|
return normalized.length ? { renderers: normalized } : undefined;
|
|
110
135
|
}
|
|
111
136
|
|
|
137
|
+
function chatJobReply(job: Job): string {
|
|
138
|
+
const result = (job.result ?? {}) as Record<string, unknown>;
|
|
139
|
+
if (typeof result['text'] === 'string' && result['text']) return result['text'];
|
|
140
|
+
if (result['report']) return JSON.stringify(result['report']);
|
|
141
|
+
return job.raw_result ?? '';
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function chatInteractionRequestId(
|
|
145
|
+
entryKey: string,
|
|
146
|
+
visitor: string,
|
|
147
|
+
visitorUid: string,
|
|
148
|
+
thread: string,
|
|
149
|
+
interaction: BailingFormInteraction,
|
|
150
|
+
): string {
|
|
151
|
+
const identity = visitorUid ? 'uid:' + visitorUid : 'visitor:' + visitor;
|
|
152
|
+
const digest = createHash('sha256').update(JSON.stringify([
|
|
153
|
+
entryKey, identity, thread, interaction.source_job_id, interaction.form_id, interaction.submission_id,
|
|
154
|
+
])).digest('hex');
|
|
155
|
+
return 'chat_form_' + digest.slice(0, 48);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function sourceJobBelongsToChat(
|
|
159
|
+
job: Job,
|
|
160
|
+
entryKey: string,
|
|
161
|
+
visitor: string,
|
|
162
|
+
visitorUid: string,
|
|
163
|
+
thread: string,
|
|
164
|
+
): boolean {
|
|
165
|
+
const metadata = job.metadata ?? {};
|
|
166
|
+
if (job.source !== 'chat:' + entryKey || metadata['chat_entry'] !== entryKey) return false;
|
|
167
|
+
if (String(metadata['thread_id'] ?? '') !== thread) return false;
|
|
168
|
+
if (visitorUid) return metadata['visitor_uid'] === visitorUid;
|
|
169
|
+
return !metadata['visitor_uid'] && metadata['visitor_id'] === visitor;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function interactionMetadataMatches(
|
|
173
|
+
job: Job,
|
|
174
|
+
entryKey: string,
|
|
175
|
+
visitor: string,
|
|
176
|
+
visitorUid: string,
|
|
177
|
+
thread: string,
|
|
178
|
+
expected: BailingFormHistoryInteraction,
|
|
179
|
+
): boolean {
|
|
180
|
+
if (!sourceJobBelongsToChat(job, entryKey, visitor, visitorUid, thread)) return false;
|
|
181
|
+
const actual = bailingFormHistoryInteraction((job.metadata ?? {})['interaction']);
|
|
182
|
+
return !!actual
|
|
183
|
+
&& actual.source_job_id === expected.source_job_id
|
|
184
|
+
&& actual.form_id === expected.form_id
|
|
185
|
+
&& actual.submission_id === expected.submission_id
|
|
186
|
+
&& actual.action === expected.action;
|
|
187
|
+
}
|
|
188
|
+
|
|
112
189
|
|
|
113
190
|
/** job → 聊天响应形态。错误不暴露内部细节(公开面)。references=知识检索命中(doc_id 留在中枢侧,不外露)。 */
|
|
114
191
|
function chatShape(job: Job, visitorId: string): Record<string, unknown> {
|
|
@@ -132,7 +209,7 @@ function chatShape(job: Job, visitorId: string): Record<string, unknown> {
|
|
|
132
209
|
|
|
133
210
|
|
|
134
211
|
export async function handleChatFor(deps: ChatApiDeps, req: IncomingMessage, res: ServerResponse, entryKey: string): Promise<void> {
|
|
135
|
-
const { ctx, config: cfgStore } = await chatRuntime(deps, `chat:${entryKey}`);
|
|
212
|
+
const { ctx, state: store, config: cfgStore } = await chatRuntime(deps, `chat:${entryKey}`);
|
|
136
213
|
if (!cfgStore) { send(res, 400, { error: '聊天入口需要 mysql 后端' }); return; }
|
|
137
214
|
const engine = deps.engineForContext(ctx);
|
|
138
215
|
const entry = await cfgStore.chatEntries.get(entryKey);
|
|
@@ -142,8 +219,19 @@ export async function handleChatFor(deps: ChatApiDeps, req: IncomingMessage, res
|
|
|
142
219
|
if (await chatRateLimited(cfgStore, entry, ipOf(req))) { send(res, 429, { done: true, error: true, reply: '提问太频繁了,请稍候片刻再试。' }); return; }
|
|
143
220
|
|
|
144
221
|
const body = (await readBody(req).catch(() => ({} as Record<string, unknown>)));
|
|
145
|
-
const
|
|
146
|
-
|
|
222
|
+
const rawMessage = String(body['message'] ?? '').trim();
|
|
223
|
+
const hasInteraction = Object.prototype.hasOwnProperty.call(body, 'interaction_response');
|
|
224
|
+
if (rawMessage && hasInteraction) { send(res, 400, { error: 'message 与 interaction_response 只能提交一个' }); return; }
|
|
225
|
+
let interaction: BailingFormInteraction | undefined;
|
|
226
|
+
if (hasInteraction) {
|
|
227
|
+
try { interaction = parseBailingFormInteraction(body['interaction_response']); }
|
|
228
|
+
catch (e) {
|
|
229
|
+
send(res, 400, { error: e instanceof BailingFormValidationError ? e.message : 'interaction_response 无效' });
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
let message = rawMessage.slice(0, 4000);
|
|
234
|
+
if (!message && !interaction) { send(res, 400, { error: 'message 或 interaction_response 必填' }); return; }
|
|
147
235
|
// visitor_id:组件生成存 localStorage,只用于会话连续性,不是身份凭证;不合规直接服务端换发
|
|
148
236
|
let visitor = String(body['visitor_id'] ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 64);
|
|
149
237
|
if (visitor.length < 8) visitor = randomUUID().replace(/-/g, '').slice(0, 16);
|
|
@@ -178,6 +266,43 @@ export async function handleChatFor(deps: ChatApiDeps, req: IncomingMessage, res
|
|
|
178
266
|
// 可选 thread_id:同一身份下按它切分平行线程(业务多会话 UI 映射)——开新会话=换 thread_id,继续当前会话=复用。
|
|
179
267
|
// 它只是已验身份内部的分区键,不跨权限边界;清洗限长防滥用。会话与对话总账同键切分,连续性一致。
|
|
180
268
|
const thread = String(body['thread_id'] ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 32);
|
|
269
|
+
let interactionMeta: BailingFormHistoryInteraction | undefined;
|
|
270
|
+
let interactionRequestId = '';
|
|
271
|
+
if (interaction) {
|
|
272
|
+
const sourceJob = await store.getJob(interaction.source_job_id);
|
|
273
|
+
// 来源不存在/跨入口/跨身份/跨线程一律按 not found 收口,避免公开面成为任务探针。
|
|
274
|
+
if (!sourceJob || !sourceJobBelongsToChat(sourceJob, entry.entry_key, visitor, visitorUid, thread)) {
|
|
275
|
+
send(res, 404, { error: 'not found' }); return;
|
|
276
|
+
}
|
|
277
|
+
if (sourceJob.status !== 'done') { send(res, 409, { error: '来源回答尚未完成,暂不能提交表单' }); return; }
|
|
278
|
+
try {
|
|
279
|
+
const form = findBailingFormDefinition(chatJobReply(sourceJob), interaction.form_id);
|
|
280
|
+
if (!form) { send(res, 400, { error: '来源回答中没有可提交的对应表单' }); return; }
|
|
281
|
+
const values = interaction.action === 'submit' ? validateBailingFormValues(form, interaction.values) : {};
|
|
282
|
+
message = buildBailingFormCanonicalInput(form, interaction, values);
|
|
283
|
+
} catch (e) {
|
|
284
|
+
send(res, 400, { error: e instanceof BailingFormValidationError ? e.message : '表单提交无效' });
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (message.length > 4000) { send(res, 400, { error: '表单提交生成的用户消息超过 4000 字上限,请缩短填写内容' }); return; }
|
|
288
|
+
interactionMeta = {
|
|
289
|
+
type: interaction.type,
|
|
290
|
+
version: interaction.version,
|
|
291
|
+
source_job_id: interaction.source_job_id,
|
|
292
|
+
form_id: interaction.form_id,
|
|
293
|
+
submission_id: interaction.submission_id,
|
|
294
|
+
action: interaction.action,
|
|
295
|
+
};
|
|
296
|
+
interactionRequestId = chatInteractionRequestId(entry.entry_key, visitor, visitorUid, thread, interaction);
|
|
297
|
+
const existing = await store.findByRequestId(interactionRequestId);
|
|
298
|
+
if (existing) {
|
|
299
|
+
if (!interactionMetadataMatches(existing, entry.entry_key, visitor, visitorUid, thread, interactionMeta)) {
|
|
300
|
+
send(res, 409, { error: 'submission_id 冲突,请重新提交' }); return;
|
|
301
|
+
}
|
|
302
|
+
send(res, 200, { ...chatShape(existing, visitor), deduped: true });
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
181
306
|
const scopeKey = chatScopeKey(entry.entry_key, visitor, visitorUid, thread);
|
|
182
307
|
const sess = await cfgStore.conversations.sessionForScope(route.route_key, scopeKey);
|
|
183
308
|
// 页面上下文(寻址):组件抓的 url/title(+可选 page_key) → 按本入口登记表模式匹配 → 解析出页面说明。
|
|
@@ -193,16 +318,29 @@ export async function handleChatFor(deps: ChatApiDeps, req: IncomingMessage, res
|
|
|
193
318
|
}
|
|
194
319
|
// 展示能力由客户端自报,只用于回答呈现提示,绝不能参与身份、权限、审批或工具放行。
|
|
195
320
|
const presentationCapabilities = normalizePresentationCapabilities(body['client_capabilities']);
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
321
|
+
let job: Job;
|
|
322
|
+
try {
|
|
323
|
+
job = await engine.launchJob({
|
|
324
|
+
requestId: interactionRequestId || `chat_${randomUUID()}`, fullInput: message,
|
|
325
|
+
route, routeKey: route.route_key,
|
|
326
|
+
target: route.target, project: route.project ?? null, projectPath,
|
|
327
|
+
profileName: route.profile, permission: route.permission, source: `chat:${entry.entry_key}`,
|
|
328
|
+
// 服务端构造:visitor_uid 只可能来自验签通过的票据,组件/访客无法伪造(鉴权总纲)
|
|
329
|
+
metadata: { chat_entry: entry.entry_key, visitor_id: visitor, no_delivery: true, ...(visitorUid ? { visitor_uid: visitorUid } : {}), ...(thread ? { thread_id: thread } : {}), ...(pageContext ? { page_context: pageContext } : {}), ...(presentationCapabilities ? { presentation_capabilities: presentationCapabilities } : {}), ...(interactionMeta ? { interaction: interactionMeta } : {}) },
|
|
330
|
+
session: { sessionId: sess.sessionId, isContinue: sess.isContinue },
|
|
331
|
+
threadScope: scopeKey, principalId: (visitorUid ? `uid:${visitorUid}` : `visitor:${visitor}`).slice(0, 64), channel: `chat:${entry.entry_key}`,
|
|
332
|
+
});
|
|
333
|
+
} catch (error) {
|
|
334
|
+
// 并发双击可能同时通过前置查询;唯一 request_id 由状态库裁决,失败方回查并复用赢家。
|
|
335
|
+
if (interactionRequestId && interactionMeta) {
|
|
336
|
+
const raced = await store.findByRequestId(interactionRequestId).catch(() => null);
|
|
337
|
+
if (raced && interactionMetadataMatches(raced, entry.entry_key, visitor, visitorUid, thread, interactionMeta)) {
|
|
338
|
+
send(res, 200, { ...chatShape(raced, visitor), deduped: true });
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
throw error;
|
|
343
|
+
}
|
|
206
344
|
|
|
207
345
|
// 聊天主链路:创建任务后立即返回 job_id,回答统一由 SSE 事件流输出。
|
|
208
346
|
send(res, 200, chatShape(job, visitor));
|
|
@@ -303,7 +441,7 @@ function chatScopeKey(entryKey: string, visitor: string, visitorUid: string, thr
|
|
|
303
441
|
* 身份纪律:带票按 uid 线索、无票按 visitor 线索;票坏=401(与 handleChat 同,组件可据此提示重登)。
|
|
304
442
|
*/
|
|
305
443
|
export async function handleChatThreadFor(deps: ChatApiDeps, req: IncomingMessage, res: ServerResponse, entryKey: string, url: URL): Promise<void> {
|
|
306
|
-
const { config: cfgStore } = await chatRuntime(deps, `chat_thread:${entryKey}`);
|
|
444
|
+
const { state: store, config: cfgStore } = await chatRuntime(deps, `chat_thread:${entryKey}`);
|
|
307
445
|
if (!cfgStore) { send(res, 400, { error: '聊天入口需要 mysql 后端' }); return; }
|
|
308
446
|
const entry = await cfgStore.chatEntries.get(entryKey);
|
|
309
447
|
if (!entry || !entry.enabled) { send(res, 404, { error: '聊天入口不存在或已停用' }); return; }
|
|
@@ -328,11 +466,17 @@ export async function handleChatThreadFor(deps: ChatApiDeps, req: IncomingMessag
|
|
|
328
466
|
if (!threadId) { send(res, 200, { visitor_id: visitor, messages: [] }); return; }
|
|
329
467
|
const rows = await cfgStore.conversations.threadMessages(threadId, 50);
|
|
330
468
|
// 出站消息现算富内容(图片/文件附件),与实时 chatShape 渲染口径一致;入站只回文本
|
|
331
|
-
const messages = rows.map((m) => {
|
|
469
|
+
const messages = await Promise.all(rows.map(async (m) => {
|
|
332
470
|
const atts = extractAttachments(m.content); // 入站也解析:用户上传的图片以  进消息,回灌后同样渲染成缩略图
|
|
333
|
-
if (m.direction === 'in')
|
|
471
|
+
if (m.direction === 'in') {
|
|
472
|
+
const job = m.job_id ? await store.getJob(m.job_id).catch(() => null) : null;
|
|
473
|
+
const interaction = job && job.thread_id === threadId && (job.metadata ?? {})['chat_entry'] === entryKey
|
|
474
|
+
? bailingFormHistoryInteraction((job.metadata ?? {})['interaction'])
|
|
475
|
+
: undefined;
|
|
476
|
+
return { r: 'u', t: m.content, j: m.job_id, ts: m.created_at, ...(atts.length ? { atts } : {}), ...(interaction ? { interaction } : {}) };
|
|
477
|
+
}
|
|
334
478
|
return { r: 'a', t: m.content, j: m.job_id, ts: m.created_at, ...(atts.length ? { atts } : {}) };
|
|
335
|
-
});
|
|
479
|
+
}));
|
|
336
480
|
send(res, 200, { visitor_id: visitor, messages });
|
|
337
481
|
}
|
|
338
482
|
|
|
@@ -440,6 +584,7 @@ export async function handleChatConfigFor(deps: ChatApiDeps, req: IncomingMessag
|
|
|
440
584
|
send(res, 200, {
|
|
441
585
|
enabled: true,
|
|
442
586
|
title: entry.title || entry.name, greeting: entry.greeting ?? '', color: entry.color || '#7a5b3a', brand: deps.cfg.brand.name, upload,
|
|
587
|
+
default_open: ap.default_open === true,
|
|
443
588
|
width: ap.width ?? 400, height: ap.height ?? 600,
|
|
444
589
|
title_align: ap.title_align === 'left' ? 'left' : 'center',
|
|
445
590
|
position: ap.position === 'left' ? 'left' : 'right',
|