Open History to see the last commit
1import {
2 MessageId,
3 type OrchestrationMessage,
4 type ProviderUploadFeedbackResult,
5} from "@t3tools/contracts";
6
7import {
8 isAtomCommandInterrupted,
9 squashAtomCommandFailure,
10 type AtomCommandResult,
11} from "./runtime.ts";
12
13type CodexFeedbackSubmissionDetails = {
14 readonly id: MessageId;
15 readonly command: string;
16 readonly createdAt: string;
17};
18
19export type CodexFeedbackSubmission = CodexFeedbackSubmissionDetails &
20 (
21 | { readonly status: "uploading" | "interrupted" }
22 | { readonly status: "sent"; readonly feedbackId: string }
23 | { readonly status: "failed"; readonly errorMessage: string }
24 );
25
26export function parseCodexFeedbackCommand(text: string): { readonly reason?: string } | null {
27 const match = /^\/feedback(?:\s+([\s\S]*))?$/iu.exec(text.trim());
28 if (!match) {
29 return null;
30 }
31 const reason = match[1]?.trim();
32 return reason ? { reason } : {};
33}
34
35export function beginCodexFeedbackSubmission(
36 submissionsInFlight: Set<string>,
37 threadKey: string,
38): (() => void) | null {
39 if (submissionsInFlight.has(threadKey)) return null;
40 submissionsInFlight.add(threadKey);
41 return () => submissionsInFlight.delete(threadKey);
42}
43
44export function codexFeedbackMessage(
45 submission: CodexFeedbackSubmission,
46 role: "user" | "assistant" = "user",
47): OrchestrationMessage {
48 const text =
49 role === "user"
50 ? submission.command
51 : submission.status === "sent"
52 ? `Feedback sent to OpenAI.\n\nThread ID: \`${submission.feedbackId}\``
53 : submission.status === "failed"
54 ? `Could not send feedback to OpenAI.\n\n${submission.errorMessage}`
55 : "Sending feedback to OpenAI...";
56
57 return {
58 id: role === "user" ? submission.id : MessageId.make(`${submission.id}:feedback`),
59 role,
60 text,
61 turnId: null,
62 streaming: false,
63 createdAt: submission.createdAt,
64 updatedAt: submission.createdAt,
65 };
66}
67
68export async function submitCodexFeedback<E>(input: {
69 readonly submission: CodexFeedbackSubmissionDetails;
70 readonly clearDraft: () => void;
71 readonly onUpdate: (submission: CodexFeedbackSubmission) => void;
72 readonly upload: () => Promise<AtomCommandResult<ProviderUploadFeedbackResult, E>>;
73}): Promise<AtomCommandResult<ProviderUploadFeedbackResult, E>> {
74 input.onUpdate({ ...input.submission, status: "uploading" });
75 input.clearDraft();
76
77 const result = await input.upload();
78 if (result._tag === "Success") {
79 input.onUpdate({
80 ...input.submission,
81 status: "sent",
82 feedbackId: result.value.feedbackId,
83 });
84 } else if (isAtomCommandInterrupted(result)) {
85 input.onUpdate({ ...input.submission, status: "interrupted" });
86 } else {
87 const error = squashAtomCommandFailure(result);
88 input.onUpdate({
89 ...input.submission,
90 status: "failed",
91 errorMessage: error instanceof Error ? error.message : "An error occurred.",
92 });
93 }
94
95 return result;
96}