|
| 1 | +import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; |
| 2 | +import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; |
| 3 | +import * as Cause from "effect/Cause"; |
| 4 | +import { act, createElement } from "react"; |
| 5 | +import { create, type ReactTestRenderer } from "react-test-renderer"; |
| 6 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; |
| 7 | + |
| 8 | +import { useQueuedMessageStore, type QueuedComposerMessage } from "../queuedMessageStore"; |
| 9 | +import { sendQueuedMessage } from "./chat/sendQueuedMessage"; |
| 10 | +import { QueuedMessageSender } from "./QueuedMessageSender"; |
| 11 | + |
| 12 | +const io = vi.hoisted(() => ({ |
| 13 | + run: vi.fn(), |
| 14 | + upload: vi.fn(), |
| 15 | + toast: vi.fn(), |
| 16 | + thread: null as unknown, |
| 17 | + shell: { runtimeMode: "full-access", interactionMode: "default" } as Record<string, unknown>, |
| 18 | +})); |
| 19 | +const config = { |
| 20 | + environment: { capabilities: { attachmentUploads: true, inlineMessageContext: true } }, |
| 21 | +}; |
| 22 | +vi.mock("@t3tools/client-runtime/state/runtime", async (load) => ({ |
| 23 | + ...(await load<typeof import("@t3tools/client-runtime/state/runtime")>()), |
| 24 | + runAtomCommand: (...args: unknown[]) => io.run(...args), |
| 25 | +})); |
| 26 | +vi.mock("../rpc/atomRegistry", () => ({ |
| 27 | + appAtomRegistry: { get: () => new Map([["env-a", config]]) }, |
| 28 | +})); |
| 29 | +vi.mock("../state/server", () => ({ environmentServerConfigsAtom: {} })); |
| 30 | +vi.mock("../state/threads", () => ({ |
| 31 | + threadEnvironment: { |
| 32 | + updateMetadata: "metadata", |
| 33 | + setRuntimeMode: "runtime", |
| 34 | + setInteractionMode: "interaction", |
| 35 | + startTurn: "start", |
| 36 | + }, |
| 37 | +})); |
| 38 | +vi.mock("../state/environments", () => ({ |
| 39 | + useEnvironment: () => ({ connection: { phase: "connected" } }), |
| 40 | +})); |
| 41 | +vi.mock("../state/entities", () => ({ |
| 42 | + useThread: () => io.thread, |
| 43 | + useThreadStatus: () => "live", |
| 44 | + useServerConfigs: () => new Map([["env-a", config]]), |
| 45 | + readThreadShell: () => io.shell, |
| 46 | + readThread: () => io.thread, |
| 47 | +})); |
| 48 | +vi.mock("./ui/toast", () => ({ toastManager: { add: (...args: unknown[]) => io.toast(...args) } })); |
| 49 | +vi.mock("../lib/attachmentUploadQueue", () => ({ |
| 50 | + startAttachmentUpload: vi.fn(), |
| 51 | + awaitAttachmentUploads: (...args: unknown[]) => io.upload(...args), |
| 52 | + getUploadedAttachments: () => [ |
| 53 | + { type: "image", id: "uploaded", name: "a.png", mimeType: "image/png", sizeBytes: 4 }, |
| 54 | + ], |
| 55 | + releaseDraftAttachments: vi.fn(), |
| 56 | +})); |
| 57 | + |
| 58 | +const threadRef = scopeThreadRef(EnvironmentId.make("env-a"), ThreadId.make("thread-a")); |
| 59 | +const threadKey = scopedThreadKey(threadRef); |
| 60 | +const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }; |
| 61 | + |
| 62 | +function enqueue(overrides: Partial<QueuedComposerMessage> = {}) { |
| 63 | + return useQueuedMessageStore.getState().enqueue(threadKey, { |
| 64 | + prompt: "follow up", |
| 65 | + images: [], |
| 66 | + files: [], |
| 67 | + terminalContexts: [], |
| 68 | + previewAnnotations: [], |
| 69 | + reviewComments: [], |
| 70 | + sendSettings: { |
| 71 | + modelSelection, |
| 72 | + runtimeMode: "full-access", |
| 73 | + interactionMode: "default", |
| 74 | + promptEffort: null, |
| 75 | + }, |
| 76 | + queuedAfterToolActivityId: null, |
| 77 | + createdAt: "2026-09-25T00:00:00Z", |
| 78 | + ...overrides, |
| 79 | + }); |
| 80 | +} |
| 81 | + |
| 82 | +const commandsRun = () => io.run.mock.calls.map((call) => call[1]); |
| 83 | +const queue = () => useQueuedMessageStore.getState().queuesByThreadKey[threadKey]; |
| 84 | + |
| 85 | +beforeEach(() => { |
| 86 | + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); |
| 87 | + useQueuedMessageStore.setState({ queuesByThreadKey: {}, lastDispatchByThreadKey: {} }); |
| 88 | + io.thread = null; |
| 89 | + io.run.mockReset().mockResolvedValue({ _tag: "Success", value: undefined }); |
| 90 | + io.upload.mockReset().mockResolvedValue(undefined); |
| 91 | + io.toast.mockReset(); |
| 92 | + io.shell = { |
| 93 | + modelSelection, |
| 94 | + branch: null, |
| 95 | + runtimeMode: "full-access", |
| 96 | + interactionMode: "default", |
| 97 | + }; |
| 98 | +}); |
| 99 | + |
| 100 | +afterEach(() => { |
| 101 | + vi.unstubAllGlobals(); |
| 102 | +}); |
| 103 | + |
| 104 | +describe("QueuedMessageSender", () => { |
| 105 | + const thread = ( |
| 106 | + status: string, |
| 107 | + { toolActivityIds = [] as string[], userMessageIds = [] as string[] } = {}, |
| 108 | + ) => ({ |
| 109 | + session: { status, activeTurnId: null, updatedAt: status }, |
| 110 | + activities: toolActivityIds.map((id, index) => ({ |
| 111 | + id, |
| 112 | + kind: "tool.completed", |
| 113 | + sequence: index, |
| 114 | + createdAt: "2026-09-25T00:00:01Z", |
| 115 | + })), |
| 116 | + messages: userMessageIds.map((id) => ({ id, role: "user" })), |
| 117 | + latestTurn: null, |
| 118 | + }); |
| 119 | + let root: ReactTestRenderer | null = null; |
| 120 | + const render = () => |
| 121 | + act(() => { |
| 122 | + if (root) root.update(createElement(QueuedMessageSender)); |
| 123 | + else root = create(createElement(QueuedMessageSender)); |
| 124 | + }); |
| 125 | + afterEach(async () => { |
| 126 | + await act(() => root?.unmount()); |
| 127 | + root = null; |
| 128 | + }); |
| 129 | + |
| 130 | + it("sends a queued message when the turn ends, with no chat view open", async () => { |
| 131 | + enqueue(); |
| 132 | + io.thread = thread("running"); |
| 133 | + await render(); |
| 134 | + expect(commandsRun()).toEqual([]); |
| 135 | + |
| 136 | + io.thread = thread("ready"); |
| 137 | + await render(); |
| 138 | + |
| 139 | + expect(commandsRun()).toEqual(["start"]); |
| 140 | + expect(io.run.mock.calls[0]?.[2]).toMatchObject({ |
| 141 | + environmentId: "env-a", |
| 142 | + input: { threadId: "thread-a", message: { text: "follow up" }, modelSelection }, |
| 143 | + }); |
| 144 | + expect(queue()).toBeUndefined(); |
| 145 | + }); |
| 146 | + |
| 147 | + it("holds the next message until the server picks up the one before it", async () => { |
| 148 | + enqueue({ prompt: "first" }); |
| 149 | + enqueue({ prompt: "second" }); |
| 150 | + io.thread = thread("ready"); |
| 151 | + await render(); |
| 152 | + await render(); |
| 153 | + expect(commandsRun()).toEqual(["start"]); |
| 154 | + |
| 155 | + // The first message started a turn; the second waits for its next tool call. |
| 156 | + io.thread = thread("running", { userMessageIds: ["first"] }); |
| 157 | + await render(); |
| 158 | + expect(commandsRun()).toEqual(["start"]); |
| 159 | + io.thread = thread("running", { userMessageIds: ["first"], toolActivityIds: ["tool-1"] }); |
| 160 | + await render(); |
| 161 | + expect(commandsRun()).toEqual(["start", "start"]); |
| 162 | + }); |
| 163 | + |
| 164 | + it("moves on to the next message after a failed one is cancelled", async () => { |
| 165 | + io.run.mockResolvedValueOnce({ _tag: "Failure", cause: Cause.fail(new Error("offline")) }); |
| 166 | + const first = enqueue({ prompt: "first" }); |
| 167 | + enqueue({ prompt: "second" }); |
| 168 | + io.thread = thread("ready"); |
| 169 | + await render(); |
| 170 | + expect(queue()?.[0]).toMatchObject({ prompt: "first", holdUntilUserAction: true }); |
| 171 | + |
| 172 | + await act(() => { |
| 173 | + useQueuedMessageStore.getState().remove(threadKey, first.id); |
| 174 | + }); |
| 175 | + await render(); |
| 176 | + |
| 177 | + expect(commandsRun()).toEqual(["start", "start"]); |
| 178 | + expect(io.run.mock.calls[1]?.[2]).toMatchObject({ input: { message: { text: "second" } } }); |
| 179 | + }); |
| 180 | +}); |
| 181 | + |
| 182 | +describe("sendQueuedMessage", () => { |
| 183 | + it("saves a mode changed before queueing, then starts the turn", async () => { |
| 184 | + io.shell = { ...io.shell, runtimeMode: "approval-required" }; |
| 185 | + const message = enqueue(); |
| 186 | + |
| 187 | + await sendQueuedMessage(threadRef, message.id); |
| 188 | + |
| 189 | + expect(commandsRun()).toEqual(["runtime", "start"]); |
| 190 | + expect(io.run.mock.calls[1]?.[2]).toMatchObject({ input: { runtimeMode: "full-access" } }); |
| 191 | + expect(queue()).toBeUndefined(); |
| 192 | + }); |
| 193 | + |
| 194 | + it("gives a message back to Stop while its upload runs, without starting a turn", async () => { |
| 195 | + let finishUpload!: () => void; |
| 196 | + io.upload.mockReturnValue(new Promise<void>((resolve) => (finishUpload = resolve))); |
| 197 | + const image = { |
| 198 | + type: "image" as const, |
| 199 | + id: "image-1", |
| 200 | + name: "a.png", |
| 201 | + mimeType: "image/png", |
| 202 | + sizeBytes: 4, |
| 203 | + previewUrl: "data:image/png;base64,AAAA", |
| 204 | + file: new File(["AAAA"], "a.png", { type: "image/png" }), |
| 205 | + }; |
| 206 | + const message = enqueue({ images: [image] }); |
| 207 | + |
| 208 | + const sending = sendQueuedMessage(threadRef, message.id); |
| 209 | + expect(useQueuedMessageStore.getState().drain(threadKey)).toHaveLength(1); |
| 210 | + finishUpload(); |
| 211 | + await sending; |
| 212 | + |
| 213 | + expect(commandsRun()).toEqual([]); |
| 214 | + expect(io.toast).not.toHaveBeenCalled(); |
| 215 | + expect(queue()).toBeUndefined(); |
| 216 | + }); |
| 217 | + |
| 218 | + it("holds a message at the head when the turn start fails", async () => { |
| 219 | + io.run.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("offline")) }); |
| 220 | + enqueue({ prompt: "first" }); |
| 221 | + const second = enqueue({ prompt: "second" }); |
| 222 | + |
| 223 | + await sendQueuedMessage(threadRef, second.id); |
| 224 | + |
| 225 | + expect(queue()?.map((entry) => [entry.prompt, entry.holdUntilUserAction])).toEqual([ |
| 226 | + ["second", true], |
| 227 | + ["first", undefined], |
| 228 | + ]); |
| 229 | + expect(io.toast).toHaveBeenCalledWith(expect.objectContaining({ description: "offline" })); |
| 230 | + }); |
| 231 | +}); |
0 commit comments