Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(wecom): harden media parsing and conflict state

david0d47414f96de
diff --git a/packages/lizi-im/src/__tests__/xdtRefs.test.ts b/packages/lizi-im/src/__tests__/xdtRefs.test.ts
index b941148b1f..f04e167a89 100644
--- a/packages/lizi-im/src/__tests__/xdtRefs.test.ts
+++ b/packages/lizi-im/src/__tests__/xdtRefs.test.ts
@@ -8,8 +8,12 @@ import { describe, it, expect } from 'vitest';
import {
classifyXdtOnly,
+ collectXdtFileLinks,
+ collectXdtImageRefs,
collectXdtImageUrls,
+ stripXdtFileLinks,
stripXdtForStreaming,
+ stripXdtImageLinks,
xdtFileUrlToAbsPath,
} from '../xdtRefs.js';
@@ -45,3 +49,40 @@ describe('xdtFileUrlToAbsPath(Windows 盘符,规则 15)', () => {
expect(xdtFileUrlToAbsPath('xdt-file:///home/u/f.txt')).toBe('/home/u/f.txt');
});
});
+
+describe('linear managed-media parser', () => {
+ it('preserves source offsets while parsing image and file refs', () => {
+ const file = 'xdt-file:///tmp/report.txt';
+ const text = `before ![chart](${BLOB}) [report](${file}) after`;
+
+ expect(collectXdtImageRefs(text)).toEqual([
+ {
+ alt: 'chart',
+ url: BLOB,
+ start: text.indexOf('!['),
+ end: text.indexOf(')') + 1,
+ },
+ ]);
+ expect(collectXdtFileLinks(text)).toEqual([
+ { alt: 'report', absPath: '/tmp/report.txt' },
+ ]);
+ expect(stripXdtFileLinks(stripXdtImageLinks(text))).toBe('before after');
+ });
+
+ it('handles long near-matches without regex backtracking', () => {
+ const nearImage = `![${'![\\\\'.repeat(20_000)}`;
+ const nearUrl = `![](xdt-image://${'![](xdt-image://'.repeat(20_000)}`;
+
+ expect(collectXdtImageUrls(nearImage)).toEqual([]);
+ expect(collectXdtImageUrls(nearUrl)).toEqual([]);
+ expect(stripXdtForStreaming(nearImage)).toBe(nearImage);
+ expect(stripXdtForStreaming(nearUrl)).toBe(nearUrl);
+ });
+
+ it('still finds a valid ref after malformed Markdown', () => {
+ const text = `broken [ prefix ![chart](${BLOB})`;
+
+ expect(collectXdtImageUrls(text)).toEqual([BLOB]);
+ expect(stripXdtImageLinks(text)).toBe('broken [ prefix ');
+ });
+});
diff --git a/packages/lizi-im/src/feishu/cards.ts b/packages/lizi-im/src/feishu/cards.ts
index c59945763c..1510c272f7 100644
--- a/packages/lizi-im/src/feishu/cards.ts
+++ b/packages/lizi-im/src/feishu/cards.ts
@@ -15,7 +15,7 @@
*/
import type { InteractiveCardSpec } from '../types.js';
-import { XDT_IMAGE_REGEX } from '../xdtRefs.js';
+import { collectXdtImageRefs } from '../xdtRefs.js';
/**
* 去掉 markdown inline code 的反引号,保留 fenced code block(```)不动。
@@ -167,11 +167,10 @@ export function buildMixedMarkdownCardV2(
): unknown {
const elements: unknown[] = [];
let lastIdx = 0;
- for (const m of text.matchAll(XDT_IMAGE_REGEX)) {
- const before = text.slice(lastIdx, m.index);
+ for (const ref of collectXdtImageRefs(text)) {
+ const before = text.slice(lastIdx, ref.start);
if (before) elements.push({ tag: 'markdown', content: stripInlineCode(before) });
- const alt = m[1] || '';
- const url = m[2];
+ const { alt, url } = ref;
const key = imageMap.get(url);
if (key) {
elements.push({
@@ -185,7 +184,7 @@ export function buildMixedMarkdownCardV2(
content: `_[图片加载失败:${alt || url}]_`,
});
}
- lastIdx = (m.index ?? 0) + m[0].length;
+ lastIdx = ref.end;
}
const tail = text.slice(lastIdx);
if (tail) elements.push({ tag: 'markdown', content: stripInlineCode(tail) });
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index db76fdf0e1..2f113ec5db 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -347,6 +347,29 @@ describe("WecomIM routing and ownership", () => {
});
});
+ it("preserves conflict status when the SDK follows a server kick with disconnected", async () => {
+ const { host } = createHost();
+ const client = new FakeClient();
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await im.init();
+ client.emit("event.disconnected_event");
+ client.emit("disconnected", "another connection took over");
+
+ expect(im.getStatus()).toEqual({ kind: "conflict", appId: "bot-1" });
+ });
+
+ it("keeps ordinary disconnects in the reconnecting state", async () => {
+ const { host } = createHost();
+ const client = new FakeClient();
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await im.init();
+ client.emit("disconnected", "network unavailable");
+
+ expect(im.getStatus()).toEqual({ kind: "connecting" });
+ });
+
it.each([
{
channel: "wecomBot:set-config",
diff --git a/packages/lizi-im/src/wecom/index.ts b/packages/lizi-im/src/wecom/index.ts
index e269f69a6e..156bf82fc7 100644
--- a/packages/lizi-im/src/wecom/index.ts
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -28,7 +28,7 @@ import {
collectXdtFileLinks,
collectXdtImageUrls,
stripXdtFileLinks,
- XDT_IMAGE_REGEX,
+ stripXdtImageLinks,
} from "../xdtRefs.js";
import {
chunkWecomMarkdown,
@@ -361,7 +361,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
}
for (const absPath of output.mediaAbsPaths ?? []) addAttachment(absPath);
- const visibleText = stripXdtFileLinks(output.text.replace(XDT_IMAGE_REGEX, "")).trim();
+ const visibleText = stripXdtFileLinks(stripXdtImageLinks(output.text)).trim();
const chunks = chunkWecomMarkdown(
visibleText || (attachments.length > 0 ? "📎 附件如下" : "_(空回复)_"),
);
@@ -398,9 +398,11 @@ export class WecomIM extends BaseIM implements TextChannelIM {
logger: createSdkLogger(this.log, botId, secret),
});
this.client = client;
+ let serverConflict = false;
client.on("authenticated", () => {
if (!this.isCurrent(client, generation)) return;
+ serverConflict = false;
this.setStatus({ kind: "connected", appId: botId });
});
client.on("reconnecting", () => {
@@ -410,6 +412,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
client.on("disconnected", (reason) => {
if (!this.isCurrent(client, generation)) return;
this.log.warn("connection disconnected", sanitizeReason(reason));
+ if (serverConflict) return;
this.setStatus({ kind: "connecting" });
});
client.on("error", (error) => {
@@ -429,6 +432,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {
});
client.on("event.disconnected_event", () => {
if (!this.isCurrent(client, generation)) return;
+ serverConflict = true;
this.setStatus({ kind: "conflict", appId: botId });
});
client.on("message.text", (frame) =>
diff --git a/packages/lizi-im/src/xdtRefs.ts b/packages/lizi-im/src/xdtRefs.ts
index 8fde1811ee..9d8127e6e7 100644
--- a/packages/lizi-im/src/xdtRefs.ts
+++ b/packages/lizi-im/src/xdtRefs.ts
@@ -14,8 +14,97 @@
import path from 'node:path';
-export const XDT_IMAGE_REGEX = /!\[([^\]]*)\]\(((?:xdt-image|cindy-media):\/\/[^)]+)\)/g;
-export const XDT_FILE_REGEX = /\[([^\]]*)\]\((xdt-file:\/\/[^)]+)\)/g;
+export interface XdtImageRef {
+ alt: string;
+ url: string;
+ start: number;
+ end: number;
+}
+
+interface ParsedXdtRef extends XdtImageRef {
+ kind: 'image' | 'file';
+}
+
+/**
+ * Parse managed-media Markdown in one forward pass. Model output is
+ * uncontrolled input, so this deliberately avoids the former global regexes:
+ * repeated near-matches could make the regex engine rescan a long suffix.
+ */
+function parseXdtRefs(text: string): ParsedXdtRef[] {
+ const refs: ParsedXdtRef[] = [];
+ let cursor = 0;
+
+ while (cursor < text.length) {
+ const openBracket = text.indexOf('[', cursor);
+ if (openBracket === -1) break;
+
+ const image = openBracket > 0 && text[openBracket - 1] === '!';
+ const start = image ? openBracket - 1 : openBracket;
+ const altStart = openBracket + 1;
+ let altEnd = altStart;
+ while (
+ altEnd < text.length &&
+ text[altEnd] !== '[' &&
+ !(text[altEnd] === ']' && text[altEnd + 1] === '(')
+ ) {
+ altEnd += 1;
+ }
+
+ // A nested opening bracket supersedes the malformed outer candidate. This
+ // both preserves later valid refs and keeps the scan strictly forward.
+ if (text[altEnd] === '[') {
+ cursor = altEnd;
+ continue;
+ }
+ if (altEnd >= text.length) break;
+
+ const urlStart = altEnd + 2;
+ const scheme = image
+ ? text.startsWith('xdt-image://', urlStart)
+ ? 'xdt-image://'
+ : text.startsWith('cindy-media://', urlStart)
+ ? 'cindy-media://'
+ : null
+ : text.startsWith('xdt-file://', urlStart)
+ ? 'xdt-file://'
+ : null;
+ if (!scheme) {
+ cursor = urlStart;
+ continue;
+ }
+
+ const endParen = text.indexOf(')', urlStart + scheme.length);
+ if (endParen === -1) break;
+ if (endParen > urlStart + scheme.length) {
+ refs.push({
+ kind: image ? 'image' : 'file',
+ alt: text.slice(altStart, altEnd),
+ url: text.slice(urlStart, endParen),
+ start,
+ end: endParen + 1,
+ });
+ }
+ cursor = endParen + 1;
+ }
+
+ return refs;
+}
+
+function replaceXdtRefs(
+ text: string,
+ refs: ReadonlyArray<ParsedXdtRef>,
+ replacement: (ref: ParsedXdtRef) => string,
+): string {
+ if (refs.length === 0) return text;
+ const parts: string[] = [];
+ let cursor = 0;
+ for (const ref of refs) {
+ parts.push(text.slice(cursor, ref.start), replacement(ref));
+ cursor = ref.end;
+ }
+ parts.push(text.slice(cursor));
+ return parts.join('');
+}
/** xdt-file://<absPath> → absPath (URL-decoded). */
export function xdtFileUrlToAbsPath(url: string): string {
@@ -35,12 +124,12 @@ export function xdtFileUrlToAbsPath(url: string): string {
/** Replace xdt-* refs with placeholder text suitable for intermediate frames. */
export function stripXdtForStreaming(text: string): string {
- return text
- .replace(XDT_IMAGE_REGEX, (_m, alt) => `[🖼️ ${alt || '图片'} · 上传中...]`)
- .replace(XDT_FILE_REGEX, (_m, alt, url) => {
- const display = alt || path.basename(xdtFileUrlToAbsPath(url));
- return `[📎 ${display} · 准备发送...]`;
- });
+ const refs = parseXdtRefs(text);
+ return replaceXdtRefs(text, refs, (ref) => {
+ if (ref.kind === 'image') return `[🖼️ ${ref.alt || '图片'} · 上传中...]`;
+ const display = ref.alt || path.basename(xdtFileUrlToAbsPath(ref.url));
+ return `[📎 ${display} · 准备发送...]`;
+ });
}
/** Detect if `text` is essentially "only xdt refs" (no real prose). Used for
@@ -48,13 +137,11 @@ export function stripXdtForStreaming(text: string): string {
export function classifyXdtOnly(
text: string,
): 'image-only' | 'file-only' | 'mixed-or-text' {
- const trimmed = text.replace(XDT_IMAGE_REGEX, '').replace(XDT_FILE_REGEX, '').trim();
+ const refs = parseXdtRefs(text);
+ const trimmed = replaceXdtRefs(text, refs, () => '').trim();
if (trimmed.length > 0) return 'mixed-or-text';
- const hasImg = XDT_IMAGE_REGEX.test(text);
- // Reset lastIndex (regex with /g is stateful) before testing again.
- XDT_IMAGE_REGEX.lastIndex = 0;
- const hasFile = XDT_FILE_REGEX.test(text);
- XDT_FILE_REGEX.lastIndex = 0;
+ const hasImg = refs.some((ref) => ref.kind === 'image');
+ const hasFile = refs.some((ref) => ref.kind === 'file');
if (hasImg && !hasFile) return 'image-only';
if (hasFile && !hasImg) return 'file-only';
return 'mixed-or-text';
@@ -62,7 +149,14 @@ export function classifyXdtOnly(
/** Remove xdt-file links entirely (since they're delivered as separate file messages). */
export function stripXdtFileLinks(text: string): string {
- return text.replace(XDT_FILE_REGEX, '');
+ const refs = parseXdtRefs(text).filter((ref) => ref.kind === 'file');
+ return replaceXdtRefs(text, refs, () => '');
+}
+
+/** Remove managed-image Markdown after it has been delivered as media. */
+export function stripXdtImageLinks(text: string): string {
+ const refs = parseXdtRefs(text).filter((ref) => ref.kind === 'image');
+ return replaceXdtRefs(text, refs, () => '');
}
export interface XdtFileLink {
@@ -73,19 +167,25 @@ export interface XdtFileLink {
/** Collect xdt-file links from text, deduped by absPath (model often repeats). */
export function collectXdtFileLinks(text: string): XdtFileLink[] {
const seen = new Map<string, XdtFileLink>();
- for (const m of text.matchAll(XDT_FILE_REGEX)) {
- const absPath = xdtFileUrlToAbsPath(m[2]);
+ for (const ref of parseXdtRefs(text)) {
+ if (ref.kind !== 'file') continue;
+ const absPath = xdtFileUrlToAbsPath(ref.url);
if (seen.has(absPath)) continue;
- seen.set(absPath, { alt: m[1] || '', absPath });
+ seen.set(absPath, { alt: ref.alt, absPath });
}
return Array.from(seen.values());
}
+/** Collect managed-image refs in source order, including text offsets. */
+export function collectXdtImageRefs(text: string): XdtImageRef[] {
+ return parseXdtRefs(text)
+ .filter((ref) => ref.kind === 'image')
+ .map(({ alt, url, start, end }) => ({ alt, url, start, end }));
+}
+
/** Collect unique xdt-image URLs from text. */
export function collectXdtImageUrls(text: string): string[] {
const set = new Set<string>();
- for (const m of text.matchAll(XDT_IMAGE_REGEX)) {
- set.add(m[2]);
- }
+ for (const ref of collectXdtImageRefs(text)) set.add(ref.url);
return Array.from(set);
}