test(stores): add state machine coverage
This commit is contained in:
@@ -0,0 +1,234 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ChatSendResponse } from "@/data/dto/chat/chat_send_response";
|
||||
import type { ChatState } from "@/stores/chat/chat-state";
|
||||
import {
|
||||
applyHttpSendOutput,
|
||||
localMessagesToUi,
|
||||
sendResponseToUiMessage,
|
||||
} from "@/stores/chat/chat-machine.helpers";
|
||||
|
||||
function makeResponse(
|
||||
overrides: Partial<Parameters<typeof ChatSendResponse.from>[0]> = {},
|
||||
): ChatSendResponse {
|
||||
return ChatSendResponse.from({
|
||||
reply: "AI reply",
|
||||
audioUrl: "",
|
||||
messageId: "msg-1",
|
||||
isGuest: false,
|
||||
timestamp: 1782356425363,
|
||||
image: { type: null, url: null },
|
||||
lockDetail: {
|
||||
locked: false,
|
||||
showContent: true,
|
||||
showUpgrade: false,
|
||||
reason: null,
|
||||
hint: null,
|
||||
detail: null,
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
function makeChatState(overrides: Partial<ChatState> = {}): ChatState {
|
||||
return {
|
||||
messages: [],
|
||||
isReplyingAI: true,
|
||||
wsConnected: false,
|
||||
upgradePromptVisible: false,
|
||||
upgradeReason: null,
|
||||
upgradeHint: null,
|
||||
upgradeDetail: null,
|
||||
unlockingPrivateMessageId: null,
|
||||
isLoadingMore: false,
|
||||
hasMore: true,
|
||||
historyOffset: 0,
|
||||
historyLoaded: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("sendResponseToUiMessage", () => {
|
||||
it("maps locked voice messages without treating them as private text", () => {
|
||||
const message = sendResponseToUiMessage(
|
||||
makeResponse({
|
||||
audioUrl:
|
||||
"https://proapi.banlv-ai.com/audio/5198b93c-2915-406a.mp3",
|
||||
lockDetail: {
|
||||
locked: true,
|
||||
showContent: false,
|
||||
showUpgrade: true,
|
||||
reason: "voice_message",
|
||||
hint: "这语气好撩呀,让人有点心跳加速呢…",
|
||||
detail: { messageId: "msg-1" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(message.content).toBe("");
|
||||
expect(message.audioUrl).toBe(
|
||||
"https://proapi.banlv-ai.com/audio/5198b93c-2915-406a.mp3",
|
||||
);
|
||||
expect(message.locked).toBe(true);
|
||||
expect(message.lockReason).toBe("voice_message");
|
||||
expect(message.lockedPrivate).toBeUndefined();
|
||||
expect(message.privateMessageHint).toBe(
|
||||
"这语气好撩呀,让人有点心跳加速呢…",
|
||||
);
|
||||
});
|
||||
|
||||
it("maps locked private text messages as private messages", () => {
|
||||
const message = sendResponseToUiMessage(
|
||||
makeResponse({
|
||||
lockDetail: {
|
||||
locked: true,
|
||||
showContent: false,
|
||||
showUpgrade: true,
|
||||
reason: "private_message",
|
||||
hint: "Elio has a private message for you.",
|
||||
detail: { messageId: "msg-1" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(message.content).toBe("");
|
||||
expect(message.locked).toBe(true);
|
||||
expect(message.lockReason).toBe("private_message");
|
||||
expect(message.isPrivate).toBe(true);
|
||||
expect(message.lockedPrivate).toBe(true);
|
||||
expect(message.privateMessageHint).toBe(
|
||||
"Elio has a private message for you.",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps paywalled image messages visible but locked", () => {
|
||||
const message = sendResponseToUiMessage(
|
||||
makeResponse({
|
||||
image: {
|
||||
type: "jpg",
|
||||
url: "https://example.com/private-photo.jpg",
|
||||
},
|
||||
lockDetail: {
|
||||
locked: true,
|
||||
showContent: false,
|
||||
showUpgrade: true,
|
||||
reason: "image",
|
||||
hint: "Activate VIP to view the full photo.",
|
||||
detail: { imageId: "image-1" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(message.content).toBe("");
|
||||
expect(message.imageUrl).toBe("https://example.com/private-photo.jpg");
|
||||
expect(message.imagePaywalled).toBe(true);
|
||||
expect(message.locked).toBe(true);
|
||||
expect(message.lockReason).toBe("image");
|
||||
expect(message.lockedPrivate).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyHttpSendOutput", () => {
|
||||
it("removes the optimistic user message when the daily limit is reached", () => {
|
||||
const context = makeChatState({
|
||||
messages: [
|
||||
{
|
||||
content: "hello",
|
||||
isFromAI: false,
|
||||
date: "2026-06-25",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const nextState = applyHttpSendOutput(context, {
|
||||
response: makeResponse({
|
||||
reply: "",
|
||||
messageId: "",
|
||||
lockDetail: {
|
||||
locked: true,
|
||||
showContent: false,
|
||||
showUpgrade: true,
|
||||
reason: "daily_limit",
|
||||
hint: "Free message limit reached.",
|
||||
detail: {
|
||||
type: "daily_msg_limit",
|
||||
usedToday: 3,
|
||||
limit: 3,
|
||||
},
|
||||
},
|
||||
}),
|
||||
reply: null,
|
||||
});
|
||||
|
||||
expect(nextState.messages).toEqual([]);
|
||||
expect(nextState.isReplyingAI).toBe(false);
|
||||
expect(nextState.upgradePromptVisible).toBe(true);
|
||||
expect(nextState.upgradeReason).toBe("daily_limit");
|
||||
expect(nextState.upgradeHint).toBeNull();
|
||||
expect(nextState.upgradeDetail).toEqual({
|
||||
type: "daily_msg_limit",
|
||||
usedToday: 3,
|
||||
limit: 3,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("localMessagesToUi", () => {
|
||||
it("maps locked voice messages from history", () => {
|
||||
const [message] = localMessagesToUi([
|
||||
{
|
||||
id: "voice-1",
|
||||
role: "assistant",
|
||||
type: "voice",
|
||||
content: "hidden voice transcript",
|
||||
createdAt: "2026-06-25T12:00:00.000Z",
|
||||
audioUrl: "https://example.com/voice.mp3",
|
||||
image: { type: null, url: null },
|
||||
lockDetail: {
|
||||
locked: true,
|
||||
showContent: false,
|
||||
showUpgrade: true,
|
||||
reason: "voice_message",
|
||||
hint: "A locked voice message is waiting.",
|
||||
detail: { messageId: "voice-1" },
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(message.content).toBe("");
|
||||
expect(message.audioUrl).toBe("https://example.com/voice.mp3");
|
||||
expect(message.locked).toBe(true);
|
||||
expect(message.lockReason).toBe("voice_message");
|
||||
expect(message.lockedPrivate).toBeUndefined();
|
||||
expect(message.privateMessageHint).toBe("A locked voice message is waiting.");
|
||||
});
|
||||
|
||||
it("hides text content for image history messages", () => {
|
||||
const [message] = localMessagesToUi([
|
||||
{
|
||||
id: "image-1",
|
||||
role: "assistant",
|
||||
type: "image",
|
||||
content: "This text should not render with an image.",
|
||||
createdAt: "2026-06-25T12:00:00.000Z",
|
||||
audioUrl: null,
|
||||
image: {
|
||||
type: "jpg",
|
||||
url: "https://example.com/image.jpg",
|
||||
},
|
||||
lockDetail: {
|
||||
locked: false,
|
||||
showContent: true,
|
||||
showUpgrade: false,
|
||||
reason: null,
|
||||
hint: null,
|
||||
detail: null,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(message.content).toBe("");
|
||||
expect(message.imageUrl).toBe("https://example.com/image.jpg");
|
||||
expect(message.imagePaywalled).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createActor, fromCallback, fromPromise, waitFor } from "xstate";
|
||||
|
||||
import {
|
||||
ChatSendResponse,
|
||||
UnlockPrivateResponse,
|
||||
type UiMessage,
|
||||
} from "@/data/dto/chat";
|
||||
import { chatMachine } from "@/stores/chat/chat-machine";
|
||||
|
||||
interface LoadHistoryOutput {
|
||||
messages: UiMessage[];
|
||||
hasMore: boolean;
|
||||
newOffset: number;
|
||||
localOverwritten: boolean;
|
||||
localCount: number;
|
||||
networkCount: number;
|
||||
}
|
||||
|
||||
interface LoadMoreHistoryOutput {
|
||||
messages: UiMessage[];
|
||||
hasMore: boolean;
|
||||
newOffset: number;
|
||||
}
|
||||
|
||||
interface SendMessageHttpOutput {
|
||||
response: ChatSendResponse;
|
||||
reply: UiMessage | null;
|
||||
}
|
||||
|
||||
interface UnlockPrivateOutput {
|
||||
messageId: string;
|
||||
response: UnlockPrivateResponse;
|
||||
}
|
||||
|
||||
function makeChatSendResponse(): ChatSendResponse {
|
||||
return ChatSendResponse.from({
|
||||
reply: "",
|
||||
audioUrl: "",
|
||||
messageId: "msg-1",
|
||||
isGuest: false,
|
||||
timestamp: Date.now(),
|
||||
image: { type: null, url: null },
|
||||
lockDetail: {
|
||||
locked: false,
|
||||
showContent: true,
|
||||
showUpgrade: false,
|
||||
reason: null,
|
||||
hint: null,
|
||||
detail: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function createTestChatMachine(
|
||||
options: {
|
||||
historyMessages?: UiMessage[];
|
||||
unlockedContent?: string;
|
||||
} = {},
|
||||
) {
|
||||
return chatMachine.provide({
|
||||
actors: {
|
||||
loadHistory: fromPromise<LoadHistoryOutput>(async () => ({
|
||||
messages: options.historyMessages ?? [],
|
||||
hasMore: false,
|
||||
newOffset: 0,
|
||||
localOverwritten: true,
|
||||
localCount: 0,
|
||||
networkCount: 0,
|
||||
})),
|
||||
loadMoreHistory: fromPromise<LoadMoreHistoryOutput, { offset: number }>(
|
||||
async () => ({
|
||||
messages: [],
|
||||
hasMore: false,
|
||||
newOffset: 0,
|
||||
}),
|
||||
),
|
||||
sendMessageHttp: fromPromise<
|
||||
SendMessageHttpOutput,
|
||||
{ content: string }
|
||||
>(async () => ({
|
||||
response: makeChatSendResponse(),
|
||||
reply: null,
|
||||
})),
|
||||
sendMessageWs: fromPromise<void, { content: string }>(async () => {}),
|
||||
unlockPrivateMessage: fromPromise<
|
||||
UnlockPrivateOutput,
|
||||
{ messageId: string }
|
||||
>(async ({ input }) => ({
|
||||
messageId: input.messageId,
|
||||
response: UnlockPrivateResponse.from({
|
||||
unlocked: true,
|
||||
content: options.unlockedContent ?? "unlocked",
|
||||
showUpgrade: false,
|
||||
paywallTriggered: false,
|
||||
privateFreeLimit: 0,
|
||||
privateUsedToday: 0,
|
||||
reason: "ok",
|
||||
}),
|
||||
})),
|
||||
chatWebSocket: fromCallback(({ sendBack }) => {
|
||||
sendBack({
|
||||
type: "ChatWebSocketConnected",
|
||||
userId: "user-1",
|
||||
});
|
||||
return () => undefined;
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("chatMachine transitions", () => {
|
||||
it("keeps guest logout disabled while allowing upgrade to non-VIP login", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatLogout" });
|
||||
expect(actor.getSnapshot().matches({ guestSession: "ready" })).toBe(true);
|
||||
|
||||
actor.send({ type: "ChatNonVipLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ nonVipUserSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatLogout" });
|
||||
expect(actor.getSnapshot().matches("idle")).toBe(true);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("enters VIP ready only after history and websocket are ready", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatVipLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ vipUserSession: "ready" }),
|
||||
);
|
||||
|
||||
const snapshot = actor.getSnapshot();
|
||||
expect(snapshot.context.historyLoaded).toBe(true);
|
||||
expect(snapshot.context.wsConnected).toBe(true);
|
||||
|
||||
actor.send({ type: "ChatNonVipLogin", token: "token" });
|
||||
await waitFor(actor, (nextSnapshot) =>
|
||||
nextSnapshot.matches({ nonVipUserSession: "ready" }),
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.wsConnected).toBe(false);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("ignores guest login while an authenticated user session is active", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatNonVipLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ nonVipUserSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
expect(actor.getSnapshot().matches({ nonVipUserSession: "ready" })).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatVipLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ vipUserSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
expect(actor.getSnapshot().matches({ vipUserSession: "ready" })).toBe(true);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("unlocks a locked private message and clears unlocking state", async () => {
|
||||
const actor = createActor(
|
||||
createTestChatMachine({
|
||||
historyMessages: [
|
||||
{
|
||||
id: "private-1",
|
||||
content: "",
|
||||
isFromAI: true,
|
||||
date: "2026-06-25",
|
||||
locked: true,
|
||||
lockReason: "private_message",
|
||||
isPrivate: true,
|
||||
lockedPrivate: true,
|
||||
privateMessageHint: "A private message is waiting.",
|
||||
},
|
||||
],
|
||||
unlockedContent: "Here is the unlocked private message.",
|
||||
}),
|
||||
).start();
|
||||
|
||||
actor.send({ type: "ChatNonVipLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ nonVipUserSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatUnlockPrivateMessage", messageId: "private-1" });
|
||||
await waitFor(
|
||||
actor,
|
||||
(snapshot) =>
|
||||
snapshot.context.messages[0]?.content ===
|
||||
"Here is the unlocked private message.",
|
||||
);
|
||||
|
||||
const [message] = actor.getSnapshot().context.messages;
|
||||
expect(message.content).toBe("Here is the unlocked private message.");
|
||||
expect(message.locked).toBe(false);
|
||||
expect(message.lockedPrivate).toBe(false);
|
||||
expect(message.privateMessageHint).toBeNull();
|
||||
expect(actor.getSnapshot().context.unlockingPrivateMessageId).toBeNull();
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user