Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions components/ChatInput.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -424,3 +424,20 @@ test("renders both queued prompts and attached status bar together", () => {
assert.match(html, /Waiting for model\.\.\./);
assert.match(html, /live-status-dot/);
});

test("renders retry banner with countdown when delayMs and startedAt are provided", () => {
const now = Date.now();
const html = renderToStaticMarkup(
React.createElement(ChatInput, {
async onSend() { return { status: "accepted" }; },
retryInfo: {
attempt: 2,
maxAttempts: 5,
delayMs: 10000,
startedAt: now,
},
}),
);

assert.match(html, /Retrying \(2\/5\) in 10s…/);
});
97 changes: 59 additions & 38 deletions components/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@
onToolPresetChange?: (preset: ToolPreset) => void;
/** Display name for the current model when the catalog does not know it. */
modelNameOverride?: string | null;
retryInfo?: { attempt: number; maxAttempts: number; errorMessage?: string } | null;
retryInfo?: { attempt: number; maxAttempts: number; delayMs?: number; startedAt?: number; errorMessage?: string } | null;
onAbortRetry?: () => void;
queuedMessages?: QueuedMessages | null;
inputHistory?: string[];
Expand Down Expand Up @@ -442,6 +442,15 @@
const [fileIndex, setFileIndex] = useState<{ cwd: string; entries: FileIndexEntry[]; truncated: boolean } | null>(null);
const [fileIndexLoading, setFileIndexLoading] = useState(false);
const [atServerResult, setAtServerResult] = useState<{ cwd: string; query: string; matches: FileIndexEntry[] } | null>(null);
const [retryNow, setRetryNow] = useState(() => Date.now());
useEffect(() => {
if (!retryInfo?.delayMs || !retryInfo?.startedAt) return;
setRetryNow(Date.now());
const interval = setInterval(() => {
setRetryNow(Date.now());
}, 1000);
return () => clearInterval(interval);
}, [retryInfo?.delayMs, retryInfo?.startedAt]);

const textareaRef = useRef<HTMLTextAreaElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -627,7 +636,7 @@
} finally {
pendingImageCountRef.current -= imageFiles.length;
}
}, []);

Check warning on line 639 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (windows-latest)

React Hook useCallback has a missing dependency: 't'. Either include it or remove the dependency array

Check warning on line 639 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (ubuntu-latest)

React Hook useCallback has a missing dependency: 't'. Either include it or remove the dependency array

const processTextFiles = useCallback(async (files: File[]) => {
const remaining = Math.max(
Expand Down Expand Up @@ -688,7 +697,7 @@
pendingTextFileCountRef.current -= textFiles.length;
pendingTextFileBytesRef.current -= textFiles.reduce((total, file) => total + file.size, 0);
}
}, []);

Check warning on line 700 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (windows-latest)

React Hook useCallback has a missing dependency: 't'. Either include it or remove the dependency array

Check warning on line 700 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (ubuntu-latest)

React Hook useCallback has a missing dependency: 't'. Either include it or remove the dependency array

