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

FeedbackService.ts

216 lines8.0 KB

1import * as NodeOS from "node:os";
2​
3import type { ThreadId } from "@t3tools/contracts";
4import * as Clock from "effect/Clock";
5import * as Context from "effect/Context";
6import * as SecureRandom from "effect/crypto/SecureRandom";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11​
12import * as ToolFailures from "../mcp/ToolFailures.ts";
13import * as Threads from "../orchestration-v2/ThreadManagementService.ts";
14import * as Projects from "../project/ProjectService.ts";
15import * as Providers from "../provider/ProviderRegistry.ts";
16import * as Settings from "../serverSettings.ts";
17import { providerDimensions } from "../telemetry/ProviderDimensions.ts";
18import {
19 FEEDBACK_AWAITING_APPROVAL_NOTE,
20 type FeedbackAwaitingApproval,
21 type FeedbackInput,
22 type FeedbackLimitError,
23 type FeedbackNotRequestedError,
24 type FeedbackOffError,
25 type FeedbackReport,
26 type FeedbackSource,
27 FeedbackStorageError,
28 resolveFeedbackSubject,
29} from "./FeedbackReport.ts";
30import * as Store from "./FeedbackStore.ts";
31import {
32 buildFeedbackTrace,
33 FEEDBACK_TRACE_ITEM_TYPES,
34 feedbackTraceWindow,
35} from "./FeedbackTrace.ts";
36import { scrubFeedback } from "./scrubFeedback.ts";
37​
38/** A requested report needs a thread with an active turn to show the user its card. */
39export class FeedbackApprovalError extends Schema.TaggedError<FeedbackApprovalError>()(
40 "FeedbackApprovalError",
41 {},
42) {
43 override get message() {
44 return "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.";
45 }
47​
48export interface FeedbackCaller {
49 readonly source: FeedbackSource;
50 readonly threadId?: ThreadId;
52​
53export class FeedbackService extends Context.Service<
54 FeedbackService,
55 {
56 /**
57 * Sends an unprompted report at once. A requested one is shown to the user in a card and
58 * returns at once; it is stored and sent only if they choose Send.
59 */
60 readonly submit: (
61 input: FeedbackInput,
62 caller: FeedbackCaller,
63 ) => Effect.Effect<
64 FeedbackReport | FeedbackAwaitingApproval,
65 | FeedbackOffError
66 | FeedbackNotRequestedError
67 | FeedbackApprovalError
68 | FeedbackLimitError
69 | FeedbackStorageError
70 >;
71 }
72>()("t3/feedback/FeedbackService") {}
73​
74const storageError = (cause: unknown) => new FeedbackStorageError({ cause });
75​
76/** `mcpToolNames` is read per report: the MCP server registers tools after this service starts. */
77const make = Effect.fn("FeedbackService.make")(function* (
78 mcpToolNames: () => ReadonlyArray<string>,
79) {
80 const threads = yield* Threads.ThreadManagementService;
81 const projects = yield* Projects.ProjectService;
82 const providers = yield* Providers.ProviderRegistry;
83 const settings = yield* Settings.ServerSettingsService;
84 const random = yield* SecureRandom.SecureRandom;
85 const store = yield* Store.FeedbackStore;
86 const failures = yield* ToolFailures.ToolFailures;
87​
88 const submit = Effect.fn("FeedbackService.submit")(function* (
89 input: FeedbackInput,
90 caller: FeedbackCaller,
91 ) {
92 const { agentFeedback } = yield* settings.getSettings.pipe(Effect.mapError(storageError));
93 // Early, so a refused report shows no card; storing applies the rule again under the lock.
94 yield* Store.allowedBy(agentFeedback.mode, input.userRequested, caller.source);
95 const subject = resolveFeedbackSubject(input.subject, mcpToolNames());
96 if (input.userRequested && caller.threadId === undefined) {
97 return yield* new FeedbackApprovalError({});
98 }
99​
100 const thread =
101 caller.threadId === undefined
102 ? undefined
103 : ((yield* threads.getThreadShell(caller.threadId).pipe(Effect.mapError(storageError))) ??
104 undefined);
105 const project =
106 thread === undefined
107 ? undefined
108 : Option.getOrUndefined(
109 yield* projects.getById(thread.projectId).pipe(Effect.mapError(storageError)),
110 );
111 const repository = project?.repositoryIdentity ?? undefined;
112 const sensitive = [
113 caller.threadId ?? "",
114 thread?.projectId ?? "",
115 NodeOS.homedir(),
116 NodeOS.userInfo().username,
117 NodeOS.hostname(),
118 thread?.worktreePath ?? "",
119 thread?.branch ?? "",
120 project?.workspaceRoot ?? "",
121 project?.title ?? "",
122 repository?.locator.remoteUrl ?? "",
123 repository?.origin?.remoteUrl ?? "",
124 repository?.webUrl ?? "",
125 repository?.canonicalKey ?? "",
126 repository?.owner !== undefined && repository.name !== undefined
127 ? `${repository.owner}/${repository.name}`
128 : "",
129 ];
130 const fields = {
131 kind: input.kind,
132 subject,
133 expected: scrubFeedback(input.expected, sensitive),
134 actual: scrubFeedback(input.actual, sensitive),
135 workaround: scrubFeedback(input.workaround, sensitive),
136 };
137 const id = yield* random.uuidV7();
138 const runId = thread?.activeRunId ?? null;
139 const providerList = yield* providers.getProviders;
140 if (!input.userRequested) {
141 return yield* store.store({
142 id,
143 preview: { ...fields, trace: null },
144 source: caller.source,
145 threadId: caller.threadId ?? null,
146 runId,
147 errorCode:
148 caller.threadId === undefined
149 ? undefined
150 : failures.latest(caller.threadId, subject, yield* Clock.currentTimeMillis),
151 dimensions:
152 caller.source === "mcp" && thread !== undefined
153 ? providerDimensions(providerList, thread.modelSelection)
154 : {},
155 });
156 }
157​
158 const threadId = caller.threadId!;
159 const run =
160 runId === null
161 ? undefined
162 : (yield* threads
163 .getThreadRecords(threadId, ["runs"], { runIds: [runId] })
164 .pipe(Effect.mapError(storageError))).runs.find((candidate) => candidate.id === runId);
165 if (run === undefined || run.rootNodeId === null) return yield* new FeedbackApprovalError({});
166 // Both traces are built now, so the card shows exactly what each choice sends.
167 const traces = yield* Effect.gen(function* () {
168 // Records cannot filter on started, so widen past the unstarted (queued) runs the last
169 // read found. Each pass reads more runs than the one before, until it holds enough
170 // started runs or the whole thread.
171 const window = feedbackTraceWindow(input.turns);
172 let limit = window;
173 let runs = (yield* threads.getThreadRecords(threadId, ["runs"], { latestRunLimit: limit }))
174 .runs;
175 while (runs.length === limit) {
176 const unstarted = runs.filter((candidate) => candidate.startedAt === null).length;
177 if (runs.length - unstarted >= window) break;
178 limit = window + unstarted;
179 runs = (yield* threads.getThreadRecords(threadId, ["runs"], { latestRunLimit: limit }))
180 .runs;
181 }
182 const { turnItems } = yield* threads.getThreadRecords(threadId, ["turnItems"], {
183 turnItemRunIds: runs.map((candidate) => candidate.id),
184 turnItemTypes: FEEDBACK_TRACE_ITEM_TYPES,
185 });
186 const build = (withText: boolean) =>
187 buildFeedbackTrace({
188 runs,
189 items: turnItems,
190 turns: input.turns,
191 withText,
192 sensitive,
193 t3Tools: mcpToolNames(),
194 driverOf: (candidate) =>
195 providerList.find((provider) => provider.instanceId === candidate.providerInstanceId)
196 ?.driver,
197 submittingRunId: run.id,
198 });
199 return { outline: build(false), conversation: build(true) };
200 }).pipe(Effect.mapError(storageError));
201 yield* store.showCard({
202 reportId: id,
203 threadId,
204 runId: run.id,
205 nodeId: run.rootNodeId,
206 preview: { ...fields, trace: traces.outline },
207 conversationTrace: traces.conversation.textTurns > 0 ? traces.conversation : null,
208 });
209 return { status: "awaiting_approval", note: FEEDBACK_AWAITING_APPROVAL_NOTE } as const;
210 });
211​
212 return FeedbackService.of({ submit });
213});
214​
215export const layer = (mcpToolNames: () => ReadonlyArray<string>) =>
216 Layer.effect(FeedbackService, make(mcpToolNames));