Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

backgroundThreadAnnouncement.test.ts

259 lines8.8 KB

1import { RunId, RuntimeRequestId } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3import { describe, expect, it } from "vite-plus/test";
4​
5import {
6 type BackgroundThreadMemory,
7 type BackgroundThreadSnapshot,
8 nextBackgroundThreadAnnouncement,
9 resolveBackgroundThreadRequest,
10 resolveBackgroundThreadRunStatus,
11} from "./backgroundThreadAnnouncement";
12​
13const firstRun = RunId.make("run-1");
14const secondRun = RunId.make("run-2");
15​
16function thread(
17 key: string,
18 title: string,
19 state: Partial<Omit<BackgroundThreadSnapshot, "key" | "title">> = {},
20): BackgroundThreadSnapshot {
21 return {
22 key,
23 title,
24 request: null,
25 requestId: null,
26 runId: firstRun,
27 runStatus: "running",
28 activeRunId: null,
29 snoozed: false,
30 ...state,
31 };
33const login = (state?: Partial<BackgroundThreadSnapshot>) =>
34 thread("env:login", "Fix login redirect", state);
35const docs = (state?: Partial<BackgroundThreadSnapshot>) =>
36 thread("env:docs", "Update docs", state);
37​
38function speak(
39 frames: ReadonlyArray<{
40 readonly threads: ReadonlyArray<BackgroundThreadSnapshot>;
41 readonly open?: string;
42 }>,
43) {
44 let memory: BackgroundThreadMemory = new Map();
45 const spoken: string[] = [];
46 for (const frame of frames) {
47 const result = nextBackgroundThreadAnnouncement(memory, frame.threads, frame.open ?? null);
48 memory = result.memory;
49 if (result.announcement !== null) spoken.push(result.announcement);
50 }
51 return spoken;
53​
54describe("nextBackgroundThreadAnnouncement", () => {
55 it("names the thread with the same words the open thread uses", () => {
56 expect(
57 speak([
58 { threads: [login()] },
59 { threads: [login({ request: "approval" })] },
60 { threads: [login()] },
61 { threads: [login({ request: "input" })] },
62 { threads: [login({ runStatus: "completed" })] },
63 { threads: [login({ runId: secondRun, runStatus: "failed" })] },
64 { threads: [login({ runId: RunId.make("run-3"), runStatus: "interrupted" })] },
65 ]),
66 ).toEqual([
67 "Needs approval: Fix login redirect",
68 "Needs your input: Fix login redirect",
69 "Done: Fix login redirect",
70 "Failed: Fix login redirect",
71 "Stopped: Fix login redirect",
72 ]);
73 });
74​
75 it("announces each run's ending once", () => {
76 expect(
77 speak([
78 { threads: [login()] },
79 { threads: [login({ runStatus: "completed" })] },
80 // Marking the thread unread or renaming it changes nothing about the run.
81 { threads: [login({ runStatus: "completed", title: "Fix the login redirect" })] },
82 // The next run can finish between two updates, so it never looks busy here.
83 { threads: [login({ runId: secondRun, runStatus: "completed" })] },
84 { threads: [login({ runId: RunId.make("run-3"), runStatus: "rolled_back" })] },
85 ]),
86 ).toEqual(["Done: Fix login redirect", "Done: Fix login redirect"]);
87 });
88​
89 it("announces a second request of the same kind", () => {
90 expect(
91 speak([
92 { threads: [login()] },
93 { threads: [login({ request: "approval", requestId: "request-1" })] },
94 { threads: [login({ request: "approval", requestId: "request-2" })] },
95 ]),
96 ).toEqual(["Needs approval: Fix login redirect", "Needs approval: Fix login redirect"]);
97 });
98​
99 it("doesn't call a thread stopped when a queued message is cancelled while it works", () => {
100 expect(
101 speak([
102 { threads: [login({ activeRunId: firstRun })] },
103 {
104 threads: [login({ runId: secondRun, runStatus: "cancelled", activeRunId: firstRun })],
105 },
106 { threads: [login({ runId: secondRun, runStatus: "cancelled" })] },
107 ]),
108 ).toEqual([]);
109 });
110​
111 it("stays quiet for threads it sees for the first time, like on launch or reconnect", () => {
112 expect(
113 speak([
114 { threads: [login({ runStatus: "completed" }), docs({ request: "approval" })] },
115 { threads: [login({ runStatus: "completed" }), docs({ request: "approval" })] },
116 // The environment drops out while it resyncs, then comes back changed.
117 { threads: [] },
118 {
119 threads: [
120 login({ runId: secondRun, runStatus: "failed" }),
121 docs({ runStatus: "completed" }),
122 ],
123 },
124 ]),
125 ).toEqual([]);
126 });
127​
128 it("leaves the open thread to its own announcer", () => {
129 expect(
130 speak([
131 { threads: [login(), docs()], open: "env:login" },
132 { threads: [login({ runStatus: "completed" }), docs()], open: "env:login" },
133 // Switching away from a thread doesn't replay its ending.
134 { threads: [login({ runStatus: "completed" }), docs()], open: "env:docs" },
135 {
136 threads: [login({ runStatus: "completed" }), docs({ request: "input" })],
137 open: "env:login",
138 },
139 ]),
140 ).toEqual(["Needs your input: Update docs"]);
141 });
142​
143 it("keeps a snoozed thread quiet, even after it wakes", () => {
144 expect(
145 speak([
146 { threads: [login({ snoozed: true })] },
147 { threads: [login({ snoozed: true, runStatus: "completed" })] },
148 { threads: [login({ runStatus: "completed" })] },
149 ]),
150 ).toEqual([]);
151 });
152​
153 it("speaks threads that change together in one announcement", () => {
154 expect(
155 speak([
156 { threads: [login(), docs()] },
157 { threads: [login({ runStatus: "completed" }), docs({ request: "approval" })] },
158 ]),
159 ).toEqual(["Done: Fix login redirect. Needs approval: Update docs"]);
160 });
161});
162​
163describe("resolveBackgroundThreadRequest", () => {
164 const question = (id: string) => ({
165 id: RuntimeRequestId.make(id),
166 kind: "user_input" as const,
167 createdAt: DateTime.makeUnsafe(0),
168 });
169 const childApproval = (parentQuestion: string | null) =>
170 resolveBackgroundThreadRequest({
171 hasPendingApprovals: false,
172 hasPendingUserInput: parentQuestion !== null,
173 pendingSubagentRequest: "approval",
174 source: { pendingRuntimeRequest: parentQuestion === null ? null : question(parentQuestion) },
175 });
176​
177 it("raises a subagent's request on the parent without borrowing the parent's request id", () => {
178 expect(childApproval(null)).toEqual({ request: "approval", requestId: null });
179 // The parent's own questions come and go while the child's approval waits.
180 expect(
181 speak([
182 { threads: [login()] },
183 { threads: [login(childApproval(null))] },
184 { threads: [login(childApproval("question-1"))] },
185 { threads: [login(childApproval("question-2"))] },
186 { threads: [login(childApproval(null))] },
187 ]),
188 ).toEqual(["Needs approval: Fix login redirect"]);
189 });
190});
191​
192describe("resolveBackgroundThreadRunStatus", () => {
193 const threadStatus = (overrides?: {
194 readonly status?: "completed" | "failed" | "interrupted";
195 readonly pendingBackgroundTasks?: ReadonlyArray<{
196 readonly taskId: string;
197 readonly kind: "command" | "monitor" | "subagent" | "background_task";
198 readonly awaited?: true;
199 }>;
200 readonly latestRunBackgroundWake?: boolean;
201 readonly latestRunStopRequested?: boolean;
202 }) => {
203 const pendingBackgroundTasks = overrides?.pendingBackgroundTasks ?? [];
204 return resolveBackgroundThreadRunStatus({
205 latestRun: { status: overrides?.status ?? "completed" },
206 pendingBackgroundTasks,
207 source: {
208 pendingBackgroundTasks,
209 latestRunBackgroundWake: overrides?.latestRunBackgroundWake ?? false,
210 latestRunStopRequested: overrides?.latestRunStopRequested ?? false,
211 },
212 });
213 };
214​
215 it("suppresses Done while awaited background work or a monitor wake holds completion, or when stop was requested", () => {
216 const heldCases = [
217 { latestRunStopRequested: true },
218 { pendingBackgroundTasks: [{ taskId: "sub-1", kind: "subagent" as const }] },
219 {
220 pendingBackgroundTasks: [
221 { taskId: "cmd-1", kind: "command" as const, awaited: true as const },
222 ],
223 },
224 {
225 latestRunBackgroundWake: true,
226 pendingBackgroundTasks: [{ taskId: "mon-1", kind: "monitor" as const }],
227 },
228 ];
229 for (const input of heldCases) {
230 expect(threadStatus(input)).toBeNull();
231 }
232 });
233​
234 it("keeps Done for unawaited background work and keeps non-completed outcomes", () => {
235 expect(
236 threadStatus({
237 pendingBackgroundTasks: [{ taskId: "cmd-1", kind: "command" }],
238 }),
239 ).toBe("completed");
240 expect(
241 threadStatus({
242 latestRunBackgroundWake: false,
243 pendingBackgroundTasks: [{ taskId: "mon-1", kind: "monitor" }],
244 }),
245 ).toBe("completed");
246 expect(
247 threadStatus({
248 status: "failed",
249 pendingBackgroundTasks: [{ taskId: "sub-1", kind: "subagent" }],
250 }),
251 ).toBe("failed");
252 expect(
253 threadStatus({
254 status: "interrupted",
255 latestRunStopRequested: true,
256 }),
257 ).toBe("interrupted");
258 });
259});