const processFiles = useCallback((files: File[]) => {
const imageFiles = files.filter((file) => file.type.startsWith("image/"));
Expand Down Expand Up @@ -2064,43 +2073,55 @@
<ModelErrorBanner error={modelError} />
<ComposerModeStatus goal={activeGoal} plan={activePlan} />
{/* Retry banner */}
{retryInfo && (
<div style={{
marginBottom: 8, padding: "5px 10px",
background: "color-mix(in srgb, var(--status-warning) 8%, transparent)", border: "1px solid color-mix(in srgb, var(--status-warning) 25%, transparent)",
borderRadius: 6, fontSize: 12, color: "var(--status-warning)",
display: "flex", alignItems: "center", gap: 6,
}}>
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
</svg>
{t("chatInput.retrying", { attempt: retryInfo.attempt, maxAttempts: retryInfo.maxAttempts })}{retryInfo.errorMessage && <span style={{ opacity: 0.7, marginLeft: 4 }}>— {retryInfo.errorMessage}</span>}
{onAbortRetry && (
<button
type="button"
onClick={onAbortRetry}
title={t("chatInput.abortRetryTitle")}
style={{
marginLeft: "auto",
padding: "3px 9px",
fontSize: 11,
color: "var(--status-warning)",
background: "transparent",
border: "1px solid color-mix(in srgb, var(--status-warning) 45%, transparent)",
borderRadius: 6,
cursor: "pointer",
whiteSpace: "nowrap",
transition: "background var(--dur-fast) var(--ease-out-warm)",
}}
onMouseEnter={(e) => { e.currentTarget.style.background = "color-mix(in srgb, var(--status-warning) 12%, transparent)"; }}
onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}
>
{t("chatInput.abortRetry")}
</button>
)}
</div>
)}
{retryInfo && (() => {
const remainingSec = (retryInfo.delayMs !== undefined && retryInfo.startedAt !== undefined)
? (() => {
const effectiveNow = Math.max(retryNow, retryInfo.startedAt);
const maxSec = Math.ceil(retryInfo.delayMs / 1000);
return Math.max(0, Math.min(maxSec, Math.ceil((retryInfo.startedAt + retryInfo.delayMs - effectiveNow) / 1000)));
})()
: undefined;
return (
<div style={{
marginBottom: 8, padding: "5px 10px",
background: "color-mix(in srgb, var(--status-warning) 8%, transparent)", border: "1px solid color-mix(in srgb, var(--status-warning) 25%, transparent)",
borderRadius: 6, fontSize: 12, color: "var(--status-warning)",
display: "flex", alignItems: "center", gap: 6,
}}>
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
</svg>
{remainingSec !== undefined
? t("chatInput.retryingWithCountdown", { attempt: retryInfo.attempt, maxAttempts: retryInfo.maxAttempts, seconds: remainingSec })
: t("chatInput.retrying", { attempt: retryInfo.attempt, maxAttempts: retryInfo.maxAttempts })}
{retryInfo.errorMessage && <span style={{ opacity: 0.7, marginLeft: 4 }}>— {retryInfo.errorMessage}</span>}
{onAbortRetry && (
<button
type="button"
onClick={onAbortRetry}
title={t("chatInput.abortRetryTitle")}
style={{
marginLeft: "auto",
padding: "3px 9px",
fontSize: 11,
color: "var(--status-warning)",
background: "transparent",
border: "1px solid color-mix(in srgb, var(--status-warning) 45%, transparent)",
borderRadius: 6,
cursor: "pointer",
whiteSpace: "nowrap",
transition: "background var(--dur-fast) var(--ease-out-warm)",
}}
onMouseEnter={(e) => { e.currentTarget.style.background = "color-mix(in srgb, var(--status-warning) 12%, transparent)"; }}
onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}
>
{t("chatInput.abortRetry")}
</button>
)}
</div>
);
})()}
{compactResultText && (
<div style={{
marginBottom: 8, padding: "5px 10px",
Expand Down
1 change: 1 addition & 0 deletions components/ChatWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1470,6 +1470,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa
{extensionDialog && (
<div style={{ marginBottom: 8 }}>
<ExtensionDialog
key={extensionDialog.id}
request={extensionDialog}
onRespond={respondToExtensionUi}
attached
Expand Down
58 changes: 58 additions & 0 deletions components/ExtensionDialog.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,61 @@ test("question selection survives request replay but is cleared for the next que
view.unmount();
}
});

test("ExtensionDialog masks sensitive input and toggles visibility", async () => {
const request = {
type: "extension_ui_request",
id: "secret-1",
method: "input",
title: "Enter API Key",
placeholder: "sk-...",
};
const responses = [];
const onRespond = (current, response) => responses.push({ id: current.id, ...response });
const dialog = (current) => React.createElement(ExtensionDialog, { request: current, onRespond, attached: true });
const view = render(dialog(request));
try {
const input = view.getByPlaceholderText("sk-...");
assert.equal(input.type, "password");
assert.equal(input.getAttribute("autocomplete"), "off");
assert.equal(input.getAttribute("data-1p-ignore"), "true");

const toggle = screen.getByRole("button", { name: "Show password" });
fireEvent.click(toggle);
assert.equal(input.type, "text");

fireEvent.click(screen.getByRole("button", { name: "Hide password" }));
assert.equal(input.type, "password");

// explicit secret: false does not mask even if title contains sensitive words
view.rerender(dialog({ ...request, id: "secret-2", secret: false }));
const plainInput = view.getByPlaceholderText("sk-...");
assert.equal(plainInput.type, "text");
assert.equal(screen.queryByRole("button", { name: "Show password" }), null);

// explicit secret: true masks regardless of title
view.rerender(dialog({
type: "extension_ui_request",
id: "secret-3",
method: "input",
title: "Random prompt",
secret: true,
}));
const maskedInput = view.container.querySelector("input");
assert.ok(maskedInput);
assert.equal(maskedInput.type, "password");

// plural prompt test: "Enter your credentials"
view.rerender(dialog({
type: "extension_ui_request",
id: "secret-4",
method: "input",
title: "Enter your credentials",
}));
const pluralInput = view.container.querySelector("input");
assert.ok(pluralInput);
assert.equal(pluralInput.type, "password");
} finally {
view.unmount();
}
});
102 changes: 79 additions & 23 deletions components/ExtensionDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";

import { useEffect, useRef, useState, useSyncExternalStore, type RefObject } from "react";
import { Eye, EyeOff } from "lucide-react";
import type { ExtensionUiRequest } from "@/lib/types";
import type { RpcAskDialogAnswer } from "@/lib/pi-types";
import { useI18n } from "@/lib/i18n";
Expand Down Expand Up @@ -195,6 +196,20 @@ function touchPointer(): boolean {
return !window.matchMedia("(pointer: fine)").matches;
}

const SENSITIVE_PATTERN = /\b(passwords?|passphrases?|secrets?|tokens?|api[_\s-]?keys?|access[_\s-]?tokens?|private[_\s-]?keys?|auth[_\s-]?tokens?|credentials?)\b/i;
const NON_SECRET_METADATA_PATTERN = /\b(token\s+(?:name|count|limit|budget|usage)|max\s+tokens)\b/i;

export function isSensitivePrompt(title?: string, placeholder?: string): boolean {
const titleText = (title ?? "").trim();
const placeholderText = (placeholder ?? "").trim();
const fullText = `${titleText} ${placeholderText}`.trim();
if (!fullText) return false;
const strippedTitle = titleText.replace(NON_SECRET_METADATA_PATTERN, "");
if (SENSITIVE_PATTERN.test(strippedTitle)) return true;
const strippedFull = fullText.replace(NON_SECRET_METADATA_PATTERN, "");
return SENSITIVE_PATTERN.test(strippedFull);
}

/** Single-select questions start on their recommended option. */
function initialAskDrafts(request: ExtensionDialogRequest): AskDraft[] {
if (request.method !== "ask") return [];
Expand Down Expand Up @@ -226,6 +241,7 @@ export function ExtensionDialog({
}) {
const { t } = useI18n();
const [value, setValue] = useState(request.method === "editor" ? request.prefill ?? "" : "");
const [showPassword, setShowPassword] = useState(false);
const [selectedOption, setSelectedOption] = useState<string | null>(null);
const requestIdRef = useRef(request.id);
// `pointerType` of the latest press: the pointer media query only describes
Expand All @@ -240,6 +256,7 @@ export function ExtensionDialog({
if (requestIdRef.current === request.id) return;
requestIdRef.current = request.id;
setValue(request.method === "editor" ? request.prefill ?? "" : "");
setShowPassword(false);
setSelectedOption(null);
setAskDrafts(initialAskDrafts(request));
}, [request]);
Expand Down Expand Up @@ -427,29 +444,68 @@ export function ExtensionDialog({
})}
</div>
)}
{request.method === "input" && (
<input
autoFocus
aria-label={request.title || request.placeholder || "Input value"}
value={value}
placeholder={request.placeholder}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") submitValue();
}}
style={{
width: "100%",
padding: "7px 10px",
borderRadius: 6,
border: "1px solid var(--border)",
background: "var(--bg-panel)",
color: "var(--text)",
outline: "none",
fontSize: 12,
fontFamily: "inherit",
}}
/>
)}
{request.method === "input" && (() => {
const isSensitive = Boolean(request.secret || request.password) ||
(request.secret !== false && request.password !== false && isSensitivePrompt(request.title, request.placeholder));
return (
<div style={{ position: "relative", width: "100%" }}>
<input
autoFocus
type={isSensitive && !showPassword ? "password" : "text"}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
autoComplete={isSensitive ? "off" : undefined}
autoCorrect={isSensitive ? "off" : undefined}
autoCapitalize={isSensitive ? "off" : undefined}
spellCheck={isSensitive ? false : undefined}
data-1p-ignore={isSensitive ? "true" : undefined}
aria-label={request.title || request.placeholder || "Input value"}
value={value}
placeholder={request.placeholder}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") submitValue();
}}
style={{
width: "100%",
padding: isSensitive ? "7px 34px 7px 10px" : "7px 10px",
borderRadius: 6,
border: "1px solid var(--border)",
background: "var(--bg-panel)",
color: "var(--text)",
outline: "none",
fontSize: 12,
fontFamily: "inherit",
}}
/>
{isSensitive && (
<button
type="button"
aria-label={showPassword ? t("chatWindow.hidePassword") : t("chatWindow.showPassword")}
title={showPassword ? t("chatWindow.hidePassword") : t("chatWindow.showPassword")}
onClick={() => setShowPassword((prev) => !prev)}
style={{
position: "absolute",
right: 6,
top: "50%",
transform: "translateY(-50%)",
width: 24,
height: 24,
padding: 0,
background: "none",
border: "none",
cursor: "pointer",
color: "var(--text-muted)",
display: "flex",
alignItems: "center",
justifyContent: "center",
borderRadius: 4,
}}
>
{showPassword ? <EyeOff size={14} aria-hidden="true" /> : <Eye size={14} aria-hidden="true" />}
</button>
)}
</div>
);
})()}
{request.method === "editor" && (
<textarea
autoFocus
Expand Down
11 changes: 9 additions & 2 deletions hooks/useAgentSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
// Queue delivery modes (set_steering_mode / set_follow_up_mode).
const [steeringMode, setSteeringMode] = useState<"all" | "one-at-a-time">("all");
const [followUpMode, setFollowUpMode] = useState<"all" | "one-at-a-time">("all");
const [retryInfo, setRetryInfo] = useState<{ attempt: number; maxAttempts: number; errorMessage?: string } | null>(null);
const [retryInfo, setRetryInfo] = useState<{ attempt: number; maxAttempts: number; delayMs?: number; startedAt?: number; errorMessage?: string } | null>(null);
const [contextUsage, setContextUsage] = useState<{ percent: number | null; contextWindow: number; tokens: number | null } | null>(null);
const [systemPrompt, setSystemPrompt] = useState<string | null>(null);
const [skillDiagnostics, setSkillDiagnostics] = useState<SkillDiagnosticsSnapshot | null>(null);
Expand Down Expand Up @@ -2412,7 +2412,14 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
break;
case "auto_retry_start": {
const msg = event.errorMessage as string | undefined;
setRetryInfo({ attempt: event.attempt as number, maxAttempts: event.maxAttempts as number, errorMessage: msg });
const delayMs = typeof event.delayMs === "number" && Number.isFinite(event.delayMs) && event.delayMs > 0 ? event.delayMs : undefined;
setRetryInfo({
attempt: event.attempt as number,
maxAttempts: event.maxAttempts as number,
delayMs,
startedAt: delayMs !== undefined ? Date.now() : undefined,
errorMessage: msg,
});
if (msg && isQuotaLikeError(msg)) lastQuotaErrorRef.current = msg;
break;
}
Expand Down
3 changes: 3 additions & 0 deletions lib/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,7 @@
"chatInput.recallQueueTitle": "Remove all queued messages and put them back into the input box for editing",
"chatInput.recallToInput": "Recall to input",
"chatInput.retrying": "Retrying ({attempt}/{maxAttempts})…",
"chatInput.retryingWithCountdown": "Retrying ({attempt}/{maxAttempts}) in {seconds}s…",
"chatInput.searching": "Searching…",
"chatInput.searchingAllFiles": "searching all files…",
"chatInput.searchModels": "Search models…",
Expand Down Expand Up @@ -565,6 +566,8 @@
"chatWindow.extensionRequest": "extension request",
"chatWindow.extensionTerminalInput": "Extension terminal input",
"chatWindow.conversation": "Conversation",
"chatWindow.showPassword": "Show password",
"chatWindow.hidePassword": "Hide password",
"chatWindow.retry": "Try again",
"chatWindow.loadingSession": "Loading session...",
"chatWindow.messageCount.one": "{count} message",
Expand Down
Loading
Loading