Skip to content

Commit 20b4aa4

Browse files
donjor-agent[bot]rsi-pr-agent
authored andcommitted
fix(voice): show redacted provider detail when cleanup fails (#1765)
Squashes: - 183117f fix(voice): show redacted provider detail when cleanup fails (#1765) (#1765) - 07fb26d fixup! fix(voice): show redacted provider detail when cleanup fails (#1765) (#1765) - ebc5bb1 fix(voice): show redacted provider detail when cleanup fails (#1765) (#1765) - 7dc9597 fixup! fix(voice): show redacted provider detail when cleanup fails (#1765) (#1765) Fork-Domain: voice-input Fork-Tier: bugfix Fork-Upstreamable: no
1 parent 284943c commit 20b4aa4

9 files changed

Lines changed: 317 additions & 164 deletions

File tree

‎apps/server/src/voice-input/VoiceText.fork.test.ts‎

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ function harness() {
4747
const reads: string[] = [];
4848
let serverModel = DEFAULT_SERVER_SETTINGS.textGenerationModelSelection;
4949
let result = "Corrected transcription";
50-
let fails = false;
50+
let failure: TextGenerationError | undefined;
5151
const instance: ProviderInstance = {
5252
instanceId: modelSelection.instanceId,
5353
driverKind: ProviderDriverKind.make("codex"),
@@ -70,10 +70,8 @@ function harness() {
7070
}),
7171
(input) => {
7272
calls.push(input);
73-
return fails
74-
? Effect.fail(
75-
new TextGenerationError({ operation: "generateTextFork", detail: "unavailable" }),
76-
)
73+
return failure !== undefined
74+
? Effect.fail(failure)
7775
: TextGenerationOperations.decodeJsonReply(
7876
input,
7977
"test",
@@ -153,8 +151,8 @@ function harness() {
153151
setResult: (value: string) => {
154152
result = value;
155153
},
156-
fail: () => {
157-
fails = true;
154+
fail: (detail = "unavailable", cause?: unknown) => {
155+
failure = new TextGenerationError({ operation: "generateTextFork", detail, cause });
158156
},
159157
};
160158
}
@@ -227,6 +225,33 @@ describe("dictation text generation", () => {
227225
).toBe("model");
228226
}),
229227
);
228+
it.effect.each([
229+
{
230+
detail: "OpenCode could not generate the text.",
231+
cause: { type: "APIError", message: "Insufficient balance" },
232+
expected: "OpenCode could not generate the text: Insufficient balance",
233+
},
234+
{
235+
detail: "",
236+
cause: {
237+
type: "APIError",
238+
message: `Bearer secret api_key=key-secret\t ${"x".repeat(220)}\n at provider (/private/token:1)`,
239+
},
240+
expected: `Bearer [REDACTED] api_key=[REDACTED] ${"x".repeat(220)}`.slice(0, 200),
241+
},
242+
])("preserves bounded, redacted provider cause", ({ detail, cause, expected }) =>
243+
Effect.gen(function* () {
244+
const h = harness();
245+
yield* h.run((s) => s.configure({ config }));
246+
h.fail(detail, cause);
247+
const error = yield* h
248+
.run((s) => s.transform({ projectId, operation: "cleanup", text: "draft" }))
249+
.pipe(Effect.flip);
250+
expect(error.detail).toBe(expected);
251+
expect(error.message).not.toContain("secret");
252+
expect(error.cause).toMatchObject({ detail, cause });
253+
}),
254+
);
230255
it.effect(
231256
"collects bounded project sources without following a symlink outside the project",
232257
() =>

‎apps/server/src/voice-input/VoiceText.fork.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,13 @@ import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
2020
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
2121
import * as ServerSettings from "../serverSettings.ts";
2222
import { expandVoiceTextTemplateFork, voiceRecentMessagesFork } from "./voiceTextPrompts.fork.ts";
23+
import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
2324
import { voiceTextGeneratorFork } from "@t3tools/provider-core/server/voiceTextGeneration.fork";
2425

2526
export class VoiceTextError extends Schema.TaggedError<VoiceTextError>()("VoiceTextError", {
2627
reason: Schema.Literals(["settings", "project", "model", "response", "context", "disabled"]),
2728
cause: Schema.optionalKey(Schema.Defect()),
29+
detail: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(200))),
2830
}) {
2931
override get message() {
3032
switch (this.reason) {
@@ -131,7 +133,31 @@ const make = Effect.gen(function* () {
131133
cwd,
132134
prompt,
133135
modelSelection: config.modelSelection,
134-
}).pipe(Effect.mapError((cause) => new VoiceTextError({ reason: "model", cause })));
136+
}).pipe(
137+
Effect.mapError((cause) => {
138+
// OpenCode v2 and ACP failures keep the provider message on the immediate cause.
139+
const providerMessage =
140+
typeof cause.cause === "object" &&
141+
cause.cause !== null &&
142+
"message" in cause.cause &&
143+
typeof cause.cause.message === "string"
144+
? cause.cause.message
145+
: "";
146+
const message = [
147+
providerMessage.trim() ? cause.detail.replace(/\.$/, "") : cause.detail,
148+
providerMessage,
149+
]
150+
.filter((part) => part.trim())
151+
.join(": ");
152+
// Match chat failure redaction before shortening provider text for the composer.
153+
const detail = makeProviderFailure({ message })
154+
.message.split(/\r\n?|\n/, 1)[0]!
155+
.replace(/\s+/g, " ")
156+
.trim()
157+
.slice(0, 200);
158+
return new VoiceTextError({ reason: "model", cause, ...(detail ? { detail } : {}) });
159+
}),
160+
);
135161
const text = result.text.trim();
136162
if (!text) return yield* new VoiceTextError({ reason: "response" });
137163
return { text };

‎apps/server/src/voice-input/http.fork.ts‎

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -96,21 +96,22 @@ const failure = (error: VoiceInput.VoiceInputError) =>
9696
),
9797
);
9898

99-
const configureSettings = (service: VoiceInput.VoiceInput["Service"]) =>
100-
Effect.gen(function* () {
101-
const refusal = yield* authorize(AuthSettingsWriteScope);
102-
if (refusal) return refusal;
103-
const request = yield* HttpServerRequest.HttpServerRequest;
104-
if (request.headers["content-type"]?.split(";")[0]?.trim() !== "application/json")
105-
return json({ error: "Expected JSON settings." }, 415);
106-
return yield* readBody(16384).pipe(
107-
Effect.flatMap((bytes) => decodeSettingsJson(new TextDecoder().decode(bytes))),
108-
Effect.mapError((cause) => new VoiceInput.VoiceInputError({ reason: "settings", cause })),
109-
Effect.flatMap(service.configure),
110-
Effect.map((settings) => json(settings)),
111-
Effect.catch(failure),
112-
);
113-
});
99+
const configureSettings = Effect.fn("http.configureSettings")(function* (
100+
service: VoiceInput.VoiceInput["Service"],
101+
) {
102+
const refusal = yield* authorize(AuthSettingsWriteScope);
103+
if (refusal) return refusal;
104+
const request = yield* HttpServerRequest.HttpServerRequest;
105+
if (request.headers["content-type"]?.split(";")[0]?.trim() !== "application/json")
106+
return json({ error: "Expected JSON settings." }, 415);
107+
return yield* readBody(16384).pipe(
108+
Effect.flatMap((bytes) => decodeSettingsJson(new TextDecoder().decode(bytes))),
109+
Effect.mapError((cause) => new VoiceInput.VoiceInputError({ reason: "settings", cause })),
110+
Effect.flatMap(service.configure),
111+
Effect.map((settings) => json(settings)),
112+
Effect.catch(failure),
113+
);
114+
});
114115

115116
export const routes = (service: VoiceInput.VoiceInput["Service"]) =>
116117
Layer.mergeAll(
@@ -208,7 +209,11 @@ const voiceTextRoutes = Layer.unwrap(
208209
Effect.catch((error) =>
209210
Effect.succeed(
210211
json(
211-
{ error: error.message, code: error.reason },
212+
{
213+
error: error.message,
214+
code: error.reason,
215+
...(error.detail ? { detail: error.detail } : {}),
216+
},
212217
error.reason === "model" || error.reason === "response" ? 502 : 400,
213218
),
214219
),

‎apps/web/src/voice-input/client.fork.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import { isVoiceTextHttpErrorFork } from "@t3tools/contracts";
2+
import * as Cause from "effect/Cause";
3+
import * as Option from "effect/Option";
14
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
25
import type * as Effect from "effect/Effect";
36
import type { HttpClient } from "effect/http";
@@ -16,6 +19,10 @@ export async function runVoiceInputRequestFork<A, E>(
1619
reportDefect: false,
1720
});
1821
if (AsyncResult.isSuccess(result)) return result.value;
22+
if (AsyncResult.isFailure(result)) {
23+
const error = Option.getOrNull(Cause.findErrorOption(result.cause));
24+
if (isVoiceTextHttpErrorFork(error)) throw error;
25+
}
1926
throw new Error(failureMessage);
2027
}
2128

apps/web/src/voice-input/useVoiceText.fork.test.tsx renamed to apps/web/src/voice-input/useVoiceText.fork.browser.test.tsx

Lines changed: 78 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
1-
import { act, useLayoutEffect } from "react";
2-
import { create, type ReactTestRenderer } from "react-test-renderer";
3-
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1+
import { useLayoutEffect } from "react";
2+
import { describe, expect, it, vi } from "vite-plus/test";
43
import {
54
EnvironmentId,
65
ProjectId,
76
ProviderInstanceId,
87
VOICE_TEXT_STARTER_PROMPTS_FORK,
98
type VoiceTextConfigFork,
109
} from "@t3tools/contracts";
10+
import * as Cause from "effect/Cause";
11+
import { AsyncResult } from "effect/reactivity";
12+
import { act, render, type Screen } from "../../test/render";
1113
import { useVoiceTextFork, type VoiceTextInputFork } from "./useVoiceText.fork";
1214

1315
const mocks = vi.hoisted(() => ({
@@ -25,18 +27,26 @@ vi.mock("../state/session", () => ({
2527
vi.mock("@t3tools/client-runtime/rpc", () => ({
2628
transformVoiceTextFork: (_prepared: unknown, input: unknown) => input,
2729
}));
28-
vi.mock("./client.fork", () => ({
29-
runVoiceInputRequestFork: (input: unknown, signal: AbortSignal) => mocks.request(input, signal),
30+
vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
31+
...(await importOriginal<object>()),
32+
executeAtomQuery: async (
33+
_registry: unknown,
34+
input: unknown,
35+
options: { signal?: AbortSignal },
36+
) => {
37+
try {
38+
return AsyncResult.success(await mocks.request(input, options.signal));
39+
} catch (error) {
40+
return AsyncResult.failure(Cause.fail(error));
41+
}
42+
},
3043
}));
31-
vi.mock("../components/ui/button", () => ({ Button: "button" }));
32-
vi.mock("../components/ui/spinner", () => ({ Spinner: "span" }));
33-
vi.mock("../components/ui/tooltip", () => ({
34-
Tooltip: "div",
35-
TooltipTrigger: "span",
36-
TooltipPopup: "span",
44+
vi.mock("../connection/runtime", () => ({
45+
connectionAtomRuntime: { atom: (input: unknown) => input },
3746
}));
47+
vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: {} }));
3848

39-
let renderer: ReactTestRenderer;
49+
let screen: Screen;
4050
let actions: ReturnType<typeof useVoiceTextFork>;
4151
let draft: {
4252
text: string;
@@ -52,15 +62,17 @@ function Probe() {
5262
});
5363
return value.controls;
5464
}
65+
function errorText() {
66+
return screen.container.textContent ?? "";
67+
}
5568
async function click(label: string) {
56-
await act(async () => {
57-
await renderer.root.findByProps({ "aria-label": label }).props.onClick();
58-
});
69+
const button = screen.container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
70+
if (!button) throw new Error(`No ${label} button.`);
71+
await act(async () => button.click());
5972
}
60-
beforeEach(async () => {
61-
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
62-
vi.stubGlobal("navigator", { language: "en-US" });
63-
vi.spyOn(console, "error").mockImplementation(() => {});
73+
async function setup() {
74+
await using stack = new AsyncDisposableStack();
75+
stack.use(vi.spyOn(console, "error").mockImplementation(() => {}));
6476
mocks.canOperate = true;
6577
mocks.config = {
6678
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test" },
@@ -88,17 +100,12 @@ beforeEach(async () => {
88100
draft = { ...draft, text, selection: { start: cursor, end: cursor } };
89101
},
90102
};
91-
await act(() => {
92-
renderer = create(<Probe />);
93-
});
94-
});
95-
afterEach(async () => {
96-
await act(() => renderer.unmount());
97-
vi.restoreAllMocks();
98-
vi.unstubAllGlobals();
99-
});
103+
screen = stack.use(await render(<Probe />, { router: false }));
104+
return stack.move();
105+
}
100106
describe("dictation text lifecycle", () => {
101107
it("cleans only the transcript, formats the committed draft, and undoes both to raw transcription", async () => {
108+
await using _fixture = await setup();
102109
let transcript = "";
103110
await act(async () => {
104111
transcript = await actions.processTranscript(
@@ -120,15 +127,17 @@ describe("dictation text lifecycle", () => {
120127
expect(draft.text).toBe("react use affect");
121128
});
122129
it("does not automatically process typed edits", async () => {
123-
await act(() => {
130+
await using _fixture = await setup();
131+
await act(async () => {
124132
draft.text = "typed use affect words";
125133
draft.revision++;
126134
actions.markDraftChanged();
127-
renderer.update(<Probe />);
135+
await screen.rerender(<Probe />);
128136
});
129137
expect(mocks.request).not.toHaveBeenCalled();
130138
});
131139
it("uses the recording snapshot for Undo when editor and session revisions differ", async () => {
140+
await using _fixture = await setup();
132141
draft = { ...draft, text: "prefix suffix", revision: 8, selection: { start: 13, end: 13 } };
133142
let transcript = "";
134143
await act(async () => {
@@ -151,6 +160,7 @@ describe("dictation text lifecycle", () => {
151160
expect(draft.text).toBe("prefix react use affect");
152161
});
153162
it("ignores a manual result after the draft was edited and reverted", async () => {
163+
await using _fixture = await setup();
154164
const response = Promise.withResolvers<{ text: string }>();
155165
mocks.request.mockReturnValueOnce(response.promise);
156166
draft.text = "use affect";
@@ -166,6 +176,7 @@ describe("dictation text lifecycle", () => {
166176
expect(draft.text).toBe("use affect");
167177
});
168178
it("cancels cleanup without formatting or discarding the raw transcript", async () => {
179+
await using _fixture = await setup();
169180
mocks.request.mockImplementationOnce(
170181
(_input, signal: AbortSignal) =>
171182
new Promise((_resolve, reject) =>
@@ -185,24 +196,57 @@ describe("dictation text lifecycle", () => {
185196
expect(draft.text).toBe("react use affect");
186197
expect(mocks.request).toHaveBeenCalledTimes(1);
187198
});
188-
it("preserves the transcript on cleanup failure", async () => {
189-
mocks.request.mockRejectedValueOnce(new Error("model failed"));
199+
it.each([
200+
{ detail: "This model is unavailable.", label: "Clean up draft" },
201+
{ detail: "Provider refused: Bearer [REDACTED] api_key=[REDACTED]", label: "Format draft" },
202+
])("preserves the draft and shows provider detail for $label", async ({ detail, label }) => {
203+
await using _fixture = await setup();
204+
mocks.request.mockRejectedValueOnce({
205+
error: "Text generation failed.",
206+
code: "model",
207+
detail,
208+
});
209+
draft.text = "raw use affect";
210+
const original = structuredClone(draft);
211+
await click(label);
212+
expect(draft).toEqual(original);
213+
expect(errorText()).toContain(`${detail} Your draft was preserved.`);
214+
});
215+
it("keeps the current text when provider detail is absent", async () => {
216+
await using _fixture = await setup();
217+
mocks.request.mockRejectedValueOnce({ error: "Text generation failed.", code: "model" });
218+
draft.text = "raw use affect";
219+
await click("Clean up draft");
220+
expect(draft.text).toBe("raw use affect");
221+
expect(errorText()).toContain("Text processing failed. Your draft was preserved.");
222+
});
223+
it("preserves the transcript and shows detail on automatic cleanup failure", async () => {
224+
await using _fixture = await setup();
225+
mocks.request.mockRejectedValueOnce({
226+
error: "Text generation failed.",
227+
code: "model",
228+
detail: "This model is unavailable.",
229+
});
190230
await act(async () => {
191231
expect(await actions.processTranscript("raw use affect", new AbortController().signal)).toBe(
192232
"raw use affect",
193233
);
194234
});
235+
expect(errorText()).toContain(
236+
"This model is unavailable. The original transcript was preserved.",
237+
);
195238
});
196239
it("does not submit cleanup without operate permission or for empty speech", async () => {
240+
await using _fixture = await setup();
197241
mocks.canOperate = false;
198-
await act(() => renderer.update(<Probe />));
242+
await screen.rerender(<Probe />);
199243
await act(async () => {
200244
expect(await actions.processTranscript("raw use affect", new AbortController().signal)).toBe(
201245
"raw use affect",
202246
);
203247
});
204248
mocks.canOperate = true;
205-
await act(() => renderer.update(<Probe />));
249+
await screen.rerender(<Probe />);
206250
await act(async () => {
207251
expect(await actions.processTranscript(" ", new AbortController().signal)).toBe(" ");
208252
});

0 commit comments

Comments
 (0)