Compare commits

...

13 Commits

Author SHA1 Message Date
DrSmoothl
8fc68c0ec3 chore(release): v2.1.0 2026-10-21 20:28:15 +08:00
DrSmoothl
b4ece8671b fix: improve client self-message reporting
Update desktop support for client-sent private and group messages.

Refs #528
2026-10-21 17:42:56 +08:00
DrSmoothl
bde7f2805d fix: handle delayed client message availability
Keep self-sent private messages available when their history becomes visible shortly after sending. Preserve account isolation while completing the report.

Refs #528
2026-10-21 17:25:13 +08:00
DrSmoothl
491b531841 feat: support client private-message reporting
Handle confirmed private messages sent from the client and preserve account isolation when sessions change. Surface unavailable messages without reporting incomplete content.

Refs #528.
2026-10-21 16:59:26 +08:00
DrSmoothl
617e7581dd fix: avoid duplicate private self-message reports
Keep repeated confirmations of the same private message from producing duplicate events while preserving distinct messages and stored content.

Refs #528.
2026-10-21 16:59:19 +08:00
DrSmoothl
27120f884a fix: resolve issue #559
Fixes #559.
2026-10-21 15:17:43 +08:00
DrSmoothl
3a4c1eeea2 fix(onebot): deduplicate client group self-message reports
Prevent repeated reports for client-originated group messages while preserving distinct sends and existing private-message behavior.

Cover opt-in reporting, message formats, account isolation, and repeated delivery.

Refs #528
2026-10-21 14:43:37 +08:00
DrSmoothl
5cd4ae61dd feat(webui): add opt-in MaiBot appearance overlay 2026-10-21 13:07:44 +08:00
DrSmoothl
28f64113e7 test(core): resolve startup fixture paths through symlinks
Canonicalize temporary fixture directories before matching build inputs and locating staged updates. Compare the child working directory with its real path so startup tests also pass when the default temporary directory is a symlink.
2026-10-20 14:24:23 +08:00
DrSmoothl
c537311ed1 fix(core): bound forward caches with nested result retention
Keep at most 512 outer results per bridge and retain their bundled nested results as one cache group. Reads refresh the whole group, shared inner results survive while another containing group remains cached, and late sender enrichment cannot resurrect evicted entries.

Collect uploaded and downloaded nested results before publishing a complete cache group. Cover eviction, account isolation, nested retrieval, shared ownership and asynchronous enrichment through the forward API.

Refs #546, #555, #557.

Co-authored-by: wanqing-last <2917149421@qq.com>
2026-10-20 13:50:21 +08:00
DrSmoothl
9d8df59370 fix(protocol): decode XML forward identities from root attributes
Recognize forward cards with an omitted protocol service ID from the root msg attributes. Decode attribute references once so resource IDs and nested lookup keys survive XML escaping, while preserving ordinary XML when the root declaration is ambiguous.

Refs #547, #556, #558.

Co-authored-by: wanqing-last <2917149421@qq.com>
2026-10-20 13:49:53 +08:00
DrSmoothl
76846f40b1 fix(onebot): resolve voice transcription for signed message IDs
Allow voice transcription results to complete for messages with negative IDs while preserving existing message identities and account isolation.

Report unmatched transcription results accurately and document the signed message ID contract.

Fixes #554
2026-10-20 13:27:40 +08:00
DrSmoothl
79522d949f fix(protocol): recover highway uploads after missing responses
Try another available upload endpoint when a transfer stops responding,
while preserving confirmed progress and the current upload session.
Report unconfirmed transfers clearly and cover recovery and publication
boundaries with regression tests.

Fixes #552
2026-10-20 08:47:48 +08:00
84 changed files with 3734 additions and 435 deletions

View File

@@ -78,6 +78,8 @@ Use focused tests while iterating. Before handing off a code change, run the ful
`pnpm dev` starts Core and can attach to local QQ processes; use it only when runtime testing is intended. `pnpm dev:web` starts the frontend, which expects a WebUI backend. Follow the existing test fakes for isolated work rather than starting a live account unnecessarily.
WebUI deployment targets use a reversible presentation overlay. Read [the host appearance contract](packages/webui/INTEGRATIONS.md) before changing it. Keep target validation in `@snowluma/common/webui-target`, implementations in the frontend target registry, and saved preferences separate from effective appearance. Default deployments must not load target assets or host listeners; do not put target-name branches in business pages.
## Implementation rules
- **Fix the cause.** Reproduce failures at the owning layer and add a regression test for the observable behavior. Avoid account-, filename-, or example-specific patches.
@@ -86,6 +88,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful
- **Keep parsing separate from effects.** QQ decoders and OneBot event converters translate data. Live state updates belong to their owning pipeline or service; reading history must not mutate live membership or pending requests.
- **Use the declared interfaces.** OneBot consumes the [Bridge interface](packages/core/src/bridge/bridge-interface.ts). Reuse package exports and existing dependency injection instead of reaching into another owner's state or building a second registry.
- **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content.
- **Preserve signed message IDs.** OneBot `message_id` / `messageId` values generated by [message-id.ts](packages/onebot/src/message-id.ts) are non-zero signed 32-bit integers; negative values are valid. Use `f.messageId()` for action inputs and preserve the value through storage, replies, lookups and result matching. Protocol representations must be converted losslessly at their boundary; changing the sign or generation rule changes existing message identities.
- **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible.
- **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter.
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and four-space TypeScript indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "2.0.3",
"version": "2.1.0",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "2.0.3",
"version": "2.1.0",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",

View File

@@ -957,6 +957,17 @@ export class HookSession extends EventEmitter {
return;
}
if (
packet.source === 'client-message' &&
(!isRealUin(packet.uin) || packet.uin !== this._uin)
) {
this.log.warn(
'Client message receipt belongs to an inactive account: PID=%d',
this.pid,
);
return;
}
const uin = packet.uin || this._uin;
// Routing requires a real UIN, but even a frame carrying UIN=0 proves the
// receive hook is alive. Attribute that evidence to the current epoch
@@ -986,6 +997,7 @@ export class HookSession extends EventEmitter {
seqId: packet.seq,
retCode: packet.error,
fromClient: false,
...(packet.source ? { source: packet.source } : {}),
body: Buffer.from(packet.body),
});
}

View File

@@ -7,6 +7,7 @@ import {
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import { isRealUin } from '@snowluma/common/uin';
import { CLIENT_MESSAGE_RECEIPT_CMD } from '@snowluma/common/protocol-types';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import path from 'path';
@@ -38,6 +39,8 @@ export enum PipeOp {
recvPacket = 6,
loginState = 7,
loginIdentityHint = 17,
clientMessageReceipt = 21,
clientMessageState = 22,
}
const PipeFlagWantReply = 1 << 0;
@@ -55,6 +58,7 @@ export interface QqHookPacket {
cmd: string;
uin: string;
body: Buffer;
source?: 'client-message';
}
export interface QqHookHello {
@@ -1369,6 +1373,44 @@ export class QqHookClient extends EventEmitter {
return;
}
if (frame.op === PipeOp.clientMessageState) {
if (frame.status === 1) {
runtimeLog.debug('Client private-message reporting is available: PID=%d', this.pid);
} else {
runtimeLog.warn(
'Client private-message reporting is unavailable: PID=%d status=%d',
this.pid,
frame.status,
);
}
return;
}
if (frame.op === PipeOp.clientMessageReceipt) {
if (
frame.cmd !== '' ||
frame.requestId !== 0 ||
frame.flags !== 0 ||
frame.value0 <= 0n ||
frame.value0 > BigInt(Number.MAX_SAFE_INTEGER) ||
!isRealUin(frame.msg)
) {
runtimeLog.warn('Invalid client message receipt: PID=%d', this.pid);
return;
}
this.emit('packet', {
seq: Number(frame.value0),
error: frame.status,
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
uin: frame.msg,
body: Buffer.from(frame.body),
source: 'client-message',
} satisfies QqHookPacket);
return;
}
if (frame.op !== PipeOp.recvPacket) {
return;
}

View File

@@ -929,6 +929,42 @@ describe('HookSession — pipe-down must not clobber a settled error', () => {
});
describe('HookSession — packet forwarding', () => {
it('forwards client receipts only for the active account without changing direction', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
const receipt: QqHookPacket = {
seq: 42,
error: 0,
cmd: 'ClientMessageReceipt',
uin: '10001',
source: 'client-message',
body: Buffer.from([1, 2, 3]),
};
for (const uin of ['', '0', '20002']) {
ctx.currentClient().firePacket({ ...receipt, uin });
}
expect(onPacket).not.toHaveBeenCalled();
ctx.currentClient().firePacket(receipt);
expect(onPacket).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
pid: 1234,
uin: '10001',
source: 'client-message',
fromClient: false,
}),
);
ctx.currentClient().fireLogin('20002');
ctx.currentClient().firePacket(receipt);
expect(onPacket).toHaveBeenCalledOnce();
await ctx.session.dispose();
});
// These tests cover the field-rename + filter logic that used to live
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means
// we can exercise the transformation with a plain vi.fn() sink, no

View File

