Skip to content

Commit 3f07998

Browse files
Coobiwclaude
authored andcommitted
fix(feishu): fetch thread context so AI can see bot replies in topic threads
When a user replies in a Feishu topic thread, the AI previously could only see the quoted parent message but not the bot's own prior replies in the thread. This made multi-turn conversations in threads feel broken. - Add `threadId` (omt_xxx) to `FeishuMessageInfo` and `getMessageFeishu` - Add `listFeishuThreadMessages()` using `container_id_type=thread` API to fetch all messages in a thread including bot replies - In `handleFeishuMessage`, fetch ThreadStarterBody and ThreadHistoryBody for topic session modes and pass them to the AI context - Reuse quoted message result when rootId === parentId to avoid redundant API calls; exclude root message from thread history to prevent duplication - Fall back to inbound ctx.threadId when rootId is absent or API fails - Fetch newest messages first (ByCreateTimeDesc + reverse) so long threads keep the most recent turns instead of the oldest Co-Authored-By: Claude Opus 4.6 <[email protected]>
1 parent 39b4185 commit 3f07998

3 files changed

Lines changed: 233 additions & 4 deletions

File tree

‎extensions/feishu/src/bot.ts‎

Lines changed: 112 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import {
2929
import { parsePostContent } from "./post.js";
3030
import { createFeishuReplyDispatcher } from "./reply-dispatcher.js";
3131
import { getFeishuRuntime } from "./runtime.js";
32-
import { getMessageFeishu, sendMessageFeishu } from "./send.js";
32+
import { getMessageFeishu, listFeishuThreadMessages, sendMessageFeishu } from "./send.js";
3333
import type { FeishuMessageContext, FeishuMediaInfo, ResolvedFeishuAccount } from "./types.js";
3434
import type { DynamicAgentCreationConfig } from "./types.js";
3535

@@ -1240,6 +1240,7 @@ export async function handleFeishuMessage(params: {
12401240

12411241
// Fetch quoted/replied message content if parentId exists
12421242
let quotedContent: string | undefined;
1243+
let quotedMsgThreadId: string | undefined;
12431244
if (ctx.parentId) {
12441245
try {
12451246
const quotedMsg = await getMessageFeishu({
@@ -1249,6 +1250,7 @@ export async function handleFeishuMessage(params: {
12491250
});
12501251
if (quotedMsg) {
12511252
quotedContent = quotedMsg.content;
1253+
quotedMsgThreadId = quotedMsg.threadId;
12521254
log(
12531255
`feishu[${account.accountId}]: fetched quoted message: ${quotedContent?.slice(0, 100)}`,
12541256
);
@@ -1258,6 +1260,106 @@ export async function handleFeishuMessage(params: {
12581260
}
12591261
}
12601262

1263+
// Fetch thread context for topic sessions — allows the AI to see bot replies in the thread
1264+
let threadStarterBody: string | undefined;
1265+
let threadHistoryBody: string | undefined;
1266+
1267+
const isTopicSessionForThread =
1268+
isGroup &&
1269+
(groupSession?.groupSessionScope === "group_topic" ||
1270+
groupSession?.groupSessionScope === "group_topic_sender");
1271+
1272+
if ((ctx.rootId || ctx.threadId) && isTopicSessionForThread) {
1273+
// 1. Fetch root message to get ThreadStarterBody and the Feishu thread_id (omt_xxx).
1274+
// Reuse the already-fetched quoted message when rootId === parentId to avoid
1275+
// a redundant API call.
1276+
// Fall back to ctx.threadId from the inbound event when:
1277+
// - rootId is absent (thread_id-only events)
1278+
// - the root message API call fails or returns no thread_id
1279+
let feishuThreadId: string | undefined = ctx.threadId;
1280+
if (ctx.rootId) {
1281+
if (ctx.rootId === ctx.parentId) {
1282+
// Reuse quoted message for both starter body and threadId.
1283+
threadStarterBody = quotedContent;
1284+
feishuThreadId = quotedMsgThreadId ?? feishuThreadId;
1285+
}
1286+
// Always fetch the root message when threadStarterBody is still empty
1287+
// (e.g. parentId != rootId) or when we still need a feishuThreadId.
1288+
if (!threadStarterBody || !feishuThreadId) {
1289+
try {
1290+
const rootMsg = await getMessageFeishu({
1291+
cfg,
1292+
messageId: ctx.rootId,
1293+
accountId: account.accountId,
1294+
});
1295+
if (rootMsg) {
1296+
if (!threadStarterBody) {
1297+
threadStarterBody = rootMsg.content;
1298+
}
1299+
feishuThreadId = rootMsg.threadId ?? feishuThreadId;
1300+
}
1301+
} catch (err) {
1302+
log(`feishu[${account.accountId}]: failed to fetch thread starter: ${String(err)}`);
1303+
}
1304+
}
1305+
}
1306+
if (feishuThreadId) {
1307+
log(
1308+
`feishu[${account.accountId}]: fetched thread starter (threadId=${feishuThreadId}): ${threadStarterBody?.slice(0, 100)}`,
1309+
);
1310+
}
1311+
1312+
// 2. Fetch thread history (includes bot replies) using omt_xxx thread ID.
1313+
// The root message is excluded (rootMessageId) since it's already provided
1314+
// separately as ThreadStarterBody.
1315+
if (feishuThreadId) {
1316+
try {
1317+
const threadMessages = await listFeishuThreadMessages({
1318+
cfg,
1319+
threadId: feishuThreadId,
1320+
currentMessageId: ctx.messageId,
1321+
// Only exclude the root message when its content was successfully
1322+
// captured as ThreadStarterBody; otherwise keep it in history so the
1323+
// thread opener is not lost after a transient root-fetch failure.
1324+
rootMessageId: threadStarterBody ? ctx.rootId : undefined,
1325+
limit: 20,
1326+
accountId: account.accountId,
1327+
});
1328+
// In group_topic_sender mode, filter to only the current sender's
1329+
// messages and bot replies to respect per-sender session isolation.
1330+
const senderScoped = groupSession?.groupSessionScope === "group_topic_sender";
1331+
const relevantMessages = senderScoped
1332+
? threadMessages.filter(
1333+
(msg) => msg.senderType === "app" || msg.senderId === ctx.senderOpenId,
1334+
)
1335+
: threadMessages;
1336+
if (relevantMessages.length > 0) {
1337+
const envelopeOpts = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
1338+
const historyParts = relevantMessages.map((msg) => {
1339+
const role = msg.senderType === "app" ? "assistant" : "user";
1340+
return core.channel.reply.formatAgentEnvelope({
1341+
channel: "Feishu",
1342+
from: `${msg.senderId ?? "Unknown"} (${role})`,
1343+
timestamp: msg.createTime,
1344+
body: msg.content,
1345+
envelope: envelopeOpts,
1346+
});
1347+
});
1348+
threadHistoryBody = historyParts.join("\n\n");
1349+
log(
1350+
`feishu[${account.accountId}]: populated thread history with ${relevantMessages.length} messages`,
1351+
);
1352+
}
1353+
} catch (err) {
1354+
log(`feishu[${account.accountId}]: failed to fetch thread history: ${String(err)}`);
1355+
}
1356+
} else {
1357+
log(
1358+
`feishu[${account.accountId}]: no threadId found for root message ${ctx.rootId ?? "none"}, skipping thread history`,
1359+
);
1360+
}
1361+
}
1362+
12611363
const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
12621364
const messageBody = buildFeishuAgentBody({
12631365
ctx,
@@ -1335,6 +1437,15 @@ export async function handleFeishuMessage(params: {
13351437
Surface: "feishu" as const,
13361438
MessageSid: ctx.messageId,
13371439
ReplyToBody: quotedContent ?? undefined,
1440+
ThreadStarterBody: threadStarterBody,
1441+
ThreadHistoryBody: threadHistoryBody,
1442+
ThreadLabel:
1443+
(ctx.rootId || ctx.threadId) && isTopicSessionForThread
1444+
? `Feishu thread in ${ctx.chatId}`
1445+
: undefined,
1446+
// Only use rootId (om_* message anchor) — threadId (omt_*) is a container
1447+
// ID and would produce invalid reply targets downstream.
1448+
MessageThreadId: ctx.rootId && isTopicSessionForThread ? ctx.rootId : undefined,
13381449
Timestamp: Date.now(),
13391450
WasMentioned: wasMentioned,
13401451
CommandAuthorized: commandAuthorized,

‎extensions/feishu/src/send.ts‎

Lines changed: 119 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ type FeishuMessageGetItem = {
6565
message_id?: string;
6666
chat_id?: string;
6767
chat_type?: FeishuChatType;
68+
thread_id?: string;
6869
msg_type?: string;
6970
body?: { content?: string };
7071
sender?: FeishuMessageSender;
@@ -151,13 +152,19 @@ function parseInteractiveCardContent(parsed: unknown): string {
151152
return "[Interactive Card]";
152153
}
153154

154-
const candidate = parsed as { elements?: unknown };
155-
if (!Array.isArray(candidate.elements)) {
155+
// Support both schema 1.0 (top-level `elements`) and 2.0 (`body.elements`).
156+
const candidate = parsed as { elements?: unknown; body?: { elements?: unknown } };
157+
const elements = Array.isArray(candidate.elements)
158+
? candidate.elements
159+
: Array.isArray(candidate.body?.elements)
160+
? candidate.body!.elements
161+
: null;
162+
if (!elements) {
156163
return "[Interactive Card]";
157164
}
158165

159166
const texts: string[] = [];
160-
for (const element of candidate.elements) {
167+
for (const element of elements) {
161168
if (!element || typeof element !== "object") {
162169
continue;
163170
}
@@ -272,12 +279,121 @@ export async function getMessageFeishu(params: {
272279
content,
273280
contentType: msgType,
274281
createTime: item.create_time ? parseInt(String(item.create_time), 10) : undefined,
282+
threadId: item.thread_id || undefined,
275283
};
276284
} catch {
277285
return null;
278286
}
279287
}
280288

289+
export type FeishuThreadMessageInfo = {
290+
messageId: string;
291+
senderId?: string;
292+
senderType?: string;
293+
content: string;
294+
contentType: string;
295+
createTime?: number;
296+
};
297+
298+
/**
299+
* List messages in a Feishu thread (topic).
300+
* Uses container_id_type=thread to directly query thread messages,
301+
* which includes both the root message and all replies (including bot replies).
302+
*/
303+
export async function listFeishuThreadMessages(params: {
304+
cfg: ClawdbotConfig;
305+
threadId: string;
306+
currentMessageId?: string;
307+
/** Exclude the root message (already provided separately as ThreadStarterBody). */
308+
rootMessageId?: string;
309+
limit?: number;
310+
accountId?: string;
311+
}): Promise<FeishuThreadMessageInfo[]> {
312+
const { cfg, threadId, currentMessageId, rootMessageId, limit = 20, accountId } = params;
313+
const account = resolveFeishuAccount({ cfg, accountId });
314+
if (!account.configured) {
315+
throw new Error(`Feishu account "${account.accountId}" not configured`);
316+
}
317+
318+
const client = createFeishuClient(account);
319+
320+
const response = (await client.im.message.list({
321+
params: {
322+
container_id_type: "thread",
323+
container_id: threadId,
324+
// Fetch newest messages first so long threads keep the most recent turns.
325+
// Results are reversed below to restore chronological order.
326+
sort_type: "ByCreateTimeDesc",
327+
page_size: Math.min(limit + 1, 50),
328+
},
329+
})) as {
330+
code?: number;
331+
msg?: string;
332+
data?: {
333+
items?: Array<{
334+
message_id?: string;
335+
root_id?: string;
336+
parent_id?: string;
337+
msg_type?: string;
338+
body?: { content?: string };
339+
sender?: {
340+
id: string;
341+
id_type: string;
342+
sender_type: string;
343+
};
344+
create_time?: string;
345+
}>;
346+
};
347+
};
348+
349+
if (response.code !== 0) {
350+
throw new Error(
351+
`Feishu thread list failed: code=${response.code} msg=${response.msg ?? "unknown"}`,
352+
);
353+
}
354+
355+
const items = response.data?.items ?? [];
356+
const results: FeishuThreadMessageInfo[] = [];
357+
358+
for (const item of items) {
359+
if (currentMessageId && item.message_id === currentMessageId) continue;
360+
if (rootMessageId && item.message_id === rootMessageId) continue;
361+
362+
let content = item.body?.content ?? "";
363+
try {
364+
const parsed = JSON.parse(content);
365+
if (item.msg_type === "text" && parsed.text) {
366+
content = parsed.text;
367+
} else if (item.msg_type === "post") {
368+
content = parsePostContent(content).textContent;
369+
} else if (item.msg_type === "interactive") {
370+
content = parseInteractiveCardContent(parsed);
371+
} else {
372+
// For unsupported types (image, file, share, system, etc.) use a
373+
// concise placeholder instead of leaking raw JSON into the prompt.
374+
content = `[${item.msg_type ?? "unknown"} message]`;
375+
}
376+
} catch {
377+
// Keep raw content if parsing fails
378+
}
379+
380+
results.push({
381+
messageId: item.message_id ?? "",
382+
senderId: item.sender?.id,
383+
senderType: item.sender?.sender_type,
384+
content,
385+
contentType: item.msg_type ?? "text",
386+
createTime: item.create_time ? parseInt(item.create_time, 10) : undefined,
387+
});
388+
389+
if (results.length >= limit) break;
390+
}
391+
392+
// Restore chronological order (oldest first) since we fetched newest-first.
393+
results.reverse();
394+
return results;
395+
}
396+
281397
export type SendFeishuMessageParams = {
282398
cfg: ClawdbotConfig;
283399
to: string;

‎extensions/feishu/src/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ export type FeishuMessageInfo = {
7272
content: string;
7373
contentType: string;
7474
createTime?: number;
75+
/** Feishu thread ID (omt_xxx) — present when the message belongs to a topic thread. */
76+
threadId?: string;
7577
};
7678

7779
export type FeishuProbeResult = BaseProbeResult<string> & {

0 commit comments

Comments
 (0)