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

FeedbackService.test.ts

1,083 lines46.7 KB

1import * as NodeOS from "node:os";
2​
3import { expect, it } from "@effect/vitest";
4import {
5 type AgentFeedbackMode,
6 DEFAULT_SERVER_SETTINGS,
7 type OrchestrationV2Run,
8 type OrchestrationV2TurnItem,
9 type Project,
10 ProviderInstanceId,
11 RunId,
12 type ServerProvider,
13 ThreadId,
14 TurnItemId,
15} from "@t3tools/contracts";
16import * as SecureRandom from "effect/crypto/SecureRandom";
17import * as DateTime from "effect/DateTime";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Fiber from "effect/Fiber";
21import * as Layer from "effect/Layer";
22import * as Queue from "effect/Queue";
23import * as Ref from "effect/Ref";
24import * as Schema from "effect/Schema";
25import * as Semaphore from "effect/Semaphore";
26import * as SqlClient from "effect/sql/SqlClient";
27import * as TestClock from "effect/testing/TestClock";
28​
29import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts";
30import * as ToolFailures from "../mcp/ToolFailures.ts";
31import * as Threads from "../orchestration-v2/ThreadManagementService.ts";
32import * as SqlitePersistence from "../persistence/Sqlite.ts";
33import * as Projects from "../project/ProjectService.ts";
34import * as Providers from "../provider/ProviderRegistry.ts";
35import * as Settings from "../serverSettings.ts";
36import * as Analytics from "../telemetry/AnalyticsService.ts";
37import {
38 FEEDBACK_AWAITING_APPROVAL_NOTE,
39 FeedbackInput,
40 FeedbackStorageError,
41} from "./FeedbackReport.ts";
42import { listFeedbackReports } from "./FeedbackList.ts";
43import * as Feedback from "./FeedbackService.ts";
44import { buildFeedbackTrace } from "./FeedbackTrace.ts";
45import * as Store from "./FeedbackStore.ts";
46​
47const threadId = ThreadId.make("thread:feedback");
48const instanceId = ProviderInstanceId.make("work-codex");
49​
50const at = (ms: number) => DateTime.makeUnsafe(ms);
51const run = (ordinal: number, started = true) =>
52 ({
53 id: RunId.make(`run:${ordinal}`),
54 ordinal,
55 providerInstanceId: instanceId,
56 modelSelection: { instanceId, model: "gpt-5.5" },
57 rootNodeId: `node:${ordinal}`,
58 startedAt: started ? at(ordinal * 60_000) : null,
59 }) as unknown as OrchestrationV2Run;
60let ordinal = 0;
61const item = (runOrdinal: number, fields: Record<string, unknown>) =>
62 ({
63 runId: RunId.make(`run:${runOrdinal}`),
64 parentItemId: null,
65 ordinal: ordinal++,
66 status: "completed",
67 startedAt: null,
68 completedAt: null,
69 ...fields,
70 }) as unknown as OrchestrationV2TurnItem;
71// Four queued runs after the six started ones: the trace still covers five started turns.
72const runs = [1, 2, 3, 4, 5, 6]
73 .map((ordinal) => run(ordinal))
74 .concat([7, 8, 9, 10].map((ordinal) => run(ordinal, false)));
75const turnItems = [
76 item(1, { type: "user_message", text: "Outside the window." }),
77 ...[2, 3, 4, 5].map((turn) => item(turn, { type: "user_message", text: `Ask ${turn}.` })),
78 ...Array.from({ length: 100 }, () => item(3, { type: "command_execution", exitCode: 0 })),
79 item(5, { type: "assistant_message", text: "Done in /srv/checkouts/acme-app-7." }),
80 item(6, {
81 type: "dynamic_tool",
82 toolName: "mcp__t3-code__t3_thread_read",
83 status: "failed",
84 startedAt: at(0),
85 completedAt: at(1_500),
86 }),
87 item(6, {
88 type: "dynamic_tool",
89 toolName: "mcp__linear__get_issue",
90 toolSource: { key: "linear", name: "Linear", kind: "integration" },
91 }),
92 item(6, { type: "dynamic_tool", toolName: "Read", parentItemId: "parent" }),
93 item(6, { type: "dynamic_tool", toolName: "Read" }),
94 item(6, { type: "command_execution", exitCode: 1 }),
95 item(6, {
96 type: "user_message",
97 text: `Look at /srv/acme-app/src/a.ts\nwith sk-proj-abcdefghij1234567890 ${"y".repeat(1_500)}`,
98 }),
99 ...[2, 6].flatMap((turn) =>
100 Array.from({ length: 6 }, () =>
101 item(turn, { type: "assistant_message", text: "z".repeat(2_000) }),
102 ),
103 ),
104 item(6, { type: "dynamic_tool", toolName: "t3-code.t3_thread_read", status: "running" }),
105 item(5, { type: "dynamic_tool", toolName: "mcp__t3-code__t3_feedback", status: "running" }),
106 item(6, { type: "dynamic_tool", toolName: "mcp__t3-code__t3_feedback", status: "failed" }),
107 // The call making the card in the active run, as Claude names it and as OpenCode 2 does.
108 item(6, { type: "dynamic_tool", toolName: "mcp__t3-code__t3_feedback", status: "running" }),
109 item(6, { type: "dynamic_tool", toolName: "t3-code-thread_1_t3_feedback", status: "running" }),
110];
111​
112it("says so when the report asks for more turns than a trace can hold", () => {
113 const many = Array.from({ length: 81 }, (_, index) => run(index + 1));
114 const trace = (turns: number) =>
115 buildFeedbackTrace({
116 runs: many,
117 items: many.map((_, index) => item(index + 1, { type: "user_message", text: "Hi" })),
118 turns,
119 withText: true,
120 sensitive: [],
121 t3Tools: [],
122 driverOf: () => undefined,
123 submittingRunId: many.at(-1)!.id,
124 });
125 expect(trace(100)).toMatchObject({ turns: 80, textTurns: 80, truncated: true });
126 expect(trace(80)).toMatchObject({ turns: 80, textTurns: 80, truncated: false });
127});
128​
129const harness = Effect.gen(function* () {
130 const mode = yield* Ref.make<AgentFeedbackMode>("auto");
131 // As in the service: updates and snapshots share one lock, and a read outside the lock can
132 // capture the settings and finish later. Arming `reading` makes the next read signal `begun`;
133 // an unlocked read signals after capturing and returns what it captured only on `release`.
134 const settingsLock = yield* Semaphore.make(1);
135 const reading = yield* Ref.make<
136 | { readonly begun: Deferred.Deferred<void>; readonly release: Deferred.Deferred<void> }
137 | undefined
138 >(undefined);
139 const readSettings = Ref.get(mode).pipe(
140 Effect.map((mode) => ({ ...DEFAULT_SERVER_SETTINGS, agentFeedback: { mode } })),
141 );
142 const unlockedRead = Effect.gen(function* () {
143 const captured = yield* readSettings;
144 const armed = yield* Ref.getAndSet(reading, undefined);
145 if (armed !== undefined) {
146 yield* Deferred.succeed(armed.begun, undefined);
147 yield* Deferred.await(armed.release);
148 }
149 return captured;
150 });
151 const snapshotBegins = Ref.getAndSet(reading, undefined).pipe(
152 Effect.flatMap((armed) =>
153 armed === undefined ? Effect.void : Deferred.succeed(armed.begun, undefined),
154 ),
155 );
156 const items = yield* Ref.make(turnItems);
157 const telemetry = yield* Ref.make(true);
158 const runId = yield* Ref.make(RunId.make("run:1"));
159 const events = yield* Ref.make<ReadonlyArray<readonly [string, unknown]>>([]);
160 // Every feedback card the service records, in order.
161 const cards = yield* Queue.unbounded<CardRecord>();
162 // The cards as the thread stores them, each its latest record.
163 const shown = yield* Ref.make(new Map<string, CardRecord>());
164 // Faults and gates for card records, and a signal when an answer reads its card.
165 const failRecords = yield* Ref.make(false);
166 // Each gate holds the first record of its status until released.
167 const recordGates = yield* Ref.make<
168 ReadonlyArray<{
169 readonly status: CardRecord["feedbackStatus"];
170 readonly entered: Deferred.Deferred<void>;
171 readonly release: Deferred.Deferred<void>;
172 }>
173 >([]);
174 // The projection rows the store reads share the database, as in the server.
175 const threads = Layer.unwrap(
176 Effect.gen(function* () {
177 const sql = yield* SqlClient.SqlClient;
178 for (const run of runs) {
179 yield* sql`INSERT INTO orchestration_v2_projection_runs ${sql.insert({
180 run_id: run.id,
181 thread_id: threadId,
182 ordinal: run.ordinal,
183 provider: "codex",
184 status: "running",
185 requested_at: "2026-01-01T00:00:00.000Z",
186 payload_json: "{}",
187 })}`;
188 }
189 const project = (card: CardRecord) => sql`
190 INSERT INTO orchestration_v2_projection_turn_items ${sql.insert({
191 turn_item_id: card.turnItemId,
192 thread_id: threadId,
193 run_id: card.runId,
194 ordinal: 0,
195 type: "feedback_request",
196 status:
197 card.feedbackStatus === "pending"
198 ? "waiting"
199 : card.feedbackStatus === "sent"
200 ? "completed"
201 : "cancelled",
202 updated_at: "2026-01-01T00:00:00.000Z",
203 payload_json: "{}",
204 })}
205 ON CONFLICT (turn_item_id) DO UPDATE SET status = excluded.status
206 WHERE orchestration_v2_projection_turn_items.status = 'waiting'`;
207 return Layer.mock(Threads.ThreadManagementService)({
208 dispatch: (command) =>
209 Effect.gen(function* () {
210 const card = command as CardRecord;
211 if (card.feedbackStatus !== "pending" && (yield* Ref.get(failRecords))) {
212 return yield* new FeedbackStorageError({ cause: "The card record failed." });
213 }
214 const gate = (yield* Ref.get(recordGates)).find(
215 (candidate) => candidate.status === card.feedbackStatus,
216 );
217 if (gate !== undefined) {
218 yield* Ref.update(recordGates, (gates) => gates.filter((other) => other !== gate));
219 yield* Deferred.succeed(gate.entered, undefined);
220 yield* Deferred.await(gate.release);
221 }
222 yield* Ref.update(shown, (cards) => {
223 const existing = cards.get(card.turnItemId);
224 // A decided card stays decided, as the orchestrator keeps it.
225 return existing === undefined || existing.feedbackStatus === "pending"
226 ? new Map(cards).set(card.turnItemId, card)
227 : cards;
228 });
229 yield* project(card).pipe(Effect.orDie);
230 yield* Queue.offer(cards, card);
231 return {};
232 }) as never,
233 getThreadRecords: (_threadId, fields, filter) =>
234 Effect.gen(function* () {
235 const stored = yield* Ref.get(items);
236 const wanted = fields as ReadonlyArray<string>;
237 const selected =
238 filter?.runIds === undefined
239 ? filter?.latestRunLimit === undefined
240 ? runs
241 : runs.slice(-filter.latestRunLimit)
242 : runs.filter((run) => filter.runIds?.includes(run.id));
243 return {
244 ...(wanted.includes("runs") ? { runs: selected } : {}),
245 ...(wanted.includes("turnItems")
246 ? {
247 turnItems: filter?.turnItemTypes?.includes("feedback_request")
248 ? [...(yield* Ref.get(shown)).values()].map(
249 ({ type: _record, commandId: _id, turnItemId, ...card }) => ({
250 ...card,
251 type: "feedback_request",
252 id: turnItemId,
253 }),
254 )
255 : stored.filter(
256 (item) =>
257 filter?.turnItemRunIds?.includes(item.runId) === true &&
258 filter.turnItemTypes?.includes(item.type) === true,
259 ),
260 }
261 : {}),
262 };
263 }) as never,
264 getThreadShell: () =>
265 Ref.get(runId).pipe(
266 Effect.map((activeRunId) => ({
267 ...liveThreadShell(threadId, { activeRunId }),
268 modelSelection: { instanceId, model: "gpt-5.5" },
269 branch: "acme/secret-launch",
270 worktreePath: "/srv/checkouts/acme-app-7",
271 })),
272 ),
273 });
274 }),
275 );
276 const layer = Feedback.layer(() => ["t3_thread_read", "t3_feedback"]).pipe(
277 Layer.provideMerge(Store.layer),
278 Layer.provideMerge(
279 Layer.mergeAll(
280 threads,
281 Layer.mock(Settings.ServerSettingsService)({
282 getSettings: unlockedRead,
283 withSettingsSnapshot: (use) =>
284 snapshotBegins.pipe(
285 Effect.andThen(settingsLock.withPermits(1)(readSettings.pipe(Effect.flatMap(use)))),
286 ),
287 }),
288 Layer.mock(Analytics.AnalyticsService)({
289 record: (event, properties) =>
290 Ref.get(telemetry).pipe(
291 Effect.tap((on) =>
292 on
293 ? Ref.update(events, (rows) => [...rows, [event, properties] as const])
294 : Effect.void,
295 ),
296 ),
297 }),
298 Layer.mock(Projects.ProjectService)({
299 getById: () =>
300 Effect.succeedSome({
301 title: "Acme Payments",
302 workspaceRoot: "/srv/acme-app",
303 repositoryIdentity: {
304 canonicalKey: "github.com/acme/payments",
305 locator: {
306 source: "git-remote",
307 remoteName: "origin",
308 remoteUrl: "git@github.com:acme/payments.git",
309 },
310 },
311 } as unknown as Project),
312 }),
313 Layer.mock(Providers.ProviderRegistry)({
314 getProviders: Effect.succeed([
315 {
316 instanceId,
317 driver: "codex",
318 auth: { status: "authenticated" },
319 models: [{ slug: "gpt-5.5", isCustom: false }],
320 } as unknown as ServerProvider,
321 ]),
322 }),
323 SecureRandom.layerWebCrypto,
324 ToolFailures.layer,
325 ),
326 ),
327 Layer.provideMerge(SqlitePersistence.layerMemory),
328 );
329 return {
330 mode,
331 settingsLock,
332 reading,
333 items,
334 telemetry,
335 runId,
336 events,
337 cards,
338 shown,
339 failRecords,
340 recordGates,
341 layer,
342 };
343});
344​
345type CardRecord = Extract<
346 Parameters<Threads.ThreadManagementService["Service"]["dispatch"]>[0],
347 { readonly type: "feedback_request.record" }
348>;
349​
350const awaiting = { status: "awaiting_approval", note: FEEDBACK_AWAITING_APPROVAL_NOTE };
351​
352/** Shows a requested report's card, which the call returns from at once. */
353const show = (cards: Queue.Queue<CardRecord>, report: FeedbackInput) =>
354 Effect.gen(function* () {
355 const feedback = yield* Feedback.FeedbackService;
356 expect(yield* feedback.submit(report, fromThread)).toEqual(awaiting);
357 const card = yield* Queue.take(cards);
358 expect(card.feedbackStatus).toBe("pending");
359 return card;
360 });
361​
362const answer = (card: CardRecord, reply: "send" | "decline", includeConversation = false) =>
363 Effect.gen(function* () {
364 const store = yield* Store.FeedbackStore;
365 yield* store.answer({
366 threadId,
367 turnItemId: card.turnItemId,
368 answer: reply,
369 includeConversation,
370 });
371 });
372​
373/** Shows a requested report, sends it, and returns the card as shown and the stored report. */
374const approved = (
375 cards: Queue.Queue<CardRecord>,
376 report: FeedbackInput,
377 includeConversation = false,
378) =>
379 Effect.gen(function* () {
380 const card = yield* show(cards, report);
381 yield* answer(card, "send", includeConversation);
382 const closed = yield* Queue.take(cards);
383 const [stored] = yield* listFeedbackReports;
384 return { card, closed, stored: stored! };
385 });
386​
387const input = {
388 kind: "bug" as const,
389 subject: "t3_thread_read",
390 expected: "Items for a completed thread.",
391 actual: "No items.",
392 workaround: "",
393 userRequested: false,
394 turns: 1,
395};
396const requested = { ...input, userRequested: true };
397const decodeFeedbackInput = Schema.decodeUnknownSync(FeedbackInput);
398const fromThread = { source: "mcp" as const, threadId };
399​
400it.effect("stores nothing and fails when agent feedback is off", () =>
401 Effect.gen(function* () {
402 const { mode, events, layer } = yield* harness;
403 yield* Ref.set(mode, "off");
404 yield* Effect.gen(function* () {
405 const feedback = yield* Feedback.FeedbackService;
406 const error = yield* Effect.flip(feedback.submit(input, fromThread));
407 expect(error._tag).toBe("FeedbackOffError");
408 expect(error.message).toContain("Settings > Labs");
409 expect((yield* Effect.flip(listFeedbackReports))._tag).toBe("FeedbackOffError");
410 }).pipe(Effect.provide(layer));
411 expect(yield* Ref.get(events)).toEqual([]);
412 }),
413);
414​
415it.effect("scrubs the caller's private values and sends only the event contract", () =>
416 Effect.gen(function* () {
417 const { telemetry, events, cards, layer } = yield* harness;
418 yield* Effect.gen(function* () {
419 const feedback = yield* Feedback.FeedbackService;
420 yield* Ref.set(telemetry, false);
421 const {
422 stored: local,
423 card,
424 closed,
425 } = yield* approved(
426 cards,
427 {
428 kind: "other",
429 subject: "mcp__t3-code__t3_thread_read",
430 expected: `Reading /srv/checkouts/acme-app-7 on acme/secret-launch as ${NodeOS.userInfo().username}`,
431 actual:
432 "git@github.com:acme/payments.git in Acme Payments with sk-proj-abcdefghij1234567890",
433 workaround: "x".repeat(400),
434 userRequested: true,
435 turns: 1,
436 },
437 true,
438 );
439 expect(local).toMatchObject({
440 kind: "other",
441 subject: "t3_thread_read",
442 expected: "Reading [redacted] on [redacted] as [redacted]",
443 actual: "[redacted] in [redacted] with [redacted]",
444 workaround: "x".repeat(300),
445 userRequested: true,
446 threadId,
447 source: "mcp",
448 sent: false,
449 });
450 expect(yield* Ref.get(events)).toEqual([]);
451 // Stored with telemetry off, but not sent: the card says so, and keeps only the outline.
452 expect(local.trace).toEqual(card.conversationTrace);
453 expect(closed).toMatchObject({ feedbackStatus: "cancelled", preview: card.preview });
454 expect(closed.conversationTrace).toBeUndefined();
455​
456 yield* Ref.set(telemetry, true);
457 const sent = yield* feedback.submit({ ...input, subject: "t3 thread show" }, fromThread);
458 expect("sent" in sent && sent.sent).toBe(true);
459 expect(yield* Ref.get(events)).toEqual([
460 [
461 "agent.feedback",
462 {
463 kind: "bug",
464 subject: "t3 thread show",
465 userRequested: false,
466 trace: null,
467 source: "mcp",
468 provider: "codex",
469 model: "gpt-5.5",
470 },
471 ],
472 ]);
473 // Not a T3 tool or command, so filed under general: the agent's word for it is not sent.
474 yield* feedback.submit({ ...input, subject: "agent-device" }, { source: "cli" });
475 expect((yield* Ref.get(events))[1]).toEqual([
476 "agent.feedback",
477 {
478 kind: "bug",
479 subject: "general",
480 userRequested: false,
481 trace: null,
482 source: "cli",
483 },
484 ]);
485 yield* feedback.submit({ ...input, subject: "mcp__t3_code__t3_thread_read" }, fromThread);
486 // Codex's second server, for T3 tools kept out of Code Mode, in both of its forms.
487 for (const subject of [
488 "t3-code-direct.t3_thread_read",
489 "mcp__t3-code-direct__t3_thread_read",
490 ])
491 yield* feedback.submit({ ...input, subject }, { source: "cli" });
492 expect(
493 (yield* listFeedbackReports).map(({ subject, userRequested, sent, threadId }) => ({
494 subject,
495 userRequested,
496 sent,
497 threadId,
498 })),
499 ).toEqual([
500 // The same problem again within a day stays on this machine.
501 { subject: "t3_thread_read", userRequested: false, sent: false, threadId: null },
502 { subject: "t3_thread_read", userRequested: false, sent: false, threadId: null },
503 { subject: "t3_thread_read", userRequested: false, sent: true, threadId },
504 { subject: "general", userRequested: false, sent: true, threadId: null },
505 { subject: "t3 thread show", userRequested: false, sent: true, threadId },
506 { subject: "t3_thread_read", userRequested: true, sent: false, threadId },
507 ]);
508 }).pipe(Effect.provide(layer));
509 }),
510);
511​
512it.effect("names the failed call a report follows, and sends each problem once a day", () =>
513 Effect.gen(function* () {
514 const { runId, events, cards, layer } = yield* harness;
515 yield* Effect.gen(function* () {
516 const feedback = yield* Feedback.FeedbackService;
517 const failures = yield* ToolFailures.ToolFailures;
518 const sentCodes = Ref.get(events).pipe(
519 Effect.map((rows) =>
520 rows.map(([, properties]) => (properties as { errorCode?: string }).errorCode),
521 ),
522 );
523 const report = feedback
524 .submit(input, fromThread)
525 .pipe(Effect.map((stored) => "sent" in stored && stored.sent));
526​
527 failures.note(threadId, "t3_thread_read", "thread_not_found", 0);
528 expect(yield* report).toBe(true);
529 // The agent's kind does not make a new problem, and neither does a new turn.
530 expect(yield* feedback.submit({ ...input, kind: "confusing" }, fromThread)).toMatchObject({
531 sent: false,
532 });
533 yield* Ref.set(runId, RunId.make("run:2"));
534 expect(yield* report).toBe(false);
535 expect(yield* sentCodes).toEqual(["thread_not_found"]);
536​
537 // Another failure of the same tool is another problem.
538 failures.note(threadId, "t3_thread_read", "invalid_request", 0);
539 expect(yield* report).toBe(true);
540 // A failure too long ago is not what the report is about, and no failure is a problem too.
541 yield* TestClock.adjust(ToolFailures.TOOL_FAILURE_REPORT_WINDOW_MS + 1);
542 expect(yield* report).toBe(true);
543 expect(yield* sentCodes).toEqual(["thread_not_found", "invalid_request", undefined]);
544 yield* Ref.set(runId, RunId.make("run:3"));
545 expect(yield* report).toBe(false);
546​
547 // A report the user approves is always sent, and carries no code.
548 yield* approved(cards, requested);
549 expect((yield* Ref.get(events)).at(-1)?.[1]).not.toHaveProperty("errorCode");
550​
551 // A day on, each problem is sent again, so a fix shows as reports that stop.
552 yield* TestClock.adjust("24 hours");
553 yield* Ref.set(runId, RunId.make("run:4"));
554 expect(yield* report).toBe(true);
555 expect(yield* listFeedbackReports).toHaveLength(8);
556 }).pipe(Effect.provide(layer));
557 }),
558);
559​
560it.effect(
561 "allows 3 unprompted reports and 3 cards per turn, and 10 reports an hour outside a turn",
562 () =>
563 Effect.gen(function* () {
564 const { mode, runId, events, cards, layer } = yield* harness;
565 yield* Effect.gen(function* () {
566 const feedback = yield* Feedback.FeedbackService;
567 const limited = Effect.flip(feedback.submit(input, fromThread)).pipe(
568 Effect.map((error) => error._tag),
569 );
570 const refused = (report: Partial<typeof input>, caller: Feedback.FeedbackCaller) =>
571 Effect.flip(feedback.submit({ ...input, ...report }, caller)).pipe(
572 Effect.map((error) => error.message),
573 );
574 // Only a thread can show the user a requested report to approve.
575 expect(yield* refused({ userRequested: true }, { source: "cli" })).toBe(
576 "A report the user asks for is shown to them for approval in their thread, and this call has no active thread turn, so nothing was sent.",
577 );
578 yield* Ref.set(mode, "on-request");
579 expect(yield* refused({}, fromThread)).toBe(
580 "Agent feedback is set to When I ask: send a report only when the user asks for one.",
581 );
582 expect(yield* refused({}, { source: "cli" })).toBe(
583 "Agent feedback is set to When I ask: ask your agent in a thread to send it, so you can approve what is sent.",
584 );
585 yield* Ref.set(mode, "auto");
586 expect(yield* Ref.get(events)).toEqual([]);
587 yield* Effect.replicateEffect(feedback.submit(input, fromThread), 3, { discard: true });
588 expect(yield* limited).toBe("FeedbackLimitError");
589 // Cards count when shown, answered or not, and apart from unprompted reports.
590 const [first] = yield* Effect.replicateEffect(show(cards, requested), 3);
591 yield* answer(first!, "decline");
592 expect(yield* refused({ userRequested: true }, fromThread)).toBe(
593 "This turn already showed the user 3 agent feedback reports to approve; nothing was shown.",
594 );
595 // No cap per thread: each new turn has room again.
596 for (const run of ["run:2", "run:3", "run:4", "run:5"]) {
597 yield* Ref.set(runId, RunId.make(run));
598 yield* Effect.replicateEffect(feedback.submit(input, fromThread), 3, { discard: true });
599 }
600 expect((yield* Effect.flip(feedback.submit(input, fromThread))).message).toBe(
601 "This turn already sent 3 agent feedback reports; nothing was sent.",
602 );
603 // Outside a turn, such as `t3 feedback`, 10 an hour.
604 const fromCli = { source: "cli" as const };
605 yield* Effect.replicateEffect(feedback.submit(input, fromCli), 10, { discard: true });
606 expect((yield* Effect.flip(feedback.submit(input, fromCli))).message).toBe(
607 "This machine already sent 10 agent feedback reports outside a turn in the last hour; nothing was sent.",
608 );
609 yield* TestClock.adjust("1 hour");
610 yield* feedback.submit(input, fromCli);
611 expect(yield* listFeedbackReports).toHaveLength(26);
612 }).pipe(Effect.provide(layer));
613 }),
614);
615​
616it.effect("a card holds the outline and the conversation, and sends the one the user picks", () =>
617 Effect.gen(function* () {
618 const { events, items, runId, cards, shown, layer } = yield* harness;
619 yield* Effect.gen(function* () {
620 const feedback = yield* Feedback.FeedbackService;
621 const unprompted = yield* feedback.submit(input, fromThread);
622 expect("trace" in unprompted && unprompted.trace).toBeNull();
623​
624 yield* Ref.set(runId, RunId.make("run:6"));
625 const fiveTurns = { ...requested, turns: 5 };
626 const card = yield* show(cards, fiveTurns);
627 const outline = card.preview.trace!;
628 expect(outline).toMatchObject({ turns: 5, textTurns: 0, truncated: true });
629 expect(outline.entries).toHaveLength(80);
630 expect(JSON.stringify(outline)).not.toMatch(/Ask|Done|acme|linear|zzz/u);
631 // Old tool calls give way first, so every turn keeps its user message.
632 expect(outline.entries.filter((entry) => entry.type === "user").map((e) => e.turn)).toEqual([
633 1, 2, 3, 4, 5,
634 ]);
635 expect(outline.entries.filter((entry) => entry.turn === 5 && entry.type === "tool")).toEqual([
636 { turn: 5, type: "tool", tool: "t3_thread_read", outcome: "error", durationMs: 1_500 },
637 { turn: 5, type: "tool", tool: "mcp", outcome: "ok" },
638 { turn: 5, type: "tool", tool: "Read", outcome: "ok" },
639 { turn: 5, type: "tool", tool: "shell", outcome: "error" },
640 { turn: 5, type: "tool", tool: "t3_thread_read", outcome: "unfinished" },
641 { turn: 5, type: "tool", tool: "t3_feedback", outcome: "error" },
642 ]);
643 expect(outline.entries.filter((entry) => entry.tool === "t3_feedback")).toEqual([
644 { turn: 4, type: "tool", tool: "t3_feedback", outcome: "unfinished" },
645 { turn: 5, type: "tool", tool: "t3_feedback", outcome: "error" },
646 ]);
647​
648 // The conversation is the same outline with the scrubbed text of its turns, newest kept
649 // first under 16 KB.
650 const conversation = card.conversationTrace!;
651 expect(Buffer.byteLength(JSON.stringify(conversation))).toBeLessThanOrEqual(16_000);
652 expect(conversation.truncated).toBe(true);
653 expect(
654 conversation.entries.map(({ text: _text, ...entry }) => entry),
655 "the same entries",
656 ).toEqual(outline.entries);
657 const texts = conversation.entries.flatMap((entry) =>
658 entry.text === undefined ? [] : [[entry.turn, entry.text] as const],
659 );
660 expect(conversation.entries.find((entry) => entry.turn === 1)).toEqual({
661 turn: 1,
662 type: "user",
663 length: 6,
664 });
665 expect(texts.filter(([turn]) => turn === 4).map(([, text]) => text)).toEqual([
666 "Ask 5.",
667 "Done in [redacted].",
668 ]);
669 expect(texts.filter(([turn]) => turn === 5)[0]?.[1]).toMatch(
670 /^Look at \[redacted\]\nwith \[redacted\] y+$/u,
671 );
672 expect(texts.every(([, text]) => Array.from(text).length <= 1_000)).toBe(true);
673 expect(conversation.textTurns).toBe(new Set(texts.map(([turn]) => turn)).size);
674​
675 // Off: the outline alone is stored and sent, and the card keeps only that.
676 yield* answer(card, "send");
677 const withoutText = yield* Queue.take(cards);
678 expect(withoutText.preview).toEqual(card.preview);
679 expect(withoutText.conversationTrace).toBeUndefined();
680 // On: the conversation is.
681 const included = yield* approved(cards, fiveTurns, true);
682 expect(included.stored.trace).toEqual(included.card.conversationTrace);
683 expect(included.closed.preview.trace).toEqual(included.card.conversationTrace);
684 expect(included.closed.conversationTrace).toBeUndefined();
685 expect([...(yield* Ref.get(shown)).values()].map((shown) => shown.feedbackStatus)).toEqual([
686 "sent",
687 "sent",
688 ]);
689 const sent = (yield* Ref.get(events)).slice(1).map(([, properties]) => properties);
690 const stored = (yield* listFeedbackReports).slice(0, 2).toReversed();
691 expect(stored.map((report) => report.trace)).toEqual([outline, conversation]);
692 expect(sent.map((properties) => (properties as { trace: unknown }).trace)).toEqual([
693 outline,
694 conversation,
695 ]);
696​
697 // Under the entry and byte caps, a message cut to 1,000 characters alone marks the text.
698 yield* Ref.update(items, (all) => all.filter((item) => item.type !== "command_execution"));
699 yield* Ref.set(runId, RunId.make("run:2"));
700 const short = yield* show(cards, requested);
701 expect(short.preview.trace?.truncated).toBe(false);
702 expect(short.conversationTrace?.truncated).toBe(true);
703 // Redaction lengthens 990 characters of addresses past the cap: that cut marks it too.
704 yield* Ref.update(items, (all) => [
705 ...all.filter(
706 (item) =>
707 !(item.type === "user_message" || item.type === "assistant_message") ||
708 Array.from(item.text).length <= 1_000,
709 ),
710 item(6, { type: "user_message", text: "ops@a.io ".repeat(110) }),
711 ]);
712 const lengthened = yield* show(cards, requested);
713 expect(lengthened.preview.trace?.truncated).toBe(false);
714 expect(lengthened.conversationTrace?.truncated).toBe(true);
715 // Turns with no message text give the card no conversation to include.
716 yield* Ref.update(items, (all) => all.filter((item) => item.type === "dynamic_tool"));
717 expect((yield* show(cards, requested)).conversationTrace).toBeUndefined();
718​
719 // The outline covers at least 5 started turns, more when the agent says the problem spans
720 // more, up to the thread's; the conversation covers the turns the agent gave, oldest text
721 // dropped first to fit.
722 yield* Ref.set(items, turnItems);
723 const { turns: _omitted, ...omitted } = requested;
724 // The thread has 6 started turns; the byte cap leaves no room for the oldest one's text.
725 const rows = [
726 { run: "run:3", report: decodeFeedbackInput(omitted), turns: 5, text: [5] },
727 { run: "run:3", report: { ...requested, turns: 3 }, turns: 5, text: [3, 4, 5] },
728 { run: "run:4", report: { ...requested, turns: 6 }, turns: 6, text: [2, 3, 4, 5, 6] },
729 { run: "run:4", report: { ...requested, turns: 20 }, turns: 6, text: [2, 3, 4, 5, 6] },
730 ];
731 for (const row of rows) {
732 yield* Ref.set(runId, RunId.make(row.run));
733 const shownCard = yield* show(cards, row.report);
734 const conversation = shownCard.conversationTrace!;
735 expect(shownCard.preview.trace!.turns).toBe(row.turns);
736 expect(conversation).toMatchObject({ turns: row.turns, textTurns: row.text.length });
737 expect([
738 ...new Set(conversation.entries.flatMap((e) => (e.text === undefined ? [] : [e.turn]))),
739 ]).toEqual(row.text);
740 }
741 expect(rows.map(({ report }) => report.turns)).toEqual([1, 3, 6, 20]);
742 }).pipe(Effect.provide(layer));
743 }),
744);
745​
746it.effect("returns as the card is shown, and stores and sends it only on Send, once", () =>
747 Effect.gen(function* () {
748 const { events, runId, cards, shown, layer } = yield* harness;
749 yield* Effect.gen(function* () {
750 const nothingKept = Effect.gen(function* () {
751 expect(yield* listFeedbackReports).toEqual([]);
752 expect(yield* Ref.get(events)).toEqual([]);
753 });
754​
755 // Decline: nothing is stored or sent, and the card drops the conversation it held.
756 const declined = yield* show(cards, requested);
757 expect(declined).toMatchObject({ runId: "run:1", nodeId: "node:1" });
758 expect(declined.conversationTrace).toBeDefined();
759 yield* nothingKept;
760 yield* answer(declined, "decline");
761 const closed = yield* Queue.take(cards);
762 expect(closed).toMatchObject({ feedbackStatus: "declined", preview: declined.preview });
763 expect(closed.conversationTrace).toBeUndefined();
764 yield* nothingKept;
765 // A decided card takes no second answer.
766 expect((yield* Effect.flip(answer(declined, "send", true))).reason).toBe("already_answered");
767 yield* nothingKept;
768​
769 // Only the thread that asked answers, and only its feedback cards.
770 const store = yield* Store.FeedbackStore;
771 for (const [thread, turnItemId] of [
772 [ThreadId.make("thread:fork"), declined.turnItemId],
773 [threadId, TurnItemId.make("turn-item:assistant-message:1")],
774 ] as const) {
775 expect(
776 (yield* Effect.flip(store.answer({ threadId: thread, turnItemId, answer: "send" })))
777 .reason,
778 ).toBe("not_found");
779 }
780​
781 // Send: exactly the shown preview is stored and sent, marked as requested.
782 const { card, closed: sentCard, stored } = yield* approved(cards, requested);
783 expect(sentCard.feedbackStatus).toBe("sent");
784 const [[, properties]] = (yield* Ref.get(events)) as [[string, Record<string, unknown>]];
785 for (const kept of [properties, stored]) {
786 expect({
787 kind: kept?.kind,
788 subject: kept?.subject,
789 expected: kept?.expected,
790 actual: kept?.actual,
791 workaround: kept?.workaround,
792 trace: kept?.trace,
793 }).toEqual(card.preview);
794 }
795 expect(properties).toMatchObject({ userRequested: true, provider: "codex" });
796​
797 // Two answers at once, from two clients or a double tap: exactly one takes effect.
798 for (const [turn, replies] of [
799 ["run:2", ["send", "send"]],
800 ["run:3", ["send", "decline"]],
801 ["run:4", ["decline", "send"]],
802 ] as const) {
803 yield* Ref.set(runId, RunId.make(turn));
804 const raced = yield* show(cards, requested);
805 const before = (yield* listFeedbackReports).length;
806 const results = yield* Effect.all(
807 replies.map((reply) => Effect.result(answer(raced, reply))),
808 { concurrency: "unbounded" },
809 );
810 expect(results.filter((result) => result._tag === "Success")).toHaveLength(1);
811 expect(results.find((result) => result._tag === "Failure")).toMatchObject({
812 failure: { reason: "already_answered" },
813 });
814 const status = (yield* Ref.get(shown)).get(raced.turnItemId)?.feedbackStatus;
815 expect((yield* listFeedbackReports).length - before).toBe(status === "sent" ? 1 : 0);
816 yield* Queue.take(cards);
817 expect(yield* Queue.size(cards)).toBe(0);
818 }
819 }).pipe(Effect.provide(layer));
820 }),
821);
822​
823it.effect("Send works after the turn stopped, while a later turn runs, and after a restart", () =>
824 Effect.gen(function* () {
825 const { runId, events, cards, layer } = yield* harness;
826 yield* Effect.gen(function* () {
827 const sql = yield* SqlClient.SqlClient;
828 const card = yield* show(cards, requested);
829 // The user stopped the turn, and a later one is running.
830 yield* sql`UPDATE orchestration_v2_projection_runs SET status = 'interrupted'
831 WHERE run_id = ${card.runId}`;
832 yield* sql`INSERT INTO orchestration_v2_projection_turn_items ${sql.insert({
833 turn_item_id: "interrupt-request",
834 thread_id: threadId,
835 run_id: card.runId,
836 ordinal: 1,
837 type: "run_interrupt_request",
838 status: "completed",
839 updated_at: "2026-01-01T00:00:00.000Z",
840 payload_json: "{}",
841 })}`;
842 yield* Ref.set(runId, RunId.make("run:2"));
843 // A store started after the card was shown, as after a restart, answers from the card.
844 yield* answer(card, "send", true).pipe(Effect.provide(Store.layer));
845 expect((yield* Queue.take(cards)).feedbackStatus).toBe("sent");
846 const [stored] = yield* listFeedbackReports;
847 expect(stored).toMatchObject({ trace: card.conversationTrace, sent: true });
848 expect(yield* Ref.get(events)).toHaveLength(1);
849 }).pipe(Effect.provide(layer));
850 }),
851);
852​
853it.effect("Send refuses while Off and closes the card; When I ask and Automatic allow it", () =>
854 Effect.gen(function* () {
855 const { mode, events, cards, layer } = yield* harness;
856 yield* Effect.gen(function* () {
857 const off = yield* show(cards, requested);
858 yield* Ref.set(mode, "off");
859 expect((yield* Effect.flip(answer(off, "send", true))).reason).toBe("feedback_off");
860 const closed = yield* Queue.take(cards);
861 expect(closed.feedbackStatus).toBe("cancelled");
862 expect(closed.conversationTrace).toBeUndefined();
863 yield* Ref.set(mode, "auto");
864 expect(yield* listFeedbackReports).toEqual([]);
865 expect(yield* Ref.get(events)).toEqual([]);
866​
867 const onRequest = yield* show(cards, requested);
868 yield* Ref.set(mode, "on-request");
869 yield* answer(onRequest, "send");
870 expect((yield* Queue.take(cards)).feedbackStatus).toBe("sent");
871 expect(yield* Ref.get(events)).toHaveLength(1);
872 }).pipe(Effect.provide(layer));
873 }),
874);
875​
876it.effect("a report stored before its card was settled settles the card on the next answer", () =>
877 Effect.gen(function* () {
878 const { telemetry, events, cards, shown, failRecords, runId, layer } = yield* harness;
879 yield* Effect.gen(function* () {
880 const status = (card: CardRecord) =>
881 Ref.get(shown).pipe(Effect.map((all) => all.get(card.turnItemId)?.feedbackStatus));
882 // The report is stored and sent, then recording the card fails, as a crash would leave it.
883 const sentCard = yield* show(cards, requested);
884 yield* Ref.set(failRecords, true);
885 expect(yield* Effect.result(answer(sentCard, "send", true))).toMatchObject({
886 _tag: "Failure",
887 failure: { reason: "record_failed" },
888 });
889 expect(yield* listFeedbackReports).toMatchObject([
890 { trace: sentCard.conversationTrace, sent: true },
891 ]);
892 expect(yield* status(sentCard)).toBe("pending");
893 yield* Ref.set(failRecords, false);
894 // Either answer, from a store started after the fault, settles it from the stored report.
895 yield* answer(sentCard, "decline").pipe(Effect.provide(Store.layer));
896 const settled = yield* Queue.take(cards);
897 expect(settled).toMatchObject({
898 feedbackStatus: "sent",
899 preview: { ...sentCard.preview, trace: sentCard.conversationTrace },
900 });
901 expect(settled.conversationTrace).toBeUndefined();
902 expect((yield* Effect.flip(answer(sentCard, "send"))).reason).toBe("already_answered");
903 expect(yield* Ref.get(events)).toHaveLength(1);
904 expect(yield* listFeedbackReports).toHaveLength(1);
905​
906 // Stored but not sent: the card closes unsent, with the outline only.
907 yield* Ref.set(runId, RunId.make("run:2"));
908 yield* Ref.set(telemetry, false);
909 const keptCard = yield* show(cards, requested);
910 yield* Ref.set(failRecords, true);
911 expect(yield* Effect.result(answer(keptCard, "send", true))).toMatchObject({
912 _tag: "Failure",
913 failure: { reason: "record_failed" },
914 });
915 yield* Ref.set(failRecords, false);
916 yield* answer(keptCard, "send");
917 const closed = yield* Queue.take(cards);
918 expect(closed).toMatchObject({ feedbackStatus: "cancelled", preview: keptCard.preview });
919 expect(closed.conversationTrace).toBeUndefined();
920 expect(yield* listFeedbackReports).toHaveLength(2);
921 }).pipe(Effect.provide(layer));
922 }),
923);
924​
925it.effect("a report handed to telemetry heals as sent even if the sent write fails", () =>
926 Effect.gen(function* () {
927 const { events, cards, failRecords, layer } = yield* harness;
928 yield* Effect.gen(function* () {
929 const sql = yield* SqlClient.SqlClient;
930 const card = yield* show(cards, requested);
931 // Every write of `sent` fails, and so does the card record after the hand-off.
932 yield* sql`CREATE TRIGGER fail_sent_write BEFORE UPDATE OF sent ON agent_feedback
933 BEGIN SELECT RAISE(ABORT, 'The sent write failed.'); END`;
934 yield* Ref.set(failRecords, true);
935 expect(yield* Effect.result(answer(card, "send"))).toMatchObject({
936 _tag: "Failure",
937 failure: { reason: "record_failed" },
938 });
939 expect(yield* Ref.get(events)).toHaveLength(1);
940 yield* sql`DROP TRIGGER fail_sent_write`;
941 yield* Ref.set(failRecords, false);
942 // The report left the machine, so the next answer settles the card as sent.
943 yield* answer(card, "decline");
944 expect((yield* Queue.take(cards)).feedbackStatus).toBe("sent");
945 expect(yield* listFeedbackReports).toMatchObject([{ sent: true }]);
946 }).pipe(Effect.provide(layer));
947 }),
948);
949​
950it.effect("a card is shown while an answer waits for the settings lock", () =>
951 Effect.gen(function* () {
952 const { settingsLock, reading, events, cards, layer } = yield* harness;
953 yield* Effect.gen(function* () {
954 const card = yield* show(cards, requested);
955 // Something else holds the settings lock for a long time, as an agent uninstall can.
956 const holding = yield* Deferred.make<void>();
957 const done = yield* Deferred.make<void>();
958 const holder = yield* settingsLock
959 .withPermits(1)(
960 Deferred.succeed(holding, undefined).pipe(Effect.andThen(Deferred.await(done))),
961 )
962 .pipe(Effect.forkChild);
963 yield* Deferred.await(holding);
964 const begun = yield* Deferred.make<void>();
965 yield* Ref.set(reading, { begun, release: yield* Deferred.make<void>() });
966 const parked = yield* Effect.forkChild(answer(card, "send"));
967 yield* Deferred.await(begun);
968 // An agent's request for another card does not wait behind the parked answer.
969 yield* show(cards, requested);
970 yield* Deferred.succeed(done, undefined);
971 yield* Fiber.join(holder);
972 yield* Fiber.join(parked);
973 expect((yield* Queue.take(cards)).feedbackStatus).toBe("sent");
974 expect(yield* Ref.get(events)).toHaveLength(1);
975 }).pipe(Effect.provide(layer));
976 }),
977);
978​
979it.effect("a Send refused while Off settles the card before a later Send can store it", () =>
980 Effect.gen(function* () {
981 const { mode, events, cards, shown, recordGates, layer } = yield* harness;
982 yield* Effect.gen(function* () {
983 const gate = (status: CardRecord["feedbackStatus"]) =>
984 Effect.gen(function* () {
985 const held = {
986 status,
987 entered: yield* Deferred.make<void>(),
988 release: yield* Deferred.make<void>(),
989 };
990 yield* Ref.update(recordGates, (gates) => [...gates, held]);
991 return held;
992 });
993 const card = yield* show(cards, requested);
994 // The first Send is refused while Off and is held as it closes the card.
995 yield* Ref.set(mode, "off");
996 const closing = yield* gate("cancelled");
997 const refused = yield* Effect.forkChild(Effect.result(answer(card, "send", true)));
998 yield* Deferred.await(closing.entered);
999 // Agent feedback is turned back on, and a second Send would be held as it marks the card
1000 // sent, after storing and sending its report.
1001 yield* Ref.set(mode, "auto");
1002 const marking = yield* gate("sent");
1003 const second = yield* Effect.forkChild(Effect.result(answer(card, "send", true)));
1004 const reachedSent = yield* Effect.forkChild(
1005 Deferred.await(marking.entered).pipe(Effect.timeoutOption("1 second")),
1006 );
1007 yield* TestClock.adjust("1 second");
1008 // The second Send waits for the first to finish, so it never stores a report.
1009 expect((yield* Fiber.join(reachedSent))._tag).toBe("None");
1010 yield* Deferred.succeed(closing.release, undefined);
1011 yield* Deferred.succeed(marking.release, undefined);
1012 expect(yield* Fiber.join(refused)).toMatchObject({
1013 _tag: "Failure",
1014 failure: { reason: "feedback_off" },
1015 });
1016 expect(yield* Fiber.join(second)).toMatchObject({
1017 _tag: "Failure",
1018 failure: { reason: "already_answered" },
1019 });
1020 expect((yield* Ref.get(shown)).get(card.turnItemId)?.feedbackStatus).toBe("cancelled");
1021 expect(yield* listFeedbackReports).toEqual([]);
1022 expect(yield* Ref.get(events)).toEqual([]);
1023 }).pipe(Effect.provide(layer));
1024 }),
1026​
1027it.effect("a mode switch under way when a report is stored wins", () =>
1028 Effect.gen(function* () {
1029 const { mode, settingsLock, reading, events, cards, layer } = yield* harness;
1030 yield* Effect.gen(function* () {
1031 const feedback = yield* Feedback.FeedbackService;
1032 const nothingKept = Effect.gen(function* () {
1033 yield* Ref.set(mode, "auto");
1034 expect(yield* listFeedbackReports).toEqual([]);
1035 expect(yield* Ref.get(events)).toEqual([]);
1036 });
1037 /**
1038 * Holds a switch to `to` mid-write under the settings lock, runs `start` until storing reads
1039 * the settings, then lets the switch finish. A read outside the lock has captured the old
1040 * mode by then, and returns it only after the switch.
1041 */
1042 const switchDuring = <A, E, R>(to: AgentFeedbackMode, start: Effect.Effect<A, E, R>) =>
1043 Effect.gen(function* () {
1044 const gate = yield* Deferred.make<void>();
1045 const updating = yield* Deferred.make<void>();
1046 const update = yield* settingsLock
1047 .withPermits(1)(
1048 Deferred.succeed(updating, undefined).pipe(
1049 Effect.andThen(Deferred.await(gate)),
1050 Effect.andThen(Ref.set(mode, to)),
1051 ),
1053 .pipe(Effect.forkChild);
1054 yield* Deferred.await(updating);
1055 const begun = yield* Deferred.make<void>();
1056 const release = yield* Deferred.make<void>();
1057 yield* Ref.set(reading, { begun, release });
1058 const call = yield* Effect.forkChild(start);
1059 yield* Deferred.await(begun);
1060 yield* Deferred.succeed(gate, undefined);
1061 yield* Fiber.join(update);
1062 yield* Deferred.succeed(release, undefined);
1063 return yield* Effect.result(Fiber.join(call));
1064 });
1065​
1066 // Automatic to Off while Send stores the card's report: nothing kept, the card closes.
1067 const card = yield* show(cards, requested);
1068 expect(yield* switchDuring("off", answer(card, "send"))).toMatchObject({
1069 _tag: "Failure",
1070 failure: { _tag: "AgentFeedbackRequestError", reason: "feedback_off" },
1071 });
1072 expect((yield* Queue.take(cards)).feedbackStatus).toBe("cancelled");
1073 yield* nothingKept;
1074​
1075 // Automatic to When I ask while an unprompted report is on its way: refused as itself.
1076 expect(yield* switchDuring("on-request", feedback.submit(input, fromThread))).toMatchObject({
1077 _tag: "Failure",
1078 failure: { _tag: "FeedbackNotRequestedError" },
1079 });
1080 yield* nothingKept;
1081 }).pipe(Effect.provide(layer));
1082 }),