Skip to content

Show editable default fields on connect secret - #110

Merged
kentcdodds merged 8 commits into
mainfrom
cursor/connect-secret-query-defaults-b946
Mar 31, 2026
Merged

kentcdodds merged 8 commits into
mainfrom
cursor/connect-secret-query-defaults-b946

Conversation

@kentcdodds

@kentcdodds kentcdodds commented Mar 30, 2026 •

Copy link
Copy Markdown
Member

Summary

  • reuse the shared secret editor fields in the connect secret flow and seed editable description, allowed hosts, and allowed capabilities from query params
  • save the reviewed secret metadata through /connect/secret.json so stored policy matches what the user sees in the form and connector binding
  • fix the shared secret editor component to follow the Remix component factory contract so the form renders correctly
  • deduplicate connect-secret normalization so save and review share one helper
  • merge latest main changes and fix account-secrets merge regressions so typecheck and E2E pass together

Testing

  • npm run test -- packages/worker/src/app/handlers/connect-secret.node.test.ts packages/worker/client/routes/connect-secret-errors.node.test.ts
  • npm run typecheck
  • npm run build
  • npm run test:e2e -- e2e/account-secrets.spec.ts
  • manual browser walkthrough on http://localhost:3742/connect/secret?... confirming editable defaults and normalized review state
  • manual browser verification that /account/secrets/user/manual-secret-check renders the selected secret detail pane after the merge fix

connect-secret-query-defaults-demo.mp4
Connect secret editable defaults
Connect secret review state
Account secrets selected secret detail pane

Open in Web Open in Cursor 

Summary by CodeRabbit

  • New Features

    • Reusable secret editor UI for description, secret value (show/hide), and dynamic allowed-hosts/capabilities lists.
    • Connect flow now seeds editable description and allowed lists from existing data or query params and shows them in the review step.
  • Bug Fixes

    • Normalizes and validates host/capability lists and rejects blank secret values to ensure clean persistence.
  • Tests

    • Added tests to verify secret save and persistence of allowed-host and allowed-capability lists.

cursoragent and others added 3 commits March 30, 2026 23:18
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
@coderabbitai

coderabbitai Bot commented Mar 30, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5b0e8cdf-370c-4a46-8aaa-5f06e653410f

📥 Commits

Reviewing files that changed from the base of the PR and between b880a5d and 8ab729f.

📒 Files selected for processing (2)
  • packages/worker/client/routes/account-secrets.tsx
  • packages/worker/client/routes/connect-secret.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/worker/client/routes/account-secrets.tsx
  • packages/worker/client/routes/connect-secret.tsx

📝 Walkthrough

Walkthrough

Extracts a reusable SecretEditorFields UI, adds normalization utilities for allowed hosts/capabilities, updates client routes to manage description and editable host/capability lists, and extends the connect-secret server handler and tests to persist and validate the richer secret metadata.

Changes

Cohort / File(s) Summary
Client routes using secret editor
packages/worker/client/routes/account-secrets.tsx, packages/worker/client/routes/connect-secret.tsx
Replaced inline secret editor UI with SecretEditorFields; added/edit-managed state for description, allowedHosts, allowedCapabilities, and showSecretValue; wired add/update/remove handlers; use shared normalization utilities; adjusted init/save flows and request payloads.
Secret editor component
packages/worker/client/routes/secret-editor-fields.tsx
New exported HOC SecretEditorFields rendering description textarea, secret value input with show/hide toggle, and dynamic repeat-list controls for allowed hosts and capabilities with add/update/remove callbacks and local styles.
Normalization utilities
packages/worker/client/routes/secret-normalization.ts
New exports normalizeAllowedHosts and normalizeAllowedCapabilities (trim, dedupe, sort; hosts lowercased).
Server handler changes
packages/worker/src/app/handlers/connect-secret.ts
POST handler now accepts value, description, allowedHosts, allowedCapabilities; normalizes inputs, validates capabilities, persists secret when value present, and calls setSecretAllowedHosts / setSecretAllowedCapabilities; rejects blank secret value with 400.
Handler tests
packages/worker/src/app/handlers/connect-secret.node.test.ts
Added mocks for saveSecret, setSecretAllowedHosts, setSecretAllowedCapabilities and a POST test asserting secret metadata and permission lists are saved with correct storage context.

Sequence Diagram

sequenceDiagram
    participant User as User
    participant Client as Client (SecretEditorFields)
    participant Handler as Handler (/connect/secret)
    participant Service as SecretsService
    participant Storage as Persistence

    User->>Client: Enter description, value, hosts, capabilities
    Client->>Client: normalizeAllowedHosts/capabilities
    Client->>Handler: POST /connect/secret.json {value, description, allowedHosts, allowedCapabilities}
    Handler->>Handler: normalize & validate capabilities
    alt value provided & non-empty
        Handler->>Service: saveSecret(storageContext, metadata)
        Service->>Storage: persist secret value & metadata
        Handler->>Service: setSecretAllowedHosts(context, hosts)
        Service->>Storage: persist allowed hosts
        Handler->>Service: setSecretAllowedCapabilities(context, capabilities)
        Service->>Storage: persist allowed capabilities
    else value blank
        Handler-->>Client: 400 Bad Request
    end
    Handler-->>Client: success response
    Client-->>User: show confirmation
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I hopped through lines with whiskered cheer,
Trimmed hosts and caps and made them clear.
Fields tucked tidy, secrets snug and bright,
I nudged the editor — now it’s just right. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Show editable default fields on connect secret' accurately describes the main change, which adds editable fields for description, allowed hosts, and allowed capabilities seeded from query parameters on the connect secret page.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cursor/connect-secret-query-defaults-b946

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@kentcdodds
kentcdodds marked this pull request as ready for review March 30, 2026 23:50
@github-actions

