Skip to content

Commit c4b34e5

Browse files
committed
fix(line): preserve resolved group identities
1 parent 18db398 commit c4b34e5

6 files changed

Lines changed: 161 additions & 71 deletions

File tree

‎extensions/line/src/bot-handlers.test.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ const { readAllowFromStoreMock, upsertPairingRequestMock } = vi.hoisted(() => ({
155155
upsertPairingRequestMock: vi.fn(async (_args: unknown) => ({ code: "CODE", created: true })),
156156
}));
157157
const downloadLineMediaMock = vi.hoisted(() => vi.fn());
158+
const getUserDisplayNameMock = vi.hoisted(() => vi.fn(async (userId: string) => userId));
158159

159160
vi.mock("openclaw/plugin-sdk/conversation-runtime", () => ({
160161
resolvePairingIdLabel: () => "lineUserId",
@@ -168,6 +169,8 @@ vi.mock("./download.js", async (importActual) => ({
168169
}));
169170

170171
vi.mock("./send.js", () => ({
172+
getLineGroupName: vi.fn(),
173+
getUserDisplayName: getUserDisplayNameMock,
171174
pushMessageLine: pairingDeliveryMocks.pushMessageLine,
172175
replyMessageLine: pairingDeliveryMocks.replyMessageLine,
173176
}));
@@ -351,6 +354,8 @@ describe("handleLineWebhookEvents", () => {
351354
downloadLineMediaMock.mockImplementation(async () => {
352355
throw new Error("downloadLineMedia should not be called from bot-handlers tests");
353356
});
357+
getUserDisplayNameMock.mockReset();
358+
getUserDisplayNameMock.mockImplementation(async (userId: string) => userId);
354359
});
355360
it("blocks group messages when groupPolicy is disabled", async () => {
356361
const processMessage = vi.fn();
@@ -859,6 +864,7 @@ describe("handleLineWebhookEvents", () => {
859864
it("records unmentioned group messages as pending history", async () => {
860865
const processMessage = vi.fn();
861866
const groupHistories = new Map<string, HistoryEntry[]>();
867+
getUserDisplayNameMock.mockResolvedValueOnce("Sora");
862868
const event = createTestMessageEvent({
863869
message: { id: "m-hist-1", type: "text", text: "hello history", quoteToken: "q-hist-1" },
864870
timestamp: 1700000000000,
@@ -879,9 +885,13 @@ describe("handleLineWebhookEvents", () => {
879885
const entries = groupHistories.get("group-hist-1");
880886
expect(entries).toHaveLength(1);
881887
const entry = entries?.[0];
882-
expect(entry?.sender).toBe("user:user-hist");
888+
expect(entry?.sender).toBe("Sora");
883889
expect(entry?.body).toBe("hello history");
884890
expect(entry?.timestamp).toBe(1700000000000);
891+
expect(getUserDisplayNameMock).toHaveBeenCalledWith(
892+
"user-hist",
893+
expect.objectContaining({ groupId: "group-hist-1" }),
894+
);
885895
});
886896

887897
it("keeps a group message recorded during a mention turn instead of clearing it", async () => {

‎extensions/line/src/bot-handlers.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ import {
4949
import { downloadLineMedia, isRetryableLineInboundMediaError } from "./download.js";
5050
import { reserveLineGroupHistory } from "./group-history.js";
5151
import { resolveLineGroupConfigEntry } from "./group-keys.js";
52-
import { getLineGroupName, pushMessageLine, replyMessageLine } from "./send.js";
52+
import { getLineGroupName, getUserDisplayName, pushMessageLine, replyMessageLine } from "./send.js";
5353
import type { LineGroupConfig, ResolvedLineAccount } from "./types.js";
5454
import type { LineWebhookTurnAdoptionLifecycle } from "./webhook-spool.js";
5555

@@ -399,11 +399,20 @@ async function handleMessageEvent(event: MessageEvent, context: LineHandlerConte
399399
const historyKey = groupId ?? roomId;
400400
const senderId = sourceInfo.userId ?? "unknown";
401401
if (historyKey && context.groupHistories) {
402+
const sender = sourceInfo.userId
403+
? await getUserDisplayName(sourceInfo.userId, {
404+
cfg,
405+
accountId: account.accountId,
406+
channelAccessToken: account.channelAccessToken,
407+
groupId,
408+
roomId,
409+
})
410+
: senderId;
402411
createChannelHistoryWindow({ historyMap: context.groupHistories }).record({
403412
historyKey,
404413
limit: context.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT,
405414
entry: {
406-
sender: `user:${senderId}`,
415+
sender,
407416
body: rawText || `<${message.type}>`,
408417
timestamp: event.timestamp,
409418
},

‎extensions/line/src/bot-message-context.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@ describe("buildLineMessageContext", () => {
111111

112112
beforeEach(async () => {
113113
logVerboseMock.mockClear();
114+
getUserProfileMock.mockClear();
115+
getLineGroupNameMock.mockClear();
114116
toInboundMediaFactsWithMetadataMock.mockClear();
115117
setActivePluginRegistry(
116118
createTestRegistry([

‎extensions/line/src/monitor.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ export async function monitorLineProvider(
177177
// The inbound context already resolved the sender's name for the agent;
178178
// reading it back costs nothing instead of asking LINE a second time.
179179
logVerbose(
180-
`line: received message from ${ctxPayload.SenderName ?? ctxPayload.From} (${ctxPayload.From})`,
180+
`line: received message from ${ctxPayload.SenderName ?? ctx.userId ?? ctxPayload.From} (${ctxPayload.From})`,
181181
);
182182
let replyTokenUsed = false;
183183
let turnAdopted = false;

‎extensions/line/src/send.identity.test.ts‎

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,31 @@ describe("LINE identity lookups", () => {
114114
});
115115

116116
it("degrades to no profile when LINE cannot answer", async () => {
117-
getGroupMemberProfileMock.mockRejectedValueOnce(new Error("404 not found"));
117+
getGroupMemberProfileMock.mockRejectedValue(new Error("404 not found"));
118118

119119
await expect(
120120
sendModule.getUserProfile("Umissing", { cfg: LINE_TEST_CFG, groupId: "Cgroup2" }),
121121
).resolves.toBeNull();
122+
await expect(
123+
sendModule.getUserProfile("Umissing", { cfg: LINE_TEST_CFG, groupId: "Cgroup2" }),
124+
).resolves.toBeNull();
125+
126+
expect(getGroupMemberProfileMock).toHaveBeenCalledTimes(1);
127+
});
128+
129+
it("keeps profile cache entries scoped to their conversation endpoint", async () => {
130+
getGroupMemberProfileMock.mockResolvedValueOnce({ displayName: "Group Sora" });
131+
getRoomMemberProfileMock.mockResolvedValueOnce({ displayName: "Room Sora" });
132+
133+
await expect(
134+
sendModule.getUserProfile("Ushared", { cfg: LINE_TEST_CFG, groupId: "Cshared" }),
135+
).resolves.toMatchObject({ displayName: "Group Sora" });
136+
await expect(
137+
sendModule.getUserProfile("Ushared", { cfg: LINE_TEST_CFG, roomId: "Rshared" }),
138+
).resolves.toMatchObject({ displayName: "Room Sora" });
139+
140+
expect(getGroupMemberProfileMock).toHaveBeenCalledTimes(1);
141+
expect(getRoomMemberProfileMock).toHaveBeenCalledTimes(1);
122142
});
123143

124144
it("resolves a group name once and serves the rest from cache", async () => {
@@ -134,11 +154,32 @@ describe("LINE identity lookups", () => {
134154
expect(getGroupSummaryMock).toHaveBeenCalledTimes(1);
135155
});
136156

157+
it("coalesces concurrent group-name cache misses", async () => {
158+
let resolveSummary: (summary: { groupId: string; groupName: string }) => void = () => {};
159+
getGroupSummaryMock.mockReturnValueOnce(
160+
new Promise((resolve) => {
161+
resolveSummary = resolve;
162+
}),
163+
);
164+
165+
const first = sendModule.getLineGroupName("Cconcurrent", { cfg: LINE_TEST_CFG });
166+
const second = sendModule.getLineGroupName("Cconcurrent", { cfg: LINE_TEST_CFG });
167+
expect(getGroupSummaryMock).toHaveBeenCalledTimes(1);
168+
169+
resolveSummary({ groupId: "Cconcurrent", groupName: "Release Squad" });
170+
await expect(Promise.all([first, second])).resolves.toEqual(["Release Squad", "Release Squad"]);
171+
});
172+
137173
it("degrades to no group name when the summary call fails", async () => {
138-
getGroupSummaryMock.mockRejectedValueOnce(new Error("403 forbidden"));
174+
getGroupSummaryMock.mockRejectedValue(new Error("403 forbidden"));
139175

140176
await expect(
141177
sendModule.getLineGroupName("Cforbidden", { cfg: LINE_TEST_CFG }),
142178
).resolves.toBeUndefined();
179+
await expect(
180+
sendModule.getLineGroupName("Cforbidden", { cfg: LINE_TEST_CFG }),
181+
).resolves.toBeUndefined();
182+
183+
expect(getGroupSummaryMock).toHaveBeenCalledTimes(1);
143184
});
144185
});

‎extensions/line/src/send.ts‎

Lines changed: 93 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,20 @@ type QuickReply = messagingApi.QuickReply;
3434
type QuickReplyItem = messagingApi.QuickReplyItem;
3535
type LineLocation = NonNullable<LineChannelData["location"]>;
3636

37-
const userProfileCache = new Map<
38-
string,
39-
{ displayName: string; pictureUrl?: string; fetchedAt: number }
40-
>();
41-
const groupNameCache = new Map<string, { groupName: string; fetchedAt: number }>();
37+
type LineUserProfile = { displayName: string; pictureUrl?: string };
38+
type LineIdentityCache<T> = {
39+
values: Map<string, { value: T; fetchedAt: number }>;
40+
pending: Map<string, Promise<T>>;
41+
};
42+
43+
const profileCache: LineIdentityCache<LineUserProfile | null> = {
44+
values: new Map(),
45+
pending: new Map(),
46+
};
47+
const groupNameCache: LineIdentityCache<string | undefined> = {
48+
values: new Map(),
49+
pending: new Map(),
50+
};
4251
const PROFILE_CACHE_TTL_MS = 5 * 60 * 1000;
4352
const PROFILE_CACHE_MAX_ENTRIES = 1000;
4453
const LINE_FLEX_ALT_TEXT_LIMIT = 1500;
@@ -48,30 +57,47 @@ const LINE_LOCATION_LABEL_LIMIT = 100;
4857
const LINE_PROVIDER_RESPONSE_MAX_BYTES = 16 * 1024;
4958

5059
// Refresh insertion order so overflow evicts expired entries first, then the oldest live fetch.
51-
function rememberLineIdentity<T extends { fetchedAt: number }>(
52-
cache: Map<string, T>,
53-
key: string,
54-
value: T,
55-
): void {
56-
cache.delete(key);
57-
cache.set(key, value);
58-
if (cache.size <= PROFILE_CACHE_MAX_ENTRIES) {
60+
function rememberLineIdentity<T>(cache: LineIdentityCache<T>, key: string, value: T): void {
61+
const entry = { value, fetchedAt: Date.now() };
62+
cache.values.delete(key);
63+
cache.values.set(key, entry);
64+
if (cache.values.size <= PROFILE_CACHE_MAX_ENTRIES) {
5965
return;
6066
}
61-
for (const [cachedKey, cached] of cache) {
62-
if (value.fetchedAt - cached.fetchedAt >= PROFILE_CACHE_TTL_MS) {
63-
cache.delete(cachedKey);
67+
for (const [cachedKey, cached] of cache.values) {
68+
if (entry.fetchedAt - cached.fetchedAt >= PROFILE_CACHE_TTL_MS) {
69+
cache.values.delete(cachedKey);
6470
}
6571
}
66-
pruneMapToMaxSize(cache, PROFILE_CACHE_MAX_ENTRIES);
72+
pruneMapToMaxSize(cache.values, PROFILE_CACHE_MAX_ENTRIES);
6773
}
6874

69-
function readLineIdentityCache<T extends { fetchedAt: number }>(
70-
cache: Map<string, T>,
75+
async function loadLineIdentity<T>(
76+
cache: LineIdentityCache<T>,
7177
key: string,
72-
): T | undefined {
73-
const cached = cache.get(key);
74-
return cached && Date.now() - cached.fetchedAt < PROFILE_CACHE_TTL_MS ? cached : undefined;
78+
load: () => Promise<T>,
79+
): Promise<T> {
80+
const cached = cache.values.get(key);
81+
if (cached && Date.now() - cached.fetchedAt < PROFILE_CACHE_TTL_MS) {
82+
return cached.value;
83+
}
84+
const pending = cache.pending.get(key);
85+
if (pending) {
86+
return await pending;
87+
}
88+
const lookup = load().then((value) => {
89+
rememberLineIdentity(cache, key, value);
90+
return value;
91+
});
92+
cache.pending.set(key, lookup);
93+
pruneMapToMaxSize(cache.pending, PROFILE_CACHE_MAX_ENTRIES);
94+
try {
95+
return await lookup;
96+
} finally {
97+
if (cache.pending.get(key) === lookup) {
98+
cache.pending.delete(key);
99+
}
100+
}
75101
}
76102

77103
interface LineSendOpts {
@@ -641,16 +667,21 @@ export async function showLoadingAnimation(
641667
}
642668
}
643669

644-
async function getLineGroupSummary(
645-
groupId: string,
646-
opts: LineClientOpts,
647-
): Promise<messagingApi.GroupSummaryResponse> {
648-
const { client } = createLineMessagingClient(opts);
649-
return await client.getGroupSummary(groupId);
650-
}
651-
652670
export type LineConversationScope = { groupId?: string; roomId?: string };
653671

672+
function lineProfileCacheKey(
673+
accountId: string,
674+
userId: string,
675+
scope: LineConversationScope,
676+
): string {
677+
const conversation = scope.groupId
678+
? ["group", scope.groupId]
679+
: scope.roomId
680+
? ["room", scope.roomId]
681+
: ["direct"];
682+
return JSON.stringify([accountId, "profile", ...conversation, userId]);
683+
}
684+
654685
// A group or room member who has not added the bot as a friend is invisible to
655686
// the plain profile endpoint, so the sender's conversation decides which one can
656687
// answer. Reading the wrong one returns 404 for exactly the people whose names
@@ -672,33 +703,29 @@ function fetchLineMemberProfile(
672703
export async function getUserProfile(
673704
userId: string,
674705
opts: LineClientOpts & { useCache?: boolean } & LineConversationScope,
675-
): Promise<{ displayName: string; pictureUrl?: string } | null> {
706+
): Promise<LineUserProfile | null> {
676707
const useCache = opts.useCache ?? true;
677-
678-
if (useCache) {
679-
const cached = readLineIdentityCache(userProfileCache, userId);
680-
if (cached) {
681-
return { displayName: cached.displayName, pictureUrl: cached.pictureUrl };
682-
}
683-
}
684-
685708
try {
686-
// Client construction resolves the account token and can throw, so it stays
687-
// inside the guard: an unresolvable name degrades to the raw id, never to a
688-
// failed inbound turn.
689-
const { client } = createLineMessagingClient(opts);
690-
const profile = await fetchLineMemberProfile(client, userId, opts);
691-
const result = {
692-
displayName: profile.displayName,
693-
pictureUrl: profile.pictureUrl,
709+
// Client construction resolves the canonical account for the cache key and
710+
// can throw; an unresolvable name must never cost the inbound turn.
711+
const { account, token } = resolveLineMessagingAccount(opts);
712+
const cacheKey = lineProfileCacheKey(account.accountId, userId, opts);
713+
const load = async () => {
714+
try {
715+
const client = new messagingApi.MessagingApiClient({ channelAccessToken: token });
716+
const profile = await fetchLineMemberProfile(client, userId, opts);
717+
return { displayName: profile.displayName, pictureUrl: profile.pictureUrl };
718+
} catch (err) {
719+
logVerbose(`line: failed to fetch profile for ${userId}: ${String(err)}`);
720+
return null;
721+
}
694722
};
695-
696-
rememberLineIdentity(userProfileCache, userId, {
697-
...result,
698-
fetchedAt: Date.now(),
699-
});
700-
701-
return result;
723+
if (!useCache) {
724+
const profile = await load();
725+
rememberLineIdentity(profileCache, cacheKey, profile);
726+
return profile;
727+
}
728+
return await loadLineIdentity(profileCache, cacheKey, load);
702729
} catch (err) {
703730
logVerbose(`line: failed to fetch profile for ${userId}: ${String(err)}`);
704731
return null;
@@ -719,18 +746,19 @@ export async function getLineGroupName(
719746
groupId: string,
720747
opts: LineClientOpts,
721748
): Promise<string | undefined> {
722-
const cached = readLineIdentityCache(groupNameCache, groupId);
723-
if (cached) {
724-
return cached.groupName;
725-
}
726749
try {
727-
const summary = await getLineGroupSummary(groupId, opts);
728-
const groupName = summary.groupName.trim();
729-
if (!groupName) {
730-
return undefined;
731-
}
732-
rememberLineIdentity(groupNameCache, groupId, { groupName, fetchedAt: Date.now() });
733-
return groupName;
750+
const { account, token } = resolveLineMessagingAccount(opts);
751+
const cacheKey = JSON.stringify([account.accountId, "group", groupId]);
752+
return await loadLineIdentity(groupNameCache, cacheKey, async () => {
753+
try {
754+
const client = new messagingApi.MessagingApiClient({ channelAccessToken: token });
755+
const summary = await client.getGroupSummary(groupId);
756+
return summary.groupName.trim() || undefined;
757+
} catch (err) {
758+
logVerbose(`line: failed to fetch group summary for ${groupId}: ${String(err)}`);
759+
return undefined;
760+
}
761+
});
734762
} catch (err) {
735763
logVerbose(`line: failed to fetch group summary for ${groupId}: ${String(err)}`);
736764
return undefined;

0 commit comments

Comments
 (0)