Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🛡️ fix(creds): confirm prose-looking values before saving credentials (#21332)

Arvin Xub136fdcb59ec
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.json
index 389f80f7d5e..4731c31738c 100644
--- a/locales/en-US/tool.json
+++ b/locales/en-US/tool.json
@@ -136,6 +136,8 @@
"credsInput.notice.typeMismatch": "A credential with key “{{key}}” already exists with a different type ({{type}}) and can't be replaced from here. Skip, and ask for it under a different key.",
"credsInput.notice.workspace": "Saved encrypted to this workspace's credentials. The values go directly to storage and are never shown to the AI.",
"credsInput.placeholder": "Enter {{field}}",
+ "credsInput.proseConfirm": "Save anyway",
+ "credsInput.proseWarning": "The value for “{{fields}}” looks like a sentence rather than a secret (it contains CJK text or a whole phrase). If it was pasted by mistake, fix it before saving; otherwise confirm with “Save anyway”.",
"credsInput.saveFailed": "Couldn't save the credential. Please try again.",
"credsInput.skip": "Skip",
"credsInput.submit": "Save",
diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.json
index 3da2782f7fb..65fb01c8d92 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -136,6 +136,8 @@
"credsInput.notice.typeMismatch": "已存在 key 为「{{key}}」的凭据,但类型不同({{type}}),不能在这里替换。请跳过,并改用其他 key。",
"credsInput.notice.workspace": "将加密保存到当前工作区的凭证。输入的值直接写入存储,AI 无法看到。",
"credsInput.placeholder": "输入 {{field}}",
+ "credsInput.proseConfirm": "确认提交",
+ "credsInput.proseWarning": "「{{fields}}」的值看起来像一句话而不是密钥(含中文或整段文本)。如果是误粘贴,请修改后再保存;确认无误可点「确认提交」。",
"credsInput.saveFailed": "凭证保存失败,请重试。",
"credsInput.skip": "跳过",
"credsInput.submit": "保存",
diff --git a/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/index.tsx b/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/index.tsx
index f0a3b133d48..1fe66b427c3 100644
--- a/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/index.tsx
+++ b/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/index.tsx
@@ -148,7 +148,9 @@ const RequestCredsInputIntervention = memo<BuiltinInterventionProps<RequestCreds
fields={fieldNames}
labels={{
cancel: t('credsInput.skip'),
+ confirmProse: t('credsInput.proseConfirm'),
placeholder: (field) => t('credsInput.placeholder', { field }),
+ proseWarning: (fields) => t('credsInput.proseWarning', { fields: fields.join(', ') }),
submit: t(existing ? 'credsInput.update' : 'credsInput.submit'),
submitting: t('credsInput.submitting'),
}}
diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.ts
index 68ec5b08d23..9180988715f 100644
--- a/packages/locales/src/default/tool.ts
+++ b/packages/locales/src/default/tool.ts
@@ -153,6 +153,9 @@ export default {
'credsInput.notice.workspace':
"Saved encrypted to this workspace's credentials. The values go directly to storage and are never shown to the AI.",
'credsInput.placeholder': 'Enter {{field}}',
+ 'credsInput.proseConfirm': 'Save anyway',
+ 'credsInput.proseWarning':
+ 'The value for “{{fields}}” looks like a sentence rather than a secret (it contains CJK text or a whole phrase). If it was pasted by mistake, fix it before saving; otherwise confirm with “Save anyway”.',
'credsInput.saveFailed': "Couldn't save the credential. Please try again.",
'credsInput.skip': 'Skip',
'credsInput.submit': 'Save',
diff --git a/packages/shared-tool-ui/src/SecretInput/SecretInputView.test.tsx b/packages/shared-tool-ui/src/SecretInput/SecretInputView.test.tsx
new file mode 100644
index 00000000000..a5f9b23d54b
--- /dev/null
+++ b/packages/shared-tool-ui/src/SecretInput/SecretInputView.test.tsx
@@ -0,0 +1,160 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, cleanup, fireEvent, render } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@lobehub/ui', () => ({
+ Button: (props: any) => <button {...props} />,
+ cssVar: { colorError: 'var(--error)', colorWarning: 'var(--warn)' },
+ Flexbox: (props: any) => <div {...props} />,
+ Icon: (props: any) => <span {...props} />,
+ InputPassword: (props: any) => <input type="password" {...props} />,
+ Text: (props: any) => <span {...props} />,
+}));
+vi.mock('lucide-react', () => ({ CircleAlert: (props: any) => <svg {...props} /> }));
+
+import SecretInputView, { isSecretSubmitDisabled } from './SecretInputView';
+
+const labels = {
+ cancel: 'Skip',
+ confirmProse: 'Save anyway',
+ placeholder: (field: string) => `Enter ${field}`,
+ proseWarning: (fields: string[]) => `Prose-looking: ${fields.join(', ')}`,
+ submit: 'Save',
+ submitting: 'Saving…',
+};
+
+describe('isSecretSubmitDisabled', () => {
+ it('keeps a completed form submittable', () => {
+ expect(isSecretSubmitDisabled({ complete: true, inert: false, proseWarning: undefined })).toBe(
+ false,
+ );
+ });
+
+ it('disables submit when blocked even though the form was completed', () => {
+ // Lookup failed / permission lost / type mismatch after completion: the
+ // fields are replaced by the reason, so Save must not go through.
+ expect(
+ isSecretSubmitDisabled({ blockedReason: 'Lookup failed', complete: true, inert: false }),
+ ).toBe(true);
+ });
+
+ it('disables an incomplete form without a pending prose confirmation', () => {
+ expect(isSecretSubmitDisabled({ complete: false, inert: false })).toBe(true);
+ });
+
+ it('disables the ordinary Save while a prose confirmation is pending', () => {
+ // Codex round-5 P2 (#4331827545): handleSubmit rejects every ordinary
+ // Save until confirmProseSubmit runs, so a clickable Save would only
+ // look stuck. The confirm control has its own gates and stays enabled.
+ expect(isSecretSubmitDisabled({ complete: true, inert: false, proseWarning: ['F'] })).toBe(
+ true,
+ );
+ });
+
+ it('disables while inert', () => {
+ expect(isSecretSubmitDisabled({ complete: true, inert: true })).toBe(true);
+ });
+});
+
+describe('SecretInputView blocked submit', () => {
+ afterEach(cleanup);
+
+ it('renders a disabled Save when a completed form later becomes blocked', () => {
+ const { getByRole } = render(
+ <SecretInputView
+ blockedReason={'A credential with this key already exists with a different type'}
+ fields={['OPENAI_API_KEY']}
+ labels={labels}
+ onCancel={vi.fn()}
+ onSubmit={vi.fn().mockResolvedValue(undefined)}
+ />,
+ );
+
+ const save = getByRole('button', { name: 'Save' }) as HTMLButtonElement;
+ expect(save.disabled).toBe(true);
+ });
+
+ it('disables the prose-confirm button when the form becomes blocked', async () => {
+ // Codex round-2 P2 (#4330386329): a prose-looking value held for
+ // confirmation must not reach the sink once the form revalidates to a
+ // blocked state — the confirm button bypasses isSecretSubmitDisabled,
+ // so it needs its own blockedReason gate.
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const { container, getByRole, rerender } = render(
+ <SecretInputView
+ fields={['OPENAI_API_KEY']}
+ labels={labels}
+ onCancel={vi.fn()}
+ onSubmit={onSubmit}
+ />,
+ );
+
+ const input = container.querySelector('input[type="password"]') as HTMLInputElement;
+ await act(async () => {
+ fireEvent.change(input, { target: { value: 'please verify my credentials now' } });
+ });
+
+ // First Save press holds the submit with a prose warning.
+ await act(async () => {
+ fireEvent.click(getByRole('button', { name: 'Save' }));
+ });
+ const confirm = getByRole('button', { name: 'Save anyway' }) as HTMLButtonElement;
+ expect(confirm.disabled).toBe(false);
+
+ // The form then revalidates to a blocked state.
+ rerender(
+ <SecretInputView
+ blockedReason={'A credential with this key already exists with a different type'}
+ fields={['OPENAI_API_KEY']}
+ labels={labels}
+ onCancel={vi.fn()}
+ onSubmit={onSubmit}
+ />,
+ );
+
+ const blockedConfirm = getByRole('button', { name: 'Save anyway' }) as HTMLButtonElement;
+ expect(blockedConfirm.disabled).toBe(true);
+
+ await act(async () => {
+ fireEvent.click(blockedConfirm);
+ });
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it('holds the ordinary Save disabled while the prose guard is active', async () => {
+ // Codex round-5 P2 (#4331827545): after the warning appears, the primary
+ // Save must render disabled instead of staying clickable-but-rejected;
+ // only "Save anyway" can submit a prose-looking value.
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const { container, getByRole } = render(
+ <SecretInputView
+ fields={['OPENAI_API_KEY']}
+ labels={labels}
+ onCancel={vi.fn()}
+ onSubmit={onSubmit}
+ />,
+ );
+
+ const input = container.querySelector('input[type="password"]') as HTMLInputElement;
+ await act(async () => {
+ fireEvent.change(input, { target: { value: 'please verify my credentials now' } });
+ });
+
+ // First Save press raises the prose warning and disables the primary Save.
+ await act(async () => {
+ fireEvent.click(getByRole('button', { name: 'Save' }));
+ });
+ const save = getByRole('button', { name: 'Save' }) as HTMLButtonElement;
+ const confirm = getByRole('button', { name: 'Save anyway' }) as HTMLButtonElement;
+ expect(save.disabled).toBe(true);
+ expect(confirm.disabled).toBe(false);
+
+ // Pressing the held Save (e.g. a stale pointer event) must not submit.
+ await act(async () => {
+ fireEvent.click(save);
+ });
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/shared-tool-ui/src/SecretInput/SecretInputView.tsx b/packages/shared-tool-ui/src/SecretInput/SecretInputView.tsx
index ad7dcc4eb78..040a91c378e 100644
--- a/packages/shared-tool-ui/src/SecretInput/SecretInputView.tsx
+++ b/packages/shared-tool-ui/src/SecretInput/SecretInputView.tsx
@@ -37,9 +37,32 @@ export interface SecretInputViewProps {
onSubmit: (values: Record<string, string>) => Promise<void>;
}
+/**
+ * Whether the primary Save button must stay disabled: blocked (lookup failed /
+ * permission lost / type mismatch — the fields are replaced by the reason, so
+ * a completed form must not submit over it), inert (disabled or a write in
+ * flight), a prose confirmation pending (handleSubmit rejects ordinary saves
+ * until `confirmProseSubmit` runs, so a clickable Save would only look stuck),
+ * or incomplete without a prose confirmation pending. The secondary "Save
+ * anyway" control has its own gates and is unaffected by this predicate.
+ */
+export const isSecretSubmitDisabled = ({
+ blockedReason,
+ complete,
+ inert,
+ proseWarning,
+}: {
+ blockedReason?: ReactNode;
+ complete: boolean;
+ inert: boolean;
+ proseWarning?: string[] | undefined;
+}) => inert || !!blockedReason || !!proseWarning || (!complete && !proseWarning);
+
/**
* Password-style form for secrets that must not enter the agent context. See
- * {@link useSecretInputForm} for how long the values are kept.
+ * {@link useSecretInputForm} for how long the values are kept, and for the
+ * prose guard that holds a submit whose values look like pasted chat text
+ * (a CJK sentence or a long multi-word paste) until the user confirms.
*/
const SecretInputView = memo<SecretInputViewProps>(
({
@@ -53,25 +76,56 @@ const SecretInputView = memo<SecretInputViewProps>(
onCancel,
onSubmit,
}) => {
- const { complete, formKey, handleChange, handleSubmit, submitting } = useSecretInputForm({
- fields,
- onSubmit,
- });
+ const {
+ complete,
+ confirmProseSubmit,
+ formKey,
+ handleChange,
+ handleSubmit,
+ proseWarning,
+ submitting,
+ } = useSecretInputForm({ fields, onSubmit });
const inert = disabled || submitting;
- const canSubmit = !inert && !blockedReason && complete;
- const actions = (
- <Flexbox horizontal gap={8} justify={'flex-end'}>
- <Button disabled={inert} onClick={onCancel}>
- {labels.cancel}
- </Button>
- <Button disabled={!canSubmit} loading={submitting} type={'primary'} onClick={handleSubmit}>
- {submitting ? labels.submitting : labels.submit}
+ const proseActions = proseWarning && (
+ <Flexbox gap={8} role={'alert'}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Icon color={cssVar.colorWarning} icon={CircleAlert} size={14} />
+ <Text fontSize={12} type={'warning'}>
+ {labels.proseWarning(proseWarning)}
+ </Text>
+ </Flexbox>
+ <Button
+ disabled={inert || !!blockedReason}
+ loading={submitting}
+ onClick={() => void confirmProseSubmit()}
+ size={'small'}
+ >
+ {labels.confirmProse}
</Button>
</Flexbox>
);
+ const actions = (
+ <Flexbox gap={8}>
+ {proseActions}
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button disabled={inert} onClick={onCancel}>
+ {labels.cancel}
+ </Button>
+ <Button
+ disabled={isSecretSubmitDisabled({ blockedReason, complete, inert, proseWarning })}
+ loading={submitting}
+ type={'primary'}
+ onClick={() => void handleSubmit()}
+ >
+ {submitting ? labels.submitting : labels.submit}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+
return (
<Flexbox gap={12}>
{notice}
@@ -95,7 +149,7 @@ const SecretInputView = memo<SecretInputViewProps>(
spellCheck={false}
onChange={(event) => handleChange(field, event.target.value)}
onPressEnter={() => {
- if (canSubmit) void handleSubmit();
+ if (complete || proseWarning) void handleSubmit();
}}
/>
</Flexbox>
diff --git a/packages/shared-tool-ui/src/SecretInput/detectProseValue.test.ts b/packages/shared-tool-ui/src/SecretInput/detectProseValue.test.ts
new file mode 100644
index 00000000000..0b646a9830d
--- /dev/null
+++ b/packages/shared-tool-ui/src/SecretInput/detectProseValue.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import { detectProseValue } from './detectProseValue';
+
+describe('detectProseValue', () => {
+ it('flags CJK text as prose', () => {
+ expect(
+ detectProseValue('绑定到某个第三方服务(OpenAI / GitHub / 其他)去做 API 调用'),
+ ).toBe(true);
+ expect(detectProseValue('日語のキーです')).toBe(true);
+ expect(detectProseValue('한국어 토큰 값')).toBe(true);
+ });
+
+ it('flags long multi-word space-separated text as prose', () => {
+ expect(detectProseValue('this is clearly a sentence pasted by accident here')).toBe(true);
+ });
+
+ it('passes real token shapes without confirmation', () => {
+ expect(detectProseValue('sk-yCUC4oGrKNU1BG95jjE2d7ghMtQh6VAE1C6t5XLtn5ROtvuQ')).toBe(false);
+ expect(
+ detectProseValue('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abc'),
+ ).toBe(false);
+ expect(detectProseValue('ghp_16C7e42F292c6912E7710c838347Ae178B4a')).toBe(false);
+ expect(detectProseValue('a1b2c3d4-e5f6-7890-abcd-ef1234567890')).toBe(false);
+ expect(detectProseValue('Bearer abc123')).toBe(false);
+ });
+
+ it('does not flag short values or empty strings', () => {
+ expect(detectProseValue('')).toBe(false);
+ expect(detectProseValue('short key')).toBe(false);
+ expect(detectProseValue('hunter2')).toBe(false);
+ });
+});
diff --git a/packages/shared-tool-ui/src/SecretInput/detectProseValue.ts b/packages/shared-tool-ui/src/SecretInput/detectProseValue.ts
new file mode 100644
index 00000000000..06d7a6f32dd
--- /dev/null
+++ b/packages/shared-tool-ui/src/SecretInput/detectProseValue.ts
@@ -0,0 +1,24 @@
+/**
+ * Heuristic guard for the secure secret form: catches values that look like
+ * prose (a pasted sentence, a chat message) rather than a secret token, so a
+ * wrong paste — the exact failure seen in T-967, where the previous chat
+ * message was pasted into the form — asks for confirmation instead of being
+ * saved silently.
+ *
+ * A value counts as prose when it contains CJK characters, Kana or Hangul
+ * (secrets are ASCII tokens; every real-world key format is) or when it is a
+ * long whitespace-separated sentence. Values with no whitespace and no CJK
+ * pass unconfirmed — that covers API keys, JWTs, tokens, base64 blobs.
+ */
+export const detectProseValue = (value: string): boolean => {
+ if (!value) return false;
+
+ // Kana, CJK Unified Ideographs + extensions, Hangul, Compatibility Ideographs.
+ if (/[\u3040-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF]/.test(value)) {
+ return true;
+ }
+
+ // A long sentence pasted from chat: multiple space-separated words.
+ const words = value.trim().split(/\s+/);
+ return words.length >= 4 && value.trim().length >= 16;
+};
diff --git a/packages/shared-tool-ui/src/SecretInput/index.ts b/packages/shared-tool-ui/src/SecretInput/index.ts
index 723c6abb33a..9990109ef43 100644
--- a/packages/shared-tool-ui/src/SecretInput/index.ts
+++ b/packages/shared-tool-ui/src/SecretInput/index.ts
@@ -1,3 +1,7 @@
-export { default as SecretInputView, type SecretInputViewProps } from './SecretInputView';
+export {
+ default as SecretInputView,
+ isSecretSubmitDisabled,
+ type SecretInputViewProps,
+} from './SecretInputView';
export type { SecretInputLabels } from './types';
export { useSecretInputForm, type UseSecretInputFormParams } from './useSecretInputForm';
diff --git a/packages/shared-tool-ui/src/SecretInput/types.ts b/packages/shared-tool-ui/src/SecretInput/types.ts
index e25bcf568b3..917e6b05a36 100644
--- a/packages/shared-tool-ui/src/SecretInput/types.ts
+++ b/packages/shared-tool-ui/src/SecretInput/types.ts
@@ -1,8 +1,15 @@
export interface SecretInputLabels {
cancel: string;
+ /** Shown on the confirm button while a prose-looking submit is held. */
+ confirmProse: string;
/** Placeholder for each field; receives the field name. */
placeholder: (field: string) => string;
submit: string;
/** Shown on the submit button while the sink write is in flight. */
submitting: string;
+ /**
+ * Warning for prose-looking values (a pasted sentence / chat text). Receives
+ * the field names held for confirmation. Undefined hides the warning row.
+ */
+ proseWarning: (fields: string[]) => string;
}
diff --git a/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.test.ts b/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.test.ts
index 902d120c6a5..a6744d70ede 100644
--- a/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.test.ts
+++ b/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.test.ts
@@ -57,9 +57,107 @@ describe('useSecretInputForm', () => {
expect(onSubmit).toHaveBeenCalledWith({ OPENAI_API_KEY: 'sk-saved' });
expect(result.current.formKey).not.toBe(formKey);
expect(result.current.complete).toBe(false);
+ });
+
+ it('holds a prose-looking submit and only the confirm control can proceed', async () => {
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() => useSecretInputForm({ fields, onSubmit }));
+
+ act(() =>
+ result.current.handleChange('OPENAI_API_KEY', '绑定到某个第三方服务去做 API 调用'),
+ );
+
+ // First Save is held: the sink never sees the values.
+ await act(() => result.current.handleSubmit());
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(result.current.proseWarning).toEqual(['OPENAI_API_KEY']);
+
+ // A second ordinary Save / Enter is still held — the explicit confirm
+ // control is the only way through.
+ await act(() => result.current.handleSubmit());
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(result.current.proseWarning).toEqual(['OPENAI_API_KEY']);
+
+ // The confirm control submits.
+ await act(() => result.current.confirmProseSubmit());
+ expect(onSubmit).toHaveBeenCalledWith({
+ OPENAI_API_KEY: '绑定到某个第三方服务去做 API 调用',
+ });
+ expect(result.current.proseWarning).toBeUndefined();
+ });
+
+ it('confirmProseSubmit approves a held prose submit', async () => {
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() => useSecretInputForm({ fields, onSubmit }));
+
+ act(() => result.current.handleChange('OPENAI_API_KEY', 'this sentence was pasted by accident'));
+
+ await act(() => result.current.handleSubmit());
+ expect(onSubmit).not.toHaveBeenCalled();
+
+ await act(() => result.current.confirmProseSubmit());
+ expect(onSubmit).toHaveBeenCalledWith({
+ OPENAI_API_KEY: 'this sentence was pasted by accident',
+ });
+ expect(result.current.proseWarning).toBeUndefined();
+ });
+
+ it('keeps the prose confirmation across a failed submission', async () => {
+ const onSubmit = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('store unavailable'))
+ .mockResolvedValueOnce(undefined);
+ const { result } = renderHook(() => useSecretInputForm({ fields, onSubmit }));
+
+ act(() => result.current.handleChange('OPENAI_API_KEY', '一段被误粘贴的中文句子'));
+
+ // Confirm via the explicit control; the save fails.
+ await act(() => result.current.confirmProseSubmit());
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+
+ // Retry via ordinary Save goes straight to the sink without asking again.
+ await act(() => result.current.handleSubmit());
+ expect(onSubmit).toHaveBeenCalledTimes(2);
+ expect(onSubmit).toHaveBeenNthCalledWith(2, {
+ OPENAI_API_KEY: '一段被误粘贴的中文句子',
+ });
+ expect(result.current.proseWarning).toBeUndefined();
+ });
+
+ it('clears the prose warning after a successful confirmed submit', async () => {
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() => useSecretInputForm({ fields, onSubmit }));
+
+ act(() => result.current.handleChange('OPENAI_API_KEY', '一段被误粘贴的中文句子'));
+ await act(() => result.current.confirmProseSubmit());
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ expect(result.current.proseWarning).toBeUndefined();
+ });
+
+ it('clears the prose warning when the user edits the field', async () => {
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() => useSecretInputForm({ fields, onSubmit }));
+
+ act(() => result.current.handleChange('OPENAI_API_KEY', '一段被误粘贴的中文句子'));
+ await act(() => result.current.handleSubmit());
+ expect(result.current.proseWarning).toEqual(['OPENAI_API_KEY']);
+
+ act(() => result.current.handleChange('OPENAI_API_KEY', 'sk-corrected'));
+ expect(result.current.proseWarning).toBeUndefined();
+
+ // The corrected value submits without any hold.
+ await act(() => result.current.handleSubmit());
+ expect(onSubmit).toHaveBeenCalledWith({ OPENAI_API_KEY: 'sk-corrected' });
+ });
+
+ it('does not hold a real token submit', async () => {
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() => useSecretInputForm({ fields, onSubmit }));
+ act(() => result.current.handleChange('OPENAI_API_KEY', 'sk-yCUC4oGrKNU1BG95jjE2d7ghMtQh6VAE1'));
await act(() => result.current.handleSubmit());
- expect(onSubmit).toHaveBeenLastCalledWith({ OPENAI_API_KEY: undefined });
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ expect(result.current.proseWarning).toBeUndefined();
});
});
diff --git a/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.ts b/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.ts
index 1bb99f5b27c..1b083ef7c53 100644
--- a/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.ts
+++ b/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.ts
@@ -1,5 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
+import { detectProseValue } from './detectProseValue';
+
export interface UseSecretInputFormParams {
fields: string[];
/**
@@ -16,11 +18,25 @@ export interface UseSecretInputFormParams {
* devtools state snapshots, draft persistence or re-render props. They are
* dropped after a successful submit or on unmount; a failed submit keeps them
* for the retry. Only which fields are filled is kept in state.
+ *
+ * Prose guard: a submit whose values look like prose (a pasted sentence or
+ * chat text, the exact T-967 failure) is held instead of handed to the sink;
+ * the view shows a warning and calls `confirmProseSubmit` to let it through.
+ * Ordinary Save / Enter stays held while the guard is active — only the
+ * explicit confirm control can submit a prose-looking value. The
+ * acknowledgment survives failed submissions (the retry must not ask the user
+ * to confirm the same values again) and resets on a successful submit or when
+ * any field is edited.
*/
export const useSecretInputForm = ({ fields, onSubmit }: UseSecretInputFormParams) => {
const valuesRef = useRef<Record<string, string>>({});
const [filled, setFilled] = useState<Set<string>>(() => new Set());
const [submitting, setSubmitting] = useState(false);
+ const [proseWarning, setProseWarning] = useState<string[] | undefined>();
+ // Set only by confirmProseSubmit. Ordinary Save / Enter stays held until
+ // this is set, so the explicit "Save anyway" control is the only way a
+ // prose-looking value reaches the sink.
+ const [proseAcknowledged, setProseAcknowledged] = useState(false);
// Bumping the key remounts the uncontrolled inputs, clearing their DOM values.
const [formKey, setFormKey] = useState(0);
@@ -33,6 +49,9 @@ export const useSecretInputForm = ({ fields, onSubmit }: UseSecretInputFormParam
const handleChange = useCallback((field: string, value: string) => {
valuesRef.current[field] = value;
+ // Editing a field resets the prose guard: the user must re-confirm.
+ setProseWarning(undefined);
+ setProseAcknowledged(false);
setFilled((prev) => {
const hasValue = value.length > 0;
if (prev.has(field) === hasValue) return prev;
@@ -43,13 +62,17 @@ export const useSecretInputForm = ({ fields, onSubmit }: UseSecretInputFormParam
});
}, []);
- const handleSubmit = useCallback(async () => {
+ const runSubmit = useCallback(async () => {
const values = Object.fromEntries(fields.map((field) => [field, valuesRef.current[field]]));
setSubmitting(true);
try {
await onSubmit(values);
+ // Success: values are consumed and the prose guard resets with them.
+ // Failure keeps both for the retry (no re-confirm needed).
valuesRef.current = {};
setFilled(new Set());
+ setProseWarning(undefined);
+ setProseAcknowledged(false);
setFormKey((key) => key + 1);
} catch {
// The caller surfaces the failure; the values stay for the retry.
@@ -58,7 +81,37 @@ export const useSecretInputForm = ({ fields, onSubmit }: UseSecretInputFormParam
}
}, [fields, onSubmit]);
+ const handleSubmit = useCallback(async () => {
+ if (submitting) return;
+
+ const proseFields = fields.filter((field) => detectProseValue(valuesRef.current[field] ?? ''));
+ if (proseFields.length > 0 && !proseAcknowledged) {
+ // Ordinary Save / Enter always holds prose-looking values until the
+ // user activates the explicit "Save anyway" confirm control.
+ setProseWarning(proseFields);
+ return;
+ }
+
+ // Acknowledged (a confirmed submit failed before): retry without asking
+ // again; only a successful submit or editing a field resets the guard.
+ await runSubmit();
+ }, [fields, proseAcknowledged, runSubmit, submitting]);
+
+ const confirmProseSubmit = useCallback(async () => {
+ if (submitting) return;
+ setProseAcknowledged(true);
+ await runSubmit();
+ }, [runSubmit, submitting]);
+
const complete = fields.length > 0 && fields.every((field) => filled.has(field));
- return { complete, formKey, handleChange, handleSubmit, submitting };
+ return {
+ complete,
+ confirmProseSubmit,
+ formKey,
+ handleChange,
+ handleSubmit,
+ proseWarning,
+ submitting,
+ };
};