github-actions Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

🔎 Preview deployed: https://kody-pr-110.kentcdodds.workers.dev

Worker: kody-pr-110
D1: kody-pr-110-db
KV: kody-pr-110-oauth-kv

Mocks:

Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
packages/worker/client/routes/connect-secret.tsx (1)

765-788: Normalization called multiple times in render.

normalizeAllowedHosts and normalizeAllowedCapabilities are called twice each here (once for the length check, once for the .map()). While functionally correct and unlikely to cause issues with small arrays, computing the normalized values once would be cleaner.

♻️ Compute normalized values once
+								const normalizedHosts = normalizeAllowedHosts(state.allowedHosts)
+								const normalizedCaps = normalizeAllowedCapabilities(state.allowedCapabilities)
								<div>
									<div css={labelCss}>Hosts to approve</div>
									<ul css={listCss}>
-										{normalizeAllowedHosts(state.allowedHosts).length > 0 ? (
-											normalizeAllowedHosts(state.allowedHosts).map((host) => (
+										{normalizedHosts.length > 0 ? (
+											normalizedHosts.map((host) => (
												<li key={host}>{host}</li>
											))
										) : (
											<li>None (approval required later).</li>
										)}
									</ul>
								</div>
								<div>
									<div css={labelCss}>Capabilities to allow</div>
									<ul css={listCss}>
-										{normalizeAllowedCapabilities(state.allowedCapabilities)
-											.length > 0 ? (
-											normalizeAllowedCapabilities(
-												state.allowedCapabilities,
-											).map((capability) => (
+										{normalizedCaps.length > 0 ? (
+											normalizedCaps.map((capability) => (
												<li key={capability}>{capability}</li>
											))
										) : (
											<li>No restrictions requested.</li>
										)}
									</ul>
								</div>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/client/routes/connect-secret.tsx` around lines 765 - 788, The
render calls normalizeAllowedHosts(state.allowedHosts) and
normalizeAllowedCapabilities(state.allowedCapabilities) twice each; compute each
normalized array once (e.g., const normalizedHosts =
normalizeAllowedHosts(state.allowedHosts) and const normalizedCapabilities =
normalizeAllowedCapabilities(state.allowedCapabilities)) and use those variables
for the length checks and the .map() calls (replace both inline calls in the
JSX), ensuring keys and fallback <li> branches remain the same.
packages/worker/client/routes/secret-editor-fields.tsx (2)

51-85: Consider consolidating the duplicate input elements.

The text and password inputs are nearly identical except for the type attribute. This could be simplified to a single input with a dynamic type.

♻️ Optional refactor to reduce duplication
-				{props.showSecretValue ? (
-					<input
-						type="text"
-						required
-						autoComplete="new-password"
-						value={props.value}
-						placeholder={props.valuePlaceholder ?? 'Enter the secret value'}
-						on={{
-							input: (event) => {
-								props.onValueChange(event.currentTarget.value)
-							},
-						}}
-						css={{
-							...inputCss,
-							paddingRight: '3rem',
-						}}
-					/>
-				) : (
-					<input
-						type="password"
-						required
-						autoComplete="new-password"
-						value={props.value}
-						placeholder={props.valuePlaceholder ?? 'Enter the secret value'}
-						on={{
-							input: (event) => {
-								props.onValueChange(event.currentTarget.value)
-							},
-						}}
-						css={{
-							...inputCss,
-							paddingRight: '3rem',
-						}}
-					/>
-				)}
+				<input
+					type={props.showSecretValue ? 'text' : 'password'}
+					required
+					autoComplete="new-password"
+					value={props.value}
+					placeholder={props.valuePlaceholder ?? 'Enter the secret value'}
+					on={{
+						input: (event) => {
+							props.onValueChange(event.currentTarget.value)
+						},
+					}}
+					css={{
+						...inputCss,
+						paddingRight: '3rem',
+					}}
+				/>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/client/routes/secret-editor-fields.tsx` around lines 51 - 85,
The two nearly identical input elements inside the conditional should be
consolidated into a single input: replace the conditional JSX around
props.showSecretValue with one <input> whose type is set dynamically (e.g.,
type={props.showSecretValue ? 'text' : 'password'}) and keep all existing
attributes and handlers (required, autoComplete="new-password",
value={props.value}, placeholder={props.valuePlaceholder ?? 'Enter the secret
value'}, the on.input callback calling props.onValueChange, and the css spread
including inputCss and paddingRight). This removes duplication while preserving
behavior tied to props.showSecretValue, props.onValueChange, inputCss and
placeholder logic.

146-167: Defensive type checks are unnecessary given the prop types.

Lines 150 and 196 check typeof host === 'string' and typeof capabilityName === 'string', but allowedHosts and allowedCapabilities are already typed as Array<string>. These guards suggest either distrust of the caller or a previous bug. If intentional for runtime safety, a comment explaining why would help.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/client/routes/secret-editor-fields.tsx` around lines 146 -
167, The runtime typeof checks (e.g., "typeof host === 'string'" and "typeof
capabilityName === 'string'") are redundant because props.allowedHosts and
props.allowedCapabilities are typed as Array<string>; remove those guards and
use the values directly in the JSX and event handlers (references:
props.allowedHosts, props.onUpdateAllowedHost, props.onRemoveAllowedHost,
props.allowedCapabilities, props.onUpdateAllowedCapability,
props.onRemoveAllowedCapability, capabilityName). If you intentionally want
runtime safety, replace the guard with a short explanatory comment above the
block stating why a runtime check is required; otherwise delete the typeof
conditions to simplify the code.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/worker/src/app/handlers/connect-secret.ts`:
- Around line 194-230: The current sequence (saveSecret followed by
setSecretAllowedHosts and setSecretAllowedCapabilities) is non-atomic so partial
failures leave a secret with stale permissions; either make these three
operations transactional in the persistence layer or add compensating rollback
logic. Fix by updating the service API so saveSecret accepts allowedHosts and
allowedCapabilities and persists them in a single DB transaction (or implement a
new saveSecretWithPermissions that wraps saveSecret + setSecretAllowedHosts +
setSecretAllowedCapabilities inside one transaction), or if a transaction is not
possible, perform cleanup by deleting the newly created secret when either
setSecretAllowedHosts or setSecretAllowedCapabilities fails (use saveSecret,
setSecretAllowedHosts, setSecretAllowedCapabilities, or a new wrapper function
to coordinate and rollback).

---

Nitpick comments:
In `@packages/worker/client/routes/connect-secret.tsx`:
- Around line 765-788: The render calls
normalizeAllowedHosts(state.allowedHosts) and
normalizeAllowedCapabilities(state.allowedCapabilities) twice each; compute each
normalized array once (e.g., const normalizedHosts =
normalizeAllowedHosts(state.allowedHosts) and const normalizedCapabilities =
normalizeAllowedCapabilities(state.allowedCapabilities)) and use those variables
for the length checks and the .map() calls (replace both inline calls in the
JSX), ensuring keys and fallback <li> branches remain the same.

In `@packages/worker/client/routes/secret-editor-fields.tsx`:
- Around line 51-85: The two nearly identical input elements inside the
conditional should be consolidated into a single input: replace the conditional
JSX around props.showSecretValue with one <input> whose type is set dynamically
(e.g., type={props.showSecretValue ? 'text' : 'password'}) and keep all existing
attributes and handlers (required, autoComplete="new-password",
value={props.value}, placeholder={props.valuePlaceholder ?? 'Enter the secret
value'}, the on.input callback calling props.onValueChange, and the css spread
including inputCss and paddingRight). This removes duplication while preserving
behavior tied to props.showSecretValue, props.onValueChange, inputCss and
placeholder logic.
- Around line 146-167: The runtime typeof checks (e.g., "typeof host ===
'string'" and "typeof capabilityName === 'string'") are redundant because
props.allowedHosts and props.allowedCapabilities are typed as Array<string>;
remove those guards and use the values directly in the JSX and event handlers
(references: props.allowedHosts, props.onUpdateAllowedHost,
props.onRemoveAllowedHost, props.allowedCapabilities,
props.onUpdateAllowedCapability, props.onRemoveAllowedCapability,
capabilityName). If you intentionally want runtime safety, replace the guard
with a short explanatory comment above the block stating why a runtime check is
required; otherwise delete the typeof conditions to simplify the code.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ab10df84-5e1c-4ffb-9326-40142f6e777b

📥 Commits

Reviewing files that changed from the base of the PR and between 38aaba0 and 6bd0f18.

📒 Files selected for processing (6)
  • packages/worker/client/routes/account-secrets.tsx
  • packages/worker/client/routes/connect-secret.tsx
  • packages/worker/client/routes/secret-editor-fields.tsx
  • packages/worker/client/routes/secret-normalization.ts
  • packages/worker/src/app/handlers/connect-secret.node.test.ts
  • packages/worker/src/app/handlers/connect-secret.ts

Comment on lines +194 to +230
if (typeof value === 'string') {
if (!value.trim()) {
return jsonResponse(
{ ok: false, error: 'Secret value is required.' },
400,
)
}
await saveSecret({
env,
userId: user.mcpUser.userId,
name,
value,
scope,
description,
storageContext,
sessionExpiresAt:
scope === 'session'
? new Date(session.exp).toISOString()
: null,
})
await setSecretAllowedHosts({
env,
userId: user.mcpUser.userId,
name,
scope,
allowedHosts: normalizedAllowedHosts,
storageContext,
})
await setSecretAllowedCapabilities({
env,
userId: user.mcpUser.userId,
name,
scope,
allowedCapabilities: normalizedAllowedCapabilities,
storageContext,
})
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Non-atomic persistence: partial failure leaves secret with stale permissions.

The three sequential operations (saveSecret, setSecretAllowedHosts, setSecretAllowedCapabilities) are not transactional. If setSecretAllowedHosts or setSecretAllowedCapabilities fails after saveSecret succeeds, the secret will exist but with its previous (or empty) permissions rather than the requested ones.

This is recoverable since the user receives an error and can retry, but worth noting. The service layer preserves existing permissions during saveSecret (per context snippet 1, lines 109-110), so re-submitting with the same payload should eventually succeed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/app/handlers/connect-secret.ts` around lines 194 - 230,
The current sequence (saveSecret followed by setSecretAllowedHosts and
setSecretAllowedCapabilities) is non-atomic so partial failures leave a secret
with stale permissions; either make these three operations transactional in the
persistence layer or add compensating rollback logic. Fix by updating the
service API so saveSecret accepts allowedHosts and allowedCapabilities and
persists them in a single DB transaction (or implement a new
saveSecretWithPermissions that wraps saveSecret + setSecretAllowedHosts +
setSecretAllowedCapabilities inside one transaction), or if a transaction is not
possible, perform cleanup by deleting the newly created secret when either
setSecretAllowedHosts or setSecretAllowedCapabilities fails (use saveSecret,
setSecretAllowedHosts, setSecretAllowedCapabilities, or a new wrapper function
to coordinate and rollback).

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Redundant normalization calls in review render path
    • Stored normalized hosts and capabilities in local variables and reused them in the review render path to avoid redundant calls.
Preview (b880a5d72f)
diff --git a/packages/worker/client/routes/account-secrets.tsx b/packages/worker/client/routes/account-secrets.tsx
--- a/packages/worker/client/routes/account-secrets.tsx
+++ b/packages/worker/client/routes/account-secrets.tsx
@@ -25,6 +25,11 @@
 	transitions,
 	typography,
 } from '#client/styles/tokens.ts'
+import { SecretEditorFields } from './secret-editor-fields.tsx'
+import {
+	normalizeAllowedCapabilities,
+	normalizeAllowedHosts,
+} from './secret-normalization.ts'
 
 type SecretScope = 'app' | 'user'
 
@@ -118,30 +123,6 @@
 	return list.filter((item): item is string => typeof item === 'string')
 }
 
-/** Matches server `normalizeAllowedHosts` in `#mcp/secrets/allowed-hosts.ts`. */
-function clientNormalizeAllowedHosts(hosts: Array<string>): Array<string> {
-	return Array.from(
-		new Set(
-			hosts
-				.map((host) => host.trim().toLowerCase())
-				.filter((host) => host.length > 0),
-		),
-	).sort()
-}
-
-/** Matches server `normalizeAllowedCapabilities` in `#mcp/secrets/allowed-capabilities.ts`. */
-function clientNormalizeAllowedCapabilities(
-	capabilities: Array<string>,
-): Array<string> {
-	return Array.from(
-		new Set(
-			capabilities
-				.map((value) => value.trim())
-				.filter((value) => value.length > 0),
-		),
-	).sort((left, right) => left.localeCompare(right))
-}
-
 function collectRepeatedTextRows(
 	form: HTMLFormElement,
 	listName: 'allowed-hosts' | 'allowed-capabilities',
@@ -564,10 +545,10 @@
 		handle.update()
 
 		try {
-			const allowedHosts = clientNormalizeAllowedHosts(
+			const allowedHosts = normalizeAllowedHosts(
 				collectRepeatedTextRows(form, 'allowed-hosts'),
 			)
-			const allowedCapabilities = clientNormalizeAllowedCapabilities(
+			const allowedCapabilities = normalizeAllowedCapabilities(
 				collectRepeatedTextRows(form, 'allowed-capabilities'),
 			)
 			const response = await fetch(accountSecretsApiPath, {
@@ -1205,272 +1186,40 @@
 										})
 									: null}
 
-								<label css={fieldCss}>
-									<span css={fieldLabelCss}>Description</span>
-									<textarea
-										value={editorState.description}
-										rows={3}
-										placeholder="What this secret is used for"
-										on={{
-											input: (event) => {
-												editorState = {
-													...editorState,
-													description: event.currentTarget.value,
-												}
-												handle.update()
-											},
-										}}
-										css={textareaCss}
-									/>
-								</label>
+								<SecretEditorFields
+									description={editorState.description}
+									onDescriptionChange={(description) => {
+										editorState = {
+											...editorState,
+											description,
+										}
+										handle.update()
+									}}
+									value={editorState.value}
+									onValueChange={(value) => {
+										editorState = {
+											...editorState,
+											value,
+										}
+										handle.update()
+									}}
+									showSecretValue={showSecretValue}
+									onToggleShowSecretValue={() => {
+										showSecretValue = !showSecretValue
+										handle.update()
+									}}
+									allowedHosts={editorState.allowedHosts}
+									onUpdateAllowedHost={updateAllowedHost}
+									onAddAllowedHost={addAllowedHost}
+									onRemoveAllowedHost={removeAllowedHost}
+									allowedCapabilities={editorState.allowedCapabilities}
+									onUpdateAllowedCapability={updateAllowedCapability}
+									onAddAllowedCapability={addAllowedCapability}
+									onRemoveAllowedCapability={removeAllowedCapability}
+									allowedHostsListName="allowed-hosts"
+									allowedCapabilitiesListName="allowed-capabilities"
+								/>
 
-								<label css={fieldCss}>
-									<span css={fieldLabelCss}>Secret value</span>
-									<div
-										css={{
-											position: 'relative',
-											display: 'flex',
-											alignItems: 'center',
-										}}
-									>
-										{showSecretValue ? (
-											<input
-												type="text"
-												required
-												autoComplete="new-password"
-												value={editorState.value}
-												placeholder="Enter the secret value"
-												on={{
-													input: (event) => {
-														editorState = {
-															...editorState,
-															value: event.currentTarget.value,
-														}
-														handle.update()
-													},
-												}}
-												css={{
-													...inputCss,
-													paddingRight: '3rem',
-												}}
-											/>
-										) : (
-											<input
-												type="password"
-												required
-												autoComplete="new-password"
-												value={editorState.value}
-												placeholder="Enter the secret value"
-												on={{
-													input: (event) => {
-														editorState = {
-															...editorState,
-															value: event.currentTarget.value,
-														}
-														handle.update()
-													},
-												}}
-												css={{
-													...inputCss,
-													paddingRight: '3rem',
-												}}
-											/>
-										)}
-										<button
-											type="button"
-											aria-label={
-												showSecretValue
-													? 'Hide secret value'
-													: 'Show secret value'
-											}
-											title={
-												showSecretValue
-													? 'Hide secret value'
-													: 'Show secret value'
-											}
-											on={{
-												click: () => {
-													showSecretValue = !showSecretValue
-													handle.update()
-												},
-											}}
-											css={{
-												position: 'absolute',
-												right: spacing.sm,
-												background: 'none',
-												border: 'none',
-												padding: 0,
-												color: colors.textMuted,
-												cursor: 'pointer',
-												display: 'flex',
-												alignItems: 'center',
-												justifyContent: 'center',
-												'&:hover': {
-													color: colors.text,
-												},
-											}}
-										>
-											{showSecretValue ? (
-												<svg
-													xmlns="http://www.w3.org/2000/svg"
-													width="20"
-													height="20"
-													viewBox="0 0 24 24"
-													fill="none"
-													stroke="currentColor"
-													stroke-width="2"
-													stroke-linecap="round"
-													stroke-linejoin="round"
-												>
-													<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24" />
-													<path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68" />
-													<path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61" />
-													<line x1="2" x2="22" y1="2" y2="22" />
-												</svg>
-											) : (
-												<svg
-													xmlns="http://www.w3.org/2000/svg"
-													width="20"
-													height="20"
-													viewBox="0 0 24 24"
-													fill="none"
-													stroke="currentColor"
-													stroke-width="2"
-													stroke-linecap="round"
-													stroke-linejoin="round"
-												>
-													<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" />
-													<circle cx="12" cy="12" r="3" />
-												</svg>
-											)}
-										</button>
-									</div>
-								</label>
-
-								<div css={{ display: 'grid', gap: spacing.sm }}>
-									<div css={{ display: 'grid', gap: spacing.xs }}>
-										<span css={fieldLabelCss}>Allowed hosts</span>
-										<p css={{ margin: 0, color: colors.textMuted }}>
-											Leave this empty to require explicit host approval before
-											a secret can be used.
-										</p>
-									</div>
-									<div
-										css={{ display: 'grid', gap: spacing.sm }}
-										data-repeat-list="allowed-hosts"
-									>
-										{editorState.allowedHosts.map((host, index) => (
-											<div
-												key={index}
-												css={{
-													display: 'grid',
-													gridTemplateColumns: 'minmax(0, 1fr) auto',
-													gap: spacing.sm,
-													[mq.mobile]: {
-														gridTemplateColumns: '1fr',
-													},
-												}}
-											>
-												<input
-													type="text"
-													value={typeof host === 'string' ? host : ''}
-													placeholder="api.example.com"
-													on={{
-														input: (event) =>
-															updateAllowedHost(
-																index,
-																event.currentTarget.value,
-															),
-													}}
-													css={inputCss}
-												/>
-												<button
-													type="button"
-													on={{ click: () => removeAllowedHost(index) }}
-													css={secondaryButtonCss}
-												>
-													Remove
-												</button>
-											</div>
-										))}
-									</div>
-									<div>
-										<button
-											type="button"
-											on={{ click: addAllowedHost }}
-											css={secondaryButtonCss}
-										>
-											Add host
-										</button>
-									</div>
-								</div>
-
-								<div css={{ display: 'grid', gap: spacing.sm }}>
-									<div css={{ display: 'grid', gap: spacing.xs }}>
-										<span css={fieldLabelCss}>Allowed capabilities</span>
-										<p css={{ margin: 0, color: colors.textMuted }}>
-											Only capabilities listed here can resolve this secret when
-											used with an
-											<code> x-kody-secret </code>
-											input.
-										</p>
-									</div>
-									<div
-										css={{ display: 'grid', gap: spacing.sm }}
-										data-repeat-list="allowed-capabilities"
-									>
-										{editorState.allowedCapabilities.map(
-											(capabilityName, index) => (
-												<div
-													key={index}
-													css={{
-														display: 'grid',
-														gridTemplateColumns: 'minmax(0, 1fr) auto',
-														gap: spacing.sm,
-														[mq.mobile]: {
-															gridTemplateColumns: '1fr',
-														},
-													}}
-												>
-													<input
-														type="text"
-														value={
-															typeof capabilityName === 'string'
-																? capabilityName
-																: ''
-														}
-														placeholder="home_lutron_set_credentials"
-														on={{
-															input: (event) =>
-																updateAllowedCapability(
-																	index,
-																	event.currentTarget.value,
-																),
-														}}
-														css={inputCss}
-													/>
-													<button
-														type="button"
-														on={{ click: () => removeAllowedCapability(index) }}
-														css={secondaryButtonCss}
-													>
-														Remove
-													</button>
-												</div>
-											),
-										)}
-									</div>
-									<div>
-										<button
-											type="button"
-											on={{ click: addAllowedCapability }}
-											css={secondaryButtonCss}
-										>
-											Add capability
-										</button>
-									</div>
-								</div>
-
 								{selectedSecret ? (
 									<div
 										css={{
@@ -1601,12 +1350,6 @@
 	boxSizing: 'border-box' as const,
 }
 
-const textareaCss = {
-	...inputCss,
-	resize: 'vertical' as const,
-	minHeight: '7rem',
-}
-
 const comboboxListCss = {
 	position: 'absolute' as const,
 	top: '100%',

diff --git a/packages/worker/client/routes/connect-secret.tsx b/packages/worker/client/routes/connect-secret.tsx
--- a/packages/worker/client/routes/connect-secret.tsx
+++ b/packages/worker/client/routes/connect-secret.tsx
@@ -7,6 +7,11 @@
 	spacing,
 	typography,
 } from '#client/styles/tokens.ts'
+import { SecretEditorFields } from './secret-editor-fields.tsx'
+import {
+	normalizeAllowedCapabilities,
+	normalizeAllowedHosts,
+} from './secret-normalization.ts'
 import { formatConnectorConfigFailureMessage } from './connect-secret-errors.ts'
 
 type StorageScope = 'app' | 'session' | 'user'
@@ -45,9 +50,12 @@
 type ConnectSecretState = {
 	step: ViewStep
 	error: string
+	description: string
 	secretValue: string
+	allowedHosts: Array<string>
+	allowedCapabilities: Array<string>
+	showSecretValue: boolean
 	existingSecret: SecretMetadata | null
-	updateConfirmed: boolean
 	confirmedReview: boolean
 }
 
@@ -64,9 +72,12 @@
 const defaultState: ConnectSecretState = {
 	step: 'loading',
 	error: '',
+	description: '',
 	secretValue: '',
+	allowedHosts: [''],
+	allowedCapabilities: [''],
+	showSecretValue: false,
 	existingSecret: null,
-	updateConfirmed: false,
 	confirmedReview: false,
 }
 
@@ -120,6 +131,22 @@
 	}
 }
 
+function toEditableRows(values: Array<string> | null | undefined) {
+	if (!Array.isArray(values) || values.length === 0) return ['']
+	return [...values]
+}
+
+function createInitialConnectSecretState(
+	params: ConnectSecretParams,
+): ConnectSecretState {
+	return {
+		...defaultState,
+		description: params.description,
+		allowedHosts: toEditableRows(params.allowedHosts),
+		allowedCapabilities: toEditableRows(params.allowedCapabilities),
+	}
+}
+
 function scopeLabel(scope: StorageScope) {
 	if (scope === 'session') return 'Session (expires when this session ends)'
 	if (scope === 'app') return 'App'
@@ -203,22 +230,28 @@
 async function saveSecretValue(
 	params: ConnectSecretParams,
 	session: ConnectSecretSession,
-	value: string,
+	input: {
+		value: string
+		description: string
+		allowedHosts: Array<string>
+		allowedCapabilities: Array<string>
+	},
 ) {
-	const response = await fetch(session.endpoints.secrets, {
+	const response = await fetch('/connect/secret.json', {
 		method: 'POST',
 		headers: {
 			Accept: 'application/json',
 			'Content-Type': 'application/json',
-			Authorization: `Bearer ${session.token}`,
 		},
-		credentials: 'omit',
+		credentials: 'include',
 		body: JSON.stringify({
-			action: 'save',
 			name: params.name,
-			value,
-			description: params.description,
 			scope: params.scope,
+			sessionToken: session.token,
+			value: input.value,
+			description: input.description,
+			allowedHosts: input.allowedHosts,
+			allowedCapabilities: input.allowedCapabilities,
 		}),
 	})
 	const payload = (await response.json().catch(() => null)) as {
@@ -233,6 +266,10 @@
 async function updateConnectorConfig(
 	params: ConnectSecretParams,
 	session: ConnectSecretSession,
+	input: {
+		allowedHosts: Array<string>
+		allowedCapabilities: Array<string>
+	},
 ) {
 	if (!params.connector) return
 	const response = await fetch('/connect/secret.json', {
@@ -247,8 +284,8 @@
 			scope: params.scope,
 			sessionToken: session.token,
 			connector: params.connector,
-			allowedHosts: params.allowedHosts,
-			allowedCapabilities: params.allowedCapabilities,
+			allowedHosts: input.allowedHosts,
+			allowedCapabilities: input.allowedCapabilities,
 		}),
 	})
 	const payload = (await response.json().catch(() => null)) as {
@@ -323,12 +360,19 @@
 			if (version !== initVersion) return
 			if (existing) {
 				setState({
+					...createInitialConnectSecretState(params),
 					step: 'update-confirm',
 					existingSecret: existing,
+					description: existing.description,
+					allowedHosts: toEditableRows(existing.allowed_hosts),
+					allowedCapabilities: toEditableRows(existing.allowed_capabilities),
 				})
 				return
 			}
-			setState({ step: 'input' })
+			setState({
+				...createInitialConnectSecretState(params),
+				step: 'input',
+			})
 		} catch (error) {
 			if (version !== initVersion) return
 			if (isSessionRefreshError(error)) {
@@ -353,6 +397,10 @@
 			return
 		}
 		const params = parseConnectSecretParams()
+		const normalizedAllowedHosts = normalizeAllowedHosts(state.allowedHosts)
+		const normalizedAllowedCapabilities = normalizeAllowedCapabilities(
+			state.allowedCapabilities,
+		)
 		if (!state.secretValue.trim()) {
 			setState({
 				step: 'error',
@@ -362,7 +410,12 @@
 		}
 		setState({ step: 'saving', error: '' })
 		try {
-			await saveSecretValue(params, session, state.secretValue)
+			await saveSecretValue(params, session, {
+				value: state.secretValue,
+				description: state.description,
+				allowedHosts: normalizedAllowedHosts,
+				allowedCapabilities: normalizedAllowedCapabilities,
+			})
 		} catch (error) {
 			if (isSessionRefreshError(error)) {
 				startInitialization()
@@ -376,7 +429,10 @@
 			return
 		}
 		try {
-			await updateConnectorConfig(params, session)
+			await updateConnectorConfig(params, session, {
+				allowedHosts: normalizedAllowedHosts,
+				allowedCapabilities: normalizedAllowedCapabilities,
+			})
 			setState({ step: 'success' })
 		} catch (error) {
 			const secretWasNewlyCreated = state.existingSecret == null
@@ -419,17 +475,72 @@
 		setState({ step: 'input', error: '' })
 	}
 
+	function updateAllowedHost(index: number, value: string) {
+		setState({
+			allowedHosts: state.allowedHosts.map((host, hostIndex) =>
+				hostIndex === index ? value : host,
+			),
+		})
+	}
+
+	function addAllowedHost() {
+		setState({
+			allowedHosts: [...state.allowedHosts, ''],
+		})
+	}
+
+	function removeAllowedHost(index: number) {
+		const nextHosts = state.allowedHosts.filter(
+			(_host, hostIndex) => hostIndex !== index,
+		)
+		setState({
+			allowedHosts: nextHosts.length > 0 ? nextHosts : [''],
+		})
+	}
+
+	function updateAllowedCapability(index: number, value: string) {
+		setState({
+			allowedCapabilities: state.allowedCapabilities.map(
+				(capability, capabilityIndex) =>
+					capabilityIndex === index ? value : capability,
+			),
+		})
+	}
+
+	function addAllowedCapability() {
+		setState({
+			allowedCapabilities: [...state.allowedCapabilities, ''],
+		})
+	}
+
+	function removeAllowedCapability(index: number) {
+		const nextCapabilities = state.allowedCapabilities.filter(
+			(_capability, capabilityIndex) => capabilityIndex !== index,
+		)
+		setState({
+			allowedCapabilities: nextCapabilities.length > 0 ? nextCapabilities : [''],
+		})
+	}
+
 	return () => {
 		const currentSearch =
 			typeof window === 'undefined' ? '' : window.location.search
 		if (currentSearch !== lastSearch) {
 			lastSearch = currentSearch
-			startInitialization()
+			// Defer: startInitialization calls handle.update(), which must not run during
+			// render (Remix component runtime throws "scheduleUpdate not implemented").
+			handle.queueTask(() => {
+				startInitialization()
+			})
 		}
 
 		const params = parseConnectSecretParams()
 		const hasInstructions = Boolean(params.instructions || params.dashboardUrl)
 		const showReview = state.step === 'review' || state.step === 'saving'
+		const normalizedAllowedHosts = normalizeAllowedHosts(state.allowedHosts)
+		const normalizedAllowedCapabilities = normalizeAllowedCapabilities(
+			state.allowedCapabilities,
+		)
 
 		return (
 			<section
@@ -516,8 +627,7 @@
 								type="button"
 								css={primaryButtonCss}
 								on={{
-									click: () =>
-										setState({ step: 'input', updateConfirmed: true }),
+									click: () => setState({ step: 'input' }),
 								}}
 							>
 								Update secret
@@ -600,20 +710,25 @@
 
 						<section css={cardCss}>
 							<h2 css={cardTitleCss}>Enter secret</h2>
-							<label css={{ display: 'grid', gap: spacing.xs }}>
-								<span css={labelCss}>Secret value</span>
-								<input
-									type="password"
-									autoComplete="new-password"
-									value={state.secretValue}
-									placeholder="Paste the secret value"
-									on={{
-										input: (event) =>
-											setState({ secretValue: event.currentTarget.value }),
-									}}
-									css={inputCss}
-								/>
-							</label>
+							<SecretEditorFields
+								description={state.description}
+								onDescriptionChange={(description) => setState({ description })}
+								value={state.secretValue}
+								onValueChange={(secretValue) => setState({ secretValue })}
+								showSecretValue={state.showSecretValue}
+								onToggleShowSecretValue={() =>
+									setState({ showSecretValue: !state.showSecretValue })
+								}
+								allowedHosts={state.allowedHosts}
+								onUpdateAllowedHost={updateAllowedHost}
+								onAddAllowedHost={addAllowedHost}
+								onRemoveAllowedHost={removeAllowedHost}
+								allowedCapabilities={state.allowedCapabilities}
+								onUpdateAllowedCapability={updateAllowedCapability}
+								onAddAllowedCapability={addAllowedCapability}
+								onRemoveAllowedCapability={removeAllowedCapability}
+								valuePlaceholder="Paste the secret value"
+							/>
 						</section>
 
 						{showReview ? (
@@ -634,10 +749,10 @@
 										<div css={labelCss}>Scope</div>
 										<div>{scopeLabel(params.scope)}</div>
 									</div>
-									{params.description ? (
+									{state.description ? (
 										<div css={{ gridColumn: '1 / -1' }}>
 											<div css={labelCss}>Description</div>
-											<div>{params.description}</div>
+											<div>{state.description}</div>
 										</div>
 									) : null}
 								</div>
@@ -651,8 +766,8 @@
 									<div>
 										<div css={labelCss}>Hosts to approve</div>
 										<ul css={listCss}>
-											{params.allowedHosts.length > 0 ? (
-												params.allowedHosts.map((host) => (
+											{normalizedAllowedHosts.length > 0 ? (
+												normalizedAllowedHosts.map((host) => (
 													<li key={host}>{host}</li>
 												))
 											) : (
@@ -663,8 +778,8 @@
 									<div>
 										<div css={labelCss}>Capabilities to allow</div>
 										<ul css={listCss}>
-											{params.allowedCapabilities.length > 0 ? (
-												params.allowedCapabilities.map((capability) => (
+											{normalizedAllowedCapabilities.length > 0 ? (
+												normalizedAllowedCapabilities.map((capability) => (
 													<li key={capability}>{capability}</li>
 												))
 											) : (
@@ -790,16 +905,6 @@
 	color: colors.text,
 }
 
-const inputCss = {
-	padding: spacing.sm,
-	borderRadius: radius.md,
-	border: `1px solid ${colors.border}`,
-	backgroundColor: colors.background,
-	color: colors.text,
-	fontFamily: typography.fontFamily,
-	fontSize: typography.fontSize.base,
-}
-
 const primaryButtonCss = {
 	padding: `${spacing.sm} ${spacing.lg}`,
 	borderRadius: radius.full,

diff --git a/packages/worker/client/routes/secret-editor-fields.tsx b/packages/worker/client/routes/secret-editor-fields.tsx
new file mode 100644
--- /dev/null
+++ b/packages/worker/client/routes/secret-editor-fields.tsx
@@ -1,0 +1,294 @@
+import { type Handle } from 'remix/component'
+import { colors, mq, radius, spacing, typography } from '#client/styles/tokens.ts'
+
+type SecretEditorFieldsProps = {
+	description: string
+	onDescriptionChange: (value: string) => void
+	value: string
+	onValueChange: (value: string) => void
+	showSecretValue: boolean
+	onToggleShowSecretValue: () => void
+	allowedHosts: Array<string>
+	onUpdateAllowedHost: (index: number, value: string) => void
+	onAddAllowedHost: () => void
+	onRemoveAllowedHost: (index: number) => void
+	allowedCapabilities: Array<string>
+	onUpdateAllowedCapability: (index: number, value: string) => void
+	onAddAllowedCapability: () => void
+	onRemoveAllowedCapability: (index: number) => void
+	valuePlaceholder?: string
+	allowedHostsListName?: string
+	allowedCapabilitiesListName?: string
+}
+
+export function SecretEditorFields(_handle: Handle) {
+	return (props: SecretEditorFieldsProps) => (
+		<>
+			<label css={fieldCss}>
+				<span css={fieldLabelCss}>Description</span>
+				<textarea
+					value={props.description}
+					rows={3}
+					placeholder="What this secret is used for"
+					on={{
+						input: (event) => {
+							props.onDescriptionChange(event.currentTarget.value)
+						},
+					}}
+					css={textareaCss}
+				/>
+			</label>
+
+			<label css={fieldCss}>
+				<span css={fieldLabelCss}>Secret value</span>
+				<div
+					css={{
+						position: 'relative',
+						display: 'flex',
+						alignItems: 'center',
+					}}
+				>
+					{props.showSecretValue ? (
+						<input
+							type="text"
+							required
+							autoComplete="new-password"
+							value={props.value}
+							placeholder={props.valuePlaceholder ?? 'Enter the secret value'}
... diff truncated: showing 800 of 1265 lines

You can send follow-ups to this agent here.

Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/worker/client/routes/connect-secret.tsx (1)

400-403: Consider extracting normalization into one helper to reduce drift risk.

Normalization is currently repeated in save and render paths; a shared helper would make future normalization rule changes safer.

♻️ Optional refactor sketch
+function getNormalizedReviewState(state: ConnectSecretState) {
+  return {
+    normalizedAllowedHosts: normalizeAllowedHosts(state.allowedHosts),
+    normalizedAllowedCapabilities: normalizeAllowedCapabilities(
+      state.allowedCapabilities,
+    ),
+  }
+}
...
-const normalizedAllowedHosts = normalizeAllowedHosts(state.allowedHosts)
-const normalizedAllowedCapabilities = normalizeAllowedCapabilities(
-  state.allowedCapabilities,
-)
+const { normalizedAllowedHosts, normalizedAllowedCapabilities } =
+  getNormalizedReviewState(state)
...
-const normalizedAllowedHosts = normalizeAllowedHosts(state.allowedHosts)
-const normalizedAllowedCapabilities = normalizeAllowedCapabilities(
-  state.allowedCapabilities,
-)
+const { normalizedAllowedHosts, normalizedAllowedCapabilities } =
+  getNormalizedReviewState(state)

Also applies to: 540-543

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/client/routes/connect-secret.tsx` around lines 400 - 403,
Extract the repeated normalization logic into a single helper (e.g.,
normalizeAllowedEntries or normalizeAllowedForState) that accepts the component
state (or the two fields state.allowedHosts and state.allowedCapabilities) and
returns normalizedAllowedHosts and normalizedAllowedCapabilities; replace direct
calls to normalizeAllowedHosts(...) and normalizeAllowedCapabilities(...) in
both the render path and the save path with this helper to ensure a single
source of truth for normalization and avoid drift across normalizeAllowedHosts
and normalizeAllowedCapabilities usage.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/worker/client/routes/connect-secret.tsx`:
- Around line 400-403: Extract the repeated normalization logic into a single
helper (e.g., normalizeAllowedEntries or normalizeAllowedForState) that accepts
the component state (or the two fields state.allowedHosts and
state.allowedCapabilities) and returns normalizedAllowedHosts and
normalizedAllowedCapabilities; replace direct calls to
normalizeAllowedHosts(...) and normalizeAllowedCapabilities(...) in both the
render path and the save path with this helper to ensure a single source of
truth for normalization and avoid drift across normalizeAllowedHosts and
normalizeAllowedCapabilities usage.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e68a5444-69fd-4bdd-93ea-49bb374cfade

📥 Commits

Reviewing files that changed from the base of the PR and between 6bd0f18 and b880a5d.

📒 Files selected for processing (1)
  • packages/worker/client/routes/connect-secret.tsx

Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
@kentcdodds

Copy link
Copy Markdown
Member Author

@cursoragent please address the CI failures on this PR

@cursor

cursor Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

The merge-regression fix restores direct /account/secrets/user/... rendering so the selected secret detail pane shows up again.

Account secrets selected detail pane

Summary

  • Merged main into the PR branch and fixed the stale clientNormalizeAllowedHosts / clientNormalizeAllowedCapabilities references in account-secrets, which were crashing the client on the merge ref and causing both the typecheck failure and the account-secrets E2E failures. account-secrets.tsx:218-246

Testing

  • ✅ npm run typecheck — directly verifies the exact failing CI typecheck issue is gone on the merged branch. terminal:1-9
  • ✅ npm run test:e2e -- e2e/account-secrets.spec.ts — re-ran the exact failing Playwright spec file from CI after the fix; both previously failing tests now pass. terminal:1-32
  • ✅ Manual browser verification on http://localhost:3744/account/secrets/user/manual-secret-check — confirmed the selected secret detail pane renders instead of the fallback “Select a secret,” because CI’s E2E failure was a real client render crash and this is the highest-signal proof it’s fixed (see video/screenshot).
Open in Web Open in Cursor 

cursoragent and others added 2 commits March 31, 2026 02:42
…-query-defaults-b946

Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
@kentcdodds
kentcdodds merged commit 273f5ab into main Mar 31, 2026
9 checks passed
@kentcdodds
kentcdodds deleted the cursor/connect-secret-query-defaults-b946 branch April 17, 2026 00:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants