feat(chat): unlock paid messages before payment

This commit is contained in:
2026-06-30 18:56:17 +08:00
parent 5f94105bc6
commit e7a9e7abe5
21 changed files with 774 additions and 31 deletions
@@ -53,6 +53,11 @@ function makeChatState(overrides: Partial<ChatState> = {}): ChatState {
lockedHistoryCount: 0,
isUnlockingHistory: false,
unlockHistoryError: null,
isUnlockingMessage: false,
unlockingMessageId: null,
unlockingMessageKind: null,
unlockMessageError: null,
unlockPaywallRequest: null,
...overrides,
};
}
@@ -3,6 +3,7 @@ import { createActor, fromCallback, fromPromise, waitFor } from "xstate";
import {
ChatSendResponse,
UnlockPrivateResponse,
type UiMessage,
} from "@/data/dto/chat";
import { chatMachine } from "@/stores/chat/chat-machine";
@@ -37,6 +38,11 @@ interface UnlockHistoryOutput {
newOffset: number;
}
interface UnlockMessageOutput {
messageId: string;
response: UnlockPrivateResponse;
}
function makeChatSendResponse(): ChatSendResponse {
return ChatSendResponse.from({
reply: "",
@@ -56,10 +62,34 @@ function makeChatSendResponse(): ChatSendResponse {
});
}
function makeUnlockPrivateResponse(
overrides: Partial<Parameters<typeof UnlockPrivateResponse.from>[0]> = {},
): UnlockPrivateResponse {
return UnlockPrivateResponse.from({
unlocked: true,
content: "unlocked content",
reason: "ok",
creditBalance: 90,
creditsCharged: 10,
requiredCredits: 10,
shortfallCredits: 0,
lockDetail: {
locked: false,
showContent: true,
showUpgrade: false,
reason: null,
hint: null,
detail: null,
},
...overrides,
});
}
function createTestChatMachine(
options: {
historyMessages?: UiMessage[];
unlockHistoryOutput?: UnlockHistoryOutput;
unlockMessageOutput?: UnlockMessageOutput;
} = {},
) {
return chatMachine.provide({
@@ -109,6 +139,13 @@ function createTestChatMachine(
newOffset: 0,
...options.unlockHistoryOutput,
})),
unlockMessage: fromPromise<UnlockMessageOutput, { messageId: string }>(
async ({ input }) =>
options.unlockMessageOutput ?? {
messageId: input.messageId,
response: makeUnlockPrivateResponse(),
},
),
},
});
}
@@ -437,6 +474,128 @@ describe("chatMachine transitions", () => {
actor.stop();
});
it("unlocks a single private message without navigating to payment", async () => {
const actor = createActor(
createTestChatMachine({
historyMessages: [
{
id: "msg-private-locked",
content: "",
isFromAI: true,
date: "2026-06-29",
locked: true,
lockReason: "private_message",
lockedPrivate: true,
privateMessageHint: "A private message is waiting.",
},
],
unlockMessageOutput: {
messageId: "msg-private-locked",
response: makeUnlockPrivateResponse({
content: "This is the unlocked private message.",
}),
},
}),
).start();
actor.send({ type: "ChatUserLogin", token: "token" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ userSession: "ready" }),
);
actor.send({
type: "ChatUnlockMessageRequested",
messageId: "msg-private-locked",
kind: "private",
});
await waitFor(actor, (snapshot) =>
snapshot.matches({ userSession: "ready" }),
);
expect(actor.getSnapshot().context.unlockPaywallRequest).toBeNull();
expect(actor.getSnapshot().context.isUnlockingMessage).toBe(false);
expect(actor.getSnapshot().context.messages).toMatchObject([
{
id: "msg-private-locked",
content: "This is the unlocked private message.",
locked: false,
lockReason: null,
lockedPrivate: false,
privateMessageHint: null,
},
]);
actor.stop();
});
it("requests payment when single message unlock lacks credits", async () => {
const actor = createActor(
createTestChatMachine({
historyMessages: [
{
id: "msg-voice-locked",
content: "",
isFromAI: true,
date: "2026-06-29",
audioUrl: "https://example.com/voice.mp3",
locked: true,
lockReason: "voice_message",
privateMessageHint: "A voice message is waiting.",
},
],
unlockMessageOutput: {
messageId: "msg-voice-locked",
response: makeUnlockPrivateResponse({
unlocked: false,
content: "",
reason: "insufficient_balance",
creditBalance: 3,
creditsCharged: 0,
requiredCredits: 10,
shortfallCredits: 7,
lockDetail: {
locked: true,
showContent: false,
showUpgrade: true,
reason: "insufficient_balance",
hint: "Insufficient credits.",
detail: { messageId: "msg-voice-locked" },
},
}),
},
}),
).start();
actor.send({ type: "ChatUserLogin", token: "token" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ userSession: "ready" }),
);
actor.send({
type: "ChatUnlockMessageRequested",
messageId: "msg-voice-locked",
kind: "voice",
});
await waitFor(
actor,
(snapshot) => snapshot.context.unlockPaywallRequest !== null,
);
expect(actor.getSnapshot().context.unlockPaywallRequest).toEqual({
messageId: "msg-voice-locked",
kind: "voice",
reason: "insufficient_balance",
creditBalance: 3,
requiredCredits: 10,
shortfallCredits: 7,
});
expect(actor.getSnapshot().context.isUnlockingMessage).toBe(false);
actor.stop();
});
it("clears the weekly limit prompt after payment succeeds", async () => {
const actor = createActor(createTestChatMachine()).start();
+8
View File
@@ -32,6 +32,10 @@ interface ChatState {
lockedHistoryCount: number;
isUnlockingHistory: boolean;
unlockHistoryError: string | null;
isUnlockingMessage: boolean;
unlockingMessageId: string | null;
unlockMessageError: string | null;
unlockPaywallRequest: MachineContext["unlockPaywallRequest"];
}
const ChatStateCtx = createContext<ChatState | null>(null);
@@ -59,6 +63,10 @@ export function ChatProvider({ children }: ChatProviderProps) {
lockedHistoryCount: state.context.lockedHistoryCount,
isUnlockingHistory: state.context.isUnlockingHistory,
unlockHistoryError: state.context.unlockHistoryError,
isUnlockingMessage: state.context.isUnlockingMessage,
unlockingMessageId: state.context.unlockingMessageId,
unlockMessageError: state.context.unlockMessageError,
unlockPaywallRequest: state.context.unlockPaywallRequest,
}),
[state],
);
+8
View File
@@ -15,6 +15,8 @@
* 设计:所有历史 / 配额相关副作用全部通过派发事件给 chat 机器处理,
* chat-screen 不直接读 AuthStorage(除 token 取值)。
*/
import type { PendingChatUnlockKind } from "@/lib/navigation/chat_unlock_session";
export type ChatEvent =
// 鉴权生命周期(登录态变化后由 ChatAuthSync 派)
| { type: "ChatGuestLogin" }
@@ -24,6 +26,12 @@ export type ChatEvent =
| { type: "ChatSendMessage"; content: string }
| { type: "ChatSendImage"; imageBase64: string }
| { type: "ChatLoadMoreHistory" }
| {
type: "ChatUnlockMessageRequested";
messageId: string;
kind: PendingChatUnlockKind;
}
| { type: "ChatUnlockPaywallNavigationConsumed" }
| { type: "ChatPaymentSucceeded" }
| { type: "ChatUnlockHistoryConfirmed" }
| { type: "ChatUnlockHistoryDismissed" }
+41 -1
View File
@@ -5,7 +5,8 @@
import { fromPromise, fromCallback } from "xstate";
import { MessageQueue } from "@/core/net/message-queue";
import type { ChatSendResponse } from "@/data/dto/chat";
import type { ChatLockDetailData } from "@/data/schemas/chat";
import type { ChatSendResponse, UnlockPrivateResponse } from "@/data/dto/chat";
import { getChatRepository } from "@/data/repositories/chat_repository";
import { Result, Logger } from "@/utils";
@@ -103,6 +104,45 @@ export const unlockHistoryActor = fromPromise<{
};
});
export interface UnlockMessageOutput {
messageId: string;
response: UnlockPrivateResponse;
}
export const unlockMessageActor = fromPromise<
UnlockMessageOutput,
{ messageId: string }
>(async ({ input }) => {
const chatRepo = getChatRepository();
const unlockResult = await chatRepo.unlockPrivateMessage(input.messageId);
if (Result.isErr(unlockResult)) {
log.error("[chat-machine] unlockMessageActor failed", {
messageId: input.messageId,
error: unlockResult.error,
});
throw unlockResult.error;
}
if (unlockResult.data.unlocked) {
const markResult = await chatRepo.markPrivateMessageUnlockedInLocal(
input.messageId,
unlockResult.data.content,
unlockResult.data.lockDetail as ChatLockDetailData,
);
if (Result.isErr(markResult)) {
log.warn("[chat-machine] mark unlocked local message failed", {
messageId: input.messageId,
error: markResult.error,
});
}
}
return {
messageId: input.messageId,
response: unlockResult.data,
};
});
export const httpMessageQueueActor = fromCallback<ChatEvent>(
({ sendBack, receive }) => {
return createMessageQueueActor(sendBack, receive);
+30
View File
@@ -1,4 +1,5 @@
import type { UiMessage } from "@/data/dto/chat";
import type { UnlockMessageOutput } from "./chat-machine.actors";
import { getChatRepository } from "@/data/repositories/chat_repository";
import { ChatSendResponse } from "@/data/dto/chat/chat_send_response";
import { todayString, Result, Logger } from "@/utils";
@@ -142,6 +143,35 @@ export type HttpSendOutput = {
reply: UiMessage | null;
};
export function applySingleUnlockOutput(
messages: readonly UiMessage[],
output: UnlockMessageOutput,
): UiMessage[] {
if (!output.response.unlocked) return [...messages];
return messages.map((message) => {
if (message.id !== output.messageId) return message;
const nextContent =
output.response.content.length > 0
? output.response.content
: message.content;
return {
...message,
content: nextContent,
locked: output.response.lockDetail.locked,
lockReason: output.response.lockDetail.reason,
imagePaywalled: message.imageUrl
? output.response.lockDetail.locked &&
output.response.lockDetail.showUpgrade
: undefined,
lockedPrivate: false,
privateMessageHint: null,
};
});
}
export function beginPendingReply(context: ChatState): Pick<
ChatState,
"isReplyingAI" | "pendingReplyCount"
+108
View File
@@ -36,6 +36,7 @@ import type { ChatEvent } from "./chat-events";
import {
applyHttpSendOutput,
applyHistoryLoadedOutput,
applySingleUnlockOutput,
beginPendingReply,
countLockedHistoryMessages,
finishPendingReply,
@@ -48,6 +49,8 @@ import {
loadMoreHistoryActor,
httpMessageQueueActor,
unlockHistoryActor,
unlockMessageActor,
type UnlockMessageOutput,
} from "./chat-machine.actors";
const log = new Logger("StoresChatChatMachine");
@@ -71,6 +74,7 @@ export const chatMachine = setup({
loadMoreHistory: loadMoreHistoryActor,
httpMessageQueue: httpMessageQueueActor,
unlockHistory: unlockHistoryActor,
unlockMessage: unlockMessageActor,
},
actions: {
enqueueMessage: sendTo("messageQueue", ({ event }) => event),
@@ -242,6 +246,78 @@ export const chatMachine = setup({
unlockHistoryPromptVisible: true,
unlockHistoryError: "Failed to unlock messages. Please try again.",
})),
markUnlockMessageStarted: assign(({ event }) => {
if (event.type !== "ChatUnlockMessageRequested") return {};
return {
isUnlockingMessage: true,
unlockingMessageId: event.messageId,
unlockingMessageKind: event.kind,
unlockMessageError: null,
unlockPaywallRequest: null,
};
}),
applyUnlockMessageSucceeded: assign(({ context, event }) => {
const output = (event as { output?: UnlockMessageOutput }).output;
if (!output) return {};
return {
messages: applySingleUnlockOutput(context.messages, output),
isUnlockingMessage: false,
unlockingMessageId: null,
unlockingMessageKind: null,
unlockMessageError: null,
unlockPaywallRequest: null,
creditBalance: output.response.creditBalance,
creditsCharged: output.response.creditsCharged,
requiredCredits: 0,
shortfallCredits: 0,
};
}),
requestUnlockPaymentFromOutput: assign(({ context, event }) => {
const output = (event as { output?: UnlockMessageOutput }).output;
if (!output) return {};
return {
isUnlockingMessage: false,
unlockingMessageId: null,
unlockingMessageKind: null,
unlockMessageError: output.response.reason,
unlockPaywallRequest: {
messageId: output.messageId,
kind: context.unlockingMessageKind ?? "private",
reason: output.response.reason,
creditBalance: output.response.creditBalance,
requiredCredits: output.response.requiredCredits,
shortfallCredits: output.response.shortfallCredits,
},
creditBalance: output.response.creditBalance,
requiredCredits: output.response.requiredCredits,
shortfallCredits: output.response.shortfallCredits,
};
}),
requestUnlockPaymentFromError: assign(({ context }) => ({
isUnlockingMessage: false,
unlockMessageError: "unlock_failed",
unlockPaywallRequest:
context.unlockingMessageId && context.unlockingMessageKind
? {
messageId: context.unlockingMessageId,
kind: context.unlockingMessageKind,
reason: "unlock_failed",
creditBalance: context.creditBalance,
requiredCredits: context.requiredCredits,
shortfallCredits: context.shortfallCredits,
}
: null,
unlockingMessageId: null,
unlockingMessageKind: null,
})),
clearUnlockPaywallRequest: assign(() => ({
unlockPaywallRequest: null,
})),
},
}).createMachine({
id: "chat",
@@ -389,6 +465,9 @@ export const chatMachine = setup({
ChatUnlockHistoryDismissed: {
actions: "dismissUnlockHistoryPrompt",
},
ChatUnlockPaywallNavigationConsumed: {
actions: "clearUnlockPaywallRequest",
},
},
initial: "initializing",
states: {
@@ -456,6 +535,11 @@ export const chatMachine = setup({
ChatLoadMoreHistory: {
target: "loadingMore",
},
ChatUnlockMessageRequested: {
guard: ({ event }) => event.messageId.trim().length > 0,
target: "unlockingMessage",
actions: "markUnlockMessageStarted",
},
},
},
sendingViaHttp: {
@@ -529,6 +613,30 @@ export const chatMachine = setup({
},
},
},
unlockingMessage: {
invoke: {
id: "unlockMessage",
src: "unlockMessage",
input: ({ context }) => ({
messageId: context.unlockingMessageId ?? "",
}),
onDone: [
{
guard: ({ event }) => event.output.response.unlocked,
target: "ready",
actions: "applyUnlockMessageSucceeded",
},
{
target: "ready",
actions: "requestUnlockPaymentFromOutput",
},
],
onError: {
target: "ready",
actions: "requestUnlockPaymentFromError",
},
},
},
},
},
},
+20
View File
@@ -1,7 +1,17 @@
import type { UiMessage } from "@/data/dto/chat";
import type { PendingChatUnlockKind } from "@/lib/navigation/chat_unlock_session";
export type ChatUpgradeReason = "weekly_limit" | "insufficient_credits";
export interface ChatUnlockPaywallRequest {
messageId: string;
kind: PendingChatUnlockKind;
reason: string;
creditBalance: number;
requiredCredits: number;
shortfallCredits: number;
}
export interface ChatState {
messages: UiMessage[];
isReplyingAI: boolean;
@@ -27,6 +37,11 @@ export interface ChatState {
lockedHistoryCount: number;
isUnlockingHistory: boolean;
unlockHistoryError: string | null;
isUnlockingMessage: boolean;
unlockingMessageId: string | null;
unlockingMessageKind: PendingChatUnlockKind | null;
unlockMessageError: string | null;
unlockPaywallRequest: ChatUnlockPaywallRequest | null;
}
export const initialState: ChatState = {
@@ -50,4 +65,9 @@ export const initialState: ChatState = {
lockedHistoryCount: 0,
isUnlockingHistory: false,
unlockHistoryError: null,
isUnlockingMessage: false,
unlockingMessageId: null,
unlockingMessageKind: null,
unlockMessageError: null,
unlockPaywallRequest: null,
};