Skip to content

Commit a0f4d54

Browse files
authored
refactor(channels): carry typed approval-prompt bindings through signal/imessage send seams (#124742)
The Signal and iMessage channel plugins inferred approval prompts by regex-sniffing rendered message text (header matching like 'Exec approval required', /approve command parsing), violating the transport-only channel doctrine: approval actions must stay typed until channel encoding. The typed envelope already existed (channelData.execApproval with approvalId/approvalKind/allowedDecisions) and every payload-level delivery path consumed it; the regex paths were redundant re-derivation at the raw send seam plus restart recovery for in-memory iMessage poll state. - Signal: delete send-level prompt sniffing entirely; all approval sends already flow through typed structured-payload or native-handler paths. - iMessage: sendMessageIMessage takes a typed approvalPrompt binding (id/kind/decisions) from the native approval handler instead of an approvalKind flag plus text re-parsing. - iMessage poller: persist pending poll targets in the plugin keyed store so restart recovery no longer regex-scans chat history; typed recent-chat discovery for handle-only DM targets stays. Split poll-target ownership into approval-reaction-poll-targets.ts (max-lines). - Plugin SDK: remove extractApprovalReactionPromptBinding — beta-only surface, never in a stable release, so no deprecation window applies; AGENTS.md now records that rule. Accepted tradeoff: approval prompts delivered by a pre-upgrade process are not rediscovered from chat text after restart (<=24h transient state; persisted reaction bindings and event-driven tapbacks still work).
1 parent ed17993 commit a0f4d54

16 files changed

Lines changed: 420 additions & 1091 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ Skills own workflows; root owns hard policy and routing. Product direction and m
105105
- Nested CLI options: when a parent option semantically applies to a leaf subcommand, declare it on both the parent and every applicable leaf so positional parsing accepts the option before or after the subcommand. Resolve the leaf value only when its source is non-default, then inherit from ancestors with `inheritOptionFromParent`. Do not expose inherited options on leaves where the semantics differ. Add real-parser coverage that enumerates every applicable leaf.
106106
- New binary fallible-operation results use `Result` from `@openclaw/normalization-core/result`; domain-rich outcomes keep named discriminated unions.
107107
- Tests may use observed examples, but prod literals need a short contract reason.
108-
- Compatibility is opt-in. "Shipped" means reachable from a release Git tag; main/GitHub/PR/unreleased code is not shipped.
108+
- Compatibility is opt-in. "Shipped" means reachable from a stable release Git tag; betas, nightlies, main/GitHub/PR/unreleased code are not shipped. Plugin SDK surface in beta-only tags carries no compat obligation — remove, don't deprecate.
109109
- Refactor default: one canonical path — delete the old one. Keep old behavior only when the user explicitly asks or for an explicit public API/config/plugin SDK/data contract, tagged upgrade path, security/migration boundary, dependency contract, or observed prod state; cite it.
110110
- Reuse canonical coercion guards (`@openclaw/normalization-core/record-coerce`; plugins: `openclaw/plugin-sdk/string-coerce-runtime`) — no local `isRecord` copies. CI guard `pnpm check:coercion-helpers` owns the carve-outs; intentionally different semantics or a file that cannot use workspace resolution gets a reasoned carve-out entry there.
111111
- Core runtime consumes only current canonical shapes/config/data. Legacy or retired shapes normalize only in doctor/migration code before runtime; no runtime shims, aliases, or fallback readers.

‎extensions/imessage/src/approval-handler.runtime.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ describe("imessageApprovalNativeRuntime", () => {
505505
pollDeliverArgs.pendingPayload.pollText,
506506
expect.objectContaining({ conversationReadOrigin: "direct-operator" }),
507507
);
508-
expect(sendMock.sendMessageIMessage.mock.calls[0]?.[2]).not.toHaveProperty("approvalKind");
508+
expect(sendMock.sendMessageIMessage.mock.calls[0]?.[2]).not.toHaveProperty("approvalPrompt");
509509
expect(actionsMock.sendPoll).toHaveBeenCalledWith(
510510
expect.objectContaining({
511511
chatGuid: "iMessage;-;+15551230000",
@@ -815,7 +815,11 @@ describe("imessageApprovalNativeRuntime", () => {
815815
"+15551230000",
816816
pollDeliverArgs.pendingPayload.text,
817817
expect.objectContaining({
818-
approvalKind: "exec",
818+
approvalPrompt: {
819+
approvalId: "exec-poll",
820+
approvalKind: "exec",
821+
allowedDecisions: ["allow-once", "deny"],
822+
},
819823
replyToId: "prompt-guid",
820824
}),
821825
);
@@ -886,7 +890,11 @@ describe("imessageApprovalNativeRuntime", () => {
886890
"+15551230000",
887891
pollDeliverArgs.pendingPayload.text,
888892
expect.objectContaining({
889-
approvalKind: "exec",
893+
approvalPrompt: {
894+
approvalId: "exec-poll",
895+
approvalKind: "exec",
896+
allowedDecisions: ["allow-once", "deny"],
897+
},
890898
replyToId: "prompt-guid",
891899
}),
892900
);

‎extensions/imessage/src/approval-handler.runtime.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ type PreparedIMessageApprovalTarget = {
6868
to: string;
6969
accountId?: string;
7070
};
71+
type IMessageApprovalPromptBinding = {
72+
approvalId: string;
73+
approvalKind: "exec" | "plugin";
74+
allowedDecisions: readonly ExecApprovalReplyDecision[];
75+
};
7176
type PendingIMessageApprovalEntry = {
7277
accountId?: string;
7378
to: string;
@@ -363,12 +368,12 @@ async function recoverIMessageApprovalTextFallback(params: {
363368
target: PreparedIMessageApprovalTarget;
364369
promptMessageId?: string;
365370
fallbackText: string;
366-
approvalKind: "exec" | "plugin";
371+
approvalPrompt: IMessageApprovalPromptBinding;
367372
}): Promise<string | undefined> {
368373
try {
369374
const result = await sendMessageIMessage(params.target.to, params.fallbackText, {
370375
config: params.cfg,
371-
approvalKind: params.approvalKind,
376+
approvalPrompt: params.approvalPrompt,
372377
conversationReadOrigin: "direct-operator",
373378
...(params.target.accountId ? { accountId: params.target.accountId } : {}),
374379
...(params.promptMessageId ? { replyToId: params.promptMessageId } : {}),
@@ -543,9 +548,14 @@ export const imessageApprovalNativeRuntime = createChannelApprovalNativeRuntimeA
543548
// fallback visible until the send receipt confirms the actual transport.
544549
const reactionFallbackVisible = !expectPoll || targetTransport !== "imessage";
545550
const promptText = reactionFallbackVisible ? pendingPayload.text : pendingPayload.pollText;
551+
const approvalPrompt: IMessageApprovalPromptBinding = {
552+
approvalId: view.approvalId,
553+
approvalKind: view.approvalKind,
554+
allowedDecisions: pendingPayload.allowedDecisions,
555+
};
546556
const result = await sendMessageIMessage(preparedTarget.to, promptText, {
547557
config: cfg,
548-
...(reactionFallbackVisible ? { approvalKind: view.approvalKind } : {}),
558+
...(reactionFallbackVisible ? { approvalPrompt } : {}),
549559
// Approval delivery is host-originated: the target comes from the
550560
// approval's own routing (origin session or a configured approver),
551561
// never from model input. Attest that so #99905's conversation-read
@@ -587,7 +597,7 @@ export const imessageApprovalNativeRuntime = createChannelApprovalNativeRuntimeA
587597
target: preparedTarget,
588598
promptMessageId: result.guid,
589599
fallbackText: pendingPayload.text,
590-
approvalKind: view.approvalKind,
600+
approvalPrompt,
591601
})
592602
: undefined;
593603
const entry: PendingIMessageApprovalEntry = {
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
// Imessage plugin module owns persisted approval reaction poll targets.
2+
import { readApprovalReactionDecisionList } from "openclaw/plugin-sdk/approval-reaction-runtime";
3+
import type { ExecApprovalReplyDecision } from "openclaw/plugin-sdk/approval-reply-runtime";
4+
import {
5+
asDateTimestampMs,
6+
isFutureDateTimestampMs,
7+
resolveExpiresAtMsFromDurationMs,
8+
} from "openclaw/plugin-sdk/number-runtime";
9+
import {
10+
createPluginStateErrorReporter,
11+
type PluginStateKeyedStore,
12+
} from "openclaw/plugin-sdk/plugin-state-runtime";
13+
import { asOptionalRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
14+
import {
15+
normalizeConversationKey,
16+
normalizeIMessageGuid,
17+
type IMessageApprovalConversationKey,
18+
} from "./approval-target-keys.js";
19+
import { getOptionalIMessageRuntime } from "./runtime.js";
20+
21+
const PERSISTENT_POLL_TARGET_NAMESPACE = "imessage.approval-reaction-poll-targets";
22+
const PERSISTENT_MAX_ENTRIES = 1000;
23+
const DEFAULT_REACTION_TARGET_TTL_MS = 24 * 60 * 60 * 1000;
24+
25+
export type PendingIMessageApprovalReactionPollTarget = {
26+
accountId: string;
27+
conversation: IMessageApprovalConversationKey;
28+
messageId: string;
29+
approvalId: string;
30+
approvalKind: "exec" | "plugin";
31+
allowedDecisions: readonly ExecApprovalReplyDecision[];
32+
expiresAtMs: number;
33+
};
34+
35+
const pendingReactionPollTargets = new Map<string, PendingIMessageApprovalReactionPollTarget>();
36+
37+
function prunePendingReactionPollTargets(nowMs = Date.now()): void {
38+
for (const [key, target] of pendingReactionPollTargets.entries()) {
39+
if (!isFutureDateTimestampMs(target.expiresAtMs, { nowMs })) {
40+
pendingReactionPollTargets.delete(key);
41+
}
42+
}
43+
}
44+
45+
function resolvePendingReactionPollExpiry(
46+
ttlMs: number | undefined,
47+
): { ttlMs: number; expiresAtMs: number } | undefined {
48+
const nowMs = asDateTimestampMs(Date.now());
49+
if (nowMs === undefined) {
50+
return undefined;
51+
}
52+
const expiresAtMs =
53+
resolveExpiresAtMsFromDurationMs(ttlMs ?? DEFAULT_REACTION_TARGET_TTL_MS, { nowMs }) ??
54+
resolveExpiresAtMsFromDurationMs(DEFAULT_REACTION_TARGET_TTL_MS, { nowMs });
55+
if (expiresAtMs === undefined) {
56+
return undefined;
57+
}
58+
return {
59+
ttlMs: expiresAtMs - nowMs,
60+
expiresAtMs,
61+
};
62+
}
63+
64+
function mergePollTargetConversation(
65+
left: IMessageApprovalConversationKey,
66+
right: IMessageApprovalConversationKey,
67+
): IMessageApprovalConversationKey {
68+
return {
69+
chatGuid: left.chatGuid ?? right.chatGuid,
70+
chatIdentifier: left.chatIdentifier ?? right.chatIdentifier,
71+
chatId: left.chatId ?? right.chatId,
72+
handle: left.handle ?? right.handle,
73+
};
74+
}
75+
76+
const reportPersistentApprovalReactionError = createPluginStateErrorReporter(
77+
getOptionalIMessageRuntime,
78+
"imessage",
79+
"approval-reaction-state",
80+
"iMessage persistent approval reaction state failed",
81+
);
82+
83+
let pendingReactionPollTargetStore:
84+
| PluginStateKeyedStore<PendingIMessageApprovalReactionPollTarget>
85+
| undefined;
86+
let pendingReactionPollTargetStoreDisabled = false;
87+
88+
function disablePendingReactionPollTargetStore(error: unknown): void {
89+
pendingReactionPollTargetStoreDisabled = true;
90+
pendingReactionPollTargetStore = undefined;
91+
reportPersistentApprovalReactionError(error);
92+
}
93+
94+
function getPendingReactionPollTargetStore():
95+
| PluginStateKeyedStore<PendingIMessageApprovalReactionPollTarget>
96+
| undefined {
97+
if (pendingReactionPollTargetStoreDisabled) {
98+
return undefined;
99+
}
100+
if (pendingReactionPollTargetStore) {
101+
return pendingReactionPollTargetStore;
102+
}
103+
try {
104+
pendingReactionPollTargetStore =
105+
getOptionalIMessageRuntime()?.state.openKeyedStore<PendingIMessageApprovalReactionPollTarget>(
106+
{
107+
namespace: PERSISTENT_POLL_TARGET_NAMESPACE,
108+
maxEntries: PERSISTENT_MAX_ENTRIES,
109+
defaultTtlMs: DEFAULT_REACTION_TARGET_TTL_MS,
110+
},
111+
);
112+
return pendingReactionPollTargetStore;
113+
} catch (error) {
114+
disablePendingReactionPollTargetStore(error);
115+
return undefined;
116+
}
117+
}
118+
119+
function readPersistedPollTarget(value: unknown): PendingIMessageApprovalReactionPollTarget | null {
120+
const target = asOptionalRecord(value);
121+
if (!target) {
122+
return null;
123+
}
124+
const accountId = typeof target.accountId === "string" ? target.accountId.trim() : "";
125+
const messageId = typeof target.messageId === "string" ? target.messageId.trim() : "";
126+
const approvalId = typeof target.approvalId === "string" ? target.approvalId.trim() : "";
127+
const expiresAtMs = asDateTimestampMs(target.expiresAtMs);
128+
const allowedDecisions = readApprovalReactionDecisionList(target.allowedDecisions);
129+
const rawConversation = asOptionalRecord(target.conversation) ?? {};
130+
const conversation: IMessageApprovalConversationKey = {
131+
...(typeof rawConversation.chatGuid === "string"
132+
? { chatGuid: rawConversation.chatGuid.trim() }
133+
: {}),
134+
...(typeof rawConversation.chatIdentifier === "string"
135+
? { chatIdentifier: rawConversation.chatIdentifier.trim() }
136+
: {}),
137+
...(typeof rawConversation.chatId === "string" || typeof rawConversation.chatId === "number"
138+
? { chatId: rawConversation.chatId }
139+
: {}),
140+
...(typeof rawConversation.handle === "string"
141+
? { handle: rawConversation.handle.trim() }
142+
: {}),
143+
};
144+
if (
145+
!accountId ||
146+
!messageId ||
147+
!approvalId ||
148+
expiresAtMs === undefined ||
149+
!allowedDecisions ||
150+
(target.approvalKind !== "exec" && target.approvalKind !== "plugin") ||
151+
!normalizeConversationKey(conversation)
152+
) {
153+
return null;
154+
}
155+
return {
156+
accountId,
157+
conversation,
158+
messageId,
159+
approvalId,
160+
approvalKind: target.approvalKind,
161+
allowedDecisions,
162+
expiresAtMs,
163+
};
164+
}
165+
166+
export function recordIMessageApprovalReactionPollTarget(params: {
167+
keys: readonly string[];
168+
accountId: string;
169+
conversation: IMessageApprovalConversationKey;
170+
messageId: string;
171+
approvalId: string;
172+
approvalKind: "exec" | "plugin";
173+
allowedDecisions: readonly ExecApprovalReplyDecision[];
174+
ttlMs?: number;
175+
}): { ttlMs: number; expiresAtMs: number } | null {
176+
const expiry = resolvePendingReactionPollExpiry(params.ttlMs);
177+
if (!expiry || params.keys.length === 0) {
178+
return null;
179+
}
180+
const target: PendingIMessageApprovalReactionPollTarget = {
181+
accountId: params.accountId,
182+
conversation: params.conversation,
183+
messageId: params.messageId,
184+
approvalId: params.approvalId,
185+
approvalKind: params.approvalKind,
186+
allowedDecisions: params.allowedDecisions,
187+
expiresAtMs: expiry.expiresAtMs,
188+
};
189+
const store = getPendingReactionPollTargetStore();
190+
for (const key of params.keys) {
191+
pendingReactionPollTargets.set(key, target);
192+
void store
193+
?.register(key, target, { ttlMs: expiry.ttlMs })
194+
.catch(disablePendingReactionPollTargetStore);
195+
}
196+
prunePendingReactionPollTargets();
197+
return expiry;
198+
}
199+
200+
export function deleteIMessageApprovalReactionPollTargets(keys: readonly string[]): void {
201+
const store = getPendingReactionPollTargetStore();
202+
for (const key of keys) {
203+
pendingReactionPollTargets.delete(key);
204+
void store?.delete(key).catch(disablePendingReactionPollTargetStore);
205+
}
206+
}
207+
208+
export async function listPendingIMessageApprovalReactionPollTargets(params: {
209+
accountId: string;
210+
}): Promise<PendingIMessageApprovalReactionPollTarget[]> {
211+
const accountId = params.accountId.trim();
212+
if (!accountId) {
213+
return [];
214+
}
215+
const nowMs = Date.now();
216+
const store = getPendingReactionPollTargetStore();
217+
if (store) {
218+
try {
219+
for (const entry of await store.entries()) {
220+
const target = readPersistedPollTarget(entry.value);
221+
if (!target || !isFutureDateTimestampMs(target.expiresAtMs, { nowMs })) {
222+
await store.delete(entry.key);
223+
continue;
224+
}
225+
pendingReactionPollTargets.set(entry.key, target);
226+
}
227+
} catch (error) {
228+
disablePendingReactionPollTargetStore(error);
229+
}
230+
}
231+
prunePendingReactionPollTargets(nowMs);
232+
const targetByApprovalAndMessage = new Map<string, PendingIMessageApprovalReactionPollTarget>();
233+
for (const target of pendingReactionPollTargets.values()) {
234+
if (target.accountId !== accountId) {
235+
continue;
236+
}
237+
const key = `${target.approvalId}:${normalizeIMessageGuid(target.messageId)}`;
238+
const existing = targetByApprovalAndMessage.get(key);
239+
if (!existing) {
240+
targetByApprovalAndMessage.set(key, target);
241+
continue;
242+
}
243+
targetByApprovalAndMessage.set(key, {
244+
...existing,
245+
conversation: mergePollTargetConversation(existing.conversation, target.conversation),
246+
expiresAtMs: Math.max(existing.expiresAtMs, target.expiresAtMs),
247+
});
248+
}
249+
return [...targetByApprovalAndMessage.values()];
250+
}
251+
252+
export function clearIMessageApprovalReactionPollTargetsForTest(): void {
253+
pendingReactionPollTargets.clear();
254+
pendingReactionPollTargetStore = undefined;
255+
pendingReactionPollTargetStoreDisabled = false;
256+
}

0 commit comments

Comments
 (0)