feat(codex): submit thread feedback to OpenAI (#7949)
This commit is contained in:
1 parent
afa8309806
commit
3db38b8814
36 files changed
+1152
-30
No files matched your search
@@ -552,7 +552,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
if (inFlightThreadIdsRef.current.has(threadKey)) return;
|
||||
inFlightThreadIdsRef.current.add(threadKey);
|
||||
try {
|
||||
await onSendMessage();
|
||||
const messageId = await onSendMessage();
|
||||
if (messageId === null) {
|
||||
return;
|
||||
}
|
||||
// Sending a prompt starts agent work: arm the lock-screen card while the
|
||||
// app is foregrounded and the activity token can be registered. Armed
|
||||
// after the send so its preference read and native Activity start don't
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { codexFeedbackMessage } from "@t3tools/client-runtime/state/threads";
|
||||
|
||||
import {
|
||||
EventId,
|
||||
@@ -22,6 +23,34 @@ import {
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
|
||||
describe("Codex feedback pseudo-messages", () => {
|
||||
it("keeps pending and completed feedback messages in the mobile thread body", () => {
|
||||
const pending = {
|
||||
id: MessageId.make("feedback-command"),
|
||||
command: "/feedback The agent stopped early.",
|
||||
createdAt: "2026-08-23T00:00:00.000Z",
|
||||
status: "uploading" as const,
|
||||
};
|
||||
const entries = [codexFeedbackMessage(pending), codexFeedbackMessage(pending, "assistant")].map(
|
||||
(message) => ({
|
||||
type: "message" as const,
|
||||
id: message.id,
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(deriveThreadFeedPresentation(entries, null, new Set())).toEqual(entries);
|
||||
expect(entries[1]?.message.text).toBe("Sending feedback to OpenAI...");
|
||||
|
||||
const completed = codexFeedbackMessage(
|
||||
{ ...pending, status: "sent", feedbackId: "codex-thread-1" },
|
||||
"assistant",
|
||||
);
|
||||
expect(completed.text).toContain("codex-thread-1");
|
||||
});
|
||||
});
|
||||
|
||||
const singleSelectQuestion = {
|
||||
id: "runtime",
|
||||
header: "Runtime",
|
||||
@@ -151,6 +180,44 @@ function makeThread(
|
||||
}
|
||||
|
||||
describe("buildThreadFeed", () => {
|
||||
it("keeps older local feedback before newer messages returned by the server", () => {
|
||||
const submission = {
|
||||
id: MessageId.make("feedback-command-ordering"),
|
||||
command: "/feedback The agent stopped early.",
|
||||
createdAt: "2026-08-23T00:00:01.000Z",
|
||||
status: "sent" as const,
|
||||
feedbackId: "codex-thread-1",
|
||||
};
|
||||
const laterMessage = {
|
||||
id: MessageId.make("later-server-message"),
|
||||
role: "assistant" as const,
|
||||
text: "Newer server response",
|
||||
turnId: null,
|
||||
createdAt: "2026-08-23T00:00:02.000Z",
|
||||
updatedAt: "2026-08-23T00:00:02.000Z",
|
||||
streaming: false,
|
||||
};
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-feedback-ordering"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Feedback ordering",
|
||||
messages: [laterMessage],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, {
|
||||
localMessages: [
|
||||
codexFeedbackMessage(submission),
|
||||
codexFeedbackMessage(submission, "assistant"),
|
||||
],
|
||||
});
|
||||
|
||||
expect(feed.map((entry) => entry.id)).toEqual([
|
||||
"feedback-command-ordering",
|
||||
"feedback-command-ordering:feedback",
|
||||
"later-server-message",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps historic work entries attributed to their turns", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
|
||||
@@ -1526,15 +1526,19 @@ export function buildThreadFeed(
|
||||
thread: OrchestrationThread,
|
||||
options?: {
|
||||
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
|
||||
readonly localMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
|
||||
},
|
||||
): ThreadFeedEntry[] {
|
||||
const loadedMessages = options?.loadedMessages ?? thread.messages;
|
||||
const messages = options?.localMessages
|
||||
? [...loadedMessages, ...options.localMessages]
|
||||
: loadedMessages;
|
||||
const oldestLoadedMessageCreatedAt =
|
||||
options?.loadedMessages !== undefined ? (loadedMessages[0]?.createdAt ?? null) : null;
|
||||
const workLogEntries = deriveWorkLogEntries(thread.activities);
|
||||
const entries = Arr.sortWith(
|
||||
[
|
||||
...loadedMessages.map<RawThreadFeedEntry>((message) => ({
|
||||
...messages.map<RawThreadFeedEntry>((message) => ({
|
||||
type: "message",
|
||||
id: message.id,
|
||||
createdAt: message.createdAt,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Alert } from "react-native";
|
||||
import * as Cause from "effect/Cause";
|
||||
|
||||
import {
|
||||
CommandId,
|
||||
@@ -11,6 +13,13 @@ import {
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import {
|
||||
codexFeedbackMessage,
|
||||
parseCodexFeedbackCommand,
|
||||
submitCodexFeedback,
|
||||
type CodexFeedbackSubmission,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
|
||||
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
|
||||
@@ -21,6 +30,7 @@ import {
|
||||
} from "../lib/composerImages";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
|
||||
import { buildThreadFeed } from "../lib/threadActivity";
|
||||
import { appAtomRegistry } from "../state/atom-registry";
|
||||
import {
|
||||
@@ -41,6 +51,8 @@ import { useSelectedThreadDetail } from "../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../state/use-thread-selection";
|
||||
import { enqueueThreadOutboxMessage } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
|
||||
export function appendReviewCommentToDraft(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -74,10 +86,16 @@ export function useThreadDraftForThread(input: {
|
||||
}
|
||||
|
||||
export function useThreadComposerState() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const { selectedThread: selectedThreadShell, selectedEnvironmentRuntime } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const composerDrafts = useAtomValue(composerDraftsAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
|
||||
Record<string, ReadonlyArray<CodexFeedbackSubmission>>
|
||||
>({});
|
||||
const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
|
||||
reportFailure: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
ensureComposerDraftsLoaded();
|
||||
@@ -90,10 +108,21 @@ export function useThreadComposerState() {
|
||||
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
);
|
||||
const selectedThreadFeed = useMemo(
|
||||
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
|
||||
[selectedThreadDetail],
|
||||
);
|
||||
const selectedThreadFeed = useMemo(() => {
|
||||
if (!selectedThreadDetail) {
|
||||
return [];
|
||||
}
|
||||
const submissions = selectedThreadKey
|
||||
? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? [])
|
||||
: [];
|
||||
return buildThreadFeed(selectedThreadDetail, {
|
||||
localMessages: submissions.flatMap((submission) =>
|
||||
submission.status === "interrupted"
|
||||
? []
|
||||
: [codexFeedbackMessage(submission), codexFeedbackMessage(submission, "assistant")],
|
||||
),
|
||||
});
|
||||
}, [feedbackSubmissionsByThreadKey, selectedThreadDetail, selectedThreadKey]);
|
||||
|
||||
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
|
||||
const draftMessage = selectedDraft?.text ?? "";
|
||||
@@ -143,6 +172,70 @@ export function useThreadComposerState() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
|
||||
(entry) => entry.instanceId === thread.modelSelection.instanceId,
|
||||
);
|
||||
const feedbackCommand =
|
||||
attachments.length === 0 &&
|
||||
(provider?.driver === "codex" || thread.session?.providerName === "codex")
|
||||
? parseCodexFeedbackCommand(text)
|
||||
: null;
|
||||
if (feedbackCommand) {
|
||||
if (thread.session === null) {
|
||||
Alert.alert("Start a Codex thread first", "Send a message before you submit feedback.");
|
||||
return null;
|
||||
}
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const result = await submitCodexFeedback({
|
||||
submission: {
|
||||
id: MessageId.make(metadata.messageId),
|
||||
command: text,
|
||||
createdAt: metadata.createdAt,
|
||||
},
|
||||
clearDraft: () => clearComposerDraftContent(threadKey),
|
||||
onUpdate: (submission) => {
|
||||
setFeedbackSubmissionsByThreadKey((current) => {
|
||||
const existing = current[threadKey] ?? [];
|
||||
const found = existing.some((entry) => entry.id === submission.id);
|
||||
return {
|
||||
...current,
|
||||
[threadKey]: found
|
||||
? existing.map((entry) => (entry.id === submission.id ? submission : entry))
|
||||
: [...existing, submission],
|
||||
};
|
||||
});
|
||||
},
|
||||
upload: () =>
|
||||
uploadThreadFeedback({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
input: {
|
||||
threadId: selectedThreadShell.id,
|
||||
...feedbackCommand,
|
||||
},
|
||||
}),
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
if (isAtomCommandInterrupted(result)) {
|
||||
return null;
|
||||
}
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not send feedback to OpenAI",
|
||||
error instanceof Error ? error.message : "An error occurred.",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const feedbackId = result.value.feedbackId;
|
||||
Alert.alert("Feedback sent to OpenAI", `Thread ID: ${feedbackId}`, [
|
||||
{ text: "OK", style: "cancel" },
|
||||
{
|
||||
text: "Copy ID",
|
||||
onPress: () => copyTextWithHaptic(feedbackId, { target: "Codex feedback thread ID" }),
|
||||
},
|
||||
]);
|
||||
return null;
|
||||
}
|
||||
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const messageId = MessageId.make(metadata.messageId);
|
||||
// Enqueue publishes the queued atom synchronously (the durable write
|
||||
@@ -175,7 +268,12 @@ export function useThreadComposerState() {
|
||||
);
|
||||
});
|
||||
return messageId;
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
}, [
|
||||
selectedEnvironmentRuntime?.serverConfig?.providers,
|
||||
selectedThreadDetail,
|
||||
selectedThreadShell,
|
||||
uploadThreadFeedback,
|
||||
]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
(value: string) => {
|
||||
|
||||
@@ -116,6 +116,7 @@ const startupDependencies = Layer.mergeAll(
|
||||
getCapabilities: () => Effect.die("unused"),
|
||||
getInstanceInfo: () => Effect.die("unused"),
|
||||
rollbackConversation: () => Effect.die("unused"),
|
||||
uploadFeedback: () => Effect.die("unused"),
|
||||
streamEvents: Stream.empty,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -37,6 +37,12 @@ describe("RPC authorization scopes", () => {
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.cloudInstallRelayClient)).toBe(AuthRelayWriteScope);
|
||||
});
|
||||
|
||||
it("requires permission to operate on a thread before uploading feedback", () => {
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.providerUploadFeedback)).toBe(
|
||||
AuthOrchestrationOperateScope,
|
||||
);
|
||||
});
|
||||
|
||||
it("reads the reviewer menu under the same scope as the pull request it belongs to", () => {
|
||||
// The candidate list is a read like the detail beside it, and asking somebody for a review is
|
||||
// a write like every other pull request operation.
|
||||
|
||||
@@ -84,6 +84,7 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.providerUploadFeedback]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
|
||||
|
||||
@@ -125,6 +125,7 @@ function createProviderServiceHarness(
|
||||
},
|
||||
}),
|
||||
rollbackConversation,
|
||||
uploadFeedback: () => unsupported(),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
|
||||
@@ -340,6 +340,7 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
},
|
||||
rollbackConversation: () => unsupported(),
|
||||
uploadFeedback: () => unsupported(),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
|
||||
@@ -125,6 +125,7 @@ function createProviderServiceHarness() {
|
||||
});
|
||||
},
|
||||
rollbackConversation: () => unsupported(),
|
||||
uploadFeedback: () => unsupported(),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
|
||||
@@ -104,6 +104,10 @@ class FakeCodexRuntime implements CodexSessionRuntimeShape {
|
||||
}),
|
||||
);
|
||||
|
||||
public readonly uploadFeedbackImpl = vi.fn((_reason?: string) =>
|
||||
Promise.resolve({ threadId: "provider-thread-1" }),
|
||||
);
|
||||
|
||||
public readonly respondToRequestImpl = vi.fn(
|
||||
(_requestId: ApprovalRequestId, _decision: ProviderApprovalDecision): Promise<void> =>
|
||||
Promise.resolve(undefined),
|
||||
@@ -142,6 +146,10 @@ class FakeCodexRuntime implements CodexSessionRuntimeShape {
|
||||
return Effect.promise(() => this.rollbackThreadImpl(numTurns));
|
||||
}
|
||||
|
||||
uploadFeedback(reason?: string) {
|
||||
return Effect.promise(() => this.uploadFeedbackImpl(reason));
|
||||
}
|
||||
|
||||
respondToRequest(requestId: ApprovalRequestId, decision: ProviderApprovalDecision) {
|
||||
return Effect.promise(() => this.respondToRequestImpl(requestId, decision));
|
||||
}
|
||||
@@ -328,6 +336,42 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uploads feedback for the active Codex thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const threadId = asThreadId("thread-feedback");
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const runtime = sessionRuntimeFactory.lastRuntime;
|
||||
NodeAssert.ok(runtime);
|
||||
|
||||
const result = yield* adapter.uploadFeedback({
|
||||
threadId,
|
||||
reason: "The agent stopped early.",
|
||||
});
|
||||
|
||||
NodeAssert.deepStrictEqual(result, { feedbackId: "provider-thread-1" });
|
||||
NodeAssert.deepStrictEqual(runtime.uploadFeedbackImpl.mock.calls, [
|
||||
["The agent stopped early."],
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects feedback for an unknown Codex thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const result = yield* adapter
|
||||
.uploadFeedback({ threadId: asThreadId("thread-feedback-missing") })
|
||||
.pipe(Effect.result);
|
||||
|
||||
NodeAssert.equal(result._tag, "Failure");
|
||||
NodeAssert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps codex model options before sending a turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
|
||||
@@ -1891,6 +1891,17 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
);
|
||||
};
|
||||
|
||||
const uploadFeedback: CodexAdapterShape["uploadFeedback"] = (input) =>
|
||||
requireSession(input.threadId).pipe(
|
||||
Effect.flatMap((session) => session.runtime.uploadFeedback(input.reason)),
|
||||
Effect.map(({ threadId }) => ({ feedbackId: threadId })),
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ProviderAdapterSessionNotFoundError"
|
||||
? cause
|
||||
: mapCodexRuntimeError(input.threadId, "feedback/upload", cause),
|
||||
),
|
||||
);
|
||||
|
||||
const respondToRequest: CodexAdapterShape["respondToRequest"] = (threadId, requestId, decision) =>
|
||||
requireSession(threadId).pipe(
|
||||
Effect.flatMap((session) => session.runtime.respondToRequest(requestId, decision)),
|
||||
@@ -1978,6 +1989,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
interruptTurn,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
uploadFeedback,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
|
||||
@@ -607,6 +607,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
checkedAt,
|
||||
models: snapshot.models,
|
||||
skills: snapshot.skills,
|
||||
slashCommands: [
|
||||
{
|
||||
name: "feedback",
|
||||
description: "Send this thread and Codex logs to OpenAI",
|
||||
input: { hint: "Describe the issue (optional)" },
|
||||
},
|
||||
],
|
||||
probe: {
|
||||
installed: true,
|
||||
version: snapshot.version ?? null,
|
||||
|
||||
@@ -142,6 +142,9 @@ export interface CodexSessionRuntimeShape {
|
||||
readonly rollbackThread: (
|
||||
numTurns: number,
|
||||
) => Effect.Effect<CodexThreadSnapshot, CodexSessionRuntimeError>;
|
||||
readonly uploadFeedback: (
|
||||
reason?: string,
|
||||
) => Effect.Effect<EffectCodexSchema.V2FeedbackUploadResponse, CodexSessionRuntimeError>;
|
||||
readonly respondToRequest: (
|
||||
requestId: ApprovalRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
@@ -1914,6 +1917,16 @@ export const makeCodexSessionRuntime = (
|
||||
});
|
||||
return parseThreadSnapshot(response);
|
||||
}),
|
||||
uploadFeedback: (reason) =>
|
||||
Effect.gen(function* () {
|
||||
const providerThreadId = yield* readProviderThreadId;
|
||||
return yield* client.request("feedback/upload", {
|
||||
classification: "bug",
|
||||
includeLogs: true,
|
||||
...(reason ? { reason } : {}),
|
||||
threadId: providerThreadId,
|
||||
});
|
||||
}),
|
||||
respondToRequest: (requestId, decision) =>
|
||||
Effect.gen(function* () {
|
||||
const pending = (yield* Ref.get(pendingApprovalsRef)).get(requestId);
|
||||
|
||||
@@ -40,6 +40,7 @@ const fakeCodexAdapter: CodexAdapter.CodexAdapterShape = {
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
uploadFeedback: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
@@ -381,6 +381,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
shortDescription: "Debug failing GitHub Actions checks",
|
||||
},
|
||||
]);
|
||||
assert.deepStrictEqual(status.slashCommands, [
|
||||
{
|
||||
name: "feedback",
|
||||
description: "Send this thread and Codex logs to OpenAI",
|
||||
input: { hint: "Describe the issue (optional)" },
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ import type {
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderTurnStartResult,
|
||||
ProviderUploadFeedbackInput,
|
||||
ProviderUploadFeedbackResult,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -197,6 +199,13 @@ function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) {
|
||||
Effect.succeed({ threadId, turns: [] }),
|
||||
);
|
||||
|
||||
const uploadFeedback = vi.fn(
|
||||
(
|
||||
input: ProviderUploadFeedbackInput,
|
||||
): Effect.Effect<ProviderUploadFeedbackResult, ProviderAdapterError> =>
|
||||
Effect.succeed({ feedbackId: `feedback-${input.threadId}` }),
|
||||
);
|
||||
|
||||
const stopAll = vi.fn(
|
||||
(): Effect.Effect<void, ProviderAdapterError> =>
|
||||
Effect.sync(() => {
|
||||
@@ -219,6 +228,7 @@ function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) {
|
||||
hasSession,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
...(provider === CODEX_DRIVER ? { uploadFeedback } : {}),
|
||||
stopAll,
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
@@ -254,6 +264,7 @@ function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) {
|
||||
hasSession,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
uploadFeedback,
|
||||
stopAll,
|
||||
};
|
||||
}
|
||||
@@ -595,6 +606,68 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
|
||||
|
||||
const routing = makeProviderServiceLayer();
|
||||
|
||||
it.effect(
|
||||
"ProviderServiceLive uploads feedback through the adapter that recovered the session",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const original = makeFakeCodexAdapter();
|
||||
const replacement = makeFakeCodexAdapter();
|
||||
const baseRegistry = makeAdapterRegistryMock({ [CODEX_DRIVER]: original.adapter });
|
||||
let swapAfterFirstLookup = false;
|
||||
let feedbackLookupCount = 0;
|
||||
const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = {
|
||||
...baseRegistry,
|
||||
getByInstance: (instanceId) => {
|
||||
if (instanceId !== codexInstanceId) {
|
||||
return baseRegistry.getByInstance(instanceId);
|
||||
}
|
||||
const useReplacement = swapAfterFirstLookup && feedbackLookupCount++ > 0;
|
||||
return Effect.succeed(useReplacement ? replacement.adapter : original.adapter);
|
||||
},
|
||||
};
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(serverConfigTestLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const threadId = asThreadId("thread-feedback-adapter-replacement");
|
||||
yield* provider.startSession(threadId, {
|
||||
provider: CODEX_DRIVER,
|
||||
providerInstanceId: codexInstanceId,
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* original.stopSession(threadId);
|
||||
original.uploadFeedback.mockClear();
|
||||
replacement.uploadFeedback.mockClear();
|
||||
swapAfterFirstLookup = true;
|
||||
|
||||
const result = yield* provider.uploadFeedback({ threadId });
|
||||
|
||||
assert.deepStrictEqual(result, { feedbackId: `feedback-${threadId}` });
|
||||
assert.strictEqual(original.uploadFeedback.mock.calls.length, 0);
|
||||
assert.deepStrictEqual(replacement.uploadFeedback.mock.calls, [[{ threadId }]]);
|
||||
}).pipe(Effect.provide(providerLayer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("ProviderServiceLive writes canonical events to the emitting thread segment", () =>
|
||||
Effect.gen(function* () {
|
||||
const codex = makeFakeCodexAdapter();
|
||||
@@ -941,6 +1014,93 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes feedback to the Codex adapter and returns its feedback ID", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const threadId = asThreadId("thread-feedback-route");
|
||||
yield* provider.startSession(threadId, {
|
||||
provider: CODEX_DRIVER,
|
||||
providerInstanceId: codexInstanceId,
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
routing.codex.uploadFeedback.mockClear();
|
||||
|
||||
const result = yield* provider.uploadFeedback({
|
||||
threadId,
|
||||
reason: "The agent stopped early.",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, { feedbackId: `feedback-${threadId}` });
|
||||
assert.deepStrictEqual(routing.codex.uploadFeedback.mock.calls, [
|
||||
[{ threadId, reason: "The agent stopped early." }],
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers a stopped Codex session before uploading feedback", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const threadId = asThreadId("thread-feedback-recover");
|
||||
yield* provider.startSession(threadId, {
|
||||
provider: CODEX_DRIVER,
|
||||
providerInstanceId: codexInstanceId,
|
||||
threadId,
|
||||
cwd: "/tmp/feedback-project",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* routing.codex.stopSession(threadId);
|
||||
routing.codex.startSession.mockClear();
|
||||
routing.codex.uploadFeedback.mockClear();
|
||||
|
||||
const result = yield* provider.uploadFeedback({ threadId });
|
||||
|
||||
assert.deepStrictEqual(result, { feedbackId: `feedback-${threadId}` });
|
||||
assert.strictEqual(routing.codex.startSession.mock.calls.length, 1);
|
||||
assert.deepStrictEqual(routing.codex.uploadFeedback.mock.calls, [[{ threadId }]]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects feedback for providers that do not support uploads", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const threadId = asThreadId("thread-feedback-claude");
|
||||
yield* provider.startSession(threadId, {
|
||||
provider: CLAUDE_AGENT_DRIVER,
|
||||
providerInstanceId: claudeAgentInstanceId,
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const error = yield* provider.uploadFeedback({ threadId }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ProviderValidationError);
|
||||
assert.include(error.issue, "does not support feedback uploads");
|
||||
routing.claude.startSession.mockClear();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not restart an unsupported provider before rejecting feedback", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const threadId = asThreadId("thread-feedback-unsupported-stopped");
|
||||
yield* provider.startSession(threadId, {
|
||||
provider: CLAUDE_AGENT_DRIVER,
|
||||
providerInstanceId: claudeAgentInstanceId,
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* routing.claude.stopSession(threadId);
|
||||
routing.claude.startSession.mockClear();
|
||||
|
||||
const error = yield* provider.uploadFeedback({ threadId }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ProviderValidationError);
|
||||
assert.include(error.issue, "does not support feedback uploads");
|
||||
assert.strictEqual(routing.claude.startSession.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("appends attachment file paths to the turn input text", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
ProviderSendTurnInput,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ProviderUploadFeedbackInput,
|
||||
type ProviderInstanceId,
|
||||
type ProviderDriverKind,
|
||||
type ProviderRuntimeEvent,
|
||||
@@ -1117,6 +1118,47 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
);
|
||||
});
|
||||
|
||||
const uploadFeedback: ProviderServiceMethod<"uploadFeedback"> = Effect.fn("uploadFeedback")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.uploadFeedback",
|
||||
schema: ProviderUploadFeedbackInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
let routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.uploadFeedback",
|
||||
allowRecovery: false,
|
||||
});
|
||||
if (routed.adapter.uploadFeedback === undefined) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.uploadFeedback",
|
||||
`Provider '${routed.adapter.provider}' does not support feedback uploads.`,
|
||||
);
|
||||
}
|
||||
if (!routed.isActive) {
|
||||
routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.uploadFeedback",
|
||||
allowRecovery: true,
|
||||
});
|
||||
}
|
||||
const uploadFeedback = routed.adapter.uploadFeedback;
|
||||
if (uploadFeedback === undefined) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.uploadFeedback",
|
||||
`Provider '${routed.adapter.provider}' does not support feedback uploads.`,
|
||||
);
|
||||
}
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.operation": "upload-feedback",
|
||||
"provider.kind": routed.adapter.provider,
|
||||
"provider.thread_id": input.threadId,
|
||||
});
|
||||
return yield* uploadFeedback(input);
|
||||
},
|
||||
);
|
||||
|
||||
const runStopAll = Effect.fn("runStopAll")(function* () {
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
const currentAdapters = yield* getAdapterEntries;
|
||||
@@ -1188,6 +1230,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
getCapabilities,
|
||||
getInstanceInfo,
|
||||
rollbackConversation,
|
||||
uploadFeedback,
|
||||
// Each access creates a fresh PubSub subscription so that multiple
|
||||
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
|
||||
// independently receive all runtime events.
|
||||
|
||||
@@ -184,6 +184,7 @@ describe("ProviderSessionReaper", () => {
|
||||
});
|
||||
},
|
||||
rollbackConversation: () => unsupported(),
|
||||
uploadFeedback: () => unsupported(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
|
||||
@@ -16,4 +16,8 @@ import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
* CodexAdapterShape — per-instance Codex adapter contract. Carries
|
||||
* a branded driver kind as the nominal discriminant.
|
||||
*/
|
||||
export interface CodexAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
|
||||
export interface CodexAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
|
||||
readonly uploadFeedback: NonNullable<
|
||||
ProviderAdapterShape<ProviderAdapterError>["uploadFeedback"]
|
||||
>;
|
||||
}
|
||||
@@ -16,6 +16,8 @@ import type {
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderUploadFeedbackInput,
|
||||
ProviderUploadFeedbackResult,
|
||||
ThreadId,
|
||||
ProviderTurnStartResult,
|
||||
TurnId,
|
||||
@@ -114,6 +116,13 @@ export interface ProviderAdapterShape<TError> {
|
||||
numTurns: number,
|
||||
) => Effect.Effect<ProviderThreadSnapshot, TError>;
|
||||
|
||||
/**
|
||||
* Upload a thread to the provider when the adapter supports feedback.
|
||||
*/
|
||||
readonly uploadFeedback?: (
|
||||
input: ProviderUploadFeedbackInput,
|
||||
) => Effect.Effect<ProviderUploadFeedbackResult, TError>;
|
||||
|
||||
/**
|
||||
* Stop all sessions owned by this adapter.
|
||||
*/
|
||||
|
||||
@@ -21,6 +21,8 @@ import type {
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ProviderUploadFeedbackInput,
|
||||
ProviderUploadFeedbackResult,
|
||||
ThreadId,
|
||||
ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -105,6 +107,13 @@ export interface ProviderServiceShape {
|
||||
readonly numTurns: number;
|
||||
}) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Upload a thread and return the provider's shareable feedback identifier.
|
||||
*/
|
||||
readonly uploadFeedback: (
|
||||
input: ProviderUploadFeedbackInput,
|
||||
) => Effect.Effect<ProviderUploadFeedbackResult, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Canonical provider runtime event stream.
|
||||
*
|
||||
|
||||
@@ -114,6 +114,8 @@ import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSna
|
||||
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
|
||||
import { PersistenceSqlError } from "./persistence/Errors.ts";
|
||||
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
|
||||
import * as ProviderService from "./provider/Services/ProviderService.ts";
|
||||
import { ProviderAdapterRequestError } from "./provider/Errors.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts";
|
||||
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
|
||||
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
|
||||
@@ -387,6 +389,7 @@ const buildAppUnderTest = (options?: {
|
||||
layers?: {
|
||||
keybindings?: Partial<Keybindings.Keybindings["Service"]>;
|
||||
providerRegistry?: Partial<ProviderRegistry.ProviderRegistry["Service"]>;
|
||||
providerService?: Partial<ProviderService.ProviderService["Service"]>;
|
||||
serverSettings?: Partial<ServerSettings.ServerSettingsService["Service"]>;
|
||||
externalLauncher?: Partial<ExternalLauncher.ExternalLauncher["Service"]>;
|
||||
vcsDriver?: Partial<VcsDriver.VcsDriver["Service"]>;
|
||||
@@ -629,18 +632,24 @@ const buildAppUnderTest = (options?: {
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ProviderRegistry.ProviderRegistry)({
|
||||
getProviders: Effect.succeed([]),
|
||||
refresh: () => Effect.succeed([]),
|
||||
refreshInstance: () => Effect.succeed([]),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null }),
|
||||
),
|
||||
setProviderMaintenanceActionState: () => Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
...options?.layers?.providerRegistry,
|
||||
}),
|
||||
Layer.mergeAll(
|
||||
Layer.mock(ProviderRegistry.ProviderRegistry)({
|
||||
getProviders: Effect.succeed([]),
|
||||
refresh: () => Effect.succeed([]),
|
||||
refreshInstance: () => Effect.succeed([]),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null }),
|
||||
),
|
||||
setProviderMaintenanceActionState: () => Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
...options?.layers?.providerRegistry,
|
||||
}),
|
||||
Layer.mock(ProviderService.ProviderService)({
|
||||
uploadFeedback: () => Effect.die("Provider feedback is not stubbed in this test"),
|
||||
...options?.layers?.providerService,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ServerSettings.ServerSettingsService)({
|
||||
@@ -4452,6 +4461,65 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("uploads Codex thread feedback through websocket rpc", () =>
|
||||
Effect.gen(function* () {
|
||||
const input = {
|
||||
threadId: ThreadId.make("thread-feedback"),
|
||||
reason: "The agent stopped early.",
|
||||
};
|
||||
const uploadFeedback = vi.fn<ProviderService.ProviderService["Service"]["uploadFeedback"]>(
|
||||
() => Effect.succeed({ feedbackId: "codex-thread-feedback" }),
|
||||
);
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
providerService: { uploadFeedback },
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.providerUploadFeedback](input)),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(response, { feedbackId: "codex-thread-feedback" });
|
||||
assert.deepStrictEqual(uploadFeedback.mock.calls, [[input]]);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("keeps feedback errors structured across websocket rpc", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-feedback-failure");
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
providerService: {
|
||||
uploadFeedback: () =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "codex",
|
||||
method: "feedback/upload",
|
||||
detail: "private provider detail",
|
||||
}),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const error = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.providerUploadFeedback]({ threadId }).pipe(Effect.flip),
|
||||
),
|
||||
);
|
||||
|
||||
assert.strictEqual(error._tag, "ProviderUploadFeedbackError");
|
||||
if (error._tag === "ProviderUploadFeedbackError") {
|
||||
assert.strictEqual(error.threadId, threadId);
|
||||
assert.strictEqual(error.message, `Failed to upload feedback for thread ${threadId}.`);
|
||||
assert.isDefined(error.cause);
|
||||
}
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("shares one preview automation broker across websocket sessions", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -55,6 +55,7 @@ const makeProviderService = (liveThreadIds: ReadonlyArray<ThreadId> = []) =>
|
||||
getCapabilities: () => Effect.die("unused"),
|
||||
getInstanceInfo: () => Effect.die("unused"),
|
||||
rollbackConversation: () => Effect.die("unused"),
|
||||
uploadFeedback: () => Effect.die("unused"),
|
||||
streamEvents: Stream.empty,
|
||||
}) satisfies ProviderService.ProviderService["Service"];
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
ProjectSearchContentsError,
|
||||
ProjectSearchEntriesError,
|
||||
ProjectWriteFileError,
|
||||
ProviderUploadFeedbackError,
|
||||
RelayClientInstallFailedError,
|
||||
type RelayClientInstallProgressEvent,
|
||||
type ServerSelfUpdateError,
|
||||
@@ -81,6 +82,7 @@ import {
|
||||
observeRpcStreamEffect as instrumentRpcStreamEffect,
|
||||
} from "./observability/RpcInstrumentation.ts";
|
||||
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
|
||||
import * as ProviderService from "./provider/Services/ProviderService.ts";
|
||||
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
|
||||
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
|
||||
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
|
||||
@@ -432,6 +434,7 @@ const makeWsRpcLayer = (
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const portDiscovery = yield* PortScanner.PortDiscovery;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
|
||||
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
@@ -1534,6 +1537,20 @@ const makeWsRpcLayer = (
|
||||
).pipe(Effect.map((providers) => ({ providers }))),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.providerUploadFeedback]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.providerUploadFeedback,
|
||||
providerService.uploadFeedback(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderUploadFeedbackError({
|
||||
threadId: input.threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "provider" },
|
||||
),
|
||||
[WS_METHODS.serverUpdateProvider]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverUpdateProvider,
|
||||
|
||||
@@ -33,6 +33,12 @@ import {
|
||||
effectiveSnoozed,
|
||||
threadWokeAt,
|
||||
} from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
codexFeedbackMessage,
|
||||
parseCodexFeedbackCommand,
|
||||
submitCodexFeedback,
|
||||
type CodexFeedbackSubmission,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
@@ -124,6 +130,7 @@ import {
|
||||
type TurnDiffSummary,
|
||||
} from "../types";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { isCommandPaletteOpen } from "../commandPaletteBus";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
@@ -1268,6 +1275,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
reportFailure: false,
|
||||
});
|
||||
const startThreadTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
|
||||
const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -1383,6 +1393,16 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
|
||||
const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
|
||||
Record<string, ReadonlyArray<CodexFeedbackSubmission>>
|
||||
>({});
|
||||
const feedbackSubmissions = useMemo(
|
||||
() => feedbackSubmissionsByThreadKey[routeThreadKey] ?? [],
|
||||
[feedbackSubmissionsByThreadKey, routeThreadKey],
|
||||
);
|
||||
const feedbackUploading = feedbackSubmissions.some(
|
||||
(submission) => submission.status === "uploading",
|
||||
);
|
||||
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
|
||||
optimisticUserMessagesRef.current = optimisticUserMessages;
|
||||
const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState<
|
||||
@@ -1444,6 +1464,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
|
||||
const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
|
||||
const sendInFlightRef = useRef(false);
|
||||
const feedbackUploadsInFlightRef = useRef(new Set<string>());
|
||||
const terminalUiOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
@@ -2603,16 +2624,29 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
return changed ? { ...message, attachments } : message;
|
||||
});
|
||||
|
||||
if (optimisticUserMessages.length === 0) {
|
||||
const localMessages = [
|
||||
...optimisticUserMessages,
|
||||
...feedbackSubmissions.flatMap((submission) =>
|
||||
submission.status === "interrupted"
|
||||
? []
|
||||
: [codexFeedbackMessage(submission), codexFeedbackMessage(submission, "assistant")],
|
||||
),
|
||||
];
|
||||
if (localMessages.length === 0) {
|
||||
return serverMessagesWithPreviewHandoff;
|
||||
}
|
||||
const serverIds = new Set(serverMessagesWithPreviewHandoff.map((message) => message.id));
|
||||
const pendingMessages = optimisticUserMessages.filter((message) => !serverIds.has(message.id));
|
||||
const pendingMessages = localMessages.filter((message) => !serverIds.has(message.id));
|
||||
if (pendingMessages.length === 0) {
|
||||
return serverMessagesWithPreviewHandoff;
|
||||
}
|
||||
return [...serverMessagesWithPreviewHandoff, ...pendingMessages];
|
||||
}, [attachmentPreviewHandoffByMessageId, displayServerMessages, optimisticUserMessages]);
|
||||
}, [
|
||||
attachmentPreviewHandoffByMessageId,
|
||||
displayServerMessages,
|
||||
feedbackSubmissions,
|
||||
optimisticUserMessages,
|
||||
]);
|
||||
const timelineEntries = useMemo(
|
||||
() =>
|
||||
deriveTimelineEntries(
|
||||
@@ -5061,7 +5095,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
isSendBusy ||
|
||||
isConnecting ||
|
||||
threadDetailLoading ||
|
||||
sendInFlightRef.current
|
||||
sendInFlightRef.current ||
|
||||
feedbackUploadsInFlightRef.current.has(routeThreadKey)
|
||||
) {
|
||||
notifyDirectAnnotationAttached();
|
||||
return;
|
||||
@@ -5136,6 +5171,101 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
composerPreviewAnnotations.length +
|
||||
composerReviewComments.length,
|
||||
});
|
||||
const feedbackCommand =
|
||||
ctxSelectedProvider === "codex" &&
|
||||
composerImages.length === 0 &&
|
||||
sendableComposerTerminalContexts.length === 0 &&
|
||||
composerElementContexts.length === 0 &&
|
||||
composerPreviewAnnotations.length === 0 &&
|
||||
composerReviewComments.length === 0
|
||||
? parseCodexFeedbackCommand(trimmed)
|
||||
: null;
|
||||
if (feedbackCommand) {
|
||||
if (!isServerThread || activeThread.session === null) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title: "Start a Codex thread first",
|
||||
description: "Send a message before you submit feedback.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
feedbackUploadsInFlightRef.current.add(routeThreadKey);
|
||||
const result = await submitCodexFeedback({
|
||||
submission: {
|
||||
id: newMessageId(),
|
||||
command: trimmed,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
clearDraft: () => {
|
||||
promptRef.current = "";
|
||||
clearComposerDraftContent(composerDraftTarget);
|
||||
composerRef.current?.resetCursorState();
|
||||
scrollToEnd();
|
||||
},
|
||||
onUpdate: (submission) => {
|
||||
setFeedbackSubmissionsByThreadKey((current) => {
|
||||
const existing = current[routeThreadKey] ?? [];
|
||||
const found = existing.some((entry) => entry.id === submission.id);
|
||||
return {
|
||||
...current,
|
||||
[routeThreadKey]: found
|
||||
? existing.map((entry) => (entry.id === submission.id ? submission : entry))
|
||||
: [...existing, submission],
|
||||
};
|
||||
});
|
||||
},
|
||||
upload: () =>
|
||||
uploadThreadFeedback({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: activeThread.id,
|
||||
...feedbackCommand,
|
||||
},
|
||||
}),
|
||||
}).finally(() => {
|
||||
feedbackUploadsInFlightRef.current.delete(routeThreadKey);
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not send feedback to OpenAI",
|
||||
description: chatActionErrorMessage(squashAtomCommandFailure(result)),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const feedbackId = result.value.feedbackId;
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "success",
|
||||
title: "Feedback sent to OpenAI",
|
||||
description: `Thread ID: ${feedbackId}`,
|
||||
timeout: 0,
|
||||
actionProps: {
|
||||
children: "Copy ID",
|
||||
onClick: () => {
|
||||
void writeTextToClipboard(feedbackId, "Codex feedback thread ID").catch(
|
||||
(error: unknown) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not copy thread ID",
|
||||
description: chatActionErrorMessage(error),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!directAnnotation && showPlanFollowUpPrompt && activeProposedPlan) {
|
||||
const followUp = resolvePlanFollowUpSubmission({
|
||||
draftText: trimmed,
|
||||
@@ -6633,7 +6763,13 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
sendDisabledReason={threadDetailLoading ? "Messages loading" : null}
|
||||
sendDisabledReason={
|
||||
feedbackUploading
|
||||
? "Sending feedback"
|
||||
: threadDetailLoading
|
||||
? "Messages loading"
|
||||
: null
|
||||
}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
externalDrawerAttached={externalComposerDrawerAttached}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
|
||||
@@ -87,7 +87,7 @@ function renderRunningActions(showSendWhileRunning: boolean, hasSendableContent:
|
||||
);
|
||||
}
|
||||
|
||||
function renderSendButton() {
|
||||
function renderSendButton(sendDisabledReason: string | null = null) {
|
||||
return renderToStaticMarkup(
|
||||
createElement(ComposerPrimaryActions, {
|
||||
compact: true,
|
||||
@@ -96,7 +96,7 @@ function renderSendButton() {
|
||||
showPlanFollowUpPrompt: false,
|
||||
promptHasText: true,
|
||||
isSendBusy: false,
|
||||
sendDisabledReason: null,
|
||||
sendDisabledReason,
|
||||
isConnecting: false,
|
||||
isEnvironmentUnavailable: false,
|
||||
isPreparingWorktree: false,
|
||||
@@ -204,6 +204,13 @@ describe("formatPendingPrimaryActionLabel", () => {
|
||||
});
|
||||
|
||||
describe("ComposerPrimaryActions", () => {
|
||||
it("disables and labels the send button while feedback is uploading", () => {
|
||||
const markup = renderSendButton("Sending feedback");
|
||||
|
||||
expect(markup).toContain("disabled");
|
||||
expect(markup).toContain('aria-label="Sending feedback"');
|
||||
});
|
||||
|
||||
it("offers Stop generation while a running turn is waiting for user input", () => {
|
||||
expect(renderPendingActions(true)).toContain('aria-label="Stop generation"');
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { CheckpointRef, EnvironmentId, MessageId, TurnId } from "@t3tools/contracts";
|
||||
import { codexFeedbackMessage } from "@t3tools/client-runtime/state/threads";
|
||||
import { createRef, type ReactNode, type Ref } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeAll, describe, expect, it, vi } from "vite-plus/test";
|
||||
@@ -236,6 +237,61 @@ function buildAssistantTimelineEntry(text: string) {
|
||||
}
|
||||
|
||||
describe("MessagesTimeline", () => {
|
||||
it("renders a feedback command and its pending response as normal thread messages", () => {
|
||||
const submission = {
|
||||
id: MessageId.make("feedback-command"),
|
||||
command: "/feedback The agent stopped early.",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
status: "uploading" as const,
|
||||
};
|
||||
const messages = [
|
||||
codexFeedbackMessage(submission),
|
||||
codexFeedbackMessage(submission, "assistant"),
|
||||
];
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={messages.map((message) => ({
|
||||
id: message.id,
|
||||
kind: "message" as const,
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
}))}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("/feedback The agent stopped early.");
|
||||
expect(markup).toContain("Sending feedback to OpenAI...");
|
||||
});
|
||||
|
||||
it("renders the returned Codex thread ID in the feedback response", () => {
|
||||
const submission = {
|
||||
id: MessageId.make("feedback-command"),
|
||||
command: "/feedback The agent stopped early.",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
status: "sent" as const,
|
||||
feedbackId: "codex-thread-1",
|
||||
};
|
||||
const messages = [
|
||||
codexFeedbackMessage(submission),
|
||||
codexFeedbackMessage(submission, "assistant"),
|
||||
];
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={messages.map((message) => ({
|
||||
id: message.id,
|
||||
kind: "message" as const,
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
}))}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Feedback sent to OpenAI.");
|
||||
expect(markup).toContain("codex-thread-1");
|
||||
});
|
||||
|
||||
it("renders the worked-for row at assistant response text size", () => {
|
||||
const turnId = TurnId.make("turn-with-fold");
|
||||
const assistantEntry = buildAssistantTimelineEntry("Done.");
|
||||
|
||||
@@ -28,6 +28,12 @@ Log in with Codex normally:
|
||||
codex login
|
||||
```
|
||||
|
||||
## Send feedback to OpenAI
|
||||
|
||||
In an existing Codex thread, send `/feedback` or `/feedback` followed by a description of the
|
||||
issue. T3 Code uploads the thread and Codex logs to OpenAI and shows a thread ID that you can copy
|
||||
and share with OpenAI employees.
|
||||
|
||||
## I Want Work And Personal Codex Accounts
|
||||
|
||||
Use one real Codex home and one shadow home.
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
|
||||
import { createAtomCommandScheduler, createEnvironmentCommand } from "./runtime.ts";
|
||||
import {
|
||||
createAtomCommandScheduler,
|
||||
createEnvironmentCommand,
|
||||
createEnvironmentRpcCommand,
|
||||
} from "./runtime.ts";
|
||||
import {
|
||||
type ArchiveThreadInput,
|
||||
type CreateThreadInput,
|
||||
@@ -199,5 +204,11 @@ export function createThreadEnvironmentAtoms<R, E>(
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
uploadFeedback: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:commands:thread:upload-feedback",
|
||||
tag: WS_METHODS.providerUploadFeedback,
|
||||
scheduler,
|
||||
concurrency,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { MessageId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
codexFeedbackMessage,
|
||||
parseCodexFeedbackCommand,
|
||||
submitCodexFeedback,
|
||||
type CodexFeedbackSubmission,
|
||||
} from "./threadFeedback.ts";
|
||||
|
||||
describe("parseCodexFeedbackCommand", () => {
|
||||
it("accepts feedback without a reason", () => {
|
||||
expect(parseCodexFeedbackCommand(" /feedback ")).toEqual({});
|
||||
});
|
||||
|
||||
it("preserves a feedback description", () => {
|
||||
expect(parseCodexFeedbackCommand("/feedback The agent stopped early.")).toEqual({
|
||||
reason: "The agent stopped early.",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts mixed-case feedback commands", () => {
|
||||
expect(parseCodexFeedbackCommand("/Feedback Retry failed.")).toEqual({
|
||||
reason: "Retry failed.",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores other slash commands and ordinary messages", () => {
|
||||
expect(parseCodexFeedbackCommand("/feedback-status")).toBeNull();
|
||||
expect(parseCodexFeedbackCommand("Please send /feedback")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("submitCodexFeedback", () => {
|
||||
const submission = {
|
||||
id: MessageId.make("feedback-message-1"),
|
||||
command: "/feedback The agent stopped early.",
|
||||
createdAt: "2026-08-23T00:00:00.000Z",
|
||||
} as const;
|
||||
|
||||
it("shows the command and clears the draft before the upload finishes", async () => {
|
||||
let draft: string = submission.command;
|
||||
let finishUpload:
|
||||
| ((result: ReturnType<typeof AsyncResult.success<{ feedbackId: string }>>) => void)
|
||||
| undefined;
|
||||
const states: CodexFeedbackSubmission[] = [];
|
||||
const upload = new Promise<ReturnType<typeof AsyncResult.success<{ feedbackId: string }>>>(
|
||||
(resolve) => {
|
||||
finishUpload = resolve;
|
||||
},
|
||||
);
|
||||
|
||||
const result = submitCodexFeedback({
|
||||
submission,
|
||||
clearDraft: () => {
|
||||
draft = "";
|
||||
},
|
||||
onUpdate: (state) => states.push(state),
|
||||
upload: () => {
|
||||
expect(draft).toBe("");
|
||||
return upload;
|
||||
},
|
||||
});
|
||||
|
||||
expect(draft).toBe("");
|
||||
expect(states).toEqual([{ ...submission, status: "uploading" }]);
|
||||
expect(codexFeedbackMessage(states[0]!)).toMatchObject({
|
||||
id: submission.id,
|
||||
role: "user",
|
||||
text: submission.command,
|
||||
});
|
||||
expect(codexFeedbackMessage(states[0]!, "assistant").text).toBe(
|
||||
"Sending feedback to OpenAI...",
|
||||
);
|
||||
|
||||
draft = "Keep this newer message.";
|
||||
finishUpload?.(AsyncResult.success({ feedbackId: "codex-thread-1" }));
|
||||
await result;
|
||||
|
||||
expect(draft).toBe("Keep this newer message.");
|
||||
expect(states.at(-1)).toEqual({
|
||||
...submission,
|
||||
status: "sent",
|
||||
feedbackId: "codex-thread-1",
|
||||
});
|
||||
expect(codexFeedbackMessage(states.at(-1)!, "assistant").text).toContain("codex-thread-1");
|
||||
});
|
||||
|
||||
it("records a failed upload without losing its user-facing error", async () => {
|
||||
const states: CodexFeedbackSubmission[] = [];
|
||||
const error = new Error("Upload rejected.");
|
||||
|
||||
await submitCodexFeedback({
|
||||
submission,
|
||||
clearDraft: () => undefined,
|
||||
onUpdate: (state) => states.push(state),
|
||||
upload: () =>
|
||||
Promise.resolve(AsyncResult.failure<{ feedbackId: string }, Error>(Cause.fail(error))),
|
||||
});
|
||||
|
||||
expect(states.at(-1)).toEqual({
|
||||
...submission,
|
||||
status: "failed",
|
||||
errorMessage: "Upload rejected.",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks interruptions without reporting them as upload failures", async () => {
|
||||
const states: CodexFeedbackSubmission[] = [];
|
||||
|
||||
await submitCodexFeedback({
|
||||
submission,
|
||||
clearDraft: () => undefined,
|
||||
onUpdate: (state) => states.push(state),
|
||||
upload: () =>
|
||||
Promise.resolve(AsyncResult.failure<{ feedbackId: string }, never>(Cause.interrupt(1))),
|
||||
});
|
||||
|
||||
expect(states.at(-1)).toEqual({ ...submission, status: "interrupted" });
|
||||
});
|
||||
|
||||
it("lets another feedback submission finish while the first remains in flight", async () => {
|
||||
let finishFirstUpload:
|
||||
| ((result: ReturnType<typeof AsyncResult.success<{ feedbackId: string }>>) => void)
|
||||
| undefined;
|
||||
const firstUpload = new Promise<ReturnType<typeof AsyncResult.success<{ feedbackId: string }>>>(
|
||||
(resolve) => {
|
||||
finishFirstUpload = resolve;
|
||||
},
|
||||
);
|
||||
const firstStates: CodexFeedbackSubmission[] = [];
|
||||
const secondStates: CodexFeedbackSubmission[] = [];
|
||||
|
||||
const first = submitCodexFeedback({
|
||||
submission,
|
||||
clearDraft: () => undefined,
|
||||
onUpdate: (state) => firstStates.push(state),
|
||||
upload: () => firstUpload,
|
||||
});
|
||||
const second = await submitCodexFeedback({
|
||||
submission: {
|
||||
...submission,
|
||||
id: MessageId.make("feedback-message-2"),
|
||||
},
|
||||
clearDraft: () => undefined,
|
||||
onUpdate: (state) => secondStates.push(state),
|
||||
upload: () => Promise.resolve(AsyncResult.success({ feedbackId: "codex-thread-2" })),
|
||||
});
|
||||
|
||||
expect(firstStates.at(-1)?.status).toBe("uploading");
|
||||
expect(second._tag).toBe("Success");
|
||||
expect(secondStates.at(-1)).toMatchObject({
|
||||
status: "sent",
|
||||
feedbackId: "codex-thread-2",
|
||||
});
|
||||
|
||||
finishFirstUpload?.(AsyncResult.success({ feedbackId: "codex-thread-1" }));
|
||||
await first;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
MessageId,
|
||||
type OrchestrationMessage,
|
||||
type ProviderUploadFeedbackResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
type AtomCommandResult,
|
||||
} from "./runtime.ts";
|
||||
|
||||
type CodexFeedbackSubmissionDetails = {
|
||||
readonly id: MessageId;
|
||||
readonly command: string;
|
||||
readonly createdAt: string;
|
||||
};
|
||||
|
||||
export type CodexFeedbackSubmission = CodexFeedbackSubmissionDetails &
|
||||
(
|
||||
| { readonly status: "uploading" | "interrupted" }
|
||||
| { readonly status: "sent"; readonly feedbackId: string }
|
||||
| { readonly status: "failed"; readonly errorMessage: string }
|
||||
);
|
||||
|
||||
export function parseCodexFeedbackCommand(text: string): { readonly reason?: string } | null {
|
||||
const match = /^\/feedback(?:\s+([\s\S]*))?$/iu.exec(text.trim());
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
const reason = match[1]?.trim();
|
||||
return reason ? { reason } : {};
|
||||
}
|
||||
|
||||
export function codexFeedbackMessage(
|
||||
submission: CodexFeedbackSubmission,
|
||||
role: "user" | "assistant" = "user",
|
||||
): OrchestrationMessage {
|
||||
const text =
|
||||
role === "user"
|
||||
? submission.command
|
||||
: submission.status === "sent"
|
||||
? `Feedback sent to OpenAI.\n\nThread ID: \`${submission.feedbackId}\``
|
||||
: submission.status === "failed"
|
||||
? `Could not send feedback to OpenAI.\n\n${submission.errorMessage}`
|
||||
: "Sending feedback to OpenAI...";
|
||||
|
||||
return {
|
||||
id: role === "user" ? submission.id : MessageId.make(`${submission.id}:feedback`),
|
||||
role,
|
||||
text,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: submission.createdAt,
|
||||
updatedAt: submission.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
export async function submitCodexFeedback<E>(input: {
|
||||
readonly submission: CodexFeedbackSubmissionDetails;
|
||||
readonly clearDraft: () => void;
|
||||
readonly onUpdate: (submission: CodexFeedbackSubmission) => void;
|
||||
readonly upload: () => Promise<AtomCommandResult<ProviderUploadFeedbackResult, E>>;
|
||||
}): Promise<AtomCommandResult<ProviderUploadFeedbackResult, E>> {
|
||||
input.onUpdate({ ...input.submission, status: "uploading" });
|
||||
input.clearDraft();
|
||||
|
||||
const result = await input.upload();
|
||||
if (result._tag === "Success") {
|
||||
input.onUpdate({
|
||||
...input.submission,
|
||||
status: "sent",
|
||||
feedbackId: result.value.feedbackId,
|
||||
});
|
||||
} else if (isAtomCommandInterrupted(result)) {
|
||||
input.onUpdate({ ...input.submission, status: "interrupted" });
|
||||
} else {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
input.onUpdate({
|
||||
...input.submission,
|
||||
status: "failed",
|
||||
errorMessage: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -729,6 +729,7 @@ export * from "./checkpointDiff.ts";
|
||||
export * from "./threadSnapshotHttp.ts";
|
||||
export * from "./composerPathSearch.ts";
|
||||
export * from "./threadCommands.ts";
|
||||
export * from "./threadFeedback.ts";
|
||||
export * from "./threadDetail.ts";
|
||||
export * from "./threadReducer.ts";
|
||||
export * from "./threadShell.ts";
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ThreadId } from "./baseSchemas.ts";
|
||||
import {
|
||||
ProviderEvent,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderUploadFeedbackError,
|
||||
ProviderUploadFeedbackInput,
|
||||
ProviderUploadFeedbackResult,
|
||||
} from "./provider.ts";
|
||||
|
||||
const decodeProviderSessionStartInput = Schema.decodeUnknownSync(ProviderSessionStartInput);
|
||||
const decodeProviderSendTurnInput = Schema.decodeUnknownSync(ProviderSendTurnInput);
|
||||
const decodeProviderSession = Schema.decodeUnknownSync(ProviderSession);
|
||||
const decodeProviderEvent = Schema.decodeUnknownSync(ProviderEvent);
|
||||
const decodeProviderUploadFeedbackInput = Schema.decodeUnknownSync(ProviderUploadFeedbackInput);
|
||||
const decodeProviderUploadFeedbackResult = Schema.decodeUnknownSync(ProviderUploadFeedbackResult);
|
||||
|
||||
function getOptionValue(
|
||||
options: ReadonlyArray<{ id: string; value: unknown }> | undefined,
|
||||
@@ -153,6 +159,39 @@ describe("ProviderSendTurnInput", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider feedback", () => {
|
||||
it("accepts a thread and an optional feedback reason", () => {
|
||||
expect(
|
||||
decodeProviderUploadFeedbackInput({
|
||||
threadId: "thread-1",
|
||||
reason: "The agent stopped early.",
|
||||
}),
|
||||
).toEqual({ threadId: "thread-1", reason: "The agent stopped early." });
|
||||
expect(decodeProviderUploadFeedbackInput({ threadId: "thread-1" })).toEqual({
|
||||
threadId: "thread-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns the shareable Codex feedback identifier", () => {
|
||||
expect(decodeProviderUploadFeedbackResult({ feedbackId: "provider-thread-1" })).toEqual({
|
||||
feedbackId: "provider-thread-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the failed thread and original cause without exposing upstream text", () => {
|
||||
const cause = new Error("provider request secret");
|
||||
const error = new ProviderUploadFeedbackError({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error.threadId).toBe("thread-1");
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error.message).toBe("Failed to upload feedback for thread thread-1.");
|
||||
expect(error.message).not.toContain("provider request secret");
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerInstanceId routing key (slice-2 invariant)", () => {
|
||||
it("decodes a ProviderSessionStartInput without providerInstanceId (legacy producer)", () => {
|
||||
const parsed = decodeProviderSessionStartInput({
|
||||
|
||||
@@ -110,6 +110,29 @@ export const ProviderRespondToUserInputInput = Schema.Struct({
|
||||
});
|
||||
export type ProviderRespondToUserInputInput = typeof ProviderRespondToUserInputInput.Type;
|
||||
|
||||
export const ProviderUploadFeedbackInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
reason: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ProviderUploadFeedbackInput = typeof ProviderUploadFeedbackInput.Type;
|
||||
|
||||
export const ProviderUploadFeedbackResult = Schema.Struct({
|
||||
feedbackId: TrimmedNonEmptyString,
|
||||
});
|
||||
export type ProviderUploadFeedbackResult = typeof ProviderUploadFeedbackResult.Type;
|
||||
|
||||
export class ProviderUploadFeedbackError extends Schema.TaggedErrorClass<ProviderUploadFeedbackError>()(
|
||||
"ProviderUploadFeedbackError",
|
||||
{
|
||||
threadId: ThreadId,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to upload feedback for thread ${this.threadId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const ProviderEventKind = Schema.Literals(["session", "notification", "request", "error"]);
|
||||
|
||||
export const ProviderEvent = Schema.Struct({
|
||||
|
||||
@@ -66,6 +66,11 @@ import {
|
||||
OrchestrationRpcSchemas,
|
||||
OrchestrationGetWorkflowScriptError,
|
||||
} from "./orchestration.ts";
|
||||
import {
|
||||
ProviderUploadFeedbackError,
|
||||
ProviderUploadFeedbackInput,
|
||||
ProviderUploadFeedbackResult,
|
||||
} from "./provider.ts";
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
import {
|
||||
PullRequestActionInput,
|
||||
@@ -211,6 +216,9 @@ export const WS_METHODS = {
|
||||
filesystemBrowse: "filesystem.browse",
|
||||
assetsCreateUrl: "assets.createUrl",
|
||||
|
||||
// Provider methods
|
||||
providerUploadFeedback: "provider.uploadFeedback",
|
||||
|
||||
// VCS methods
|
||||
vcsPull: "vcs.pull",
|
||||
vcsRefreshStatus: "vcs.refreshStatus",
|
||||
@@ -665,6 +673,12 @@ export const WsAssetsCreateUrlRpc = Rpc.make(WS_METHODS.assetsCreateUrl, {
|
||||
error: Schema.Union([AssetAccessError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsProviderUploadFeedbackRpc = Rpc.make(WS_METHODS.providerUploadFeedback, {
|
||||
payload: ProviderUploadFeedbackInput,
|
||||
success: ProviderUploadFeedbackResult,
|
||||
error: Schema.Union([ProviderUploadFeedbackError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsSubscribeVcsStatusRpc = Rpc.make(WS_METHODS.subscribeVcsStatus, {
|
||||
payload: VcsStatusInput,
|
||||
success: VcsStatusStreamEvent,
|
||||
@@ -1034,6 +1048,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsShellOpenInEditorRpc,
|
||||
WsFilesystemBrowseRpc,
|
||||
WsAssetsCreateUrlRpc,
|
||||
WsProviderUploadFeedbackRpc,
|
||||
WsSubscribeVcsStatusRpc,
|
||||
WsVcsPullRpc,
|
||||
WsVcsRefreshStatusRpc,
|
||||
|
||||
Reference in new issue
Block a user