@@ -12,6 +12,7 @@ import {
type LogEntry,
} from '@snowluma/common/logger';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CLIENT_MESSAGE_RECEIPT_CMD } from '@snowluma/common/protocol-types';
import {
HEADER_SIZE,
listLiveLinuxPipePids,
@@ -147,6 +148,113 @@ describe('QqHookClient login wait lifecycle', () => {
});
});
describe('QqHookClient client message receipts', () => {
it('preserves receipt provenance and failure status separately from normal packets', async () => {
const sockets = mockControlPipe(12345, () => {});
const client = new QqHookClient(12345);
const onPacket = vi.fn();
try {
await client.startRecv(onPacket);
const socket = sockets.mock.results[0]!.value;
const body = Buffer.from([1, 2, 3]);
socket.emit(
'data',
pipeFrame({ op: PipeOp.clientMessageReceipt, value0: 42n, message: '10001', body }),
);
socket.emit(
'data',
pipeFrame({
op: PipeOp.clientMessageReceipt,
value0: 43n,
message: '10001',
status: -1,
}),
);
socket.emit(
'data',
pipeFrame({
op: PipeOp.recvPacket,
value0: 44n,
message: '10001',
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
body,
}),
);
expect(onPacket.mock.calls.map(([packet]) => packet)).toEqual([
{
seq: 42,
error: 0,
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
uin: '10001',
body,
source: 'client-message',
},
{
seq: 43,
error: -1,
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
uin: '10001',
body: Buffer.alloc(0),
source: 'client-message',
},
{ seq: 44, error: 0, cmd: CLIENT_MESSAGE_RECEIPT_CMD, uin: '10001', body },
]);
} finally {
client.close();
}
});
it('reports unsupported capability and invalid envelopes without breaking normal receive', async () => {
const entries: LogEntry[] = [];
setLogLevel('warn');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const sockets = mockControlPipe(12345, () => {});
const client = new QqHookClient(12345);
const onPacket = vi.fn();
try {
await client.startRecv(onPacket);
const socket = sockets.mock.results[0]!.value;
socket.emit('data', pipeFrame({ op: PipeOp.clientMessageState, status: -1 }));
for (const patch of [
{ value0: 0n },
{ value0: BigInt(Number.MAX_SAFE_INTEGER) + 1n },
{ message: '' },
{ cmd: 'unexpected' },
{ requestId: 1 },
]) {
socket.emit(
'data',
pipeFrame({
op: PipeOp.clientMessageReceipt,
value0: 42n,
message: '10001',
...patch,
}),
);
}
expect(onPacket).not.toHaveBeenCalled();
expect(
entries.filter(
(entry) => entry.scope === 'QQHook.Runtime' && entry.level === 'warn',
),
).toHaveLength(6);
socket.emit(
'data',
pipeFrame({ op: PipeOp.recvPacket, cmd: 'normal', message: '10001', value0: 44n }),
);
expect(onPacket).toHaveBeenCalledOnce();
} finally {
client.close();
unsubscribe();
}
});
});
describe('listLiveLinuxPipePids', () => {
it('ignores stale-looking control socket names when the probe rejects them', async () => {
const runtimeDir = await makeRuntimeDir();

View File

@@ -1,13 +1,17 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "2.0.3",
"version": "2.1.0",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
"./webui-target": {
"types": "./src/webui-target.ts",
"default": "./src/webui-target.ts"
},
"./update-source": {
"types": "./src/update-source.ts",
"default": "./src/update-source.ts"

View File

@@ -1,3 +1,5 @@
export const CLIENT_MESSAGE_RECEIPT_CMD = 'ClientMessageReceipt';
export interface PacketInfo {
pid: number;
uin: string;
@@ -6,6 +8,7 @@ export interface PacketInfo {
seqId: number;
retCode: number;
fromClient: boolean;
source?: 'client-message';
body: Uint8Array;
}
export type PacketSink = (packet: PacketInfo) => void;

View File

@@ -0,0 +1,100 @@
/** Browser-safe contract shared by startup, the WebUI and embedding hosts.
* Targets are deployment choices; they never belong in the saved UI preferences. */
export const WEBUI_TARGETS = {
maibot: {
label: '麦麦 / 一键包',
styles: ['millennium'],
defaultStyle: 'millennium',
},
} as const;
export type WebuiTarget = keyof typeof WEBUI_TARGETS;
export type WebuiColorMode = 'light' | 'dark' | 'system';
export type WebuiPresentation = {
[T in WebuiTarget]: {
version: 1;
target: T;
style: (typeof WEBUI_TARGETS)[T]['styles'][number];
mode: WebuiColorMode;
};
}[WebuiTarget];
/** null releases the override for this document, without changing deployment opt-in. */
export type WebuiPresentationUpdate = WebuiPresentation | { version: 1; target: null };
export const WEBUI_PRESENTATION_EVENT = 'snowluma:host-appearance';
export const WEBUI_TARGET_BOOTSTRAP_ID = 'snowluma-webui-target';
export function resolveWebuiTarget(raw: string | undefined): WebuiTarget | null {
if (raw === undefined || raw.trim() === '') {
return null;
}
const value = raw.trim();
if (!Object.hasOwn(WEBUI_TARGETS, value)) {
throw new Error(
`Invalid SNOWLUMA_WEBUI_TARGET: ${JSON.stringify(value)}. Expected ${Object.keys(WEBUI_TARGETS).join(', ')} or an empty value.`,
);
}
return value as WebuiTarget;
}
export function defaultWebuiPresentation(target: WebuiTarget): WebuiPresentation {
return { version: 1, target, style: WEBUI_TARGETS[target].defaultStyle, mode: 'system' };
}
export function parseWebuiPresentation(value: unknown): WebuiPresentationUpdate {
if (
!value ||
typeof value !== 'object' ||
!('version' in value) ||
value.version !== 1 ||
!('target' in value)
) {
throw new TypeError('Invalid host appearance: expected a version 1 presentation');
}
if (value.target === null) {
return { version: 1, target: null };
}
if (typeof value.target !== 'string' || !Object.hasOwn(WEBUI_TARGETS, value.target)) {
throw new TypeError('Invalid host appearance target');
}
const target = value.target as WebuiTarget;
const styles: readonly string[] = WEBUI_TARGETS[target].styles;
if (!('style' in value) || typeof value.style !== 'string' || !styles.includes(value.style)) {
throw new TypeError(`Invalid host appearance style for ${target}`);
}
if (
!('mode' in value) ||
(value.mode !== 'light' && value.mode !== 'dark' && value.mode !== 'system')
) {
throw new TypeError('Invalid host appearance color mode');
}
// Both discriminants have been checked against the same target registry.
return { version: 1, target, style: value.style, mode: value.mode } as WebuiPresentation;
}
/** Inject before the cached pre-paint theme script. Default HTML stays byte-for-byte intact. */
export function injectWebuiTarget(html: string, target: WebuiTarget | null): string {
if (target === null) {
return html;
}
if (!html.includes('<head>')) {
throw new Error('WebUI HTML is missing <head>; cannot inject runtime target');
}
const json = JSON.stringify(defaultWebuiPresentation(target)).replaceAll('<', '\\u003c');
return html.replace(
'<head>',
`<head>\n <script id="${WEBUI_TARGET_BOOTSTRAP_ID}" type="application/json">${json}</script>`,
);
}

View File

@@ -0,0 +1,51 @@
import { describe, expect, it } from 'vitest';
import {
defaultWebuiPresentation,
injectWebuiTarget,
parseWebuiPresentation,
resolveWebuiTarget,
} from '../src/webui-target';
describe('deployment presentation contract', () => {
it('requires explicit opt-in and rejects misspelled deployments', () => {
expect(resolveWebuiTarget(undefined)).toBeNull();
expect(resolveWebuiTarget(' ')).toBeNull();
expect(resolveWebuiTarget('maibot')).toBe('maibot');
expect(() => resolveWebuiTarget('mai-bot')).toThrow('SNOWLUMA_WEBUI_TARGET');
expect(() => resolveWebuiTarget('__proto__')).toThrow('SNOWLUMA_WEBUI_TARGET');
});
it('keeps the unconfigured document intact and injects before cached appearance', () => {
const html = '<html><head><script>readSavedAppearance()</script></head></html>';
expect(injectWebuiTarget(html, null)).toBe(html);
const injected = injectWebuiTarget(html, 'maibot');
expect(injected.indexOf('snowluma-webui-target')).toBeLessThan(
injected.indexOf('readSavedAppearance'),
);
expect(injected).toContain(JSON.stringify(defaultWebuiPresentation('maibot')));
expect(() => injectWebuiTarget('broken html', 'maibot')).toThrow('missing <head>');
});
it('validates the version, target, style and color mode without accepting arbitrary CSS', () => {
const valid = defaultWebuiPresentation('maibot');
expect(parseWebuiPresentation(valid)).toEqual(valid);
expect(
parseWebuiPresentation({ ...valid, mode: 'dark', css: 'body{display:none}' }),
).toEqual({ ...valid, mode: 'dark' });
expect(parseWebuiPresentation({ version: 1, target: null })).toEqual({
version: 1,
target: null,
});
for (const input of [
null,
{},
{ ...valid, version: 2 },
{ ...valid, target: 'other' },
{ ...valid, style: 'modern' },
{ ...valid, mode: 'blue' },
]) {
expect(() => parseWebuiPresentation(input)).toThrow();
}
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "2.0.3",
"version": "2.1.0",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",

View File

@@ -0,0 +1,69 @@
import { createLogger } from '@snowluma/common/logger';
import type { ForwardNodePayload } from '@snowluma/protocol/events';
const MAX_CACHED_FORWARDS = 512;
const log = createLogger('Bridge.Forward');
type ForwardLayers = Map<string, ForwardNodePayload[]>;
interface ForwardCacheHit {
rootId: string;
resId: string;
layers: ForwardLayers;
nodes: ForwardNodePayload[];
}
/** Nested results share the lifetime and recency of the result that supplied them. */
export class ForwardResultCache {
private readonly entries = new Map<string, ForwardLayers>();
get(resId: string): ForwardCacheHit | undefined {
let hit: ForwardCacheHit | undefined;
// A nested result can be supplied by several retained outer results.
for (const [rootId, layers] of this.entries) {
const nodes = layers.get(resId);
if (nodes) {
hit = { rootId, resId, layers, nodes };
}
}
if (hit) {
this.entries.delete(hit.rootId);
this.entries.set(hit.rootId, hit.layers);
}
return hit;
}
set(rootId: string, layers: ReadonlyMap<string, ForwardNodePayload[]>): void {
if (!layers.has(rootId)) {
throw new Error('forward cache entry is missing its outer result');
}
this.entries.delete(rootId);
this.entries.set(rootId, new Map(layers));
while (this.entries.size > MAX_CACHED_FORWARDS) {
const oldest = this.entries.entries().next().value!;
this.entries.delete(oldest[0]);
log.trace(
'forward cache evicted: res_id=%s layers=%d remaining=%d',
oldest[0],
oldest[1].size,
this.entries.size,
);
}
}
update(hit: ForwardCacheHit, nodes: ForwardNodePayload[]): void {
// Enrichment may finish after eviction or replacement. It must not revive
// an old result or turn a nested result into an independent cache entry.
if (
this.entries.get(hit.rootId) === hit.layers &&
hit.layers.get(hit.resId) === hit.nodes
) {
hit.layers.set(hit.resId, nodes);
}
}
}

View File

@@ -25,16 +25,15 @@ import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { Bridge } from '../bridge';
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
import { ForwardResultCache } from './forward-cache';
import { resolveSelfUid, toInt } from './shared';
function asBridge(ctx: BridgeContext): Bridge {
return ctx as unknown as Bridge;
}
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
// of the process — that's enough because OneBot clients typically
// resolve a forward immediately after receiving the parent message.
const forwardResCache = new Map<string, ForwardNodePayload[]>();
// Share within a bridge without retaining disconnected accounts.
const forwardCaches = new WeakMap<BridgeContext, ForwardResultCache>();
const log = createLogger('Bridge.Forward');
@@ -77,6 +76,7 @@ interface ForwardUploadResult {
// callers concatenate these to their own actions list so the
// outermost upload carries the full tree.
innerActions: ForwardInnerAction[];
cachedLayers: Map<string, ForwardNodePayload[]>;
}
// Local hex-decode helper — avoids importing the heavyweight `pipeline`
@@ -353,7 +353,18 @@ function assertNoWindowShakeInForward(nodes: ForwardNodePayload[]): void {
}
export class ForwardApi {
constructor(private readonly ctx: BridgeContext) {}
private readonly cache: ForwardResultCache;
constructor(private readonly ctx: BridgeContext) {
let cache = forwardCaches.get(ctx);
if (!cache) {
cache = new ForwardResultCache();
forwardCaches.set(ctx, cache);
}
this.cache = cache;
}
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
// Reject the complete recursive tree before identity resolution, media
@@ -367,7 +378,8 @@ export class ForwardApi {
assertPrivateForwardFileCapacity(nodes);
}
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
const { resId, cachedLayers } = await this.uploadRecursive(nodes, groupId, userId);
this.cache.set(resId, cachedLayers);
return resId;
}
@@ -593,6 +605,7 @@ export class ForwardApi {
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
const myInnerActions: ForwardInnerAction[] = [];
const cachedLayers = new Map<string, ForwardNodePayload[]>();
const processedNodes: ForwardNodePayload[] = [];
const isGroup = groupId !== undefined;
@@ -605,6 +618,11 @@ export class ForwardApi {
// and `inner.innerActions` already contains deeper layers.
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
myInnerActions.push(...inner.innerActions);
for (const [resId, cached] of inner.cachedLayers) {
cachedLayers.set(resId, cached);
}
// Replace the inner placeholder element with a forward preview
// pointing at the inner res_id. `forwardUuid: inner.uuid`
// baked into the LightApp JSON's `meta.detail.uniseq` is what
@@ -692,7 +710,7 @@ export class ForwardApi {
throw new Error('upload forward message response missing res_id');
}
forwardResCache.set(
cachedLayers.set(
resId,
uploadReadyNodes.map((node) => ({
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
@@ -714,20 +732,21 @@ export class ForwardApi {
// from (1) — no separate fetch needed.
uuid: randomUUID(),
innerActions: myInnerActions,
cachedLayers,
};
}
async fetch(resId: string): Promise<ForwardNodePayload[]> {
const bridge = asBridge(this.ctx);
const cached = forwardResCache.get(resId);
const cached = this.cache.get(resId);
if (cached) {
const nodes = cloneNodes(cached);
const nodes = cloneNodes(cached.nodes);
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
// Bundled inner nodes are cached un-enriched; enrich
// on read (a no-op once names are present) and persist so later hits skip.
if (await this.enrichSenders(nodes)) {
forwardResCache.set(resId, cloneNodes(nodes));
this.cache.update(cached, cloneNodes(nodes));
}
return nodes;
@@ -820,9 +839,7 @@ export class ForwardApi {
// matching piggyback body, decode it into inner nodes, and seed
// the cache by the inner resId so a follow-up `fetch(innerResId)`
// hits the cache instead of the wire.
if (piggybackByUuid.size > 0) {
this.consumePiggybacks(nodes, piggybackByUuid);
}
const cachedLayers = this.collectForwardLayers(resId, nodes, piggybackByUuid);
// Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty
// or stamped with the "QQ用户" placeholder (#174) — the long-msg member name
@@ -830,7 +847,8 @@ export class ForwardApi {
await this.enrichSenders(nodes);
if (nodes.length > 0) {
forwardResCache.set(resId, cloneNodes(nodes));
cachedLayers.set(resId, cloneNodes(nodes));
this.cache.set(resId, cachedLayers);
}
return nodes;
@@ -1017,20 +1035,22 @@ export class ForwardApi {
return out;
}
/** Recursively resolve forward previews against the piggyback table.
/** Resolve forward previews against the piggyback table.
* For every `{type: 'forward', resId, forwardUuid}` element we find,
* look up the uniseq in the piggyback map; if hit, decode the
* inner msgBody and cache it by inner resId, then descend into that
* inner layer to resolve deeper nestings carried in the SAME
* piggyback set (NapCat hoists the entire tree's piggybacks onto
* the outermost action list). */
private consumePiggybacks(
private collectForwardLayers(
resId: string,
nodes: ForwardNodePayload[],
piggybackByUuid: Map<string, PushMsgBody[]>,
): void {
const seen = new Set<string>();
): Map<string, ForwardNodePayload[]> {
const layers = new Map([[resId, cloneNodes(nodes)]]);
const decodedByUuid = new Map<string, ForwardNodePayload[]>();
const visit = (chain: ForwardNodePayload[]): void => {
for (const chain of layers.values()) {
for (const node of chain) {
for (const elem of node.elements) {
if (elem.type !== 'forward') {
@@ -1040,7 +1060,7 @@ export class ForwardApi {
const uuid = elem.forwardUuid;
const innerResId = elem.resId;
if (!uuid || !innerResId || seen.has(uuid)) {
if (!uuid || !innerResId || layers.has(innerResId)) {
continue;
}
@@ -1050,15 +1070,19 @@ export class ForwardApi {
continue;
}
seen.add(uuid);
const innerNodes = this.decodeMsgBodiesToNodes(body);
forwardResCache.set(innerResId, cloneNodes(innerNodes));
visit(innerNodes);
let innerNodes = decodedByUuid.get(uuid);
if (!innerNodes) {
innerNodes = cloneNodes(this.decodeMsgBodiesToNodes(body));
decodedByUuid.set(uuid, innerNodes);
}
layers.set(innerResId, innerNodes);
}
}
};
}
visit(nodes);
return layers;
}
}

View File

@@ -4,7 +4,13 @@ import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPushOrThrow, SysMsgDedup } from '@snowluma/protocol/msg-push';
import {
MSG_PUSH_CMD,
parseMsgPushOrThrow,
SysMsgDedup,
decodeClientMessageReceipt,
fetchClientMessage,
} from '@snowluma/protocol/msg-push';
import { KICK_NT_CMD, parseKickNT } from '@snowluma/protocol/kick-nt';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
@@ -38,6 +44,10 @@ export class Bridge implements BridgeInterface {
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
private disposePromise_: Promise<void> | null = null;
private readonly pendingPackets_ = new Set<Promise<void>>();
private readonly clientMessageTasks_ = new Map<
string,
{ connection: ProcessConnection; work: Promise<void> }
>();
private rosterWarmupStarted_ = false;
private settleRosterWarmup!: (result: RosterWarmupResult) => void;
private readonly rosterWarmup = new Promise<RosterWarmupResult>((resolve) => {
@@ -111,9 +121,13 @@ export class Bridge implements BridgeInterface {
bindPid(pid: number, client: PacketSender): void {
const previous = this.activeConnection;
const existing = this.connections.get(pid);
this.connections.delete(pid);
// A new login stays healthy until the watchdog confirms a failure.
this.connections.set(pid, { pid, client, receiveHealthy: true });
const connection =
existing?.client === client ? existing : { pid, client, receiveHealthy: true };
connection.receiveHealthy = true;
this.connections.set(pid, connection);
if (previous?.pid !== pid || previous.client !== client) {
runtimeLog.trace(
@@ -190,12 +204,85 @@ export class Bridge implements BridgeInterface {
return Promise.reject(new Error('Bridge is disposed'));
}
const work = this.identity.initialization.then(() => this.pipeline.process(pkt));
const connection = this.connections.get(pkt.pid);
const work = this.identity.initialization.then(() =>
pkt.source === 'client-message'
? this.processClientMessage(pkt, connection)
: this.pipeline.process(pkt),
);
this.pendingPackets_.add(work);
void work.finally(() => this.pendingPackets_.delete(work)).catch(() => undefined);
return work;
}
private async processClientMessage(
pkt: PacketInfo,
connection: ProcessConnection | undefined,
): Promise<void> {
const requireConnection = (): ProcessConnection => {
if (
this.disposePromise_ ||
!connection ||
this.connections.get(pkt.pid) !== connection
) {
throw new Error('Client message receipt belongs to an inactive connection');
}
return connection;
};
const current = requireConnection();
const receipt = decodeClientMessageReceipt(pkt, this.identity.uin);
const key = JSON.stringify([
pkt.pid,
receipt.peerUid,
receipt.sequence,
receipt.clientSequence,
receipt.timestamp,
]);
const pending = this.clientMessageTasks_.get(key);
if (pending?.connection === current) {
return pending.work;
}
if (this.clientMessageTasks_.size >= 256) {
throw new Error('Too many pending client message lookups');
}
runtimeLog.trace(
'client_message_lookup_start uin=%j pid=%d seqId=%d',
this.identity.uin,
pkt.pid,
pkt.seqId,
);
const work = (async () => {
const source: PacketSender = {
sendPacket: (cmd, body, timeout) =>
requireConnection().client.sendPacket(cmd, body, timeout),
};
const event = await fetchClientMessage(source, this.identity, receipt);
requireConnection();
await this.pipeline.processEvents(pkt, [event]);
runtimeLog.trace(
'client_message_lookup_complete uin=%j pid=%d seqId=%d',
this.identity.uin,
pkt.pid,
pkt.seqId,
);
})();
const task = { connection: current, work };
this.clientMessageTasks_.set(key, task);
try {
await work;
} finally {
if (this.clientMessageTasks_.get(key) === task) {
this.clientMessageTasks_.delete(key);
}
}
}
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) {
return;

View File

@@ -1,6 +1,7 @@
import { APP_VERSION } from '@snowluma/common/version';
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { resolveWebuiTarget } from '@snowluma/common/webui-target';
import { registerStaticFrontend } from './static-frontend';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { getRuntimeIntegrity, hasLowProcessIntegrity } from '@snowluma/bridge';
import {
@@ -636,6 +637,15 @@ export async function initWebUI(
updateRoot?: string;
} = {},
): Promise<{ port: number; stop: () => Promise<void> }> {
const webuiTarget = resolveWebuiTarget(process.env.SNOWLUMA_WEBUI_TARGET);
if (webuiTarget) {
log.info(
'presentation target enabled: %s (runtime override; saved appearance is preserved)',
webuiTarget,
);
}
const host = listener.host || '127.0.0.1';
const tlsEnabled = listener.tlsEnabled === true;
const bootCheck = checkListenerExposure({
@@ -2267,29 +2277,7 @@ export async function initWebUI(
// Build path is relative to the bundled / dev __dirname. SPA fallback to
// index.html so client-side routes (if any) keep working.
const staticRoot = path.resolve(__dirname, 'client');
app.use('/*', serveStatic({ root: staticRoot }));
const indexHtmlPath = path.join(staticRoot, 'index.html');
app.get('*', (c) => {
// SPA fallback: only for navigations that didn't hit a static asset.
if (
c.req.path.startsWith('/api/') ||
c.req.path.startsWith('/avatar/') ||
c.req.path.startsWith('/ui-asset/')
) {
return c.text('not found', 404);
}
if (existsSync(indexHtmlPath)) {
const html = readFileSync(indexHtmlPath, 'utf8');
return c.html(html);
}
return c.text(
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
404,
);
});
registerStaticFrontend(app, staticRoot, webuiTarget);
const finalPort = await findAvailablePort(desiredPort, { host });

View File

@@ -0,0 +1,34 @@
import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
import type { Hono, Context } from 'hono';
import { serveStatic } from '@hono/node-server/serve-static';
import { injectWebuiTarget, type WebuiTarget } from '@snowluma/common/webui-target';
/** All document entry paths share runtime injection, including direct index.html requests. */
export function registerStaticFrontend(app: Hono, root: string, target: WebuiTarget | null): void {
const indexPath = path.join(root, 'index.html');
const document = (c: Context) => {
if (!existsSync(indexPath)) {
return c.text(
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
404,
);
}
// A packaged frontend can be reused with a different deployment target on restart.
c.header('Cache-Control', 'no-store');
return c.html(injectWebuiTarget(readFileSync(indexPath, 'utf8'), target));
};
app.get('/', document);
app.get('/index.html', document);
app.use('/*', serveStatic({ root }));
app.get('*', (c) => {
if (['/api/', '/avatar/', '/ui-asset/'].some((prefix) => c.req.path.startsWith(prefix))) {
return c.text('not found', 404);
}
return document(c);
});
}

View File

@@ -35,7 +35,7 @@ function message(...elems: Elem[]): PushMsgBody {
};
}
function setup(downloads: Map<string, LongMsgResult>) {
function setup(downloads: Map<string, LongMsgResult>, selfUin = '10001') {
const requested: string[] = [];
const bridge = mockBridge({
sendRawPacket: vi.fn(async (command: string, bytes: Uint8Array) => {
@@ -61,21 +61,194 @@ function setup(downloads: Map<string, LongMsgResult>) {
};
}),
});
bridge.identity.uin = selfUin;
const forward = new ForwardApi(bridge as unknown as BridgeContext);
const ctx = {
selfId: 10001,
selfId: Number(selfUin),
bridge: { apis: { forward } },
converterCtx: {
selfId: 10001,
selfId: Number(selfUin),
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
},
} as unknown as OneBotInstanceContext;
return { api: buildApiContext(ctx), requested };
return { api: buildApiContext(ctx), requested, bridge, forward };
}
function plainResult(text: string): LongMsgResult {
return {
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: [message({ text: { str: text } })] },
},
],
};
}
function nestedResult(inner: string, key: string, body?: PushMsgBody): LongMsgResult {
return {
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: [message(forwardCard('xml', inner, key))] },
},
{
actionCommand: key,
actionData: { msgBody: [body ?? message({ text: { str: 'inner content' } })] },
},
],
};
}
async function fillCache(
api: ReturnType<typeof setup>['api'],
downloads: Map<string, LongMsgResult>,
prefix: string,
count: number,
): Promise<void> {
for (let index = 0; index < count; index++) {
const id = `${prefix}-${index}`;
downloads.set(id, plainResult(id));
await api.getForwardMsg(id);
}
}
describe('get_forward_msg / cache lifetime', () => {
it('bounds cached results while refreshing recently read results', async () => {
const downloads = new Map([
['cache-cold', plainResult('cold')],
['cache-hot', plainResult('hot')],
]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('cache-cold');
await api.getForwardMsg('cache-hot');
await fillCache(api, downloads, 'cache-pressure', 510);
await api.getForwardMsg('cache-hot');
await fillCache(api, downloads, 'cache-overflow', 1);
requested.length = 0;
await api.getForwardMsg('cache-hot');
await api.getForwardMsg('cache-cold');
expect(requested).toEqual(['cache-cold']);
});
it('isolates cached content between bridge accounts', async () => {
const first = setup(new Map([['same-resource', plainResult('account one')]]));
const second = setup(new Map([['same-resource', plainResult('account two')]]), '10002');
await first.api.getForwardMsg('same-resource');
expect((await second.api.getForwardMsg('same-resource'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'account two' } },
]);
expect(second.requested).toEqual(['same-resource']);
});
it('keeps nested results with a hot outer result under cache pressure', async () => {
const downloads = new Map([['hot-outer', nestedResult('hot-inner', 'hot-inner-key')]]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('hot-outer');
await fillCache(api, downloads, 'nested-pressure', 511);
await api.getForwardMsg('hot-inner');
await fillCache(api, downloads, 'nested-overflow', 1);
requested.length = 0;
expect((await api.getForwardMsg('hot-outer'))[0]?.message).toEqual([
{ type: 'forward', data: { id: 'hot-inner' } },
]);
expect((await api.getForwardMsg('hot-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'inner content' } },
]);
expect(requested).toEqual([]);
});
it('keeps an inner result attached to its outer result after sender enrichment', async () => {
const nameless = message({ text: { str: 'unnamed sender' } });
nameless.responseHead!.grp!.memberCard = '';
const downloads = new Map([
['enrich-outer', nestedResult('enrich-inner', 'enrich-key', nameless)],
]);
const { api, requested, bridge } = setup(downloads);
bridge.apis.contacts.fetchGroupMemberList.mockResolvedValue([
{ uin: 20002, nickname: 'resolved nickname', card: 'resolved card' },
]);
await api.getForwardMsg('enrich-outer');
await fillCache(api, downloads, 'enrich-pressure', 511);
requested.length = 0;
expect((await api.getForwardMsg('enrich-inner'))[0]).toMatchObject({
sender: { nickname: 'resolved card' },
});
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce();
await api.getForwardMsg('enrich-outer');
await api.getForwardMsg('enrich-inner');
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce();
expect(requested).toEqual([]);
});
it('retains a shared inner result while another containing outer result remains cached', async () => {
const downloads = new Map([
['shared-outer-a', nestedResult('shared-inner', 'shared-key-a')],
['shared-outer-b', nestedResult('shared-inner', 'shared-key-b')],
]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('shared-outer-a');
await api.getForwardMsg('shared-outer-b');
await fillCache(api, downloads, 'shared-pressure', 510);
await api.getForwardMsg('shared-outer-a');
await fillCache(api, downloads, 'shared-overflow', 1);
requested.length = 0;
expect((await api.getForwardMsg('shared-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'inner content' } },
]);
expect(requested).toEqual([]);
});
it('restores all nested results when an evicted outer result is downloaded again', async () => {
const downloads = new Map([
['restore-outer', nestedResult('restore-inner', 'restore-key')],
]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('restore-outer');
await api.getForwardMsg('restore-inner');
await fillCache(api, downloads, 'restore-pressure', 512);
requested.length = 0;
await api.getForwardMsg('restore-outer');
expect((await api.getForwardMsg('restore-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'inner content' } },
]);
expect(requested).toEqual(['restore-outer']);
});
it('does not resurrect evicted nested results when enrichment finishes late', async () => {
const nameless = message({ text: { str: 'late sender' } });
nameless.responseHead!.grp!.memberCard = '';
const downloads = new Map([
['late-outer', nestedResult('late-inner', 'late-key', nameless)],
]);
const { api, requested, bridge } = setup(downloads);
const members = [{ uin: 20002, nickname: 'late name', card: '' }];
let finishEnrichment!: () => void;
const enrichment = new Promise<typeof members>((resolve) => {
finishEnrichment = () => resolve(members);
});
bridge.apis.contacts.fetchGroupMemberList.mockReturnValueOnce(enrichment);
await api.getForwardMsg('late-outer');
const pending = api.getForwardMsg('late-inner');
await vi.waitFor(() =>
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce(),
);
await fillCache(api, downloads, 'late-pressure', 512);
finishEnrichment();
expect((await pending)[0]).toMatchObject({ sender: { nickname: 'late name' } });
requested.length = 0;
await expect(api.getForwardMsg('late-inner')).rejects.toThrow('payload is empty');
await api.getForwardMsg('late-outer');
expect((await api.getForwardMsg('late-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'late sender' } },
]);
expect(requested).toEqual(['late-inner', 'late-outer']);
});
});
describe('get_forward_msg / nested downloads (#529)', () => {
it.each(['xml', 'lightApp'] as const)(
'resolves siblings and three levels of %s forwards from one outer payload',

View File

@@ -40,6 +40,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
}));
import { ForwardApi } from '../../src/bridge/apis/forward';
import type { BridgeContext } from '../../src/bridge/bridge-context';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
@@ -107,6 +108,49 @@ function findLightAppJson(msgBody: PushMsgBody[]): {
}
describe('forward / nested upload wire alignment', () => {
it('bounds uploaded results while keeping a recently read nested upload together', async () => {
let sequence = 0;
const sendRawPacket = vi.fn(async (command: string) => {
if (command !== 'trpc.group.long_msg_interface.MsgService.SsoSendLongMsg') {
throw new Error('test cache miss');
}
return uploadResponseWithResId(`upload-cache-${++sequence}`);
});
const bridge = mockBridge({ sendRawPacket });
const forward = new ForwardApi(bridge as unknown as BridgeContext);
const outer = await forward.upload([
{
userUin: 111,
nickname: 'outer',
elements: [],
innerForward: [
{
userUin: 222,
nickname: 'inner',
elements: [{ type: 'text', text: 'nested upload' }],
},
],
},
]);
const filler = [{ userUin: 111, nickname: 'filler', elements: [] }];
for (let index = 0; index < 511; index++) {
await forward.upload(filler);
}
await forward.fetch('upload-cache-1');
await forward.upload(filler);
const uploadedCount = sendRawPacket.mock.calls.length;
const sameBridgeApi = new ForwardApi(bridge as unknown as BridgeContext);
expect((await sameBridgeApi.fetch(outer))[0]?.elements[0]?.resId).toBe('upload-cache-1');
expect((await sameBridgeApi.fetch('upload-cache-1'))[0]?.elements).toEqual([
{ type: 'text', text: 'nested upload' },
]);
expect(sendRawPacket).toHaveBeenCalledTimes(uploadedCount);
await expect(forward.fetch('upload-cache-3')).rejects.toThrow('test cache miss');
});
it('outer LongMsgResult contains both MultiMsg and the inner uuid piggyback action', async () => {
// Inner upload returns inner-res; outer upload returns outer-res.
const responses = ['inner-res', 'outer-res'];

View File

@@ -305,6 +305,51 @@ describe('apis/group-file', () => {
expect(publishSpy).toHaveBeenCalledOnce();
});
it.each([true, false])(
'publishes only after the upload is confirmed (confirmed=%s)',
async (confirmed) => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
fileId: 'fid-confirm',
uploadIp: '127.0.0.1',
uploadPort: 443,
fileKey: new Uint8Array([1]),
checkKey: new Uint8Array([2]),
},
},
}),
),
);
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
const failure = new Error('highway upload transport failed; current chunk unconfirmed');
vi.mocked(highwayClient.uploadHighwayHttp).mockImplementationOnce(async () => {
expect(publishSpy).not.toHaveBeenCalled();
if (!confirmed) {
throw failure;
}
});
const upload = api.upload(12345, 'base64://AQID', 'confirmed.txt');
if (confirmed) {
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm' });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm');
} else {
await expect(upload).rejects.toBe(failure);
expect(publishSpy).not.toHaveBeenCalled();
}
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
},
);
it('upload caches the upload metadata for later resend by file_id', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(

View File

@@ -0,0 +1,234 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CLIENT_MESSAGE_RECEIPT_CMD, type PacketInfo } from '@snowluma/common/protocol-types';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import { protobuf_encode } from '@snowluma/proton';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from '../src/bridge/bridge';
const bridges: Bridge[] = [];
const timestamp = 1_700_000_000;
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((accept) => {
resolve = accept;
});
return { promise, resolve };
}
afterEach(async () => {
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
vi.useRealTimers();
vi.restoreAllMocks();
});
function packet(): PacketInfo {
const uid = Buffer.from('u_test_peer');
const header = Buffer.alloc(8);
header[0] = 1;
header[1] = uid.length;
header.writeUInt32LE(9, 4);
return {
pid: 1234,
uin: '10001',
source: 'client-message',
serviceCmd: CLIENT_MESSAGE_RECEIPT_CMD,
seqId: 42,
retCode: 0,
fromClient: false,
body: Buffer.concat([
header,
uid,
protobuf_encode<SendMessageResponse>({ privateSequence: 87, timestamp1: timestamp }),
]),
};
}
function response(): SendPacketResult {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(
protobuf_encode<SsoGetC2cMsgResponse>({
friendUid: 'u_test_peer',
messages: [
{
responseHead: {
fromUin: 10001,
fromUid: 'u_test_self',
toUin: 20002,
toUid: 'u_test_peer',
},
contentHead: {
msgType: 166,
sequence: 9,
ntMsgSeq: 87,
timestamp,
msgId: 123456,
},
body: { richText: { elems: [{ text: { str: 'hello' } }] } },
},
],
}),
),
};
}
async function setup() {
const bridge = new Bridge(IdentityService.memory('10001'));
bridges.push(bridge);
vi.spyOn(bridge.apis.contacts, 'fetchFriendList').mockResolvedValue([
{ uin: 10001, uid: 'u_test_self', nickname: 'self', remark: '' },
]);
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockResolvedValue([]);
const sendPacket = vi.fn<PacketSender['sendPacket']>(async () => response());
const sender = { sendPacket };
bridge.bindPid(1234, sender);
await bridge.whenRosterWarmupSettled();
const received = vi.fn();
bridge.events.on('friend_message', received);
return { bridge, sendPacket, sender, received };
}
describe('Bridge client message recovery', () => {
it('does not retry a delayed lookup on a detached or replacement connection', async () => {
const ctx = await setup();
vi.useFakeTimers();
ctx.sendPacket.mockResolvedValue({
...response(),
responseData: Buffer.from(
protobuf_encode<SsoGetC2cMsgResponse>({
result: 100000301,
friendUid: 'u_test_peer',
}),
),
});
const work = ctx.bridge.onPacket(packet());
const rejected = expect(work).rejects.toThrow('inactive connection');
await vi.advanceTimersByTimeAsync(0);
expect(ctx.sendPacket).toHaveBeenCalledOnce();
ctx.bridge.detachPid(1234);
const replacement = vi.fn<PacketSender['sendPacket']>();
ctx.bridge.bindPid(1234, { sendPacket: replacement });
await vi.runAllTimersAsync();
await rejected;
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(replacement).not.toHaveBeenCalled();
expect(ctx.received).not.toHaveBeenCalled();
});
it('dispatches confirmed content through the normal event pipeline', async () => {
const ctx = await setup();
await ctx.bridge.onPacket(packet());
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(ctx.received).toHaveBeenCalledOnce();
expect(ctx.received).toHaveBeenCalledWith(
expect.objectContaining({
kind: 'friend_message',
selfUin: 10001,
senderUin: 10001,
peerUin: 20002,
ntMsgSeq: 87,
clientSeq: 9,
elements: [{ type: 'text', text: 'hello' }],
}),
);
});
it('does not treat an ordinary packet with the same command as a receipt', async () => {
const ctx = await setup();
const ordinary = packet();
delete ordinary.source;
await ctx.bridge.onPacket(ordinary);
expect(ctx.sendPacket).not.toHaveBeenCalled();
expect(ctx.received).not.toHaveBeenCalled();
});
it('shares an in-flight lookup across repeated receipts and ordinary PID observations', async () => {
const ctx = await setup();
const result = deferred<SendPacketResult>();
const started = deferred<void>();
ctx.sendPacket.mockImplementation(() => {
started.resolve();
return result.promise;
});
const first = ctx.bridge.onPacket(packet());
await started.promise;
ctx.bridge.bindPid(1234, ctx.sender);
const duplicate = ctx.bridge.onPacket(packet());
await Promise.resolve();
result.resolve(response());
await Promise.all([first, duplicate]);
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(ctx.received).toHaveBeenCalledOnce();
});
it.each(['detach', 'replace', 'reattach', 'dispose'] as const)(
'rejects a lookup completed after %s',
async (action) => {
const ctx = await setup();
const result = deferred<SendPacketResult>();
const started = deferred<void>();
ctx.sendPacket.mockImplementation(() => {
started.resolve();
return result.promise;
});
const work = ctx.bridge.onPacket(packet());
const rejected = expect(work).rejects.toThrow('inactive connection');
await started.promise;
let disposal: Promise<void> | undefined;
if (action === 'dispose') {
disposal = ctx.bridge.dispose();
} else if (action === 'replace') {
ctx.bridge.bindPid(1234, { sendPacket: vi.fn() });
} else {
ctx.bridge.detachPid(1234);
if (action === 'reattach') {
ctx.bridge.bindPid(1234, ctx.sender);
}
}
result.resolve(response());
await rejected;
await disposal;
expect(ctx.received).not.toHaveBeenCalled();
},
);
it('queries the originating connection even when another process is active', async () => {
const ctx = await setup();
const other = { sendPacket: vi.fn<PacketSender['sendPacket']>() };
ctx.bridge.bindPid(4321, other);
await ctx.bridge.onPacket(packet());
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(other.sendPacket).not.toHaveBeenCalled();
});
it('rejects unavailable, detached and wrong-account receipts before querying', async () => {
const ctx = await setup();
await expect(ctx.bridge.onPacket({ ...packet(), retCode: -1 })).rejects.toThrow(
'unavailable',
);
await expect(ctx.bridge.onPacket({ ...packet(), uin: '20002' })).rejects.toThrow('account');
ctx.bridge.detachPid(1234);
await expect(ctx.bridge.onPacket(packet())).rejects.toThrow('inactive connection');
expect(ctx.sendPacket).not.toHaveBeenCalled();
expect(ctx.received).not.toHaveBeenCalled();
});
it('surfaces lookup failure and allows a later receipt to retry', async () => {
const ctx = await setup();
ctx.sendPacket.mockRejectedValueOnce(new Error('lookup failed'));
await expect(ctx.bridge.onPacket(packet())).rejects.toThrow('lookup failed');
expect(ctx.received).not.toHaveBeenCalled();
await ctx.bridge.onPacket(packet());
expect(ctx.sendPacket).toHaveBeenCalledTimes(2);
expect(ctx.received).toHaveBeenCalledOnce();
});
});

View File

@@ -15,8 +15,9 @@
// 一连接,但仍全部成功。
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import type { HttpConn0x6FF501Response } from '@snowluma/proto-defs/highway';
import { protobuf_encode } from '@snowluma/proton';
import type { HttpConn0x6FF501Response, ReqDataHighwayHead } from '@snowluma/proto-defs/highway';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { unpackHighwayFrame } from '@snowluma/protocol/highway/utils';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { EventEmitter } from 'events';
@@ -79,6 +80,8 @@ class FakeSocket extends EventEmitter {
writable = true;
posts = 0;
headers: string[] = [];
frames: Buffer[] = [];
closeBeforeResponse = false;
connectFailure?: Error | 'timeout';
private connectTimer?: ReturnType<typeof setTimeout>;
private buf = Buffer.alloc(0);
@@ -141,6 +144,7 @@ class FakeSocket extends EventEmitter {
}
this.headers.push(s.slice(0, he));
this.frames.push(Buffer.from(this.buf.subarray(he + 4, total)));
this.buf = this.buf.subarray(total);
this.posts += 1;
const thisPost = this.posts;
@@ -157,6 +161,14 @@ class FakeSocket extends EventEmitter {
return;
}
if (this.closeBeforeResponse) {
this.writable = false;
this.readableEnded = true;
this.emit('end');
this.emit('close');
return;
}
if (thisPost === this.errorAfterPartialOnPost) {
const full = httpWrap(this.responseFrame);
this.emit('data', full.subarray(0, full.length - 3));
@@ -443,7 +455,7 @@ describe('fetchHighwaySession trace lifecycle', () => {
});
});
describe('Highway initial connection selection', () => {
describe('Highway connection selection', () => {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
@@ -582,24 +594,160 @@ describe('Highway initial connection selection', () => {
expect(source.closeCount).toBe(1);
});
it('stays on the selected node after data was sent without an acknowledgement', async () => {
it.each([0, HIGHWAY_BLOCK_SIZE])(
'retries only the unconfirmed chunk at offset %i on the next node',
async (offset) => {
vi.useFakeTimers();
installFactory(() => {
const host = createConnectionMock.mock.lastCall?.[0].host;
const socket = new FakeSocket(
buildEmptyHighwayResponseFrame(),
'keepalive',
host === '192.0.2.1' && offset > 0 ? 2 : -1,
);
socket.closeBeforeResponse = host === '192.0.2.1' && offset === 0;
return socket;
});
const session = sessionWithCandidates();
const original = structuredClone(session);
const source = new RecordingChunkSource(offset + 80);
const extend = new Uint8Array([0x12, 0x34]);
const upload = uploadHighwayHttp(
makeBridge(),
session,
71,
source,
new Uint8Array(16),
extend,
);
const completed = expect(upload).resolves.toBeUndefined();
await Promise.all([completed, vi.runAllTimersAsync()]);
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
session.servers,
);
const [failed, recovered] = createdSockets as FakeSocket[];
expect(recovered!.posts).toBe(1);
const first = unpackHighwayFrame(failed!.frames.at(-1)!);
const retry = unpackHighwayFrame(recovered!.frames[0]!);
const firstHead = protobuf_decode<ReqDataHighwayHead>(first.head);
const retryHead = protobuf_decode<ReqDataHighwayHead>(retry.head);
expect(retry.body).toEqual(first.body);
expect(retryHead).toEqual({
...firstHead,
msgBaseHead: { ...firstHead.msgBaseHead, retryTimes: 1 },
});
expect(retryHead.msgSegHead?.dataOffset ?? 0n).toBe(BigInt(offset));
expect(retryHead.bytesReqExtendInfo).toEqual(Buffer.from(extend));
expect(source.reads).toEqual(
offset === 0
? [{ offset: 0, length: 80 }]
: [
{ offset: 0, length: HIGHWAY_BLOCK_SIZE },
{ offset, length: 80 },
],
);
expect(source.closeCount).toBe(1);
expect(session).toEqual(original);
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
},
);
it('bounds retries across nodes and reports the unconfirmed chunk without advancing progress', async () => {
vi.useFakeTimers();
installFactory(
(idx) =>
new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', idx === 0 ? 1 : -1),
);
installFactory(() => {
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
socket.closeBeforeResponse = true;
return socket;
});
const session = sessionWithCandidates();
const source = new RecordingChunkSource(80);
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const upload = uploadHighwayHttp(
makeBridge(),
session,
71,
source,
new Uint8Array(16),
new Uint8Array(),
);
const failed = expect(upload).rejects.toThrow(
/transport failed after 3 attempts.*acknowledgedBytes=0.*unconfirmed/,
);
await Promise.all([failed, vi.runAllTimersAsync()]);
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual([
session.servers[0],
session.servers[1],
session.servers[0],
]);
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
expect(source.closeCount).toBe(1);
const terminals = highwayTrace(entries).filter((entry) =>
entry.message.startsWith('highway_put_terminal '),
);
expect(terminals).toHaveLength(1);
expect(terminals[0]!.message).toContain('outcome=failed reason=transport_exhausted');
expect(terminals[0]!.message).toContain('uploadedBytes=0');
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
} finally {
unsubscribe();
}
});
it('continues after the actual failed node and skips candidates that cannot reconnect', async () => {
vi.useFakeTimers();
installFactory(() => {
const host = createConnectionMock.mock.lastCall?.[0].host;
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
if (host === '192.0.2.1') {
socket.connectFailure = new Error('ECONNREFUSED');
} else if (host === '192.0.2.2') {
socket.closeBeforeResponse = true;
} else if (host === '192.0.2.3') {
socket.connectFailure = 'timeout';
}
return socket;
});
const session = {
...makeSession(),
servers: Array.from({ length: 4 }, (_, i) => ({ host: `192.0.2.${i + 1}`, port: 443 })),
};
const source = new RecordingChunkSource(80);
const upload = uploadHighwayHttp(
makeBridge(),
session,
1004,
new RecordingChunkSource(1),
71,
source,
new Uint8Array(16),
new Uint8Array(),
);
await Promise.all([expect(upload).resolves.toBeUndefined(), vi.runAllTimersAsync()]);
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
session.servers,
);
expect((createdSockets as FakeSocket[]).map((socket) => socket.posts)).toEqual([
0, 1, 0, 1,
]);
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
expect(source.closeCount).toBe(1);
});
it('keeps the successful node when the peer closes after acknowledgement', async () => {
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'closeafter'));
const session = sessionWithCandidates();
await uploadHighwayHttp(
makeBridge(),
session,
71,
new RecordingChunkSource(HIGHWAY_BLOCK_SIZE + 80),
new Uint8Array(16),
new Uint8Array(),
);
const completed = expect(upload).resolves.toBeUndefined();
await vi.runAllTimersAsync();
await completed;
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual([
session.servers[0],
session.servers[0],

View File

@@ -1,5 +1,5 @@
import { spawn } from 'node:child_process';
import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { cp, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import { builtinModules } from 'node:module';
import os from 'node:os';
import path from 'node:path';
@@ -14,7 +14,8 @@ let root: string;
let staging: string;
beforeAll(async () => {
compiled = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-build-'));
// Module resolution uses canonical paths, including when the temp directory is a symlink.
compiled = await realpath(await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-build-')));
const loaded = await loadConfigFromFile(
{ command: 'build', mode: 'production' },
fileURLToPath(new URL('../vite.config.ts', import.meta.url)),
@@ -114,7 +115,7 @@ afterAll(async () => {
await rm(compiled, { recursive: true, force: true });
});
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-test-'));
root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-test-')));
staging = await updateDirectory(root);
await releaseFixture(root, '1.0.0');
await cp(path.join(compiled, '1.0.0/index.mjs'), path.join(root, 'index.mjs'));
@@ -158,7 +159,7 @@ describe('packaged startup', () => {
expect(JSON.parse(result.output)).toEqual({
version: '1.0.0',
node: process.execPath,
cwd: os.tmpdir(),
cwd: await realpath(os.tmpdir()),
args: ['value with spaces'],
oldAlive: false,
});

View File

@@ -0,0 +1,47 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { Hono } from 'hono';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { registerStaticFrontend } from '../src/webui/static-frontend';
let root: string;
const html = '<!doctype html><html><head><title>SnowLuma</title></head><body>app</body></html>';
beforeEach(() => {
root = mkdtempSync(path.join(tmpdir(), 'snowluma-presentation-'));
writeFileSync(path.join(root, 'index.html'), html);
writeFileSync(path.join(root, 'asset.js'), 'window.asset = true;');
});
afterEach(() => rmSync(root, { recursive: true, force: true }));
describe('runtime target document delivery', () => {
it.each(['/', '/index.html', '/settings?tab=appearance'])(
'injects on %s before authentication',
async (url) => {
const app = new Hono();
registerStaticFrontend(app, root, 'maibot');
const response = await app.request(url);
expect(response.status).toBe(200);
expect(response.headers.get('cache-control')).toBe('no-store');
expect(await response.text()).toContain('"target":"maibot"');
},
);
it('reuses the exact same built frontend for an unconfigured deployment', async () => {
const app = new Hono();
registerStaticFrontend(app, root, null);
expect(await (await app.request('/index.html')).text()).toBe(html);
});
it('does not inject into assets or API error responses', async () => {
const app = new Hono();
registerStaticFrontend(app, root, 'maibot');
expect(await (await app.request('/asset.js')).text()).toBe('window.asset = true;');
for (const url of ['/api/missing', '/avatar/missing', '/ui-asset/missing']) {
expect((await app.request(url)).status).toBe(404);
}
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "2.0.3",
"version": "2.1.0",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "2.0.3",
"version": "2.1.0",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",

View File

@@ -302,7 +302,7 @@ function arrayField<E>(
}
export const f = {
/** Positive integer (>0): group_id / user_id / message_id. */
/** Positive integer (>0): group_id / user_id. */
uint(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), {
type: 'uint',

View File

@@ -166,7 +166,8 @@ type PipelineEventReason =
| 'pipeline_threw'
| 'recalled_before_backfill'
| 'recalled_after_backfill'
| 'waiter_notified';
| 'waiter_notified'
| 'waiter_not_found';
async function convertAndDispatch(
ctx: OneBotInstanceContext,
@@ -458,8 +459,14 @@ function handlePttTransResult(
event: Extract<QQEventVariant, { kind: 'ptt_trans_result' }>,
state: EventTraceState,
): void {
deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text);
traceEventTerminal(log, event.kind, state, 'internal', 'waiter_notified');
const notified = deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text);
traceEventTerminal(
log,
event.kind,
state,
'internal',
notified ? 'waiter_notified' : 'waiter_not_found',
);
}
function convertOnly<K extends EventKind>(

View File

@@ -70,8 +70,8 @@ export class OneBotInstance {
private readonly startedAt = Date.now();
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
private readonly statusCommandCooldown = new Map<string, number>();
/** Action-side events awaiting a possible canonical QQ echo. */
private readonly pendingSelfSentEchoes = new Map<
/** Reported self sends retained while matching subsequent QQ echoes. */
private readonly recentSelfSentEvents = new Map<
string,
{ event: JsonObject; expiresAt: number }
>();
@@ -464,7 +464,7 @@ export class OneBotInstance {
}
if (source === 'bridge') {
if (this.consumePendingSelfSentEcho(event)) {
if (this.isDuplicateSelfSentEcho(event)) {
this.log.trace(
'duplicate self-message echo suppressed message_id=%d message_seq=%d',
toInt(event.message_id),
@@ -478,8 +478,12 @@ export class OneBotInstance {
);
return;
}
if (event.post_type === 'message_sent') {
this.rememberSelfSentEvent(event);
}
} else {
this.rememberPendingSelfSentEcho(event);
this.rememberSelfSentEvent(event);
}
// The send path already logged the real peer and payload. Logging its
@@ -523,7 +527,7 @@ export class OneBotInstance {
]);
}
private rememberPendingSelfSentEcho(event: JsonObject): void {
private rememberSelfSentEvent(event: JsonObject): void {
const key = selfSentEventKey(event);
if (key === null) {
@@ -531,11 +535,11 @@ export class OneBotInstance {
}
const now = Date.now();
this.sweepPendingSelfSentEchoes(now);
this.pendingSelfSentEchoes.set(key, { event, expiresAt: now + SELF_SENT_ECHO_WINDOW_MS });
this.sweepSelfSentEvents(now);
this.recentSelfSentEvents.set(key, { event, expiresAt: now + SELF_SENT_ECHO_WINDOW_MS });
}
private consumePendingSelfSentEcho(event: JsonObject): boolean {
private isDuplicateSelfSentEcho(event: JsonObject): boolean {
const key = selfSentEventKey(event);
if (key === null) {
@@ -543,21 +547,20 @@ export class OneBotInstance {
}
const now = Date.now();
this.sweepPendingSelfSentEchoes(now);
const pending = this.pendingSelfSentEchoes.get(key);
this.sweepSelfSentEvents(now);
const pending = this.recentSelfSentEvents.get(key);
if (!pending || !sameSelfSentMessage(pending.event, event)) {
return false;
}
this.pendingSelfSentEchoes.delete(key);
return true;
}
private sweepPendingSelfSentEchoes(now: number): void {
for (const [key, pending] of this.pendingSelfSentEchoes) {
private sweepSelfSentEvents(now: number): void {
for (const [key, pending] of this.recentSelfSentEvents) {
if (pending.expiresAt <= now) {
this.pendingSelfSentEchoes.delete(key);
this.recentSelfSentEvents.delete(key);
}
}
}

View File

@@ -5,8 +5,12 @@ interface Pending {
const pending = new Map<string, Pending>();
export function pttTransKey(selfUin: number, msgId: number): string {
return selfUin + ':' + msgId;
export function pttTransKey(selfUin: number, msgId: number | bigint): string {
if (typeof msgId === 'number' && !Number.isSafeInteger(msgId)) {
throw new RangeError('PTT message id must be a safe integer or bigint');
}
return selfUin + ':' + BigInt.asIntN(64, BigInt(msgId));
}
/** Register before triggering; only this request may settle its own response or timeout. */
@@ -53,6 +57,13 @@ export function requestPttTransText(
}
/** QQ push results identify the account and message, not an individual trigger request. */
export function deliverPttTransText(key: string, text: string): void {
pending.get(key)?.resolve(text);
export function deliverPttTransText(key: string, text: string): boolean {
const waiter = pending.get(key);
if (!waiter) {
return false;
}
waiter.resolve(text);
return true;
}

View File

@@ -3,8 +3,8 @@ import type { JsonObject } from './types';
export const SELF_SENT_ECHO_WINDOW_MS = 120_000;
/**
* Match the action-side copy of a sent message with QQ's later canonical
* echo. The message hash alone is insufficient because it is a signed 32-bit
* Match a reported self send with a later QQ echo, including repeated
* pushes. The message hash alone is insufficient because it is a signed 32-bit
* value and can collide; sequence, conversation and a bounded time window are
* part of the identity as well.
*/

View File

@@ -9,6 +9,11 @@ import {
type LogEntry,
} from '@snowluma/common/logger';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPushOrThrow } from '@snowluma/protocol/msg-push';
import type { PushMsg } from '@snowluma/proto-defs/message';
import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans';
import { protobuf_encode } from '@snowluma/proton';
// Wrap convertEvent in a vi.fn that delegates to the real impl by
// default, so one test can override it to return null without making
@@ -28,8 +33,15 @@ vi.mock('../src/modules/message-actions', async () => {
import { convertEvent, type ConverterContext } from '../src/event-converter';
import { registerEventPipeline } from '../src/event-pipeline';
import { buildDispatchPayload, pickDispatchJson } from '../src/event-filter';
import type { OneBotInstanceContext } from '../src/instance-context';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
import { backfillReplyTarget } from '../src/modules/message-actions';
import {
deliverPttTransText,
pttTransKey,
requestPttTransText,
} from '../src/modules/ptt-trans-waiter';
import { TempSessionStore } from '../src/temp-session-store';
import type {
FriendMessage,
@@ -107,6 +119,28 @@ function makeMemberJoin(): GroupMemberJoin {
};
}
function decodePttTransPush(selfId: number, msgId: bigint, text: string): QQEventVariant[] {
return parseMsgPushOrThrow(
{
pid: 1,
uin: String(selfId),
serviceCmd: MSG_PUSH_CMD,
seqId: 1,
retCode: 0,
fromClient: false,
body: protobuf_encode<PushMsg>({
message: {
contentHead: { msgType: 528, subType: 61, timestamp: 1700000000 },
body: {
msgContent: protobuf_encode<PttTransPush>({ item: { msgId, text } }),
},
},
}),
},
IdentityService.memory(String(selfId)),
);
}
function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
ctx: OneBotInstanceContext;
bus: BridgeEventBus;
@@ -168,6 +202,79 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
}
describe('registerEventPipeline', () => {
it('matches transcription pushes to signed message IDs without rounding or crossing accounts', async () => {
vi.useFakeTimers();
const previousLevel = getLogLevel();
const entries: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
setLogLevel('trace');
const cases = [
{ selfId: SELF_ID, msgId: -373767942, wireId: 18446744073335783674n },
{ selfId: SELF_ID, msgId: -373767943, wireId: 18446744073335783673n },
{ selfId: SELF_ID + 1, msgId: -373767942, wireId: 18446744073335783674n },
{ selfId: SELF_ID, msgId: -2147483648, wireId: 18446744071562067968n },
{ selfId: SELF_ID, msgId: -1, wireId: 18446744073709551615n },
{ selfId: SELF_ID, msgId: 147311541, wireId: 147311541n },
{ selfId: SELF_ID, msgId: 2147483647, wireId: 2147483647n },
{
selfId: SELF_ID,
msgId: hashMessageIdInt32(1, 12345, PRIVATE_MESSAGE_EVENT),
wireId: 18446744073124008294n,
},
];
const requests = cases.map((item, index) => {
const context = makeContext({ selfId: item.selfId, uin: String(item.selfId) });
const handle = registerEventPipeline(context.ctx);
const key = pttTransKey(item.selfId, item.msgId);
const text = `transcription ${index}`;
const result = requestPttTransText(key, 20_000, async () => '');
return { ...item, ...context, handle, key, text, result };
});
const settled = Promise.allSettled(requests.map(({ result }) => result));
try {
expect(cases.at(-1)?.msgId).toBe(-585543322);
for (const request of requests.toReversed()) {
const events = decodePttTransPush(request.selfId, request.wireId, request.text);
expect(events).toHaveLength(1);
await request.bus.emit(events[0]!);
}
await vi.advanceTimersByTimeAsync(20_000);
expect(await settled).toEqual(
requests.map(({ text }) => ({ status: 'fulfilled', value: text })),
);
expect(vi.getTimerCount()).toBe(0);
expect(requests.flatMap(({ dispatchCalls }) => dispatchCalls)).toEqual([]);
expect(
entries.filter(
(entry) =>
entry.scope === 'Event' &&
entry.message.startsWith('event_terminal kind=ptt_trans_result') &&
entry.message.includes('reason=waiter_notified'),
),
).toHaveLength(requests.length);
expect(
entries.some(
(entry) =>
entry.message.startsWith('event_input kind=ptt_trans_result') &&
entry.message.includes('msgId:18446744073335783674'),
),
).toBe(true);
} finally {
for (const request of requests) {
deliverPttTransText(request.key, 'cleanup');
request.handle.stop();
await request.handle.drain();
}
unsubscribe();
setLogLevel(previousLevel);
vi.useRealTimers();
}
});
it('caches meta and dispatches a converted event for friend_message', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
@@ -219,6 +326,100 @@ describe('registerEventPipeline', () => {
expect(dispatchCalls[0].message_type).toBe('group');
});
it('reports a received client group push according to each adapter self-message option', async () => {
const { ctx, bus, metaCalls, dispatchCalls, dispatchArgs } = makeContext();
ctx.converterCtx.messageIdResolver = (_isGroup, sessionId, sequence, eventName) =>
hashMessageIdInt32(sequence, sessionId, eventName);
const handle = registerEventPipeline(ctx);
const identity = IdentityService.memory(SELF_UIN);
const packet = {
pid: 1,
uin: SELF_UIN,
serviceCmd: MSG_PUSH_CMD,
seqId: 1,
retCode: 0,
fromClient: false,
body: protobuf_encode<PushMsg>({
message: {
responseHead: {
fromUin: SELF_ID,
grp: { groupUin: GROUP_ID, memberCard: 'self', groupName: 'test group' },
},
contentHead: {
msgType: 82,
sequence: 5637,
timestamp: 1_700_000_000,
msgId: 335502226,
},
body: { richText: { elems: [{ text: { str: 'client group send' } }] } },
},
}),
};
try {
const events = parseMsgPushOrThrow(packet, identity);
expect(events).toHaveLength(1);
for (const event of events) {
await bus.emit(event);
}
const messageId = hashMessageIdInt32(5637, GROUP_ID, GROUP_MESSAGE_EVENT);
expect(metaCalls).toEqual([
{
id: messageId,
meta: expect.objectContaining({
isGroup: true,
targetId: GROUP_ID,
sequence: 5637,
random: 335502226,
}),
},
]);
expect(dispatchCalls).toHaveLength(1);
const event = dispatchCalls[0];
expect(event).toMatchObject({
post_type: 'message_sent',
message_type: 'group',
self_id: SELF_ID,
user_id: SELF_ID,
group_id: GROUP_ID,
message_id: messageId,
message_seq: 5637,
raw_message: 'client group send',
});
expect(dispatchArgs[0].source).toBe('bridge');
const payload = buildDispatchPayload(event);
expect(
pickDispatchJson(payload, { reportSelfMessage: false, messageFormat: 'array' }),
).toBeNull();
expect(
JSON.parse(
pickDispatchJson(payload, { reportSelfMessage: true, messageFormat: 'array' })!,
),
).toMatchObject({
post_type: 'message_sent',
message: [{ type: 'text', data: { text: 'client group send' } }],
});
expect(
JSON.parse(
pickDispatchJson(payload, {
reportSelfMessage: true,
messageFormat: 'string',
})!,
),
).toMatchObject({
post_type: 'message_sent',
message: 'client group send',
});
} finally {
handle.stop();
await handle.drain();
await identity.close();
}
});
it('caches meta with random=0 for temp_message and dispatches as private+sub_type=group', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
@@ -540,7 +741,7 @@ describe('registerEventPipeline', () => {
kind: 'ptt_trans_result',
time: 1700000000,
selfUin: SELF_ID,
msgId: 99,
msgId: 99n,
text: 'done',
});
@@ -555,7 +756,7 @@ describe('registerEventPipeline', () => {
expect.stringContaining('outcome=dropped reason=converter_returned_null'),
expect.stringContaining('outcome=failed reason=converter_threw'),
expect.stringContaining('outcome=dropped reason=recalled_before_backfill'),
expect.stringContaining('outcome=internal reason=waiter_notified'),
expect.stringContaining('outcome=internal reason=waiter_not_found'),
]),
);
expect(

View File

@@ -8,6 +8,10 @@ describe('hashMessageIdInt32', () => {
expect(id1).toBe(id2);
});
it('preserves negative hashes as valid message IDs', () => {
expect(hashMessageIdInt32(1, 12345, PRIVATE_MESSAGE_EVENT)).toBe(-585543322);
});
it('returns non-zero', () => {
// The function ensures id !== 0 by setting it to 1
const id = hashMessageIdInt32(0, 0, '');

View File

@@ -8,6 +8,13 @@ import {
afterEach(() => vi.useRealTimers());
describe('PTT transcription requests', () => {
it.each([Number(18446744073335783674n), 1.5, NaN, Infinity])(
'rejects an inexact numeric message id: %s',
(msgId) => {
expect(() => pttTransKey(10001, msgId)).toThrow(RangeError);
},
);
it('keeps accounts isolated for the same message id', async () => {
const first = requestPttTransText(pttTransKey(10001, 1), 20_000, async () => '');
const second = requestPttTransText(pttTransKey(10002, 1), 20_000, async () => '');
@@ -19,8 +26,9 @@ describe('PTT transcription requests', () => {
it.each(['text', ''])('accepts a pushed transcription: %j', async (text) => {
const result = requestPttTransText('account:push', 20_000, async () => '');
deliverPttTransText('account:push', text);
expect(deliverPttTransText('account:push', text)).toBe(true);
await expect(result).resolves.toBe(text);
expect(deliverPttTransText('account:push', text)).toBe(false);
});
it('registers before triggering so an immediate push is not lost', async () => {

View File

@@ -175,7 +175,7 @@ function makeInstanceHarness(
acceptingActions: true,
uin: String(SELF_ID),
statusCommandCooldown: new Map([['p:20002', Date.now()]]),
pendingSelfSentEchoes: new Map(),
recentSelfSentEvents: new Map(),
});
const dispatch = (
instance as unknown as {
@@ -203,7 +203,153 @@ function privateSentEvent(overrides: JsonObject = {}): JsonObject {
};
}
function groupSentEvent(overrides: JsonObject = {}): JsonObject {
return {
...privateSentEvent(),
message_type: 'group',
sub_type: 'normal',
message_id: -7654321,
message_seq: RECEIPT.sequence,
group_id: 30003,
target_id: undefined,
...overrides,
};
}
describe('OneBot self-sent events', () => {
it('reports a client private send once across repeated confirmations and pushes', async () => {
const { dispatch, emitEvent, stored } = makeInstanceHarness();
const event = privateSentEvent({ message_id: -7654321 });
await Promise.all([dispatch(event, 'bridge'), dispatch({ ...event }, 'bridge')]);
await dispatch({ ...event, raw_message: 'canonical content' }, 'bridge');
expect(emitEvent).toHaveBeenCalledExactlyOnceWith(event);
expect(stored.get(-7654321)?.raw_message).toBe('canonical content');
});
it('keeps private action deduplication for more than one echo', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = privateSentEvent();
await dispatch(event, 'send');
await dispatch({ ...event }, 'bridge');
await dispatch({ ...event }, 'bridge');
expect(emitEvent).toHaveBeenCalledOnce();
});
it('distinguishes private sends by identity and peer even when text is identical', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = privateSentEvent();
await dispatch(event, 'bridge');
await dispatch({ ...event, message_seq: RECEIPT.clientSequence + 1 }, 'bridge');
await dispatch({ ...event, target_id: PEER_ID + 1 }, 'bridge');
await dispatch({ ...event, message_id: -7654321 }, 'bridge');
expect(emitEvent).toHaveBeenCalledTimes(4);
});
it('keeps private deduplication isolated and expires it without deleting history', async () => {
vi.useFakeTimers();
try {
const first = makeInstanceHarness();
const second = makeInstanceHarness();
const event = privateSentEvent();
await first.dispatch(event, 'bridge');
await second.dispatch(
{ ...event, self_id: SELF_ID + 1, user_id: SELF_ID + 1 },
'bridge',
);
expect(second.emitEvent).toHaveBeenCalledOnce();
await first.dispatch(event, 'bridge');
expect(first.emitEvent).toHaveBeenCalledOnce();
vi.advanceTimersByTime(120_000);
await first.dispatch(event, 'bridge');
expect(first.emitEvent).toHaveBeenCalledTimes(2);
expect(first.stored.has(987654)).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('reports a client group send once across repeated server pushes', async () => {
const { dispatch, emitEvent, stored } = makeInstanceHarness();
const event = groupSentEvent();
await dispatch(event, 'bridge');
await dispatch({ ...event, raw_message: 'canonical echo' }, 'bridge');
await dispatch({ ...event, raw_message: 'latest canonical echo' }, 'bridge');
expect(emitEvent).toHaveBeenCalledOnce();
expect(emitEvent).toHaveBeenCalledWith(event);
expect(stored.get(-7654321)?.raw_message).toBe('latest canonical echo');
});
it('reports concurrent copies of a client group send only once', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = groupSentEvent();
await Promise.all([
dispatch({ ...event }, 'bridge'),
dispatch({ ...event }, 'bridge'),
dispatch({ ...event }, 'bridge'),
]);
expect(emitEvent).toHaveBeenCalledOnce();
});
it('keeps group sends with identical text but different message identities', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = groupSentEvent();
await dispatch(event, 'bridge');
await dispatch({ ...event, message_seq: RECEIPT.sequence + 1 }, 'bridge');
await dispatch({ ...event, group_id: 30004 }, 'bridge');
await dispatch({ ...event, message_id: -7654322 }, 'bridge');
expect(emitEvent).toHaveBeenCalledTimes(4);
});
it('keeps group deduplication isolated between account instances', async () => {
const first = makeInstanceHarness();
const second = makeInstanceHarness();
await first.dispatch(groupSentEvent(), 'bridge');
await second.dispatch(
groupSentEvent({ self_id: SELF_ID + 1, user_id: SELF_ID + 1 }),
'bridge',
);
expect(first.emitEvent).toHaveBeenCalledOnce();
expect(second.emitEvent).toHaveBeenCalledOnce();
});
it('expires group self-send identities without treating stored history as already reported', async () => {
vi.useFakeTimers();
try {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = groupSentEvent();
await dispatch(event, 'bridge');
await dispatch({ ...event }, 'bridge');
expect(emitEvent).toHaveBeenCalledOnce();
vi.advanceTimersByTime(120_000);
await dispatch({ ...event }, 'bridge');
expect(emitEvent).toHaveBeenCalledTimes(2);
} finally {
vi.useRealTimers();
}
});
it('keeps the timestamp bound when a group sequence and hash are reused', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = groupSentEvent();
await dispatch(event, 'bridge');
await dispatch({ ...event, time: RECEIPT.timestamp + 121 }, 'bridge');
expect(emitEvent).toHaveBeenCalledTimes(2);
});
it('does not publish an event suppressed by the persistence recall check', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
// The event's cache operation is the final authority after asynchronous

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "2.0.3",
"version": "2.1.0",
"private": true,
"type": "module",
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",

View File

@@ -79,12 +79,20 @@ export interface SendMessageResponse {
result?: pb<1, int_32>;
errMsg?: pb<2, string>;
timestamp1?: pb<3, uint_32>;
reviewResult?: pb<6, int_32>;
serverResult?: pb<7, SendMessageServerResult>;
field10?: pb<10, uint_32>;
groupSequence?: pb<11, uint_32>;
timestamp2?: pb<12, uint_32>;
privateSequence?: pb<14, uint_32>;
}
export interface SendMessageServerResult {
type?: pb<1, int_32>;
code?: pb<2, int_32>;
message?: pb<3, string>;
}
// MentionExtra (for building @mention text element)
export interface MentionExtraSend {
type?: pb<3, int_32>;

View File

@@ -1,4 +1,4 @@
import type { pb, pb_repeated, uint_32, bool } from '@snowluma/proton';
import type { pb, pb_repeated, uint_32, int_32, bool } from '@snowluma/proton';
import type { PushMsgBody } from './message';
// trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg — fetch private (c2c)
@@ -15,6 +15,8 @@ export interface SsoGetC2cMsg {
}
export interface SsoGetC2cMsgResponse {
result?: pb<1, int_32>;
errorMessage?: pb<2, string>;
friendUid?: pb<4, string>;
messages?: pb_repeated<7, PushMsgBody>;
}

View File

@@ -12,10 +12,8 @@ import type { pb, uint_32, uint_64 } from '@snowluma/proton';
* fields (uuid / md5) and the response `text` tag should be confirmed with a
* single live capture before relying on them.
*
* Flow: send Trans{C2C,Group}PttReq → response carries the text inline when
* transcription is already done; when it's empty the server transcribes
* asynchronously (no dedicated push command exists — see NotifyTransUpdate),
* so the caller re-sends with backoff until the text arrives or it times out.
* Flow: the response can carry completed text inline. Otherwise, the caller
* waits for an asynchronous result correlated with the original message ID.
*/
/** Source ptt-element field (NT internal tag) noted in the comment after each. */
@@ -73,7 +71,7 @@ export interface GroupPttTransResult {
/**
* Outer response. `type` echoes the scene; result is at field 2 (group) /
* field 3 (c2c). An empty `text` with `errCode == 0` means "transcribing,
* retry later".
* await the result push".
*/
export interface PttTransResp {
type?: pb<1, uint_32>;

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "2.0.3",
"version": "2.1.0",
"private": true,
"type": "module",
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",

View File

@@ -495,7 +495,7 @@ export interface GroupMsgEmojiLikeEvent extends QQEvent {
*/
export interface PttTransResultEvent extends QQEvent {
kind: 'ptt_trans_result';
msgId: number;
msgId: bigint;
text: string;
}

View File

@@ -336,11 +336,14 @@ function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.
async function connectHighway(
servers: HighwayServer[],
): Promise<{ socket: net.Socket; server: HighwayServer }> {
startIndex = 0,
): Promise<{ socket: net.Socket; server: HighwayServer; serverIndex: number }> {
const deadline = Date.now() + HIGHWAY_CONNECT_BUDGET_MS;
const errors: Error[] = [];
for (const server of servers) {
for (let i = 0; i < servers.length; i++) {
const serverIndex = (startIndex + i) % servers.length;
const server = servers[serverIndex]!;
const remaining = deadline - Date.now();
if (remaining <= 0) {
@@ -353,7 +356,7 @@ async function connectHighway(
server.port,
Math.min(HIGHWAY_CONNECT_TIMEOUT_MS, remaining),
);
return { socket, server };
return { socket, server, serverIndex };
} catch (cause) {
const error = new Error(`${server.host}:${server.port}: ${highwayErrorText(cause)}`, {
cause,
@@ -698,6 +701,7 @@ async function uploadHighwayHttpOperation(
let socket: net.Socket | null = null;
let connectCount = 0;
let server = session.servers[0]!;
let serverIndex = 0;
const dropSocket = (): void => {
if (socket) {
@@ -771,13 +775,10 @@ async function uploadHighwayHttpOperation(
try {
if (!socket) {
// Select only before the first connection succeeds. Zero acknowledged
// bytes does not mean no data was sent to an already connected node.
if (connectCount === 0) {
({ socket, server } = await connectHighway(session.servers));
} else {
socket = await tcpConnect(server.host, server.port);
}
({ socket, server, serverIndex } = await connectHighway(
session.servers,
serverIndex,
));
connectCount += 1;
trace.connectCount = connectCount;
@@ -824,17 +825,23 @@ async function uploadHighwayHttpOperation(
trace.failureReason = 'transport_exhausted';
const exhausted = new Error(
`highway upload transport failed after ${transportAttempts} attempts ` +
`(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}): ${String(err)}`,
`(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}` +
` acknowledgedBytes=${offset}; current chunk unconfirmed): ${String(err)}`,
{ cause: err },
);
trace.error = exhausted;
throw exhausted;
}
// Keep the current session and chunk intact when changing nodes.
// Missing acknowledgement does not prove the previous node received nothing.
serverIndex = (serverIndex + 1) % session.servers.length;
log.trace(
'highway_put_branch branch=chunk_retry offset=%d bytes=%d attempt=%d error=%j',
'highway_put_branch branch=chunk_retry offset=%d bytes=%d attempt=%d nextServer=%j error=%j',
offset,
chunkSize,
transportAttempts,
session.servers[serverIndex],
highwayErrorText(err),
);
await sleepMs(HIGHWAY_RETRY_BASE_MS * transportAttempts);

View File

@@ -0,0 +1,195 @@
import { CLIENT_MESSAGE_RECEIPT_CMD, type PacketInfo } from '@snowluma/common/protocol-types';
import type { PacketSender } from '@snowluma/common/packet-sender';
import { isRealUin } from '@snowluma/common/uin';
import { createLogger } from '@snowluma/common/logger';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { FriendMessage } from '../events';
import type { IdentityService } from '../identity-service';
import { classifyMessageSurvival } from './blank-filter';
import { buildContextFromMessage } from './context';
import { decodeFriendMessage } from './decoders/friend-message';
import { PkgType } from './enums';
import { SSO_GET_C2C_MSG_CMD } from './fetch-c2c-history';
import { requirePacketResponse } from './packet-response';
const log = createLogger('MsgPush.ClientMessage');
const historyRetryDelays = [100, 250, 500, 1000, 2000] as const;
export interface ClientMessageReceipt {
readonly peerUid: string;
readonly clientSequence: number;
readonly sequence: number;
readonly timestamp: number;
}
export function decodeClientMessageReceipt(pkt: PacketInfo, selfUin: string): ClientMessageReceipt {
if (
pkt.source !== 'client-message' ||
pkt.serviceCmd !== CLIENT_MESSAGE_RECEIPT_CMD ||
!isRealUin(selfUin) ||
pkt.uin !== selfUin
) {
throw new Error('Client message receipt has an invalid source or account');
}
if (pkt.retCode !== 0) {
throw new Error(`Client message receipt is unavailable (status=${pkt.retCode})`);
}
const body = Buffer.from(pkt.body);
if (body.length < 12 || body.length > 8 + 128 + 65536) {
throw new Error('Client message receipt has an invalid length');
}
const peerLength = body[1]!;
const ackOffset = 8 + peerLength;
if (
body[0] !== 1 ||
body.readUInt16LE(2) !== 0 ||
peerLength < 3 ||
peerLength > 128 ||
ackOffset >= body.length ||
body.length - ackOffset > 65536
) {
throw new Error('Client message receipt has an invalid envelope');
}
const peerUid = body.subarray(8, ackOffset).toString('utf8');
const clientSequence = body.readUInt32LE(4);
if (!/^u_[A-Za-z0-9_-]+$/.test(peerUid) || clientSequence === 0) {
throw new Error('Client message receipt has an invalid message identity');
}
const ack = protobuf_decode<SendMessageResponse>(body.subarray(ackOffset));
if (
(ack.result ?? 0) !== 0 ||
(ack.reviewResult ?? 0) !== 0 ||
(ack.serverResult?.code ?? 0) !== 0
) {
throw new Error('Client message was not accepted');
}
const sequence = ack.privateSequence;
const timestamp = ack.timestamp1;
if (!sequence || !timestamp || (ack.groupSequence ?? 0) !== 0) {
throw new Error('Client message receipt has no valid private message confirmation');
}
return { peerUid, clientSequence, sequence, timestamp };
}
export async function fetchClientMessage(
sender: PacketSender,
identity: IdentityService,
receipt: ClientMessageReceipt,
): Promise<FriendMessage> {
const request = protobuf_encode<SsoGetC2cMsg>({
friendUid: receipt.peerUid,
startSequence: receipt.sequence,
endSequence: receipt.sequence,
});
let response: SsoGetC2cMsgResponse;
for (let attempt = 0; ; attempt++) {
const result = await sender.sendPacket(SSO_GET_C2C_MSG_CMD, Buffer.from(request), 5000);
response = protobuf_decode<SsoGetC2cMsgResponse>(
requirePacketResponse(result, 'Client message lookup'),
);
if (response.friendUid && response.friendUid !== receipt.peerUid) {
throw new Error('Client message lookup returned another conversation');
}
// A successful send can precede visibility in message storage. Only
// its explicit not-yet-stored result permits retrying this exact ID.
if (
response.result === 100000301 &&
response.friendUid === receipt.peerUid &&
!response.messages?.length
) {
const delay = historyRetryDelays[attempt];
if (delay === undefined) {
throw new Error(
`Client message history is still unavailable after ${attempt + 1} attempts (code=${response.result})`,
);
}
log.debug(
'Confirmed client message is not yet in history: attempt=%d nextDelayMs=%d',
attempt + 1,
delay,
);
await new Promise<void>((resolve) => setTimeout(resolve, delay));
continue;
}
if ((response.result ?? 0) !== 0) {
throw new Error(`Client message lookup failed (code=${response.result})`);
}
break;
}
if (response.messages?.length !== 1) {
throw new Error(
`Client message lookup expected one message, received ${response.messages?.length ?? 0}`,
);
}
const message = response.messages[0]!;
const head = message.contentHead;
const route = message.responseHead;
const selfUin = Number(identity.uin);
if (
!head ||
!route ||
route.fromUin !== selfUin ||
route.toUid !== receipt.peerUid ||
!route.toUin ||
route.grp != null ||
head.ntMsgSeq !== receipt.sequence ||
head.sequence !== receipt.clientSequence ||
head.timestamp !== receipt.timestamp
) {
throw new Error('Client message lookup did not match the confirmed message');
}
if (
![
PkgType.PrivateMessage,
PkgType.PrivateRecordMessage,
PkgType.PrivateFileMessage,
PkgType.ForwardFakePrivateMessage,
].includes(head.msgType ?? 0)
) {
throw new Error('Client message lookup returned an unsupported message type');
}
const context = buildContextFromMessage(message, selfUin, identity);
if (!context) {
throw new Error('Client message lookup has no message context');
}
const events = decodeFriendMessage(context);
const event = events[0];
if (
events.length !== 1 ||
event?.kind !== 'friend_message' ||
classifyMessageSurvival(context.head, event.elements, context.body) !== 'keep'
) {
throw new Error('Client message lookup has no supported message content');
}
return event;
}

View File

@@ -205,7 +205,7 @@ function decodePttTransResult(ctx: MsgPushContext): QQEventVariant[] {
return [];
}
const msgId = Number(item.msgId ?? 0n);
const msgId = item.msgId ?? 0n;
const text = item.text ?? '';
if (!msgId || !text) {

View File

@@ -26,6 +26,7 @@ import { deriveSysMsgDedupIdentity, SysMsgDedup } from './sysmsg-dedup';
export { deriveSysMsgDedupIdentity, SysMsgDedup } from './sysmsg-dedup';
export type { SysMsgDedupIdentity } from './sysmsg-dedup';
export { decodeClientMessageReceipt, fetchClientMessage } from './client-message-receipt';
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
export {

View File

@@ -35,6 +35,7 @@ import {
MAX_RICH_CARD_OUTPUT_BYTES,
ntImageUrlFromFileId,
} from './helpers';
import { readXmlMsgAttributes } from './xml-card';
type ElemDecoded = Elem;
type RichTextDecoded = RichText;
@@ -135,14 +136,16 @@ function decodeRichMsgCard(
return invalidCard(data.length, 'invalid_xml', decoded.budgetBytes);
}
if (svcId === 35) {
const match = /\bm_resid="([^"]+)"/.exec(content);
const rootAttributes = svcId === 0 || svcId === 35 ? readXmlMsgAttributes(content) : undefined;
if (svcId === 35 || (svcId === 0 && rootAttributes?.get('serviceID') === '35')) {
const resId = rootAttributes?.get('m_resid');
// XML forwards link bundled inner messages by m_fileName, just as
// LightApp forwards use uniseq. Keep it for the outer payload lookup.
const fileName = /\bm_fileName="([^"]+)"/.exec(content)?.[1];
const fileName = rootAttributes?.get('m_fileName') || undefined;
return {
element: match
? { type: 'forward', resId: match[1], forwardUuid: fileName }
element: resId
? { type: 'forward', resId, forwardUuid: fileName }
: { type: 'xml', text: content, subType: svcId },
error: null,
inputBytes: data.length,

View File

@@ -0,0 +1,121 @@
const NAME_START =
':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D' +
'\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF' +
'\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u{10000}-\\u{EFFFF}';
const ATTRIBUTE = new RegExp(
`([${NAME_START}][\\u0300-\\u036F${NAME_START}\\-.0-9\\u00B7\\u203F-\\u2040]*)` +
`[\\t\\r\\n ]*=[\\t\\r\\n ]*(?:"([^"<]*)"|'([^'<]*)')`,
'uy',
);
const SPACE = /[\t\r\n ]*/y;
const ENTITIES = new Map([
['amp', '&'],
['lt', '<'],
['gt', '>'],
['quot', '"'],
['apos', "'"],
]);
function decodeAttribute(value: string): string | undefined {
let valid = true;
// Literal whitespace is normalized before expanding character references.
const decoded = value
.replace(/\r\n|[\t\r\n]/g, ' ')
.replace(
/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);|&/g,
(_match, entity: string | undefined) => {
const named = entity === undefined ? undefined : ENTITIES.get(entity);
if (named !== undefined) {
return named;
}
if (entity?.startsWith('#')) {
const code = entity.startsWith('#x')
? Number.parseInt(entity.slice(2), 16)
: Number.parseInt(entity.slice(1), 10);
if (
code === 9 ||
code === 10 ||
code === 13 ||
(code >= 0x20 && code <= 0xd7ff) ||
(code >= 0xe000 && code <= 0xfffd) ||
(code >= 0x10000 && code <= 0x10ffff)
) {
return String.fromCodePoint(code);
}
}
valid = false;
return '';
},
);
return valid ? decoded : undefined;
}
/** Read the first element's attributes without searching comments, values or descendants. */
export function readXmlMsgAttributes(content: string): ReadonlyMap<string, string> | undefined {
let cursor = content.startsWith('\uFEFF') ? 1 : 0;
for (;;) {
SPACE.lastIndex = cursor;
SPACE.exec(content);
cursor = SPACE.lastIndex;
const closing = content.startsWith('<!--', cursor)
? '-->'
: content.startsWith('<?', cursor)
? '?>'
: undefined;
if (!closing) {
break;
}
const end = content.indexOf(closing, cursor + (closing === '-->' ? 4 : 2));
if (end < 0) {
return undefined;
}
cursor = end + closing.length;
}
if (!content.startsWith('<msg', cursor)) {
return undefined;
}
cursor += 4;
const attributes = new Map<string, string>();
for (;;) {
const beforeSpace = cursor;
SPACE.lastIndex = cursor;
SPACE.exec(content);
cursor = SPACE.lastIndex;
if (content[cursor] === '>' || content.startsWith('/>', cursor)) {
return attributes;
}
if (cursor === beforeSpace) {
return undefined;
}
ATTRIBUTE.lastIndex = cursor;
const match = ATTRIBUTE.exec(content);
if (!match || attributes.has(match[1]!)) {
return undefined;
}
const value = decodeAttribute(match[2] ?? match[3]!);
if (value === undefined) {
return undefined;
}
attributes.set(match[1]!, value);
cursor = ATTRIBUTE.lastIndex;
}
}

View File

@@ -85,8 +85,18 @@ export class IncomingPacketPipeline {
}
process(pkt: PacketInfo): Promise<void> {
return this.processWithHandlers(pkt, this.cmdHandlers_.get(pkt.serviceCmd));
}
processEvents(pkt: PacketInfo, events: readonly QQEventVariant[]): Promise<void> {
return this.processWithHandlers(pkt, [() => [...events]]);
}
private processWithHandlers(
pkt: PacketInfo,
handlers: readonly CmdParser[] | undefined,
): Promise<void> {
const startedAt = Date.now();
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) {
this.packetLog.trace(() => [

View File

@@ -0,0 +1,345 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CLIENT_MESSAGE_RECEIPT_CMD, type PacketInfo } from '@snowluma/common/protocol-types';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { IdentityService } from '../../src/identity-service';
import {
decodeClientMessageReceipt,
fetchClientMessage,
} from '../../src/msg-push/client-message-receipt';
import { SSO_GET_C2C_MSG_CMD } from '../../src/msg-push/fetch-c2c-history';
const self = '10001';
const peer = 'u_test_peer';
const time = 1_700_000_000;
const identities: IdentityService[] = [];
afterEach(async () => {
vi.useRealTimers();
await Promise.all(identities.splice(0).map((identity) => identity.close()));
});
function packet(ack: SendMessageResponse = { privateSequence: 87, timestamp1: time }): PacketInfo {
const uid = Buffer.from(peer);
const header = Buffer.alloc(8);
header[0] = 1;
header[1] = uid.length;
header.writeUInt32LE(9, 4);
return {
pid: 1234,
uin: self,
seqId: 42,
retCode: 0,
fromClient: false,
source: 'client-message',
serviceCmd: CLIENT_MESSAGE_RECEIPT_CMD,
body: Buffer.concat([header, uid, protobuf_encode<SendMessageResponse>(ack)]),
};
}
function message(): PushMsgBody {
return {
responseHead: { fromUin: Number(self), fromUid: 'u_test_self', toUin: 20002, toUid: peer },
contentHead: { msgType: 166, sequence: 9, ntMsgSeq: 87, timestamp: time, msgId: 123456 },
body: { richText: { elems: [{ text: { str: 'hello' } }, { face: { index: 1 } }] } },
};
}
function lookupResponse(response: SsoGetC2cMsgResponse): SendPacketResult {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SsoGetC2cMsgResponse>(response)),
};
}
function setup(messages = [message()], friendUid = peer) {
const identity = IdentityService.memory(self);
identities.push(identity);
const sendPacket = vi.fn<PacketSender['sendPacket']>(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SsoGetC2cMsgResponse>({ friendUid, messages })),
}));
const receipt = decodeClientMessageReceipt(packet(), self);
return {
sendPacket,
identity,
receipt,
run: () => fetchClientMessage({ sendPacket }, identity, receipt),
};
}
describe('client message receipts', () => {
it('decodes a confirmation and retrieves exactly its conversation and sequence', async () => {
const ctx = setup();
expect(ctx.receipt).toEqual({
peerUid: peer,
clientSequence: 9,
sequence: 87,
timestamp: time,
});
const event = await ctx.run();
expect(ctx.sendPacket).toHaveBeenCalledOnce();
const [cmd, body] = ctx.sendPacket.mock.calls[0]!;
expect(cmd).toBe(SSO_GET_C2C_MSG_CMD);
expect(protobuf_decode<SsoGetC2cMsg>(body)).toMatchObject({
friendUid: peer,
startSequence: 87,
endSequence: 87,
});
expect(event).toMatchObject({
kind: 'friend_message',
selfUin: 10001,
senderUin: 10001,
peerUin: 20002,
clientSeq: 9,
ntMsgSeq: 87,
sequenceAuthoritative: true,
time,
elements: [
{ type: 'text', text: 'hello' },
{ type: 'face', faceId: 1 },
],
});
});
it.each([
{ source: undefined },
{ serviceCmd: 'MessageSvc.PbSendMsg' },
{ uin: '20002' },
{ retCode: -1 },
] satisfies Partial<PacketInfo>[])('rejects invalid provenance or status: %j', (patch) => {
expect(() => decodeClientMessageReceipt({ ...packet(), ...patch }, self)).toThrow();
});
it.each([
{ result: 1 },
{ reviewResult: 1 },
{ serverResult: { code: -1 } },
{ privateSequence: 0 },
{ timestamp1: 0 },
{ groupSequence: 5 },
] satisfies SendMessageResponse[])(
'rejects an unsuccessful or incomplete confirmation: %j',
(patch) => {
expect(() =>
decodeClientMessageReceipt(
packet({ privateSequence: 87, timestamp1: time, ...patch }),
self,
),
).toThrow();
},
);
it.each([
[
'version',
(body: Buffer) => {
body[0] = 2;
},
],
[
'reserved',
(body: Buffer) => {
body[2] = 1;
},
],
[
'uid length',
(body: Buffer) => {
body[1] = 129;
},
],
[
'uid',
(body: Buffer) => {
body[8] = 0xff;
},
],
[
'client sequence',
(body: Buffer) => {
body.writeUInt32LE(0, 4);
},
],
] as const)('rejects a malformed %s', (_name, mutate) => {
const pkt = packet();
const body = Buffer.from(pkt.body);
mutate(body);
expect(() => decodeClientMessageReceipt({ ...pkt, body }, self)).toThrow();
});
it('rejects truncated and excessive bodies', () => {
for (const body of [
new Uint8Array(),
packet().body.subarray(0, 8 + peer.length),
new Uint8Array(8 + 128 + 65537),
]) {
expect(() => decodeClientMessageReceipt({ ...packet(), body }, self)).toThrow();
}
});
it.each([
[
'sender',
(msg: PushMsgBody) => {
msg.responseHead!.fromUin = 20002;
},
],
[
'recipient',
(msg: PushMsgBody) => {
msg.responseHead!.toUid = 'u_other';
},
],
[
'missing recipient',
(msg: PushMsgBody) => {
delete msg.responseHead!.toUin;
},
],
[
'client sequence',
(msg: PushMsgBody) => {
msg.contentHead!.sequence = 10;
},
],
[
'server sequence',
(msg: PushMsgBody) => {
msg.contentHead!.ntMsgSeq = 88;
},
],
[
'timestamp',
(msg: PushMsgBody) => {
msg.contentHead!.timestamp = time + 1;
},
],
[
'group',
(msg: PushMsgBody) => {
msg.responseHead!.grp = { groupCode: 30003 };
},
],
[
'type',
(msg: PushMsgBody) => {
msg.contentHead!.msgType = 82;
},
],
[
'empty content',
(msg: PushMsgBody) => {
msg.body = {};
},
],
[
'unknown content',
(msg: PushMsgBody) => {
msg.body = { richText: { elems: [{ commonElem: { serviceType: 999 } }] } };
},
],
[
'control',
(msg: PushMsgBody) => {
msg.contentHead!.c2cCmd = 1;
},
],
] as const)('rejects an incorrect %s in the lookup', async (_name, mutate) => {
const msg = message();
mutate(msg);
await expect(setup([msg]).run()).rejects.toThrow();
});
it('rejects missing, ambiguous and cross-conversation results', async () => {
await expect(setup([]).run()).rejects.toThrow('expected one');
await expect(setup([message(), message()]).run()).rejects.toThrow('expected one');
await expect(setup([message()], 'u_other').run()).rejects.toThrow('conversation');
});
it('retries only the confirmed message while storage catches up', async () => {
const ctx = setup();
vi.useFakeTimers();
ctx.sendPacket.mockResolvedValueOnce(
lookupResponse({ result: 100000301, friendUid: peer, messages: [] }),
);
const work = ctx.run();
await vi.advanceTimersByTimeAsync(99);
expect(ctx.sendPacket).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
expect(await work).toMatchObject({ ntMsgSeq: 87, clientSeq: 9 });
expect(ctx.sendPacket).toHaveBeenCalledTimes(2);
expect(ctx.sendPacket.mock.calls[1]).toEqual(ctx.sendPacket.mock.calls[0]);
});
it('reports a bounded failure when storage never contains the confirmed message', async () => {
const ctx = setup();
vi.useFakeTimers();
ctx.sendPacket.mockResolvedValue(
lookupResponse({ result: 100000301, friendUid: peer, messages: [] }),
);
const rejected = expect(ctx.run()).rejects.toThrow('still unavailable after 6 attempts');
await vi.runAllTimersAsync();
await rejected;
expect(ctx.sendPacket).toHaveBeenCalledTimes(6);
});
it.each([
{ result: 100000302, friendUid: peer, messages: [] },
{ result: 100000301, friendUid: 'u_other', messages: [] },
{ result: 100000301, messages: [] },
{ result: 100000301, friendUid: peer, messages: [message()] },
] satisfies SsoGetC2cMsgResponse[])(
'does not retry unrelated or inconsistent errors: %j',
async (response) => {
const ctx = setup();
ctx.sendPacket.mockResolvedValue(lookupResponse(response));
await expect(ctx.run()).rejects.toThrow();
expect(ctx.sendPacket).toHaveBeenCalledOnce();
},
);
it('preserves distinct identities for equal text', async () => {
const first = setup();
const msg = message();
msg.contentHead = { ...msg.contentHead, sequence: 10, ntMsgSeq: 88 };
const second = setup([msg]);
const event = await fetchClientMessage(second, second.identity, {
...second.receipt,
clientSequence: 10,
sequence: 88,
});
expect((await first.run()).ntMsgSeq).toBe(87);
expect(event.ntMsgSeq).toBe(88);
expect(event.elements).toEqual((await first.run()).elements);
});
it.each([
{ success: false, gotResponse: false, responseData: null },
{ success: true, gotResponse: false, responseData: null },
{ success: true, gotResponse: true, responseData: Buffer.alloc(0) },
] satisfies Partial<SendPacketResult>[])(
'surfaces unsuccessful lookup transport: %j',
async (result) => {
const ctx = setup();
ctx.sendPacket.mockResolvedValue({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: null,
...result,
});
await expect(ctx.run()).rejects.toThrow('Client message lookup');
},
);
});

View File

@@ -61,6 +61,99 @@ function lengthDelimited(fieldNumber: number, payload: Uint8Array): Uint8Array {
]);
}
function xmlCardBody(xml: string, serviceId = 0): MessageBody {
return {
richText: {
elems: [
{
richMsg: {
serviceId,
template1: Buffer.concat([Buffer.from([0]), Buffer.from(xml, 'utf8')]),
},
},
],
},
};
}
describe('decodeRichBody / XML forward attributes', () => {
it('round-trips escaped resource IDs through the real sender and receiver', async () => {
const resId = 'res&<>"\'&lt;\t\n\r中文😀end';
const elems = await buildSendElems([{ type: 'forward', resId }]);
const body = protobuf_decode<MessageBody>(
protobuf_encode<MessageBody>({ richText: { elems } }),
);
expect(decodeRichBody(body, true)).toEqual([
{ type: 'forward', resId, forwardUuid: expect.any(String) },
]);
});
it.each([0, 35])(
'reads quoted root attributes and decodes entities once (service=%s)',
(serviceId) => {
const xml =
'\uFEFF <?xml version="1.0"?> <!-- header --> <?card data?>' +
'<msg brief="a > b" serviceID = \'&#51;&#x35;\' ' +
'm_resid = "res&amp;&lt;&gt;&quot;&apos;&amp;lt;" ' +
"m_fileName = 'key&#9;&#xA;&#13;&#x1F642;' />";
expect(decodeRichBody(xmlCardBody(xml, serviceId), true)).toEqual([
{
type: 'forward',
resId: 'res&<>"\'&lt;',
forwardUuid: 'key\t\n\r🙂',
},
]);
},
);
it.each([
'<msg><title>serviceID="35" m_resid="fake"</title></msg>',
'<msg><!-- serviceID="35" m_resid="fake" --></msg>',
'<msg><child serviceID="35" m_resid="fake" /></msg>',
'<wrapper><msg serviceID="35" m_resid="fake" /></wrapper>',
'<!-- <msg serviceID="35" m_resid="fake" /> --><msg />',
'<?test <msg serviceID="35" m_resid="fake" /> ?><msg />',
'<msg><![CDATA[<msg serviceID="35" m_resid="fake" />]]></msg>',
'<msg brief=\'serviceID="35" m_resid="fake"\' />',
'<msg data-serviceID="35" m_resid="fake" />',
'<msg serviceID="35" data-m_resid="fake" />',
'<msg serviceID="35"><child m_resid="fake" /></msg>',
'<msg serviceID="35" m_resid="first" m_resid="second" />',
'<msg serviceID="35"m_resid="fake" />',
])(
'preserves XML when forward attributes are not an unambiguous root declaration: %s',
(xml) => {
expect(decodeRichBody(xmlCardBody(xml), true)).toEqual([
{ type: 'xml', text: xml, subType: 0 },
]);
},
);
it.each([0, 35])('does not borrow a child resource ID (service=%s)', (serviceId) => {
const xml = '<msg serviceID="35"><msg m_resid="child" m_fileName="child-key" /></msg>';
expect(decodeRichBody(xmlCardBody(xml, serviceId), true)).toEqual([
{ type: 'xml', text: xml, subType: serviceId },
]);
});
it('preserves an explicit non-forward protocol type', () => {
const xml = '<msg serviceID="35" m_resid="other-card" />';
expect(decodeRichBody(xmlCardBody(xml, 2), true)).toEqual([
{ type: 'xml', text: xml, subType: 2 },
]);
});
it.each(['&unknown;', '&#0;', '&#xD800;', '&#x110000;', '&amp'])(
'preserves XML rather than inventing a lookup key for invalid entity %s',
(entity) => {
const xml = `<msg serviceID="35" m_resid="res${entity}" />`;
expect(decodeRichBody(xmlCardBody(xml, 35), true)).toEqual([
{ type: 'xml', text: xml, subType: 35 },
]);
},
);
});
describe('decodeRichBody / forward LightApp', () => {
it('emits {type:"forward", resId, forwardUuid} for com.tencent.multimsg', () => {
const body: MessageBody = {

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "2.0.3",
"version": "2.1.0",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl with edge-case fixes applied.",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "2.0.3",
"version": "2.1.0",
"private": true,
"type": "module",
"main": "index.mjs",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "2.0.3",
"version": "2.1.0",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/sqlite",
"version": "2.0.3",
"version": "2.1.0",
"private": true,
"type": "module",
"description": "SnowLuma asynchronous SQLite facade, native loader and release assets.",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "2.0.3",
"version": "2.1.0",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "2.0.3",
"version": "2.1.0",
"private": true,
"type": "module",
"main": "./src/index.ts",

View File

@@ -0,0 +1,111 @@
# Host appearance overlays
Set `SNOWLUMA_WEBUI_TARGET=maibot` on the **SnowLuma process** to use MaiBot's
millennium appearance. The same release bundle supports standalone and embedded
deployments. An unset or empty value keeps the existing SnowLuma experience;
unknown values fail WebUI startup with an explicit diagnostic.
This first adapter implements **millennium only**, in light and dark modes.
Other MaiBot styles are not implemented. There is no new appearance selector in
SnowLuma. The host owns theme changes; existing theme controls are unavailable
while managed, and the settings page explains which preferences are preserved.
## Runtime and ownership
1. Core reads the environment at startup. [Static document delivery](../core/src/webui/static-frontend.ts)
injects a validated, public JSON bootstrap into `/`, `/index.html` and SPA
fallback documents. Documents use `Cache-Control: no-store`. No secrets or
arbitrary environment variables reach the browser.
2. [Frontend bootstrap](src/appearance/runtime.ts) loads only the selected
target's assets before mounting React. Standalone deployments load no target
stylesheet, font or host listener. Vite development serves the same bootstrap
when its process has the environment variable; production builds remain neutral.
3. [ThemeContext](src/contexts/ThemeContext.tsx) keeps `savedAppearance` separate
from effective `appearance`. Only saved preferences enter localStorage or
`config/ui.json`. Target updates never invoke the persistence API.
4. The target owns colors, fonts, radius, wallpaper, CSS variable overrides,
custom CSS and custom cursor presentation. These saved values are preserved
but suspended. UI scale, density, motion/accessibility, navigation layout and
data preferences remain available. Safe-mode restrictions still apply when
returning to native appearance.
5. A single layout effect applies effective appearance. Changes do not reload
the document, change React keys or restart sessions. All target rules are
scoped to `html[data-webui-target]`, including portals under `body`.
## Host protocol, version 1
The contract lives in [common/webui-target.ts](../common/src/webui-target.ts).
The deployment environment is an opt-in, **not a live transport**. Existing
launchers need to implement the sender below; merely setting the environment
variable cannot convey another process's current theme.
A same-document embedding bridge (for example Electron `executeJavaScript`)
publishes the latest snapshot before dispatching the event:
```js
const appearance = {
version: 1,
target: 'maibot',
style: 'millennium',
mode: 'dark', // 'light' | 'dark' | 'system'
};
window.__SNOWLUMA_HOST_APPEARANCE__ = appearance;
window.dispatchEvent(new CustomEvent('snowluma:host-appearance', { detail: appearance }));
```
The snapshot handles messages sent before React or the lazy asset loader is
ready. Publish on each guest `dom-ready` and whenever the host's resolved
brightness changes. A host that already follows MaiBot should forward its own
resolved `light`/`dark` state; this avoids competing sources of truth. Validate
the guest's expected origin before injecting, serialize values with
`JSON.stringify`, and do not enable Node integration in the guest.
Send `{ version: 1, target: null }` using the same mechanism to release the
override for the current document. The original appearance returns immediately.
The opted-in document keeps its host subscription so the host can reapply the
target later. Listeners are released on provider unmount. This does not change
the startup environment or enable a target in a standalone deployment.
The current adapter starts with millennium and system brightness before a host
snapshot arrives. The last valid snapshot remains active if the host stops
sending. Snapshots are not persisted or shared across origins/tabs. A reload
requires the host to publish again. Unsupported versions, targets, styles or
modes are rejected with `[SnowLuma appearance]` console diagnostics; the previous
valid snapshot remains. The host cannot supply CSS, URLs or executable content
through this protocol. No unauthenticated HTTP write endpoint is introduced.
## Adding a target
- Add its identifier, styles and default style to `WEBUI_TARGETS` in the shared
contract. Keep validation at this boundary; do not accept arbitrary strings.
- Add one lazy loader to the exhaustive [frontend registry](src/appearance/registry.ts).
Implement a pure saved-to-effective resolver and scoped stylesheet under
`src/appearance/targets`. Keep any fonts local with their redistribution license.
- Use semantic color variables, shared component classes and neutral
`data-ui-surface` markers. Do not add target-name checks to business pages.
- Never persist resolved overrides, mutate saved preferences, introduce a
second DOM theme writer, or remount the application to switch presentation.
- Test default asset/listener isolation, initial document routes, malformed
messages, rapid updates, cleanup and exact restoration of saved preferences.
Verify forms, focus, scroll, portals and mobile layout with an isolated backend.
Electron integration needs a separate real-host check.
## Sources and checks
The adapter follows the main MaiBot repository's
[millennium stylesheet](https://github.com/Mai-with-u/MaiBot/blob/5c7637e6913c84d1c3d5e742fa9e95a7e70d3501/dashboard/src/styles/millennium.css),
not the archived standalone WebUI. Colors/materials also match the
[OneKey shell](https://github.com/Mai-with-u/MaiBotOneKey/blob/e8073b0bce35c8c4da973b06156602e14c42fee5/src/renderer/src/styles/millennium.css).
The bundled Jersey 20 font is from that MaiBot revision, copyright The Soft Type
Project Authors, under the [SIL Open Font License](src/appearance/targets/assets/Jersey20-OFL.txt).
Its license is emitted alongside the font in production assets.
Focused checks (from the repository root):
```sh
pnpm --filter @snowluma/common exec vitest run tests/webui-target.test.ts
pnpm --filter @snowluma/core exec vitest run tests/webui-static-frontend.test.ts
pnpm --filter webui exec vitest run tests/target-appearance.test.ts
```
Run the normal workspace checks from `AGENTS.md` before handing off changes.

View File

@@ -3,6 +3,14 @@
SnowLuma's browser console is a Vite + React application for managing runtime
status, OneBot configuration, logs, storage, and server settings.
## Host appearance integration
`SNOWLUMA_WEBUI_TARGET=maibot` opts a deployment into a reversible millennium
appearance overlay. Standalone defaults are unchanged. Hosts drive live light/dark
updates without saving over personal preferences or adding another selector.
See [the integration contract and extension guide](INTEGRATIONS.md) before changing
target startup, theme ownership, host messaging or scoped styles.
## Interaction conventions
- Destructive actions and second confirmations stay in modal dialogs.

View File

@@ -17,6 +17,9 @@
<script>
(function () {
try {
// Deployment overlays are prepared before React mounts. Do not flash
// a saved palette/font underneath an opted-in host presentation.
if (document.getElementById('snowluma-webui-target')) return;
var raw = localStorage.getItem('snowluma_ui_appearance');
var a = raw ? JSON.parse(raw) : {};
if (!a || typeof a !== 'object') a = {};

View File

@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "2.0.3",
"version": "2.1.0",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -0,0 +1,29 @@
import type { WebuiPresentation, WebuiTarget } from '@snowluma/common/webui-target';
import type { UiAppearance } from '@/types';
export interface TargetAppearance {
css: string;
licenseUrl?: string;
resolve: (saved: UiAppearance, presentation: WebuiPresentation) => UiAppearance;
}
export function resolveAppearance(
saved: UiAppearance,
presentation: WebuiPresentation | null,
target: TargetAppearance | null,
): UiAppearance {
if (!presentation) {
return saved;
}
if (!target) {
throw new Error('Target appearance must be prepared before mounting ThemeProvider');
}
return target.resolve(saved, presentation);
}
// Exhaustive: adding a shared target requires a frontend implementation here.
export const targetLoaders = {
maibot: () => import('./targets/maibot').then((module) => module.maibotAppearance),
} satisfies Record<WebuiTarget, () => Promise<TargetAppearance>>;

View File

@@ -0,0 +1,104 @@
import {
parseWebuiPresentation,
WEBUI_PRESENTATION_EVENT,
WEBUI_TARGET_BOOTSTRAP_ID,
type WebuiPresentation,
} from '@snowluma/common/webui-target';
import { createPresentationStore, type PresentationStore } from './store';
import { targetLoaders, type TargetAppearance } from './registry';
declare global {
interface Window {
/** The embedding host sets this before dispatching WEBUI_PRESENTATION_EVENT. */
__SNOWLUMA_HOST_APPEARANCE__?: unknown;
}
}
const bootstrap =
typeof document === 'undefined' ? null : document.getElementById(WEBUI_TARGET_BOOTSTRAP_ID);
const initial = bootstrap
? parseWebuiPresentation(JSON.parse(bootstrap.textContent || 'null'))
: null;
export const presentationStore = createPresentationStore(initial?.target ?? null);
let targetAppearance: TargetAppearance | null = null;
function acceptHostValue(store: PresentationStore, value: unknown): void {
try {
store.receive(value);
} catch (error) {
// Reject only the bad update; keep the last valid presentation and expose the failure.
console.error('[SnowLuma appearance] Rejected host update', error);
}
}
export function subscribeHostAppearance(host: Window, store: PresentationStore): () => void {
if (store.target === null) {
return () => {};
}
const receive = (event: Event) =>
acceptHostValue(store, (event as CustomEvent<unknown>).detail);
host.addEventListener(WEBUI_PRESENTATION_EVENT, receive);
// Covers messages sent before React subscribed, including while the lazy CSS was loading.
if (host.__SNOWLUMA_HOST_APPEARANCE__ !== undefined) {
acceptHostValue(store, host.__SNOWLUMA_HOST_APPEARANCE__);
}
return () => host.removeEventListener(WEBUI_PRESENTATION_EVENT, receive);
}
export function applyPresentationAttributes(presentation: WebuiPresentation | null): void {
const root = document.documentElement;
if (presentation) {
root.dataset.webuiTarget = presentation.target;
root.dataset.webuiStyle = presentation.style;
} else {
delete root.dataset.webuiTarget;
delete root.dataset.webuiStyle;
}
}
export function getTargetAppearance(): TargetAppearance | null {
return targetAppearance;
}
/** Called before mounting React; standalone deployments do not load any target assets. */
export async function prepareTargetAppearance(): Promise<void> {
const target = presentationStore.target;
if (target === null) {
return;
}
targetAppearance = await targetLoaders[target]();
const style = document.createElement('style');
style.id = 'snowluma-target-styles';
style.textContent = targetAppearance.css;
document.head.appendChild(style);
if (targetAppearance.licenseUrl) {
const license = document.createElement('link');
license.rel = 'license';
license.href = targetAppearance.licenseUrl;
document.head.appendChild(license);
}
if (window.__SNOWLUMA_HOST_APPEARANCE__ !== undefined) {
acceptHostValue(presentationStore, window.__SNOWLUMA_HOST_APPEARANCE__);
}
const presentation = presentationStore.getSnapshot();
applyPresentationAttributes(presentation);
if (presentation) {
const dark =
presentation.mode === 'system'
? window.matchMedia('(prefers-color-scheme: dark)').matches
: presentation.mode === 'dark';
document.documentElement.classList.toggle('dark', dark);
document.documentElement.classList.toggle('light', !dark);
document.documentElement.style.colorScheme = dark ? 'dark' : 'light';
}
}

View File

@@ -0,0 +1,51 @@
import {
defaultWebuiPresentation,
parseWebuiPresentation,
type WebuiPresentation,
type WebuiTarget,
} from '@snowluma/common/webui-target';
/** Synchronous snapshots avoid stale async style loads winning a rapid host theme change. */
export function createPresentationStore(target: WebuiTarget | null) {
let snapshot: WebuiPresentation | null = target ? defaultWebuiPresentation(target) : null;
const listeners = new Set<() => void>();
return {
target,
getSnapshot: () => snapshot,
subscribe(listener: () => void) {
if (target) {
listeners.add(listener);
}
return () => {
listeners.delete(listener);
};
},
receive(value: unknown) {
// Host code cannot opt a standalone deployment into a target.
if (target === null) {
return;
}
const update = parseWebuiPresentation(value);
if (update.target !== null && update.target !== target) {
throw new Error(
`Host appearance target does not match deployment target ${target}`,
);
}
const next = update.target === null ? null : update;
if (JSON.stringify(next) === JSON.stringify(snapshot)) {
return;
}
snapshot = next;
listeners.forEach((listener) => listener());
},
};
}
export type PresentationStore = ReturnType<typeof createPresentationStore>;

View File

@@ -0,0 +1,93 @@
Copyright 2023 The Soft Type Project Authors (https://github.com/scfried/soft-type-jersey)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View File

@@ -0,0 +1,233 @@
/* MaiBot millennium: plastic case, recessed screen, raised keys.
Only loaded for this target; every rule remains scoped so release is reversible. */
@font-face {
font-family: "SnowLuma Jersey 20";
src: url("./assets/Jersey20-Regular.ttf") format("truetype");
font-weight: 400;
font-style: normal;
font-display: swap;
size-adjust: 118%;
unicode-range: U+0000-024F;
}
html[data-webui-target="maibot"] {
--mil-shell: #ddd4bf;
--mil-panel: #ebe4d2;
--mil-hi: #f6f1e3;
--mil-lo: #bdb39c;
--mil-drop: #9c927b;
--mil-line: #5a544a;
--mil-ink: #4a443a;
--mil-print: #5f5849;
--mil-screen: #fbf9f0;
--mil-screen-ink: #3a3833;
--mil-key: #f3eee1;
--mil-key-side: #c2b8a1;
--mil-key-hi: #fffaf0;
--mil-key-hover: #fbf7ec;
--mil-on: #8fd6a0;
--mil-on-ink: #2f3a2b;
--mil-on-side: #5fa873;
--mil-accent-text: #236b43;
--background: var(--mil-shell);
--foreground: var(--mil-ink);
--card: var(--mil-panel);
--card-foreground: var(--mil-ink);
--popover: var(--mil-panel);
--popover-foreground: var(--mil-ink);
--primary: var(--mil-accent-text);
--primary-foreground: var(--mil-screen);
--secondary: var(--mil-key);
--secondary-foreground: var(--mil-ink);
--muted: var(--mil-shell);
--muted-foreground: var(--mil-print);
--accent: var(--mil-on);
--accent-foreground: var(--mil-on-ink);
--destructive: #b53724;
--destructive-foreground: #fffaf0;
--success: #2a7d50;
--warning: #8f4f18;
--log-info: #315b7c;
--log-success: #2a7d50;
--log-warn: #8f4f18;
--log-error: #b53724;
--border: var(--mil-lo);
--input: var(--mil-screen);
--ring: var(--mil-accent-text);
--sidebar: var(--mil-panel);
--sidebar-foreground: var(--mil-ink);
--sidebar-primary: var(--mil-accent-text);
--sidebar-primary-foreground: var(--mil-screen);
--sidebar-accent: var(--mil-on);
--sidebar-accent-foreground: var(--mil-on-ink);
--sidebar-border: var(--mil-lo);
--sidebar-ring: var(--mil-accent-text);
--shadow-card: inset 1px 1px var(--mil-hi), inset -1px -1px var(--mil-lo), 0 3px 0 var(--mil-drop);
--mil-key-shadow: inset 1px 1px var(--mil-key-hi), inset -1px -1px var(--mil-key-side), 0 2px 0 var(--mil-key-side);
--mil-screen-shadow: inset 1px 1px 2px var(--mil-lo), inset -1px -1px var(--mil-hi);
--radius-sm: 0px;
--radius-md: 0px;
--radius-lg: 0px;
--radius-xl: 0px;
}
html[data-webui-target="maibot"].dark {
--mil-shell: #2f2c28;
--mil-panel: #3a3631;
--mil-hi: #4a453f;
--mil-lo: #2a2723;
--mil-drop: #1d1b18;
--mil-line: #171513;
--mil-ink: #ebe4d2;
--mil-print: #b5ad9a;
--mil-screen: #1e221e;
--mil-screen-ink: #e8e2cf;
--mil-key: #4d4841;
--mil-key-side: #2e2b27;
--mil-key-hi: #60594f;
--mil-key-hover: #595249;
--mil-accent-text: #8fd6a0;
--primary-foreground: #2f3a2b;
--sidebar-primary-foreground: #2f3a2b;
--border: #746c5d;
--sidebar-border: #746c5d;
--destructive: #f08a77;
--destructive-foreground: #352019;
--success: #8fd6a0;
--warning: #e5b278;
--log-info: #99bdd8;
--log-success: #8fd6a0;
--log-warn: #e5b278;
--log-error: #f08a77;
}
/* Preserve accessibility preferences above both target palettes. */
html[data-webui-target="maibot"][data-contrast="high"] {
--border: var(--mil-ink);
--sidebar-border: var(--mil-ink);
--muted-foreground: var(--mil-ink);
}
html[data-webui-target="maibot"] :is(.ui-card, [data-ui-surface="panel"], [role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]) {
border: 1px solid var(--mil-line);
border-radius: 0;
background: var(--mil-panel);
color: var(--mil-ink);
box-shadow: var(--shadow-card);
backdrop-filter: none;
}
html[data-webui-target="maibot"] [data-ui-surface="chrome"] {
background: var(--mil-panel);
box-shadow: inset 1px 1px var(--mil-hi), inset -1px -1px var(--mil-lo);
}
html[data-webui-target="maibot"] [data-ui-surface="canvas"] {
border-radius: 0;
box-shadow: none;
}
/* The desktop rail clips a fixed-width inner sidebar. Its separator must
belong to the animated outer edge, not the clipped inner panel. */
html[data-webui-target="maibot"] [data-ui-surface="sidebar"] {
border-inline-end: 1px solid var(--sidebar-border);
}
html[data-webui-target="maibot"] :is([data-ui-control], pre, table) {
border-radius: 0;
background: var(--mil-screen);
color: var(--mil-screen-ink);
box-shadow: var(--mil-screen-shadow);
caret-color: var(--mil-accent-text);
}
html[data-webui-target="maibot"] :is([data-ui-control], input, textarea):focus-visible {
outline: 2px solid var(--ring);
outline-offset: 2px;
}
html[data-webui-target="maibot"] :is(.ui-button, [role="tab"], .ui-nav-item) {
border: 1px solid var(--mil-line);
border-radius: 0;
background: var(--mil-key);
color: var(--mil-ink);
box-shadow: var(--mil-key-shadow);
}
html[data-webui-target="maibot"] :is(.ui-button, [role="tab"], .ui-nav-item):hover:not(:disabled) {
background: var(--mil-key-hover);
}
/* Keep the whole keycap inside the collapsed rail instead of cropping the
expanded key's right edge. Text stays mounted and retains its nowrap rules. */
html[data-webui-target="maibot"] nav[data-collapsed="true"] .ui-nav-item {
width: 3rem;
}
html[data-webui-target="maibot"] :is(.ui-button[data-variant="default"], [role="tab"][aria-selected="true"], .ui-nav-item[aria-current="page"]) {
background: var(--mil-on);
color: var(--mil-on-ink);
box-shadow: inset 1px 1px #c1ebcb, inset -1px -1px var(--mil-on-side), 0 2px 0 var(--mil-on-side);
}
html[data-webui-target="maibot"] .ui-button[data-variant="destructive"] {
background: var(--destructive);
color: var(--destructive-foreground);
}
html[data-webui-target="maibot"] .ui-button[data-variant="default"]:hover:not(:disabled) {
background: color-mix(in srgb, var(--mil-on) 85%, var(--mil-key-hi));
}
html[data-webui-target="maibot"] .ui-button[data-variant="destructive"]:hover:not(:disabled) {
background: color-mix(in srgb, var(--destructive) 90%, var(--mil-ink));
}
html[data-webui-target="maibot"] .ui-button:is([data-variant="ghost"], [data-variant="link"]) {
background: transparent;
border-color: transparent;
box-shadow: none;
}
html[data-webui-target="maibot"] :is(.ui-button, [role="tab"], .ui-nav-item):active:not(:disabled) {
box-shadow: var(--mil-screen-shadow);
scale: 1;
}
html[data-webui-target="maibot"] .ui-nav-item[aria-current="page"] :is(svg, span) {
color: var(--mil-on-ink);
}
html[data-webui-target="maibot"] .ui-nav-highlight {
display: none;
}
html[data-webui-target="maibot"] .ui-segmented {
border-radius: 0;
background: var(--mil-screen);
box-shadow: var(--mil-screen-shadow);
}
html[data-webui-target="maibot"] .ui-segmented-thumb {
border-radius: 0;
background: var(--mil-on);
box-shadow: var(--mil-key-shadow);
}
html[data-webui-target="maibot"] .ui-segmented-thumb span {
color: var(--mil-on-ink);
}
html[data-webui-target="maibot"] [data-ui-decoration] {
display: none;
}
html[data-webui-target="maibot"] ::selection {
background: var(--mil-on);
color: var(--mil-on-ink);
}
html[data-webui-target="maibot"] * {
scrollbar-color: var(--mil-print) var(--mil-shell);
}

View File

@@ -0,0 +1,27 @@
import type { TargetAppearance } from '../registry';
import css from './maibot.css?inline';
import licenseUrl from './assets/Jersey20-OFL.txt?url';
export const maibotAppearance: TargetAppearance = {
css,
licenseUrl,
resolve: (saved, presentation) => ({
...saved,
mode: presentation.mode,
palette: 'default',
accentMode: 'preset',
accentScope: 'global',
darkIntensity: 'soft',
sidebarStyle: 'follow',
background: { ...saved.background, type: 'none' },
fontSans: 'custom',
fontSansCustom:
'"SnowLuma Jersey 20", system-ui, "PingFang SC", "Microsoft YaHei", sans-serif',
fontMono: 'default',
fontMonoCustom: '',
radius: 0,
customCss: '',
cssVars: {},
customPointerSystem: false,
}),
};

View File

@@ -126,7 +126,7 @@ export function SegmentedControl({
<div
role="radiogroup"
aria-label={label}
className={`relative inline-block select-none rounded-[9px] border border-border bg-muted/70 p-[3px] shadow-[inset_0_1px_2px_rgb(0_0_0/0.07)] ${className}`}
className={`ui-segmented relative inline-block select-none rounded-[9px] border border-border bg-muted/70 p-[3px] shadow-[inset_0_1px_2px_rgb(0_0_0/0.07)] ${className}`}
>
<div
className="relative grid"
@@ -150,7 +150,7 @@ export function SegmentedControl({
<motion.div
aria-hidden
className="pointer-events-none absolute inset-y-0 left-0 overflow-hidden rounded-[6px] bg-foreground text-background shadow-[0_1px_2px_rgb(0_0_0/0.28)]"
className="ui-segmented-thumb pointer-events-none absolute inset-y-0 left-0 overflow-hidden rounded-[6px] bg-foreground text-background shadow-[0_1px_2px_rgb(0_0_0/0.28)]"
style={{ width: `${100 / count}%`, x: thumbX }}
initial={false}
>

View File

@@ -55,6 +55,7 @@ export function MainLayout({ status, onLogout, notice, children }: MainLayoutPro
{/* Desktop sidebar (hidden in kiosk) */}
{!isMobile && !kiosk && (
<motion.aside
data-ui-surface="sidebar"
initial={false}
animate={{ width: showCollapsed ? 64 : 248 }}
transition={
@@ -133,6 +134,7 @@ export function MainLayout({ status, onLogout, notice, children }: MainLayoutPro
Depth comes from a soft shadow + the canvas tone sitting on the
(sidebar-toned) chrome, not a border. */}
<div
data-ui-surface="canvas"
className={cn(
'flex min-w-0 flex-1 flex-col overflow-hidden',
!isMobile && !kiosk && 'rounded-tl-2xl',

View File

@@ -137,7 +137,10 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
setNavItems(reconciled.map((i) => (i.id === id ? { ...i, visible: !i.visible } : i)));
return (
<div className="flex h-full w-full flex-col overflow-hidden bg-sidebar text-sidebar-foreground">
<div
data-ui-surface="chrome"
className="flex h-full w-full flex-col overflow-hidden bg-sidebar text-sidebar-foreground"
>
{/* Brand — logo sits in a fixed 48px column centred in the collapsed
rail; the wordmark to its right is clipped (never unmounted) when the
rail narrows. */}
@@ -206,7 +209,7 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
</Reorder.Group>
</div>
) : (
<nav className="flex flex-col gap-1 px-2 py-2">
<nav data-collapsed={collapsed} className="flex flex-col gap-1 px-2 py-2">
{orderedNav.map(({ to, label, icon: Icon, description }) => {
const isActive = pathname === to;
return (
@@ -217,7 +220,7 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
onClick={onItemClick}
aria-current={isActive ? 'page' : undefined}
className={cn(
'group relative flex items-center rounded-lg py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
'ui-nav-item group relative flex items-center rounded-lg py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
isActive
? 'text-sidebar-accent-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground',
@@ -232,7 +235,7 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
<motion.span
layoutId="sidebar-active-pill"
className={cn(
'absolute inset-y-0 rounded-lg bg-sidebar-accent',
'ui-nav-highlight absolute inset-y-0 rounded-lg bg-sidebar-accent',
collapsed ? 'left-0.5 w-11' : 'inset-x-0',
)}
transition={{
@@ -244,7 +247,7 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
{!collapsed && (
<motion.span
layoutId="sidebar-active-bar"
className="absolute left-0 top-1/2 h-5 w-0.5 -translate-y-1/2 rounded-full bg-primary"
className="ui-nav-highlight absolute left-0 top-1/2 h-5 w-0.5 -translate-y-1/2 rounded-full bg-primary"
transition={{
type: 'spring',
stiffness: 380,

View File

@@ -54,7 +54,10 @@ export function TopBar({
);
return (
<header className="z-30 flex min-h-16 shrink-0 items-center gap-[4px] bg-background px-[max(10px,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] pt-[env(safe-area-inset-top)] md:gap-2 md:px-4">
<header
data-ui-surface="chrome"
className="z-30 flex min-h-16 shrink-0 items-center gap-[4px] bg-background px-[max(10px,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] pt-[env(safe-area-inset-top)] md:gap-2 md:px-4"
>
{/* Mobile-only menu trigger. On desktop there's no collapse button — the
sidebar auto-expands on hover/focus, and its boundary with the content
is a soft surface-tone shift, not a hard border. */}

View File

@@ -353,6 +353,7 @@ function LoginShell({
wide?: boolean;
children: ReactNode;
}) {
const { managedBy } = useTheme();
return (
<div
className={cn(
@@ -360,9 +361,10 @@ function LoginShell({
customBg ? 'bg-transparent' : 'bg-background',
)}
>
{fxOn && <LoginWaves />}
{fxOn && !managedBy && <LoginWaves />}
<div
data-ui-decoration=""
className="pointer-events-none absolute inset-0"
style={{
background:
@@ -393,6 +395,7 @@ function LoginShell({
</Card>
<motion.button
style={{ display: managedBy ? 'none' : undefined }}
type="button"
onClick={() => onHelpOpen(true)}
whileHover={reduce ? undefined : { scale: 1.04 }}

View File

@@ -189,6 +189,7 @@ export function SettingsPage() {
function SettingsNav({ tab, onChange }: { tab: SettingsTab; onChange: (t: SettingsTab) => void }) {
return (
<nav
data-ui-surface="panel"
aria-label="设置导航"
className={cn(
'flex flex-wrap gap-1 rounded-xl border bg-card p-1.5',
@@ -518,7 +519,14 @@ function TopbarPanel() {
function AppearancePanel() {
const isDesktop = useDesktopSidebar();
const { appearance, setAppearance, uploadBackground, removeBackground, resolved } = useTheme();
const {
savedAppearance: appearance,
setAppearance,
uploadBackground,
removeBackground,
resolved,
managedBy,
} = useTheme();
const a = appearance;
// A Catppuccin flavor fixes its own light/dark + darkness, so the mode and
// intensity controls are inert while one is active.
@@ -560,205 +568,234 @@ function AppearancePanel() {
return (
<div className="flex flex-col gap-5">
<Group
title="主题"
icon={Sun}
description="配色方案、明暗模式与深色风格。所有改动立即生效并保存到服务器,跨设备同步。"
>
<SettingRow
label="配色方案"
hint="“默认”跟随下方明暗模式;Catppuccin 为整套配色,会自行决定明暗。"
layout="stack"
{managedBy && (
<p className="text-sm leading-relaxed text-muted-foreground" role="status">
外观跟随{managedBy}
。原有配色、字体和背景已保留,退出集成后恢复;缩放与无障碍设置仍可调整。
</p>
)}
<fieldset disabled={!!managedBy} className="contents" aria-label="主题、配色与背景">
<Group
title="主题"
icon={Sun}
description={
managedBy
? '下方显示已保留的个人设置;当前界面外观由宿主管理。'
: '配色方案、明暗模式与深色风格。所有改动立即生效并保存到服务器,跨设备同步。'
}
>
<div className="flex flex-wrap gap-2.5" role="radiogroup" aria-label="配色方案">
{PALETTE_OPTIONS.map((p) => {
const active = a.palette === p.id;
return (
<button
key={p.id}
type="button"
role="radio"
aria-checked={active}
aria-label={p.label}
onClick={() => setAppearance({ palette: p.id })}
className={cn(
'flex w-[5.5rem] flex-col items-center gap-1.5 rounded-xl border p-1.5 transition-[border-color,box-shadow] duration-150 ease-out cursor-pointer outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40',
active
? 'border-primary ring-2 ring-primary/30'
: 'border-border hover:border-foreground/30',
)}
>
<span
className="flex h-11 w-full items-center justify-center rounded-lg"
style={{ backgroundColor: p.preview.bg }}
<SettingRow
label="配色方案"
hint="“默认”跟随下方明暗模式;Catppuccin 为整套配色,会自行决定明暗。"
layout="stack"
>
<div
className="flex flex-wrap gap-2.5"
role="radiogroup"
aria-label="配色方案"
>
{PALETTE_OPTIONS.map((p) => {
const active = a.palette === p.id;
return (
<button
key={p.id}
type="button"
role="radio"
aria-checked={active}
aria-label={p.label}
onClick={() => setAppearance({ palette: p.id })}
className={cn(
'flex w-[5.5rem] flex-col items-center gap-1.5 rounded-xl border p-1.5 transition-[border-color,box-shadow] duration-150 ease-out cursor-pointer outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40',
active
? 'border-primary ring-2 ring-primary/30'
: 'border-border hover:border-foreground/30',
)}
>
<span
className="flex gap-1 rounded-md px-1.5 py-1 shadow-sm"
style={{ backgroundColor: p.preview.surface }}
className="flex h-11 w-full items-center justify-center rounded-lg"
style={{ backgroundColor: p.preview.bg }}
>
{p.preview.dots.map((d, i) => (
<span
key={i}
className="size-1.5 rounded-full"
style={{ backgroundColor: d }}
/>
))}
<span
className="flex gap-1 rounded-md px-1.5 py-1 shadow-sm"
style={{ backgroundColor: p.preview.surface }}
>
{p.preview.dots.map((d, i) => (
<span
key={i}
className="size-1.5 rounded-full"
style={{ backgroundColor: d }}
/>
))}
</span>
</span>
</span>
<span className="text-xs font-medium">{p.label}</span>
</button>
);
})}
</div>
</SettingRow>
<SettingRow
label="显示模式"
hint={paletteFixed ? '当前由 Catppuccin 配色决定明暗。' : undefined}
>
<Segmented
value={a.mode}
options={MODE_OPTIONS}
onChange={(mode) => setAppearance({ mode })}
disabled={paletteFixed}
/>
</SettingRow>
<SettingRow
label="深色强度"
hint={
paletteFixed
? 'Catppuccin 配色自带明暗,无需调节。'
: '“纯黑”将深色背景压到接近纯黑,适合 OLED 屏幕(仅深色模式下可见)。'
}
layout="stack"
>
<Segmented
value={a.darkIntensity}
options={DARK_INTENSITY_OPTIONS}
onChange={(darkIntensity) => setAppearance({ darkIntensity })}
disabled={paletteFixed}
/>
</SettingRow>
</Group>
<span className="text-xs font-medium">{p.label}</span>
</button>
);
})}
</div>
</SettingRow>
<SettingRow
label="显示模式"
hint={
managedBy
? '明暗模式跟随宿主。'
: paletteFixed
? '当前由 Catppuccin 配色决定明暗。'
: undefined
}
>
<Segmented
value={a.mode}
options={MODE_OPTIONS}
onChange={(mode) => setAppearance({ mode })}
disabled={paletteFixed}
/>
</SettingRow>
<SettingRow
label="深色强度"
hint={
managedBy
? '深色材质由宿主外观决定。'
: paletteFixed
? 'Catppuccin 配色自带明暗,无需调节。'
: '“纯黑”将深色背景压到接近纯黑,适合 OLED 屏幕(仅深色模式下可见)。'
}
layout="stack"
>
<Segmented
value={a.darkIntensity}
options={DARK_INTENSITY_OPTIONS}
onChange={(darkIntensity) => setAppearance({ darkIntensity })}
disabled={paletteFixed}
/>
</SettingRow>
</Group>
<Group title="强调色" icon={Palette} description="按钮、链接与高亮使用的主色调。">
<SettingRow label="预设色" layout="stack">
<div className="flex flex-wrap items-center gap-2">
{ACCENTS.map((spec) => {
const active = a.accentMode === 'preset' && a.accentPreset === spec.id;
return (
<button
key={spec.id}
type="button"
onClick={() =>
setAppearance({
accentMode: 'preset',
accentPreset: spec.id,
})
}
title={spec.label}
aria-label={spec.label}
className={cn(
'relative flex size-9 items-center justify-center rounded-full border transition-transform cursor-pointer hover:scale-105',
active
? 'border-foreground/30 ring-2 ring-primary'
: 'border-border',
)}
style={{ backgroundColor: spec.swatch }}
>
{active && (
<Check
className="size-4 text-white drop-shadow-sm"
strokeWidth={3}
/>
)}
</button>
);
})}
<label
title="自定义颜色"
className={cn(
'relative flex size-9 cursor-pointer items-center justify-center overflow-hidden rounded-full border transition-transform hover:scale-105',
a.accentMode === 'custom'
? 'border-foreground/30 ring-2 ring-primary'
: 'border-border',
)}
style={{
background:
<Group title="强调色" icon={Palette} description="按钮、链接与高亮使用的主色调。">
<SettingRow label="预设色" layout="stack">
<div className="flex flex-wrap items-center gap-2">
{ACCENTS.map((spec) => {
const active =
a.accentMode === 'preset' && a.accentPreset === spec.id;
return (
<button
key={spec.id}
type="button"
onClick={() =>
setAppearance({
accentMode: 'preset',
accentPreset: spec.id,
})
}
title={spec.label}
aria-label={spec.label}
className={cn(
'relative flex size-9 items-center justify-center rounded-full border transition-transform cursor-pointer hover:scale-105',
active
? 'border-foreground/30 ring-2 ring-primary'
: 'border-border',
)}
style={{ backgroundColor: spec.swatch }}
>
{active && (
<Check
className="size-4 text-white drop-shadow-sm"
strokeWidth={3}
/>
)}
</button>
);
})}
<label
title="自定义颜色"
className={cn(
'relative flex size-9 cursor-pointer items-center justify-center overflow-hidden rounded-full border transition-transform hover:scale-105',
a.accentMode === 'custom'
? a.accentCustom
: 'conic-gradient(from 0deg, #f43f5e, #f59e0b, #10b981, #0ea5e9, #8b5cf6, #f43f5e)',
}}
>
<input
type="color"
value={toColorInputValue(a.accentCustom)}
onChange={(e) => pickCustomAccent(e.target.value)}
className="absolute inset-0 cursor-pointer opacity-0"
aria-label="自定义强调色"
/>
{a.accentMode === 'custom' && (
<Check
className="pointer-events-none size-4 text-white drop-shadow-sm"
strokeWidth={3}
? 'border-foreground/30 ring-2 ring-primary'
: 'border-border',
)}
style={{
background:
a.accentMode === 'custom'
? a.accentCustom
: 'conic-gradient(from 0deg, #f43f5e, #f59e0b, #10b981, #0ea5e9, #8b5cf6, #f43f5e)',
}}
>
<input
type="color"
value={toColorInputValue(a.accentCustom)}
onChange={(e) => pickCustomAccent(e.target.value)}
className="absolute inset-0 cursor-pointer opacity-0"
aria-label="自定义强调色"
/>
)}
</label>
</div>
</SettingRow>
<SettingRow
label="应用范围"
hint="“仅侧栏”时,按钮等全局元素保持默认蓝,强调色只染侧栏选中项。"
>
<Segmented
value={a.accentScope}
options={SCOPE_OPTIONS}
onChange={(accentScope) => setAppearance({ accentScope })}
/>
</SettingRow>
<SettingRow label="侧栏样式">
<Segmented
value={a.sidebarStyle}
options={SIDEBAR_STYLE_OPTIONS}
onChange={(sidebarStyle) => setAppearance({ sidebarStyle })}
/>
</SettingRow>
</Group>
<BackgroundCard
appearance={a}
setAppearance={setAppearance}
uploadBackground={uploadBackground}
removeBackground={removeBackground}
/>
{a.accentMode === 'custom' && (
<Check
className="pointer-events-none size-4 text-white drop-shadow-sm"
strokeWidth={3}
/>
)}
</label>
</div>
</SettingRow>
<SettingRow
label="应用范围"
hint="“仅侧栏”时,按钮等全局元素保持默认蓝,强调色只染侧栏选中项。"
>
<Segmented
value={a.accentScope}
options={SCOPE_OPTIONS}
onChange={(accentScope) => setAppearance({ accentScope })}
/>
</SettingRow>
<SettingRow label="侧栏样式">
<Segmented
value={a.sidebarStyle}
options={SIDEBAR_STYLE_OPTIONS}
onChange={(sidebarStyle) => setAppearance({ sidebarStyle })}
/>
</SettingRow>
</Group>
<BackgroundCard
appearance={a}
setAppearance={setAppearance}
uploadBackground={uploadBackground}
removeBackground={removeBackground}
/>
</fieldset>
<Group title="排版与界面" icon={Palette} description="字体、圆角、缩放与密度。">
<SettingRow label="界面字体" layout="stack">
<FontField
value={a.fontSans}
custom={a.fontSansCustom}
presets={FONT_SANS_OPTIONS}
onChange={(fontSans) => setAppearance({ fontSans })}
onCustomChange={(fontSansCustom) => setAppearance({ fontSansCustom })}
placeholder="例如:LXGW WenKai, PingFang SC"
/>
</SettingRow>
<SettingRow label="等宽字体" hint="用于日志与代码。" layout="stack">
<FontField
value={a.fontMono}
custom={a.fontMonoCustom}
presets={FONT_MONO_OPTIONS}
onChange={(fontMono) => setAppearance({ fontMono })}
onCustomChange={(fontMonoCustom) => setAppearance({ fontMonoCustom })}
placeholder="例如:Cascadia Code, Sarasa Mono SC"
/>
</SettingRow>
<SettingRow label="圆角">
<Segmented
value={a.radius}
options={RADIUS_OPTIONS.map((r) => ({ value: r.value, label: r.label }))}
onChange={(radius) => setAppearance({ radius })}
/>
</SettingRow>
<fieldset disabled={!!managedBy} className="contents" aria-label="字体与圆角">
<SettingRow label="界面字体" layout="stack">
<FontField
value={a.fontSans}
custom={a.fontSansCustom}
presets={FONT_SANS_OPTIONS}
onChange={(fontSans) => setAppearance({ fontSans })}
onCustomChange={(fontSansCustom) => setAppearance({ fontSansCustom })}
placeholder="例如:LXGW WenKai, PingFang SC"
/>
</SettingRow>
<SettingRow label="等宽字体" hint="用于日志与代码。" layout="stack">
<FontField
value={a.fontMono}
custom={a.fontMonoCustom}
presets={FONT_MONO_OPTIONS}
onChange={(fontMono) => setAppearance({ fontMono })}
onCustomChange={(fontMonoCustom) => setAppearance({ fontMonoCustom })}
placeholder="例如:Cascadia Code, Sarasa Mono SC"
/>
</SettingRow>
<SettingRow label="圆角">
<Segmented
value={a.radius}
options={RADIUS_OPTIONS.map((r) => ({
value: r.value,
label: r.label,
}))}
onChange={(radius) => setAppearance({ radius })}
/>
</SettingRow>
</fieldset>
<SliderSettingRow
label="界面缩放"
hint="整体放大或缩小界面,适合高分屏或视力需要。"
@@ -779,10 +816,12 @@ function AppearancePanel() {
</SettingRow>
</Group>
<ThemeVarsPanel
cssVars={a.cssVars}
onChange={(cssVars) => setAppearance({ cssVars })}
/>
<fieldset disabled={!!managedBy} className="contents" aria-label="主题变量">
<ThemeVarsPanel
cssVars={a.cssVars}
onChange={(cssVars) => setAppearance({ cssVars })}
/>
</fieldset>
<TopbarPanel />
@@ -816,6 +855,7 @@ function AppearancePanel() {
>
<ToggleSwitch
value={a.customPointerSystem}
disabled={!!managedBy}
onChange={(customPointerSystem) => setAppearance({ customPointerSystem })}
ariaLabel="自定义光标"
/>
@@ -1432,7 +1472,7 @@ function validateCss(css: string): string | null {
}
function AdvancedPanel() {
const { appearance, setAppearance } = useTheme();
const { savedAppearance: appearance, setAppearance, managedBy } = useTheme();
const { runAction } = useActionFeedback();
const cssRef = useRef<HTMLTextAreaElement>(null);
const [cssWarn, setCssWarn] = useState<string | null>(null);
@@ -1572,77 +1612,83 @@ function AdvancedPanel() {
return (
<div className="flex flex-col gap-5">
<Card>
<CardHeader className="gap-1">
<CardTitle className="flex items-center gap-2 text-[15px]">
<Code2 className="size-4 text-primary" /> 自定义 CSS
</CardTitle>
<CardDescription className="text-[12px] leading-relaxed">
高级用户可注入自定义样式,登录后全局生效(登录页不受影响)。
若改坏了界面,在地址后加{' '}
<code className="rounded bg-muted px-1 py-0.5 font-mono text-meta">
?safe-mode=1
</code>{' '}
可临时禁用自定义 CSS 进来修复。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-1.5">
<span className="mr-1 text-xs text-muted-foreground">插入模板:</span>
{CSS_SNIPPETS.map((s) => (
<button
key={s.label}
type="button"
onClick={() => insertSnippet(s.css)}
className="inline-flex items-center gap-1 rounded-md border bg-muted/40 px-2 py-1 text-xs font-medium text-muted-foreground transition-colors cursor-pointer outline-none hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/40"
>
<Plus className="size-3" /> {s.label}
</button>
))}
</div>
<Textarea
ref={cssRef}
value={appearance.customCss}
onChange={(e) => {
setAppearance({ customCss: e.target.value });
{managedBy && (
<p className="text-sm text-muted-foreground">
自定义 CSS 已保留,跟随{managedBy}外观期间暂停应用。
</p>
)}
<fieldset disabled={!!managedBy} className="contents" aria-label="自定义 CSS">
<Card>
<CardHeader className="gap-1">
<CardTitle className="flex items-center gap-2 text-[15px]">
<Code2 className="size-4 text-primary" /> 自定义 CSS
</CardTitle>
<CardDescription className="text-[12px] leading-relaxed">
高级用户可注入自定义样式,登录后全局生效(登录页不受影响)。
若改坏了界面,在地址后加{' '}
<code className="rounded bg-muted px-1 py-0.5 font-mono text-meta">
?safe-mode=1
</code>{' '}
可临时禁用自定义 CSS 进来修复。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-1.5">
<span className="mr-1 text-xs text-muted-foreground">插入模板:</span>
{CSS_SNIPPETS.map((s) => (
<button
key={s.label}
type="button"
onClick={() => insertSnippet(s.css)}
className="inline-flex items-center gap-1 rounded-md border bg-muted/40 px-2 py-1 text-xs font-medium text-muted-foreground transition-colors cursor-pointer outline-none hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/40"
>
<Plus className="size-3" /> {s.label}
</button>
))}
</div>
<Textarea
ref={cssRef}
value={appearance.customCss}
onChange={(e) => {
setAppearance({ customCss: e.target.value });
if (cssWarn) {
setCssWarn(null);
}
}}
onBlur={(e) => setCssWarn(validateCss(e.target.value))}
maxLength={50000}
spellCheck={false}
placeholder={
'/* 例如:放大侧栏字号 */\n.text-sidebar-foreground { font-size: 1.05em; }'
}
className="h-64 resize-y rounded-lg bg-card/40 p-3 font-mono text-base leading-relaxed md:text-[12px]"
/>
{cssWarn && (
<p className="flex items-start gap-1.5 text-xs text-warning">
<AlertTriangle className="mt-px size-3.5 shrink-0" /> {cssWarn}
</p>
)}
<div className="flex items-center justify-between gap-2">
<span className="text-meta text-muted-foreground">
{appearance.customCss.length} / 50000 字符
</span>
<Button
variant="ghost"
size="sm"
onClick={() => {
setAppearance({ customCss: '' });
setCssWarn(null);
if (cssWarn) {
setCssWarn(null);
}
}}
disabled={!appearance.customCss}
className="text-destructive hover:text-destructive"
>
<Trash2 className="size-4" /> 清空
</Button>
</div>
</CardContent>
</Card>
onBlur={(e) => setCssWarn(validateCss(e.target.value))}
maxLength={50000}
spellCheck={false}
placeholder={
'/* 例如:放大侧栏字号 */\n.text-sidebar-foreground { font-size: 1.05em; }'
}
className="h-64 resize-y rounded-lg bg-card/40 p-3 font-mono text-base leading-relaxed md:text-[12px]"
/>
{cssWarn && (
<p className="flex items-start gap-1.5 text-xs text-warning">
<AlertTriangle className="mt-px size-3.5 shrink-0" /> {cssWarn}
</p>
)}
<div className="flex items-center justify-between gap-2">
<span className="text-meta text-muted-foreground">
{appearance.customCss.length} / 50000 字符
</span>
<Button
variant="ghost"
size="sm"
onClick={() => {
setAppearance({ customCss: '' });
setCssWarn(null);
}}
disabled={!appearance.customCss}
className="text-destructive hover:text-destructive"
>
<Trash2 className="size-4" /> 清空
</Button>
</div>
</CardContent>
</Card>
</fieldset>
<Card>
<CardHeader className="gap-1">
<CardTitle className="text-[15px]">备份与重置</CardTitle>

View File

@@ -10,12 +10,12 @@ const OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [
];
export function ThemeToggle({ className }: { className?: string }) {
const { appearance, mode, setMode } = useTheme();
const { appearance, mode, setMode, managedBy } = useTheme();
// A Catppuccin flavor fixes light/dark, so this quick toggle would be inert
// (and its pill would desync from the forced scheme) — hide it. Light/dark is
// then changed by switching the palette back to “默认” in settings.
if (paletteResolved(appearance.palette)) {
if (managedBy || paletteResolved(appearance.palette)) {
return null;
}

View File

@@ -50,6 +50,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
className={cn(buttonVariants({ variant, size, press: !isStatic }), className)}
ref={ref}
data-press-scale={isStatic ? undefined : ''}
data-variant={variant ?? 'default'}
{...props}
/>
);

View File

@@ -7,6 +7,7 @@ import {
useMemo,
useRef,
useState,
useSyncExternalStore,
type ReactNode,
} from 'react';
import { flushSync } from 'react-dom';
@@ -14,6 +15,14 @@ import { MotionConfig } from 'motion/react';
import { actionErrorMessage, useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { webuiSessionHeaders } from '@/lib/api/session-headers';
import type { Palette, ThemeMode, UiAppearance, UiBackground } from '@/types';
import { WEBUI_TARGETS, type WebuiPresentation } from '@snowluma/common/webui-target';
import { resolveAppearance } from '@/appearance/registry';
import {
applyPresentationAttributes,
getTargetAppearance,
presentationStore,
subscribeHostAppearance,
} from '@/appearance/runtime';
// Re-export the appearance value types so consumers (settings page etc.) can
// import them straight from the context module.
@@ -745,8 +754,13 @@ function cssVarsCss(a: UiAppearance): string {
return decls ? `:root{${decls}}` : '';
}
function applyAppearance(a: UiAppearance, resolved: 'light' | 'dark'): void {
function applyAppearance(
a: UiAppearance,
resolved: 'light' | 'dark',
presentation: WebuiPresentation | null,
): void {
const root = document.documentElement;
applyPresentationAttributes(presentation);
root.classList.remove('light', 'dark');
root.classList.add(resolved);
@@ -811,7 +825,9 @@ function applyAppearance(a: UiAppearance, resolved: 'light' | 'dark'): void {
// Palette (base/surface tokens) first, then accent (--primary/--ring) — a
// disjoint var set, layered after so it composes with any flavor. The
// operator's variable-panel overrides come last so they win over both.
el.textContent = `${paletteVarsCss(a)}\n${accentVarsCss(a)}\n${cssVarsCss(a)}`;
el.textContent = presentation
? ''
: `${paletteVarsCss(a)}\n${accentVarsCss(a)}\n${cssVarsCss(a)}`;
// Custom CSS — appended AFTER the accent block so it is the last style in
// <head> and can override anything. Skipped under ?safe-mode=1 (escape
@@ -1078,7 +1094,12 @@ function writeCache(a: UiAppearance): void {
// ─── Context ───────────────────────────────────────────────────────────────
interface ThemeContextValue {
/** Effective presentation for components. Never persist this object. */
appearance: UiAppearance;
/** User preferences underneath the deployment overlay. Only these are persisted. */
savedAppearance: UiAppearance;
presentation: WebuiPresentation | null;
managedBy: string | null;
/** True once the first server load attempt has resolved. */
ready: boolean;
resolved: 'light' | 'dark';
@@ -1112,6 +1133,14 @@ function getSystemTheme(): 'light' | 'dark' {
export function ThemeProvider({ children }: { children: ReactNode }) {
const { runAction, startAction } = useActionFeedback();
const [appearance, setAppearanceState] = useState<UiAppearance>(readCache);
const presentation = useSyncExternalStore(
presentationStore.subscribe,
presentationStore.getSnapshot,
);
const effectiveAppearance = useMemo(
() => resolveAppearance(appearance, presentation, getTargetAppearance()),
[appearance, presentation],
);
const [systemTheme, setSystemTheme] = useState<'light' | 'dark'>(getSystemTheme);
const [ready, setReady] = useState(false);
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -1123,8 +1152,10 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
// A Catppuccin flavor fixes light/dark; otherwise honor mode (+ system).
const resolved: 'light' | 'dark' =
paletteResolved(appearance.palette) ??
(appearance.mode === 'system' ? systemTheme : appearance.mode);
paletteResolved(effectiveAppearance.palette) ??
(effectiveAppearance.mode === 'system' ? systemTheme : effectiveAppearance.mode);
useLayoutEffect(() => subscribeHostAppearance(window, presentationStore), []);
// Track the OS theme for `mode: 'system'`.
useEffect(() => {
@@ -1167,11 +1198,11 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
// application doesn't flash. The pre-mount flash is handled by the inline
// bootstrap script in index.html.
useLayoutEffect(() => {
applyAppearance(appearance, resolved);
}, [appearance, resolved]);
applyAppearance(effectiveAppearance, resolved, presentation);
}, [effectiveAppearance, resolved, presentation]);
useLayoutEffect(() => {
applyBackgroundLayer(appearance);
}, [appearance]);
applyBackgroundLayer(effectiveAppearance);
}, [effectiveAppearance]);
// Cancel a pending save when the provider unmounts.
useEffect(
@@ -1358,7 +1389,10 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
const value = useMemo<ThemeContextValue>(
() => ({
appearance,
appearance: effectiveAppearance,
savedAppearance: appearance,
presentation,
managedBy: presentation ? WEBUI_TARGETS[presentation.target].label : null,
ready,
resolved,
setAppearance,
@@ -1366,12 +1400,14 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
removeBackground,
formatClock,
reloadAppearance,
mode: appearance.mode,
mode: effectiveAppearance.mode,
setMode: (m: ThemeMode) => setAppearance({ mode: m }),
pollInterval: appearance.pollInterval,
}),
[
appearance,
effectiveAppearance,
presentation,
ready,
resolved,
setAppearance,

View File

@@ -2,9 +2,19 @@ import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App.tsx';
import { prepareTargetAppearance } from './appearance/runtime';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
);
const root = document.getElementById('root')!;
void prepareTargetAppearance()
.then(() => {
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>,
);
})
.catch((error: unknown) => {
console.error('[SnowLuma appearance] Startup failed', error);
root.textContent = '界面外观加载失败,请刷新重试。详细原因见浏览器控制台。';
});

View File

@@ -0,0 +1,106 @@
import { describe, expect, it, vi } from 'vitest';
import { defaultWebuiPresentation, WEBUI_PRESENTATION_EVENT } from '@snowluma/common/webui-target';
import { createPresentationStore } from '../src/appearance/store';
import { subscribeHostAppearance } from '../src/appearance/runtime';
import { resolveAppearance } from '../src/appearance/registry';
import { maibotAppearance } from '../src/appearance/targets/maibot';
import { DEFAULT_APPEARANCE } from '../src/contexts/ThemeContext';
const initial = defaultWebuiPresentation('maibot');
describe('reversible presentation overlay', () => {
it('retains saved appearance, wallpaper, custom CSS and accessibility preferences', () => {
const saved = structuredClone(DEFAULT_APPEARANCE);
Object.assign(saved, {
customCss: 'body { color: red; }',
palette: 'catppuccin-mocha',
radius: 1,
fontSansCustom: 'My Font',
customPointerSystem: true,
reduceMotion: true,
disableMotion: true,
highContrast: true,
uiScale: 1.2,
});
saved.background.type = 'image';
saved.background.hasImage = true;
const before = structuredClone(saved);
const effective = resolveAppearance(saved, { ...initial, mode: 'light' }, maibotAppearance);
expect(effective).toMatchObject({
mode: 'light',
palette: 'default',
radius: 0,
customCss: '',
background: { type: 'none' },
customPointerSystem: false,
reduceMotion: true,
disableMotion: true,
highContrast: true,
uiScale: 1.2,
});
expect(saved).toEqual(before);
expect(resolveAppearance(saved, null, maibotAppearance)).toBe(saved);
expect(resolveAppearance(saved, null, null)).toBe(saved);
});
it('cannot enable a target through host messages on a standalone deployment', () => {
const store = createPresentationStore(null);
const host = new EventTarget() as Window;
const add = vi.spyOn(host, 'addEventListener');
const cleanup = subscribeHostAppearance(host, store);
store.receive(initial);
expect(store.getSnapshot()).toBeNull();
expect(add).not.toHaveBeenCalled();
cleanup();
});
it('applies the latest of rapid updates synchronously, deduplicates, releases and restores', () => {
const store = createPresentationStore('maibot');
const notify = vi.fn();
const cleanup = store.subscribe(notify);
store.receive(initial);
expect(notify).not.toHaveBeenCalled();
store.receive({ ...initial, mode: 'dark' });
store.receive({ ...initial, mode: 'light' });
expect(store.getSnapshot()?.mode).toBe('light');
store.receive({ version: 1, target: null });
expect(store.getSnapshot()).toBeNull();
store.receive(initial);
expect(store.getSnapshot()).toEqual(initial);
cleanup();
store.receive({ ...initial, mode: 'dark' });
expect(notify).toHaveBeenCalledTimes(4);
});
it('reads pre-mount host state, reports invalid input and cleans up subscriptions', () => {
const store = createPresentationStore('maibot');
const host = new EventTarget() as Window;
host.__SNOWLUMA_HOST_APPEARANCE__ = { ...initial, mode: 'dark' };
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
const cleanup = subscribeHostAppearance(host, store);
try {
expect(store.getSnapshot()?.mode).toBe('dark');
host.dispatchEvent(
new CustomEvent(WEBUI_PRESENTATION_EVENT, {
detail: { ...initial, mode: 'invalid' },
}),
);
expect(error).toHaveBeenCalledOnce();
expect(store.getSnapshot()?.mode).toBe('dark');
host.dispatchEvent(
new CustomEvent(WEBUI_PRESENTATION_EVENT, {
detail: { ...initial, mode: 'light' },
}),
);
expect(store.getSnapshot()?.mode).toBe('light');
cleanup();
host.dispatchEvent(new CustomEvent(WEBUI_PRESENTATION_EVENT, { detail: initial }));
expect(store.getSnapshot()?.mode).toBe('light');
} finally {
cleanup();
error.mockRestore();
}
});
});

View File

@@ -3,11 +3,25 @@ import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import { injectWebuiTarget, resolveWebuiTarget } from '@snowluma/common/webui-target';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
plugins: [tailwindcss(), react()],
plugins: [
tailwindcss(),
react(),
{
name: 'webui-runtime-target',
// Production builds are target-neutral. Core injects the deployment at request time.
apply: 'serve',
transformIndexHtml: {
order: 'pre',
handler: (html) =>
injectWebuiTarget(html, resolveWebuiTarget(process.env.SNOWLUMA_WEBUI_TARGET)),
},
},
],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),