Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import { RunId, ThreadId } from "@t3tools/contracts";
3import * as Effect from "effect/Effect";
4
5import { readLatestMessages, type ThreadTools, waitForRun } from "./thread.ts";
6
7const threadId = ThreadId.make("thread-1");
8const runId = RunId.make("run-1");
9
10/** Answers each tool call with the next scripted response for that tool. */
11const scriptedTools = (script: Record<string, Array<unknown>>) => {
12 const calls: Array<{ readonly tool: string; readonly args: unknown }> = [];
13 const call = ((tool: string, args: unknown) => {
14 calls.push({ tool, args });
15 const next = script[tool]?.shift();
16 return next === undefined ? Effect.die(`unscripted ${tool} call`) : Effect.succeed(next);
17 }) as ThreadTools["call"];
18 return { tools: { call } satisfies ThreadTools, calls };
19};
20
21it.effect("--wait follows the sent run to its continuation's terminal status", () =>
22 Effect.gen(function* () {
23 const continuation = RunId.make("run-2");
24 const { tools, calls } = scriptedTools({
25 t3_thread_wait: [
26 { threadId, runId, status: "running", timedOut: true },
27 { threadId, runId: continuation, status: "failed", timedOut: false },
28 ],
29 t3_thread_read: [{ thread: { pendingRequestCount: 0 } }],
30 });
31
32 const outcome = yield* waitForRun(tools, threadId, runId);
33
34 assert.deepStrictEqual(outcome, { type: "ended", runId: continuation, status: "failed" });
35 assert.deepStrictEqual(
36 calls.filter((entry) => entry.tool === "t3_thread_wait").map((entry) => entry.args),
37 [
38 { threadId, runId, timeoutMs: 15_000 },
39 { threadId, runId, timeoutMs: 15_000 },
40 ],
41 );
42 }),
43);
44
45it.effect("--wait stops when the thread waits for an answer instead of polling forever", () =>
46 Effect.gen(function* () {
47 const { tools } = scriptedTools({
48 t3_thread_wait: [
49 { threadId, runId, status: "queued", timedOut: true },
50 { threadId, runId, status: "queued", timedOut: true },
51 ],
52 t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
53 });
54
55 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), { type: "needs_input" });
56 }),
57);
58
59it.effect("--wait reports its run's result when a later run is the one waiting", () =>
60 Effect.gen(function* () {
61 const { tools } = scriptedTools({
62 t3_thread_wait: [
63 { threadId, runId, status: "running", timedOut: true },
64 { threadId, runId, status: "completed", timedOut: false },
65 ],
66 t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
67 });
68
69 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), {
70 type: "ended",
71 runId,
72 status: "completed",
73 });
74 }),
75);
76
77/** Serves t3_thread_read pages the way the server does: positions count every item. */
78const timelineTools = (types: ReadonlyArray<string>) => {
79 const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type }));
80 const served: Array<number> = [];
81 const call = ((_tool: string, input: unknown) => {
82 const args = input as { readonly afterPosition?: number; readonly limit: number };
83 // Scanning one match past the page keeps reads of huge fixtures linear.
84 const matching: typeof items = [];
85 for (let position = (args.afterPosition ?? -1) + 1; position < items.length; position++) {
86 const item = items[position]!;
87 if (["user_message", "assistant_message", "proposed_plan"].includes(item.type)) {
88 matching.push(item);
89 if (matching.length > args.limit) break;
90 }
91 }
92 const page = matching.slice(0, args.limit);
93 served.push(page.length);
94 return Effect.succeed({
95 thread: { itemCount: items.length },
96 items: page,
97 nextPosition: page.at(-1)?.position ?? null,
98 hasMore: matching.length > page.length,
99 });
100 }) as ThreadTools["call"];
101 const latest = (count: number) =>
102 items
103 .filter((item) => item.type === "user_message" || item.type === "assistant_message")
104 .slice(-count)
105 .map((item) => item.itemId);
106 return { tools: { call } satisfies ThreadTools, served, latest };
107};
108
109const tail = (tools: number) => [...Array<string>(tools).fill("tool_call"), "assistant_message"];
110
111it.effect("show reads the end of a long thread, not its whole history", () =>
112 Effect.gen(function* () {
113 const { tools, served, latest } = timelineTools([
114 ...Array.from({ length: 1000 }, (_, index) =>
115 index % 2 === 0 ? "user_message" : "assistant_message",
116 ),
117 ...Array.from({ length: 10 }, () => tail(30)).flat(),
118 "proposed_plan",
119 ]);
120
121 const { messages } = yield* readLatestMessages(tools, threadId, 10);
122
123 assert.deepStrictEqual(
124 messages.map((item) => item.itemId),
125 latest(10),
126 );
127 assert.isBelow(
128 served.reduce((sum, count) => sum + count, 0),
129 100,
130 );
131 }),
132);
133
134it.effect("show widens back to the first item when the thread has fewer messages", () =>
135 Effect.gen(function* () {
136 const { tools, latest } = timelineTools([
137 "user_message",
138 ...Array.from({ length: 4 }, () => tail(150)).flat(),
139 ]);
140
141 const { messages } = yield* readLatestMessages(tools, threadId, 10);
142
143 assert.deepStrictEqual(
144 messages.map((item) => item.itemId),
145 latest(10),
146 );
147 assert.lengthOf(messages, 5);
148 }),
149);
150
151it.effect("show returns a --messages count larger than one call can spread", () =>
152 Effect.gen(function* () {
153 const { tools, latest } = timelineTools(Array<string>(200_000).fill("assistant_message"));
154
155 const { messages } = yield* readLatestMessages(tools, threadId, 200_000);
156
157 assert.deepStrictEqual(
158 messages.map((item) => item.itemId),
159 latest(200_000),
160 );
161 }),
162);