Open History to see the last commit
1import {
2 EventId,
3 GuestMessageId,
4 GuestShareId,
5 MessageId,
6 ProviderDriverKind,
7 RunId,
8 TurnItemId,
9 type GuestShareView,
10 type GuestStreamEvent,
11 type OrchestrationV2TurnItem,
12 type ThreadGuestMessage,
13} from "@t3tools/contracts";
14import * as DateTime from "effect/DateTime";
15import { describe, expect, it } from "vite-plus/test";
16
17import { makeThreadProjectionFixture } from "../../test-fixtures";
18import {
19 applyGuestStreamEvent,
20 formatGuestExpiry,
21 guestFilesProblem,
22 initialGuestStreamState,
23 inviteShareId,
24 parseGuestStreamEvent,
25 unplacedGuestMessages,
26 type GuestStreamState,
27} from "./guestStream.logic";
28
29const view: GuestShareView = {
30 shareId: GuestShareId.make("share-1"),
31 title: "Fix login",
32 guestName: "Sam",
33 expiresAt: "2026-10-24T00:00:00.000Z",
34 messages: [],
35 model: { driver: null, name: "gpt-5.4" },
36};
37
38const projection = makeThreadProjectionFixture();
39const now = DateTime.makeUnsafe("2026-10-23T10:00:00.000Z");
40
41const base = {
42 threadId: projection.thread.id,
43 runId: RunId.make("run-1"),
44 nodeId: null,
45 providerThreadId: null,
46 providerTurnId: null,
47 nativeItemRef: null,
48 parentItemId: null,
49 ordinal: 1,
50 status: "completed",
51 title: null,
52 startedAt: now,
53 completedAt: now,
54 updatedAt: now,
55} as const;
56
57const reply = (id: string, text: string): OrchestrationV2TurnItem => ({
58 ...base,
59 id: TurnItemId.make(id),
60 type: "assistant_message",
61 messageId: MessageId.make(id),
62 text,
63 streaming: false,
64});
65
66const guestMessageRow = (id: string, guestMessageId: GuestMessageId): OrchestrationV2TurnItem => ({
67 ...base,
68 id: TurnItemId.make(id),
69 type: "user_message",
70 createdBy: "user",
71 creationSource: "web",
72 messageId: MessageId.make(id),
73 inputIntent: "turn_start",
74 text: "Why?",
75 context: { version: 1, records: [], guest: { guestMessageId, name: "Sam", text: "Why?" } },
76 attachments: [],
77});
78
79const snapshot = (snapshotSequence = 1): GuestStreamEvent => ({
80 type: "thread",
81 item: { kind: "snapshot", snapshotSequence, projection },
82});
83
84const itemEvent = (sequence: number, item: OrchestrationV2TurnItem): GuestStreamEvent => ({
85 type: "thread",
86 item: {
87 kind: "event",
88 sequence,
89 event: {
90 id: EventId.make(`event-${sequence}`),
91 type: "turn-item.updated",
92 threadId: projection.thread.id,
93 driver: ProviderDriverKind.make("codex"),
94 providerInstanceId: projection.thread.providerInstanceId,
95 occurredAt: now,
96 payload: item,
97 },
98 },
99});
100
101const apply = (events: ReadonlyArray<GuestStreamEvent>, state = initialGuestStreamState) =>
102 events.reduce<GuestStreamState>(applyGuestStreamEvent, state);
103
104const itemIds = (state: GuestStreamState) =>
105 state.projection?.visibleTurnItems.map((row) => row.item.id) ?? [];
106
107describe("applyGuestStreamEvent", () => {
108 it("builds the thread from the snapshot and applies each later event once", () => {
109 const once = apply([{ type: "view", view }, snapshot(1), itemEvent(2, reply("a1", "Hi"))]);
110 expect(itemIds(once)).toEqual(["a1"]);
111 // A replayed or older event changes nothing.
112 expect(apply([itemEvent(2, reply("a1", "Changed"))], once)).toBe(once);
113 });
114
115 it("replaces the thread on a new snapshot, as after a reconnect", () => {
116 const before = apply([snapshot(1), itemEvent(2, reply("a1", "Hi")), { type: "ended" }]);
117 const after = apply([snapshot(1)], { ...before, ended: false });
118 expect(itemIds(after)).toEqual([]);
119 });
120
121 it("ends when the view names another link than the page's", () => {
122 const state = apply([
123 { type: "view", view },
124 { type: "view", view: { ...view, shareId: GuestShareId.make("share-2") } },
125 ]);
126 expect(state.ended).toBe(true);
127 expect(state.view?.shareId).toBe(view.shareId);
128 });
129
130 it("remembers a waiting message across a reconnect until its row arrives", () => {
131 const waiting = {
132 id: GuestMessageId.make("m1"),
133 text: "Why?",
134 status: "pending" as const,
135 submittedAt: "2026-10-23T10:00:00.000Z",
136 };
137 const sent = { ...waiting, status: "sent" as const };
138 const queued = apply([
139 { type: "view", view: { ...view, messages: [waiting] } },
140 snapshot(1),
141 { type: "view", view: { ...view, messages: [sent] } },
142 ]);
143 expect([...queued.awaitingRowIds]).toEqual([waiting.id]);
144
145 // Once placed, a later snapshot whose window no longer holds the row must not resurrect it.
146 const placed = apply([itemEvent(2, guestMessageRow("u1", waiting.id)), snapshot(3)], queued);
147 expect(placed.awaitingRowIds.size).toBe(0);
148 });
149});
150
151describe("parseGuestStreamEvent", () => {
152 it("decodes a valid frame and rejects malformed ones", () => {
153 expect(parseGuestStreamEvent(JSON.stringify({ type: "ended" }))).toEqual({ type: "ended" });
154 expect(parseGuestStreamEvent("{not json")).toBeNull();
155 expect(parseGuestStreamEvent(JSON.stringify({ type: "unknown" }))).toBeNull();
156 });
157});
158
159describe("unplacedGuestMessages", () => {
160 const message = (id: string, status: ThreadGuestMessage["status"], submittedAt: string) => ({
161 id: GuestMessageId.make(id),
162 text: id,
163 status,
164 submittedAt,
165 });
166
167 it("shows pending ones, and resolved ones only if this page saw them waiting", () => {
168 const messages = [
169 message("late", "pending", "2026-10-23T10:05:00.000Z"),
170 message("placed", "sent", "2026-10-23T10:00:00.000Z"),
171 message("queued", "sent", "2026-10-23T09:59:00.000Z"),
172 message("dismissed", "dismissed", "2026-10-23T10:01:00.000Z"),
173 message("old-history", "sent", "2026-10-23T09:00:00.000Z"),
174 ];
175 const seen = new Set(
176 ["placed", "queued", "dismissed", "late"].map((id) => GuestMessageId.make(id)),
177 );
178 const items = [
179 {
180 position: 0,
181 visibility: "local" as const,
182 sourceThreadId: projection.thread.id,
183 sourceItemId: TurnItemId.make("u1"),
184 item: guestMessageRow("u1", GuestMessageId.make("placed")),
185 },
186 ];
187 expect(unplacedGuestMessages(messages, items, seen).map((m) => m.id)).toEqual([
188 "queued",
189 "dismissed",
190 "late",
191 ]);
192 });
193});
194
195describe("formatGuestExpiry", () => {
196 const now = Date.parse("2026-10-23T00:00:00.000Z");
197 it("shows whole hours, then minutes, then expired", () => {
198 expect(formatGuestExpiry("2026-10-23T23:59:00.000Z", now)).toBe("23h left");
199 expect(formatGuestExpiry("2026-10-23T00:45:30.000Z", now)).toBe("45m left");
200 expect(formatGuestExpiry("2026-10-23T00:00:00.000Z", now)).toBe("Expired");
201 });
202});
203
204describe("inviteShareId", () => {
205 it("reads the share id before the signature and rejects anything else", () => {
206 expect(inviteShareId("k3J9xQ2mT8vL5nR1pW7yZa.sig")).toBe("k3J9xQ2mT8vL5nR1pW7yZa");
207 expect(inviteShareId("no-signature")).toBeNull();
208 expect(inviteShareId(".sig")).toBeNull();
209 expect(inviteShareId("")).toBeNull();
210 });
211});
212
213describe("guestFilesProblem", () => {
214 const file = (type: string, size = 1) => ({ type, size });
215 it("takes up to four files and 10 MB, with images in the types the owner's composer takes", () => {
216 expect(guestFilesProblem([file("image/png"), file("application/pdf"), file("")])).toBeNull();
217 expect(guestFilesProblem([1, 2, 3, 4, 5].map(() => file("image/png")))).toMatch(/up to 4/);
218 expect(guestFilesProblem([file("image/png", 10 * 1024 * 1024 + 1)])).toMatch(/10 MB/);
219 expect(guestFilesProblem([file("image/svg+xml")])).toMatch(/PNG, JPEG, GIF, or WebP/);
220 expect(guestFilesProblem([file("text/plain", 0)])).toMatch(/cannot be attached/);
221 });
222});