refactor(chat): split machine by business flow
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createActor, fromCallback, waitFor } from "xstate";
|
||||
|
||||
import type { UiMessage } from "@/data/dto/chat";
|
||||
import type { ChatEvent } from "@/stores/chat/chat-events";
|
||||
import { chatMachine } from "@/stores/chat/chat-machine";
|
||||
|
||||
import { createTestChatMachine } from "./chat-machine.test-utils";
|
||||
|
||||
describe("chat history flow", () => {
|
||||
it("enters user ready after history is loaded", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
const snapshot = actor.getSnapshot();
|
||||
expect(snapshot.context.historyLoaded).toBe(true);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("renders local history before network history sync finishes", async () => {
|
||||
let resolveNetwork!: () => void;
|
||||
const networkReleased = new Promise<void>((resolve) => {
|
||||
resolveNetwork = resolve;
|
||||
});
|
||||
const localMessage: UiMessage = {
|
||||
id: "local-msg",
|
||||
content: "cached local message",
|
||||
isFromAI: true,
|
||||
date: "2026-07-02",
|
||||
};
|
||||
const networkMessage: UiMessage = {
|
||||
id: "network-msg",
|
||||
content: "fresh network message",
|
||||
isFromAI: true,
|
||||
date: "2026-07-02",
|
||||
};
|
||||
const machine = chatMachine.provide({
|
||||
actors: {
|
||||
loadHistory: fromCallback<ChatEvent>(({ sendBack }) => {
|
||||
sendBack({
|
||||
type: "ChatLocalHistoryLoaded",
|
||||
output: {
|
||||
messages: [localMessage],
|
||||
localCount: 1,
|
||||
},
|
||||
});
|
||||
void networkReleased.then(() => {
|
||||
sendBack({
|
||||
type: "ChatNetworkHistoryLoaded",
|
||||
output: {
|
||||
messages: [networkMessage],
|
||||
localOverwritten: true,
|
||||
localCount: 1,
|
||||
networkCount: 1,
|
||||
},
|
||||
});
|
||||
});
|
||||
return () => undefined;
|
||||
}),
|
||||
},
|
||||
});
|
||||
const actor = createActor(machine).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.messages).toMatchObject([
|
||||
{ id: "local-msg", content: "cached local message" },
|
||||
]);
|
||||
|
||||
resolveNetwork();
|
||||
await waitFor(
|
||||
actor,
|
||||
(snapshot) => snapshot.context.messages[0]?.id === "network-msg",
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.messages).toMatchObject([
|
||||
{ id: "network-msg", content: "fresh network message" },
|
||||
]);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
import { fromCallback, fromPromise } from "xstate";
|
||||
|
||||
import {
|
||||
ChatSendResponse,
|
||||
UnlockPrivateResponse,
|
||||
type UiMessage,
|
||||
} from "@/data/dto/chat";
|
||||
import { chatMachine } from "@/stores/chat/chat-machine";
|
||||
import type { ChatEvent } from "@/stores/chat/chat-events";
|
||||
import type {
|
||||
UnlockMessageOutput as MachineUnlockMessageOutput,
|
||||
UnlockMessageRequest,
|
||||
} from "@/stores/chat/chat-machine.helpers";
|
||||
|
||||
export interface SendMessageHttpOutput {
|
||||
response: ChatSendResponse;
|
||||
reply: UiMessage | null;
|
||||
}
|
||||
|
||||
export interface UnlockHistoryOutput {
|
||||
unlocked: boolean;
|
||||
reason: string;
|
||||
shortfallCredits: number;
|
||||
messages: UiMessage[];
|
||||
}
|
||||
|
||||
export interface TestUnlockMessageOutput {
|
||||
messageId: string;
|
||||
response: UnlockPrivateResponse;
|
||||
}
|
||||
|
||||
export function makeChatSendResponse(): ChatSendResponse {
|
||||
return ChatSendResponse.from({
|
||||
reply: "",
|
||||
audioUrl: "",
|
||||
messageId: "msg-1",
|
||||
isGuest: false,
|
||||
timestamp: Date.now(),
|
||||
image: { type: null, url: null },
|
||||
lockDetail: {
|
||||
locked: false,
|
||||
reason: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function makeUnlockPrivateResponse(
|
||||
overrides: Partial<Parameters<typeof UnlockPrivateResponse.from>[0]> = {},
|
||||
): UnlockPrivateResponse {
|
||||
return UnlockPrivateResponse.from({
|
||||
unlocked: true,
|
||||
content: "unlocked content",
|
||||
audioUrl: "",
|
||||
reason: "ok",
|
||||
creditBalance: 90,
|
||||
creditsCharged: 10,
|
||||
requiredCredits: 10,
|
||||
shortfallCredits: 0,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
export function createTestChatMachine(
|
||||
options: {
|
||||
historyMessages?: UiMessage[];
|
||||
sendMessageHttpError?: Error;
|
||||
unlockHistoryOutput?: UnlockHistoryOutput;
|
||||
unlockHistoryError?: Error;
|
||||
unlockMessageOutput?: TestUnlockMessageOutput;
|
||||
} = {},
|
||||
) {
|
||||
return chatMachine.provide({
|
||||
actors: {
|
||||
loadHistory: createLoadHistoryCallback(options.historyMessages ?? []),
|
||||
sendMessageHttp: fromPromise<
|
||||
SendMessageHttpOutput,
|
||||
{ content: string }
|
||||
>(async () => {
|
||||
if (options.sendMessageHttpError) {
|
||||
throw options.sendMessageHttpError;
|
||||
}
|
||||
return {
|
||||
response: makeChatSendResponse(),
|
||||
reply: null,
|
||||
};
|
||||
}),
|
||||
httpMessageQueue: fromCallback<ChatEvent>(({ receive, sendBack }) => {
|
||||
receive((event) => {
|
||||
if (event.type !== "ChatSendMessage") return;
|
||||
sendBack({ type: "ChatQueuedSendStarted" });
|
||||
sendBack({
|
||||
type: "ChatQueuedHttpDone",
|
||||
output: {
|
||||
response: makeChatSendResponse(),
|
||||
reply: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
return () => undefined;
|
||||
}),
|
||||
unlockHistory: fromPromise<UnlockHistoryOutput>(async () => {
|
||||
if (options.unlockHistoryError) {
|
||||
throw options.unlockHistoryError;
|
||||
}
|
||||
return {
|
||||
unlocked: true,
|
||||
reason: "ok",
|
||||
shortfallCredits: 0,
|
||||
messages: [],
|
||||
...options.unlockHistoryOutput,
|
||||
};
|
||||
}),
|
||||
unlockMessage: fromPromise<
|
||||
MachineUnlockMessageOutput,
|
||||
UnlockMessageRequest
|
||||
>(async ({ input }) => {
|
||||
const output = options.unlockMessageOutput ?? {
|
||||
messageId: input.messageId ?? input.displayMessageId,
|
||||
response: makeUnlockPrivateResponse(),
|
||||
};
|
||||
return {
|
||||
displayMessageId: input.displayMessageId,
|
||||
request: input,
|
||||
response: output.response,
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function createLoadHistoryCallback(
|
||||
messages: UiMessage[],
|
||||
networkMessages: UiMessage[] = messages,
|
||||
) {
|
||||
return fromCallback<ChatEvent>(({ sendBack }) => {
|
||||
sendBack({
|
||||
type: "ChatLocalHistoryLoaded",
|
||||
output: {
|
||||
messages,
|
||||
localCount: messages.length,
|
||||
},
|
||||
});
|
||||
sendBack({
|
||||
type: "ChatNetworkHistoryLoaded",
|
||||
output: {
|
||||
messages: networkMessages,
|
||||
localOverwritten: true,
|
||||
localCount: messages.length,
|
||||
networkCount: networkMessages.length,
|
||||
},
|
||||
});
|
||||
return () => undefined;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createActor, fromCallback, fromPromise, waitFor } from "xstate";
|
||||
|
||||
import type { ChatEvent } from "@/stores/chat/chat-events";
|
||||
import { chatMachine } from "@/stores/chat/chat-machine";
|
||||
|
||||
import {
|
||||
createLoadHistoryCallback,
|
||||
createTestChatMachine,
|
||||
makeChatSendResponse,
|
||||
type SendMessageHttpOutput,
|
||||
type UnlockHistoryOutput,
|
||||
} from "./chat-machine.test-utils";
|
||||
|
||||
describe("chat send flow", () => {
|
||||
it("allows multiple messages to be queued without leaving ready state", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatSendMessage", content: "hello" });
|
||||
actor.send({ type: "ChatSendMessage", content: "still there?" });
|
||||
|
||||
expect(actor.getSnapshot().matches({ userSession: "ready" })).toBe(true);
|
||||
expect(actor.getSnapshot().context.messages).toMatchObject([
|
||||
{ content: "hello", isFromAI: false },
|
||||
{ content: "still there?", isFromAI: false },
|
||||
]);
|
||||
|
||||
await waitFor(
|
||||
actor,
|
||||
(snapshot) => snapshot.context.pendingReplyCount === 0,
|
||||
);
|
||||
expect(actor.getSnapshot().context.isReplyingAI).toBe(false);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("applies direct HTTP actor output with a type-bound action", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({
|
||||
type: "ChatSendImage",
|
||||
imageBase64: "data:image/png;base64,image",
|
||||
});
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }) &&
|
||||
snapshot.context.pendingReplyCount === 0,
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.isReplyingAI).toBe(false);
|
||||
expect(actor.getSnapshot().context.messages).toMatchObject([
|
||||
{ content: "[Image]", isFromAI: false },
|
||||
]);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("restores ready state when the direct HTTP actor fails", async () => {
|
||||
const actor = createActor(
|
||||
createTestChatMachine({
|
||||
sendMessageHttpError: new Error("send failed"),
|
||||
}),
|
||||
).start();
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({
|
||||
type: "ChatSendImage",
|
||||
imageBase64: "data:image/png;base64,image",
|
||||
});
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.isReplyingAI).toBe(false);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("tracks replying state by queued batch instead of user message count", async () => {
|
||||
const machine = chatMachine.provide({
|
||||
actors: {
|
||||
loadHistory: createLoadHistoryCallback([]),
|
||||
sendMessageHttp: fromPromise<
|
||||
SendMessageHttpOutput,
|
||||
{ content: string }
|
||||
>(async () => ({
|
||||
response: makeChatSendResponse(),
|
||||
reply: null,
|
||||
})),
|
||||
httpMessageQueue: fromCallback<ChatEvent>(({ receive, sendBack }) => {
|
||||
const pending: string[] = [];
|
||||
receive((event) => {
|
||||
if (event.type !== "ChatSendMessage") return;
|
||||
pending.push(event.content);
|
||||
if (pending.length !== 2) return;
|
||||
sendBack({ type: "ChatQueuedSendStarted" });
|
||||
sendBack({
|
||||
type: "ChatQueuedHttpDone",
|
||||
output: {
|
||||
response: makeChatSendResponse(),
|
||||
reply: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
return () => undefined;
|
||||
}),
|
||||
unlockHistory: fromPromise<UnlockHistoryOutput>(async () => ({
|
||||
unlocked: true,
|
||||
reason: "ok",
|
||||
shortfallCredits: 0,
|
||||
messages: [],
|
||||
})),
|
||||
},
|
||||
});
|
||||
const actor = createActor(machine).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatSendMessage", content: "first" });
|
||||
actor.send({ type: "ChatSendMessage", content: "second" });
|
||||
|
||||
await waitFor(
|
||||
actor,
|
||||
(snapshot) => snapshot.context.messages.length === 2,
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.pendingReplyCount).toBe(0);
|
||||
expect(actor.getSnapshot().context.isReplyingAI).toBe(false);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createActor, waitFor } from "xstate";
|
||||
|
||||
import { createTestChatMachine } from "./chat-machine.test-utils";
|
||||
|
||||
describe("chat session flow", () => {
|
||||
it("keeps guest logout disabled and supports user to guest transition", 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: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("allows explicit logout from user session", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatLogout" });
|
||||
expect(actor.getSnapshot().matches("idle")).toBe(true);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("keeps a promotion separate from normal history", async () => {
|
||||
const actor = createActor(
|
||||
createTestChatMachine({
|
||||
historyMessages: [
|
||||
{
|
||||
id: "history-1",
|
||||
content: "Existing history",
|
||||
isFromAI: true,
|
||||
date: "2026-07-13",
|
||||
},
|
||||
],
|
||||
}),
|
||||
).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
actor.send({
|
||||
type: "ChatPromotionInjected",
|
||||
promotion: {
|
||||
promotionType: "voice",
|
||||
lockType: "voice_message",
|
||||
clientLockId: "promotion-1",
|
||||
createdAt: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const context = actor.getSnapshot().context;
|
||||
expect(context.messages).toHaveLength(1);
|
||||
expect(context.promotion?.message).toMatchObject({
|
||||
id: "promotion:promotion-1",
|
||||
locked: true,
|
||||
lockReason: "voice_message",
|
||||
});
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("switches to guest session when guest login arrives during user session", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("ignores repeated user login while an authenticated user session is active", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatSendMessage", content: "keep this message" });
|
||||
await waitFor(
|
||||
actor,
|
||||
(snapshot) => snapshot.context.messages.length === 1,
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "another-token" });
|
||||
|
||||
expect(actor.getSnapshot().matches({ userSession: "ready" })).toBe(true);
|
||||
expect(actor.getSnapshot().context.messages).toMatchObject([
|
||||
{ content: "keep this message", isFromAI: false },
|
||||
]);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
+7
-483
@@ -1,490 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createActor, fromCallback, fromPromise, waitFor } from "xstate";
|
||||
import { createActor, waitFor } from "xstate";
|
||||
|
||||
import { ChatSendResponse } from "@/data/dto/chat";
|
||||
|
||||
import {
|
||||
ChatSendResponse,
|
||||
UnlockPrivateResponse,
|
||||
type UiMessage,
|
||||
} from "@/data/dto/chat";
|
||||
import { chatMachine } from "@/stores/chat/chat-machine";
|
||||
import type { ChatEvent } from "@/stores/chat/chat-events";
|
||||
import type {
|
||||
UnlockMessageOutput as MachineUnlockMessageOutput,
|
||||
UnlockMessageRequest,
|
||||
} from "@/stores/chat/chat-machine.helpers";
|
||||
|
||||
interface SendMessageHttpOutput {
|
||||
response: ChatSendResponse;
|
||||
reply: UiMessage | null;
|
||||
}
|
||||
|
||||
interface UnlockHistoryOutput {
|
||||
unlocked: boolean;
|
||||
reason: string;
|
||||
shortfallCredits: number;
|
||||
messages: UiMessage[];
|
||||
}
|
||||
|
||||
interface TestUnlockMessageOutput {
|
||||
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,
|
||||
reason: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function makeUnlockPrivateResponse(
|
||||
overrides: Partial<Parameters<typeof UnlockPrivateResponse.from>[0]> = {},
|
||||
): UnlockPrivateResponse {
|
||||
return UnlockPrivateResponse.from({
|
||||
unlocked: true,
|
||||
content: "unlocked content",
|
||||
audioUrl: "",
|
||||
reason: "ok",
|
||||
creditBalance: 90,
|
||||
creditsCharged: 10,
|
||||
requiredCredits: 10,
|
||||
shortfallCredits: 0,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
function createTestChatMachine(
|
||||
options: {
|
||||
historyMessages?: UiMessage[];
|
||||
sendMessageHttpError?: Error;
|
||||
unlockHistoryOutput?: UnlockHistoryOutput;
|
||||
unlockHistoryError?: Error;
|
||||
unlockMessageOutput?: TestUnlockMessageOutput;
|
||||
} = {},
|
||||
) {
|
||||
return chatMachine.provide({
|
||||
actors: {
|
||||
loadHistory: createLoadHistoryCallback(options.historyMessages ?? []),
|
||||
sendMessageHttp: fromPromise<
|
||||
SendMessageHttpOutput,
|
||||
{ content: string }
|
||||
>(async () => {
|
||||
if (options.sendMessageHttpError) {
|
||||
throw options.sendMessageHttpError;
|
||||
}
|
||||
return {
|
||||
response: makeChatSendResponse(),
|
||||
reply: null,
|
||||
};
|
||||
}),
|
||||
httpMessageQueue: fromCallback<ChatEvent>(({ receive, sendBack }) => {
|
||||
receive((event) => {
|
||||
if (event.type !== "ChatSendMessage") return;
|
||||
sendBack({ type: "ChatQueuedSendStarted" });
|
||||
sendBack({
|
||||
type: "ChatQueuedHttpDone",
|
||||
output: {
|
||||
response: makeChatSendResponse(),
|
||||
reply: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
return () => undefined;
|
||||
}),
|
||||
unlockHistory: fromPromise<UnlockHistoryOutput>(async () => {
|
||||
if (options.unlockHistoryError) {
|
||||
throw options.unlockHistoryError;
|
||||
}
|
||||
return {
|
||||
unlocked: true,
|
||||
reason: "ok",
|
||||
shortfallCredits: 0,
|
||||
messages: [],
|
||||
...options.unlockHistoryOutput,
|
||||
};
|
||||
}),
|
||||
unlockMessage: fromPromise<
|
||||
MachineUnlockMessageOutput,
|
||||
UnlockMessageRequest
|
||||
>(async ({ input }) => {
|
||||
const output = options.unlockMessageOutput ?? {
|
||||
messageId: input.messageId ?? input.displayMessageId,
|
||||
response: makeUnlockPrivateResponse(),
|
||||
};
|
||||
return {
|
||||
displayMessageId: input.displayMessageId,
|
||||
request: input,
|
||||
response: output.response,
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function createLoadHistoryCallback(
|
||||
messages: UiMessage[],
|
||||
networkMessages: UiMessage[] = messages,
|
||||
) {
|
||||
return fromCallback<ChatEvent>(({ sendBack }) => {
|
||||
sendBack({
|
||||
type: "ChatLocalHistoryLoaded",
|
||||
output: {
|
||||
messages,
|
||||
localCount: messages.length,
|
||||
},
|
||||
});
|
||||
sendBack({
|
||||
type: "ChatNetworkHistoryLoaded",
|
||||
output: {
|
||||
messages: networkMessages,
|
||||
localOverwritten: true,
|
||||
localCount: messages.length,
|
||||
networkCount: networkMessages.length,
|
||||
},
|
||||
});
|
||||
return () => undefined;
|
||||
});
|
||||
}
|
||||
|
||||
describe("chatMachine transitions", () => {
|
||||
it("keeps guest logout disabled and supports user to guest transition", 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: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("allows explicit logout from user session", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatLogout" });
|
||||
expect(actor.getSnapshot().matches("idle")).toBe(true);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("enters user ready after history is loaded", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
const snapshot = actor.getSnapshot();
|
||||
expect(snapshot.context.historyLoaded).toBe(true);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("keeps a promotion separate from normal history", async () => {
|
||||
const actor = createActor(
|
||||
createTestChatMachine({
|
||||
historyMessages: [
|
||||
{
|
||||
id: "history-1",
|
||||
content: "Existing history",
|
||||
isFromAI: true,
|
||||
date: "2026-07-13",
|
||||
},
|
||||
],
|
||||
}),
|
||||
).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
actor.send({
|
||||
type: "ChatPromotionInjected",
|
||||
promotion: {
|
||||
promotionType: "voice",
|
||||
lockType: "voice_message",
|
||||
clientLockId: "promotion-1",
|
||||
createdAt: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const context = actor.getSnapshot().context;
|
||||
expect(context.messages).toHaveLength(1);
|
||||
expect(context.promotion?.message).toMatchObject({
|
||||
id: "promotion:promotion-1",
|
||||
locked: true,
|
||||
lockReason: "voice_message",
|
||||
});
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("renders local history before network history sync finishes", async () => {
|
||||
let resolveNetwork!: () => void;
|
||||
const networkReleased = new Promise<void>((resolve) => {
|
||||
resolveNetwork = resolve;
|
||||
});
|
||||
const localMessage: UiMessage = {
|
||||
id: "local-msg",
|
||||
content: "cached local message",
|
||||
isFromAI: true,
|
||||
date: "2026-07-02",
|
||||
};
|
||||
const networkMessage: UiMessage = {
|
||||
id: "network-msg",
|
||||
content: "fresh network message",
|
||||
isFromAI: true,
|
||||
date: "2026-07-02",
|
||||
};
|
||||
const machine = chatMachine.provide({
|
||||
actors: {
|
||||
loadHistory: fromCallback<ChatEvent>(({ sendBack }) => {
|
||||
sendBack({
|
||||
type: "ChatLocalHistoryLoaded",
|
||||
output: {
|
||||
messages: [localMessage],
|
||||
localCount: 1,
|
||||
},
|
||||
});
|
||||
void networkReleased.then(() => {
|
||||
sendBack({
|
||||
type: "ChatNetworkHistoryLoaded",
|
||||
output: {
|
||||
messages: [networkMessage],
|
||||
localOverwritten: true,
|
||||
localCount: 1,
|
||||
networkCount: 1,
|
||||
},
|
||||
});
|
||||
});
|
||||
return () => undefined;
|
||||
}),
|
||||
},
|
||||
});
|
||||
const actor = createActor(machine).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.messages).toMatchObject([
|
||||
{ id: "local-msg", content: "cached local message" },
|
||||
]);
|
||||
|
||||
resolveNetwork();
|
||||
await waitFor(
|
||||
actor,
|
||||
(snapshot) => snapshot.context.messages[0]?.id === "network-msg",
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.messages).toMatchObject([
|
||||
{ id: "network-msg", content: "fresh network message" },
|
||||
]);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("switches to guest session when guest login arrives during user session", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("ignores repeated user login while an authenticated user session is active", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatSendMessage", content: "keep this message" });
|
||||
await waitFor(
|
||||
actor,
|
||||
(snapshot) => snapshot.context.messages.length === 1,
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "another-token" });
|
||||
|
||||
expect(actor.getSnapshot().matches({ userSession: "ready" })).toBe(true);
|
||||
expect(actor.getSnapshot().context.messages).toMatchObject([
|
||||
{ content: "keep this message", isFromAI: false },
|
||||
]);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("allows multiple messages to be queued without leaving ready state", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatSendMessage", content: "hello" });
|
||||
actor.send({ type: "ChatSendMessage", content: "still there?" });
|
||||
|
||||
expect(actor.getSnapshot().matches({ userSession: "ready" })).toBe(true);
|
||||
expect(actor.getSnapshot().context.messages).toMatchObject([
|
||||
{ content: "hello", isFromAI: false },
|
||||
{ content: "still there?", isFromAI: false },
|
||||
]);
|
||||
|
||||
await waitFor(
|
||||
actor,
|
||||
(snapshot) => snapshot.context.pendingReplyCount === 0,
|
||||
);
|
||||
expect(actor.getSnapshot().context.isReplyingAI).toBe(false);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("applies direct HTTP actor output with a type-bound action", async () => {
|
||||
const actor = createActor(createTestChatMachine()).start();
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({
|
||||
type: "ChatSendImage",
|
||||
imageBase64: "data:image/png;base64,image",
|
||||
});
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }) &&
|
||||
snapshot.context.pendingReplyCount === 0,
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.isReplyingAI).toBe(false);
|
||||
expect(actor.getSnapshot().context.messages).toMatchObject([
|
||||
{ content: "[Image]", isFromAI: false },
|
||||
]);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("restores ready state when the direct HTTP actor fails", async () => {
|
||||
const actor = createActor(
|
||||
createTestChatMachine({
|
||||
sendMessageHttpError: new Error("send failed"),
|
||||
}),
|
||||
).start();
|
||||
|
||||
actor.send({ type: "ChatGuestLogin" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({
|
||||
type: "ChatSendImage",
|
||||
imageBase64: "data:image/png;base64,image",
|
||||
});
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ guestSession: "ready" }),
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.isReplyingAI).toBe(false);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it("tracks replying state by queued batch instead of user message count", async () => {
|
||||
const machine = chatMachine.provide({
|
||||
actors: {
|
||||
loadHistory: createLoadHistoryCallback([]),
|
||||
sendMessageHttp: fromPromise<
|
||||
SendMessageHttpOutput,
|
||||
{ content: string }
|
||||
>(async () => ({
|
||||
response: makeChatSendResponse(),
|
||||
reply: null,
|
||||
})),
|
||||
httpMessageQueue: fromCallback<ChatEvent>(({ receive, sendBack }) => {
|
||||
const pending: string[] = [];
|
||||
receive((event) => {
|
||||
if (event.type !== "ChatSendMessage") return;
|
||||
pending.push(event.content);
|
||||
if (pending.length !== 2) return;
|
||||
sendBack({ type: "ChatQueuedSendStarted" });
|
||||
sendBack({
|
||||
type: "ChatQueuedHttpDone",
|
||||
output: {
|
||||
response: makeChatSendResponse(),
|
||||
reply: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
return () => undefined;
|
||||
}),
|
||||
unlockHistory: fromPromise<UnlockHistoryOutput>(async () => ({
|
||||
unlocked: true,
|
||||
reason: "ok",
|
||||
shortfallCredits: 0,
|
||||
messages: [],
|
||||
})),
|
||||
},
|
||||
});
|
||||
const actor = createActor(machine).start();
|
||||
|
||||
actor.send({ type: "ChatUserLogin", token: "token" });
|
||||
await waitFor(actor, (snapshot) =>
|
||||
snapshot.matches({ userSession: "ready" }),
|
||||
);
|
||||
|
||||
actor.send({ type: "ChatSendMessage", content: "first" });
|
||||
actor.send({ type: "ChatSendMessage", content: "second" });
|
||||
|
||||
await waitFor(
|
||||
actor,
|
||||
(snapshot) => snapshot.context.messages.length === 2,
|
||||
);
|
||||
|
||||
expect(actor.getSnapshot().context.pendingReplyCount).toBe(0);
|
||||
expect(actor.getSnapshot().context.isReplyingAI).toBe(false);
|
||||
|
||||
actor.stop();
|
||||
});
|
||||
createTestChatMachine,
|
||||
makeUnlockPrivateResponse,
|
||||
} from "./chat-machine.test-utils";
|
||||
|
||||
describe("chat unlock flow", () => {
|
||||
it("prompts before unlocking multiple locked history messages after payment", async () => {
|
||||
const actor = createActor(
|
||||
createTestChatMachine({
|
||||
Reference in New Issue
Block a user