fix(onebot): preserve public Qzone input semantics

Keep comment and reply text unchanged and support structured input in the debug console. Report malformed input before sending a request.

Refs #587
This commit is contained in:
DrSmoothl committed 2026-10-25 23:26:55 +08:00
1 parent 2f1aadffbe
commit dafe2082f1
10 files changed
+464 -113

No files matched your search

+64 -14
View File
@@ -1546,17 +1546,28 @@
},
{
"name": "content",
"type": "message",
"type": "string | object[]",
"required": true,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": true
}
}
]
},
"desc": "非空文本,或非空上游 RichItem 对象数组;不是 OneBot 消息段"
"desc": "非空文本,或非空上游 RichItem 对象数组;字符串始终原样发送,富文本请直接传对象数组,不是 OneBot 消息段"
}
],
"invariants": [
"content must be non-empty text or a non-empty array of RichItem objects"
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
@@ -1566,7 +1577,21 @@
"description": "get_qzone_public_feeds 返回的完整 feeds 条目,保留所有原始 cell 字段"
},
"content": {
"description": "非空文本,或非空上游 RichItem 对象数组;不是 OneBot 消息段"
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": true
}
}
],
"description": "非空文本,或非空上游 RichItem 对象数组;字符串始终原样发送,富文本请直接传对象数组,不是 OneBot 消息段"
}
},
"required": [
@@ -13889,12 +13914,25 @@
},
{
"name": "content",
"type": "message",
"type": "string | object[]",
"required": true,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": true
}
}
]
},
"desc": "非空文本,或非空上游 RichItem 对象数组;不是 OneBot 消息段"
"desc": "非空文本,或非空上游 RichItem 对象数组;字符串始终原样发送,富文本请直接传对象数组,不是 OneBot 消息段"
},
{
"name": "reply",
@@ -13907,9 +13945,7 @@
"desc": "评论或回复页返回的完整回复对象,保留 user 等原始字段"
}
],
"invariants": [
"content must be non-empty text or a non-empty array of RichItem objects"
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
@@ -13924,7 +13960,21 @@
"description": "详情或评论页返回的完整评论对象,保留 user 等原始字段"
},
"content": {
"description": "非空文本,或非空上游 RichItem 对象数组;不是 OneBot 消息段"
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": true
}
}
],
"description": "非空文本,或非空上游 RichItem 对象数组;字符串始终原样发送,富文本请直接传对象数组,不是 OneBot 消息段"
},
"reply": {
"type": "object",
+64 -14
View File
@@ -1549,17 +1549,28 @@ export const ACTIONS: CatalogAction[] = [
},
{
"name": "content",
"type": "message",
"type": "string | object[]",
"required": true,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": true
}
}
]
},
"desc": "非空文本,或非空上游 RichItem 对象数组;不是 OneBot 消息段"
"desc": "非空文本,或非空上游 RichItem 对象数组;字符串始终原样发送,富文本请直接传对象数组,不是 OneBot 消息段"
}
],
"invariants": [
"content must be non-empty text or a non-empty array of RichItem objects"
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
@@ -1569,7 +1580,21 @@ export const ACTIONS: CatalogAction[] = [
"description": "get_qzone_public_feeds 返回的完整 feeds 条目,保留所有原始 cell 字段"
},
"content": {
"description": "非空文本,或非空上游 RichItem 对象数组;不是 OneBot 消息段"
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": true
}
}
],
"description": "非空文本,或非空上游 RichItem 对象数组;字符串始终原样发送,富文本请直接传对象数组,不是 OneBot 消息段"
}
},
"required": [
@@ -13892,12 +13917,25 @@ export const ACTIONS: CatalogAction[] = [
},
{
"name": "content",
"type": "message",
"type": "string | object[]",
"required": true,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": true
}
}
]
},
"desc": "非空文本,或非空上游 RichItem 对象数组;不是 OneBot 消息段"
"desc": "非空文本,或非空上游 RichItem 对象数组;字符串始终原样发送,富文本请直接传对象数组,不是 OneBot 消息段"
},
{
"name": "reply",
@@ -13910,9 +13948,7 @@ export const ACTIONS: CatalogAction[] = [
"desc": "评论或回复页返回的完整回复对象,保留 user 等原始字段"
}
],
"invariants": [
"content must be non-empty text or a non-empty array of RichItem objects"
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
@@ -13927,7 +13963,21 @@ export const ACTIONS: CatalogAction[] = [
"description": "详情或评论页返回的完整评论对象,保留 user 等原始字段"
},
"content": {
"description": "非空文本,或非空上游 RichItem 对象数组;不是 OneBot 消息段"
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": true
}
}
],
"description": "非空文本,或非空上游 RichItem 对象数组;字符串始终原样发送,富文本请直接传对象数组,不是 OneBot 消息段"
},
"reply": {
"type": "object",
+37
View File
@@ -505,6 +505,43 @@ export const f = {
},
);
},
/** Literal text or upstream rich items; strings must never be decoded as messages. */
textOrObjectArray(): Field<string | JsonObject[]> {
return new FieldImpl<string | JsonObject[]>(
(raw, field) => {
if (typeof raw === 'string' && raw.length > 0) {
return ok(raw);
}
if (
Array.isArray(raw) &&
raw.length > 0 &&
raw.every(
(item): item is JsonObject =>
typeof item === 'object' && item !== null && !Array.isArray(item),
)
) {
return ok(raw);
}
return err(field, 'expected non-empty text or a non-empty array of objects');
},
{
type: 'string | object[]',
required: true,
schema: {
anyOf: [
{ type: 'string', minLength: 1 },
{
type: 'array',
minItems: 1,
items: { type: 'object', additionalProperties: true },
},
],
},
},
);
},
/** OneBot message union: string | segment[] | object. A string that looks
* like a JSON array is parsed (matches legacy `asMessage`); otherwise the
* value passes through. Output stays `JsonValue` — downstream ctx.* accept it. */
+8 -34
View File
@@ -1,12 +1,16 @@
import { defineAction, f } from '../action-kit';
import { okResponse, type JsonObject, type JsonValue } from '../types';
import { okResponse, type JsonObject } from '../types';
const feed = f
.object()
.describe('get_qzone_public_feeds 返回的完整 feeds 条目,保留所有原始 cell 字段');
const comment = f.object().describe('详情或评论页返回的完整评论对象,保留 user 等原始字段');
const reply = f.object().describe('评论或回复页返回的完整回复对象,保留 user 等原始字段');
const content = f.message().describe('非空文本,或非空上游 RichItem 对象数组;不是 OneBot 消息段');
const content = f
.textOrObjectArray()
.describe(
'非空文本,或非空上游 RichItem 对象数组;字符串始终原样发送,富文本请直接传对象数组,不是 OneBot 消息段',
);
const objectResult = { type: 'object', additionalProperties: true };
const feedSource =
'feed 必须原样取自 get_qzone_public_feeds 的 feeds 数组,不能用旧说说 tid 拼造;示例中的占位字段须整体替换。';
@@ -38,16 +42,6 @@ const replyExample: JsonObject = {
like: { id: '<like-id-from-reply>', count: 0, status: 0 },
};
function validContent(value: JsonValue): value is string | JsonObject[] {
return typeof value === 'string'
? value.length > 0
: Array.isArray(value) &&
value.length > 0 &&
value.every(
(item) => typeof item === 'object' && item !== null && !Array.isArray(item),
);
}
export const actions = [
defineAction({
name: 'get_qzone_public_capabilities',
@@ -249,18 +243,8 @@ export const actions = [
returns: '上游评论结果,包含新评论,保留未知字段。',
returnsSchema: objectResult,
params: { feed, content },
rules: (r) => [
r.rule('content must be non-empty text or a non-empty array of RichItem objects', (p) =>
validContent(p.content),
),
],
run: async (p, ctx) =>
okResponse(
await ctx.bridge.apis.qzone.commentPublicFeed(
p.feed,
p.content as string | JsonObject[],
),
),
okResponse(await ctx.bridge.apis.qzone.commentPublicFeed(p.feed, p.content)),
}),
defineAction({
name: 'reply_qzone_public_feed',
@@ -286,19 +270,9 @@ export const actions = [
returns: '上游回复结果,包含新回复,保留未知字段。',
returnsSchema: objectResult,
params: { feed, comment, content, reply: reply.optional() },
rules: (r) => [
r.rule('content must be non-empty text or a non-empty array of RichItem objects', (p) =>
validContent(p.content),
),
],
run: async (p, ctx) =>
okResponse(
await ctx.bridge.apis.qzone.replyPublicFeed(
p.feed,
p.comment,
p.content as string | JsonObject[],
p.reply,
),
await ctx.bridge.apis.qzone.replyPublicFeed(p.feed, p.comment, p.content, p.reply),
),
}),
defineAction({
+54
View File
@@ -143,6 +143,60 @@ describe('f.object — open JSON object', () => {
});
});
describe('f.textOrObjectArray — literal text and upstream rich items', () => {
const spec = defineAction({
name: 't',
params: { content: f.textOrObjectArray() },
run: () => okResponse(),
});
it.each(['[]', '[1,2]', '[{"type":0,"content":"hello"}]', ' \n中文 '])(
'preserves literal string %j without decoding or trimming it',
(content) => {
expect(expectOk(spec.parse({ content })).content).toBe(content);
},
);
it('preserves the original object array and unknown fields', () => {
const content = [{ type: 0, content: 'hello', future: { values: [null, 1] } }];
expect(expectOk(spec.parse({ content })).content).toBe(content);
});
it.each(
['', [], null, 1, false, {}, [null], [1], [[]], [{ type: 0 }, 'text']].map((content) => ({
content,
})),
)('rejects invalid rich content $content at the named field', ({ content }) => {
expect(expectErr(spec.parse({ content })).field).toBe('content');
});
it('retains required and optional field policies', () => {
expect(expectErr(spec.parse({})).reason).toBe('is required');
const optional = defineAction({
name: 't',
params: { content: f.textOrObjectArray().optional() },
run: () => okResponse(),
});
expect(expectOk(optional.parse({}))).toEqual({ content: undefined });
expect(expectErr(optional.parse({ content: null })).field).toBe('content');
});
it('describes text and object arrays without OneBot message semantics', () => {
const field = f.textOrObjectArray();
expect(field.doc.type).toBe('string | object[]');
expect(field.toJsonSchema()).toEqual({
anyOf: [
{ type: 'string', minLength: 1 },
{
type: 'array',
minItems: 1,
items: { type: 'object', additionalProperties: true },
},
],
});
});
});
describe('f.message — union passthrough + JSON-array string', () => {
const spec = defineAction({ name: 't', params: { m: f.message() }, run: () => okResponse() });
it('parses a JSON-array string, passes plain string / array through', () => {
@@ -245,15 +245,34 @@ describe('qzone public actions', () => {
},
);
it('accepts a JSON-array string through the existing message coercer', async () => {
const commentPublicFeed = vi.fn().mockResolvedValue(result);
it.each(['comment_qzone_public_feed', 'reply_qzone_public_feed'])(
'%s preserves literal text even when it looks like JSON',
async (action) => {
const { method } = cases.find((entry) => entry.action === action)!;
const invoke = vi.fn().mockResolvedValue(result);
const handler = makeHandler({ [method]: invoke });
await makeHandler({ commentPublicFeed }).handle('comment_qzone_public_feed', {
feed,
content: '[{"type":0,"content":"hello"}]',
});
expect(commentPublicFeed).toHaveBeenCalledWith(feed, [{ type: 0, content: 'hello' }]);
});
for (const content of [
'[]',
'[1,2]',
'[{"type":0,"content":"hello"}]',
' ["中文"]\n',
'{"text":"hello"}',
]) {
expect(
await handler.handle(action, { feed, comment, content, reply }),
).toMatchObject({
status: 'ok',
retcode: 0,
});
expect(invoke).toHaveBeenLastCalledWith(
...(action === 'comment_qzone_public_feed'
? [feed, content]
: [feed, comment, content, reply]),
);
}
},
);
it.each(['comment_qzone_public_feed', 'reply_qzone_public_feed'])(
'%s rejects missing, empty, scalar or mixed content without effects',
@@ -26,6 +26,7 @@ import { ParamField } from '@/components/debug/param-field';
import { Segmented } from '@/components/debug/segmented';
import { useApi } from '@/lib/api';
import { useDebugTasks } from '@/contexts/DebugTaskContext';
import { buildActionParams } from '@/lib/action-params';
import { clearHistory, loadHistory, pushHistory, type InvokeRecord } from '@/lib/debug-history';
import { cn } from '@/lib/utils';
import type { DebugActionDoc, DebugStreamFrame, QQInfo } from '@/types';
@@ -46,37 +47,6 @@ function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
}
function coerceParam(type: string, raw: string): unknown {
if (raw === '') {
return undefined;
}
if (/int|uint|number|messageId/i.test(type)) {
const n = Number(raw);
return Number.isFinite(n) ? n : raw;
}
if (type === 'bool' || type === 'boolean') {
return raw === 'true' || raw === '1';
}
if (type === 'message') {
const t = raw.trim();
if ((t.startsWith('[') && t.endsWith(']')) || (t.startsWith('{') && t.endsWith('}'))) {
try {
return JSON.parse(t);
} catch {
/* fall through to literal */
}
}
return raw;
}
return raw;
}
function Field({ label, children }: { label: ReactNode; children: ReactNode }) {
return (
<label className="flex flex-col gap-1.5">
@@ -171,19 +141,11 @@ export function ActionTester({
return parsed as Record<string, unknown>;
}
const out: Record<string, unknown> = {};
if (doc) {
for (const p of doc.params) {
const v = coerceParam(p.type, fields[p.name] ?? '');
if (v !== undefined) {
out[p.name] = v;
}
}
try {
return buildActionParams(doc?.params ?? [], fields);
} catch (error) {
return { __error: error instanceof Error ? error.message : String(error) };
}
return out;
};
const runInvoke = async () => {
@@ -5,6 +5,7 @@
// group_id, an image a FileSource, a bool a switch, an enum a select.
import { useState } from 'react';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dropdown } from '@/components/interior/dropdown';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { Picker } from '@/components/ui/picker';
@@ -220,6 +221,26 @@ export function ParamField({
);
}
if (param.type === 'object' || param.type === 'string | object[]') {
return (
<div className="space-y-1.5">
<Textarea
value={value}
onChange={(e) => onChange(e.target.value)}
aria-label={param.name}
placeholder={param.type === 'object' ? '{\n \n}' : '"你好"'}
className="min-h-24 font-mono text-xs"
spellCheck={false}
/>
<p className="text-xs text-muted-foreground">
{param.type === 'object'
? '粘贴完整 JSON 对象,保留原始字段。'
: '文本填写 JSON 字符串(如 "你好"),富文本填写对象数组。'}
</p>
</div>
);
}
if (isNumericType(param.type)) {
return (
<Input
+76
View File
@@ -0,0 +1,76 @@
import type { DebugActionParam } from '@/types';
function coerceParam({ name, type }: DebugActionParam, raw: string): unknown {
if (raw === '') {
return undefined;
}
if (/int|uint|number|messageId/i.test(type)) {
const n = Number(raw);
return Number.isFinite(n) ? n : raw;
}
if (type === 'bool' || type === 'boolean') {
return raw === 'true' || raw === '1';
}
if (type === 'object' || type === 'string | object[]') {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
throw new Error(`${name} 的 JSON 格式无效`);
}
const isObject = (value: unknown) =>
typeof value === 'object' && value !== null && !Array.isArray(value);
if (type === 'object' && !isObject(parsed)) {
throw new Error(`${name} 必须是 JSON 对象`);
}
if (
type === 'string | object[]' &&
typeof parsed !== 'string' &&
!(Array.isArray(parsed) && parsed.every(isObject))
) {
throw new Error(`${name} 必须是 JSON 字符串或对象数组`);
}
return parsed;
}
if (type === 'message') {
const t = raw.trim();
if ((t.startsWith('[') && t.endsWith(']')) || (t.startsWith('{') && t.endsWith('}'))) {
try {
return JSON.parse(t);
} catch {
/* fall through to literal */
}
}
return raw;
}
return raw;
}
export function buildActionParams(
params: DebugActionParam[],
fields: Record<string, string>,
): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const param of params) {
const value = coerceParam(param, fields[param.name] ?? '');
if (value !== undefined) {
out[param.name] = value;
}
}
return out;
}
+108
View File
@@ -0,0 +1,108 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { ParamField } from '../src/components/debug/param-field';
import { buildActionParams } from '../src/lib/action-params';
describe('debug action form parameters', () => {
const objectParam = { name: 'feed', type: 'object', required: true };
it('passes pasted objects with nested and unknown fields to the action', () => {
const feed = { identity: { id: 'opaque' }, future: [1, null, { enabled: true }] };
expect(buildActionParams([objectParam], { feed: JSON.stringify(feed, null, 2) })).toEqual({
feed,
});
});
it.each(['{bad', '[]', 'null', '1', 'false', '"text"'])(
'rejects invalid object input %s with the field name',
(feed) => {
expect(() => buildActionParams([objectParam], { feed })).toThrow(/feed/);
},
);
it('omits an untouched optional object rather than sending an empty string', () => {
expect(buildActionParams([{ ...objectParam, required: false }], { feed: '' })).toEqual({});
});
it('renders an object editor that accepts multiline JSON', () => {
const html = renderToStaticMarkup(
<ParamField
param={objectParam}
value={'{\n "id": "opaque"\n}'}
onChange={() => undefined}
uin=""
groupContext=""
actionName="get_qzone_public_feed_detail"
/>,
);
expect(html).toContain('<textarea');
expect(html).toContain('aria-label="feed"');
});
const contentParam = { name: 'content', type: 'string | object[]', required: true };
it.each(['[]', '[1,2]', '[{"type":0,"content":"hello"}]', ' \n中文 '])(
'preserves JSON-looking text %j when entered as a JSON string',
(content) => {
expect(buildActionParams([contentParam], { content: JSON.stringify(content) })).toEqual(
{ content },
);
},
);
it('passes a real rich-item array without converting it to OneBot segments', () => {
const content = [{ type: 0, content: 'hello', future: { keep: true } }];
expect(buildActionParams([contentParam], { content: JSON.stringify(content) })).toEqual({
content,
});
});
it.each(['[bad', '[1,2]', 'null', '1', 'false', '{}', '[null]', '[[]]'])(
'reports invalid rich content %s before invoking an action',
(content) => {
expect(() => buildActionParams([contentParam], { content })).toThrow(/content/);
},
);
it('renders rich content as an explicit JSON editor without the OneBot message builder', () => {
const html = renderToStaticMarkup(
<ParamField
param={contentParam}
value={'"[1,2]"'}
onChange={() => undefined}
uin=""
groupContext=""
actionName="comment_qzone_public_feed"
/>,
);
expect(html).toContain('<textarea');
expect(html).toContain('aria-label="content"');
expect(html).toContain('JSON 字符串');
expect(html).not.toContain('role="radiogroup"');
});
it('keeps existing scalar and OneBot message conversions', () => {
const fields = {
message_id: '-123',
enable: 'false',
message: '[{"type":"text","data":{"text":"hello"}}]',
text: '[1,2]',
};
expect(
buildActionParams(
[
{ name: 'message_id', type: 'messageId', required: true },
{ name: 'enable', type: 'bool', required: true },
{ name: 'message', type: 'message', required: true },
{ name: 'text', type: 'string', required: true },
],
fields,
),
).toEqual({
message_id: -123,
enable: false,
message: [{ type: 'text', data: { text: 'hello' } }],
text: '[1,2]',
});
});
});