Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

improvement(web): manage an external agent's API key in its form (#168)

Croff4610626658e2
diff --git a/apps/web/messages/ar/settings.json b/apps/web/messages/ar/settings.json
index 6844f02f..90878c2d 100644
--- a/apps/web/messages/ar/settings.json
+++ b/apps/web/messages/ar/settings.json
@@ -201,12 +201,17 @@
"memoryHint": "الوكيل بيفتكر آخر رسايل في نفس سلسلة المحادثة.",
"memoryCount": "تذكّر آخر N رسالة",
"memoryCountPlaceholder": "مثل: 20",
- "keyWarning": "انسخ المفتاح ده دلوقتي. لأسباب أمنية بيظهر مرة واحدة بس ومش هينفع تسترجعه بعد كده.",
+ "keyWarning": "انسخه دلوقتي. المفتاح بيظهر مرة واحدة بس.",
+ "apiKeyHint": "المفتاح اللي الوكيل بيوثّق بيه طلباته",
+ "keyOnCreate": "بيتولّد وقت إنشاء الوكيل وبيظهر مرة واحدة بس.",
+ "currentKey": "المفتاح الحالي",
+ "currentKeyHint": "بنخزّن أول حروف المفتاح بس.",
+ "showKey": "إظهار المفتاح",
+ "hideKey": "إخفاء المفتاح",
"copyKey": "نسخ المفتاح",
"dismiss": "تجاهل",
"regenerateTitle": "إعادة توليد مفتاح API",
"regenerateConfirm": "إعادة توليد المفتاح",
- "keyRegenerated": "أُعيد توليد المفتاح",
"apiKey": "مفتاح API",
"apiKeyValue": "مفتاح API {start}…",
"runHistory": "سجل التشغيل",
@@ -224,7 +229,7 @@
"moreActions": "إجراءات أخرى",
"createdOn": "أُنشئ {date}",
"runsSubtitle": "@{username} · تشغيلات الإشارة والتفويض",
- "regenerateMessage": "هيتعمل مفتاح جديد لـ <v>{name}</v> والمفتاح الحالي هيقف على طول. أي اتصال شغال بيه هيقع لحد ما تحطّ فيه المفتاح الجديد.",
+ "regenerateMessage": "مفتاح <v>{name}</v> الحالي هيبطّل يشتغل على طول. حدّث أي حاجة بتستخدمه بالمفتاح الجديد.",
"deleteMessage": "<v>{name}</v> ومفتاح API بتاعها هيتشالوا، وهتتشال من أي مهام كانت مسنودة ليها أو مفوّضة ليها. مش هينفع ترجع في ده.",
"actionCount": "{count, plural, zero {لا إجراءات} one {إجراء واحد} two {إجراءان} few {# إجراءات} many {# إجراءً} other {# إجراء}}",
"toolCount": "{count, plural, zero {لا أدوات} one {أداة واحدة} two {أداتان} few {# أدوات} many {# أداة} other {# أداة}}",
diff --git a/apps/web/messages/en/settings.json b/apps/web/messages/en/settings.json
index 585c1dd7..cc1094ae 100644
--- a/apps/web/messages/en/settings.json
+++ b/apps/web/messages/en/settings.json
@@ -201,12 +201,17 @@
"memoryHint": "Recall recent messages within a conversation thread.",
"memoryCount": "Remember last N messages",
"memoryCountPlaceholder": "e.g. 20",
- "keyWarning": "Copy this key now. For security, it is shown only once and cannot be retrieved later.",
+ "keyWarning": "Copy it now. The key is shown only once.",
+ "apiKeyHint": "The key the agent authenticates with",
+ "keyOnCreate": "Issued when you create the agent, shown once.",
+ "currentKey": "Current key",
+ "currentKeyHint": "Only its first characters are stored.",
+ "showKey": "Show key",
+ "hideKey": "Hide key",
"copyKey": "Copy key",
"dismiss": "Dismiss",
"regenerateTitle": "Regenerate API key",
"regenerateConfirm": "Regenerate key",
- "keyRegenerated": "Key regenerated",
"apiKey": "API key",
"apiKeyValue": "API key {start}…",
"runHistory": "Run history",
@@ -224,7 +229,7 @@
"moreActions": "More actions",
"createdOn": "Created {date}",
"runsSubtitle": "@{username} · mention and delegation runs",
- "regenerateMessage": "A new key will be issued for <v>{name}</v> and the current one will stop working immediately. Every existing connection using it will break until it is updated with the new key.",
+ "regenerateMessage": "The current key for <v>{name}</v> stops working right away. Update everything that uses it with the new key.",
"deleteMessage": "<v>{name}</v> and its API key will be removed, and it will be cleared from any issues it was assigned or delegated to. This cannot be undone.",
"actionCount": "{count, plural, one {# action} other {# actions}}",
"toolCount": "{count, plural, one {# tool} other {# tools}}",
diff --git a/apps/web/messages/ru/settings.json b/apps/web/messages/ru/settings.json
index db7dec07..869c3cd9 100644
--- a/apps/web/messages/ru/settings.json
+++ b/apps/web/messages/ru/settings.json
@@ -201,12 +201,17 @@
"memoryHint": "Помнить недавние сообщения внутри ветки разговора.",
"memoryCount": "Помнить последние N сообщений",
"memoryCountPlaceholder": "напр. 20",
- "keyWarning": "Скопируйте этот ключ сейчас. Из соображений безопасности он показывается только один раз и его нельзя получить позже.",
+ "keyWarning": "Скопируйте сейчас. Ключ показывается один раз.",
+ "apiKeyHint": "Ключ, которым агент подтверждает запросы",
+ "keyOnCreate": "Выдаётся при создании агента, показывается один раз.",
+ "currentKey": "Текущий ключ",
+ "currentKeyHint": "Хранится только начало ключа.",
+ "showKey": "Показать ключ",
+ "hideKey": "Скрыть ключ",
"copyKey": "Скопировать ключ",
"dismiss": "Скрыть",
"regenerateTitle": "Перевыпустить API-ключ",
"regenerateConfirm": "Перевыпустить ключ",
- "keyRegenerated": "Ключ перевыпущен",
"apiKey": "API-ключ",
"apiKeyValue": "API-ключ {start}…",
"runHistory": "История запусков",
@@ -224,7 +229,7 @@
"moreActions": "Другие действия",
"createdOn": "Создан {date}",
"runsSubtitle": "@{username} · запуски по упоминаниям и делегированию",
- "regenerateMessage": "Для <v>{name}</v> будет выпущен новый ключ, а текущий сразу перестанет работать. Каждое существующее подключение с ним сломается, пока его не обновят новым ключом.",
+ "regenerateMessage": "Текущий ключ <v>{name}</v> перестанет работать сразу. Обновите новым ключом всё, что им пользуется.",
"deleteMessage": "<v>{name}</v> и его API-ключ будут удалены, а сам он снят со всех задач, где был исполнителем или делегатом. Это нельзя отменить.",
"actionCount": "{count, plural, one {# действие} few {# действия} many {# действий} other {# действия}}",
"toolCount": "{count, plural, one {# инструмент} few {# инструмента} many {# инструментов} other {# инструмента}}",
diff --git a/apps/web/messages/uk/settings.json b/apps/web/messages/uk/settings.json
index 73c6af59..d3aad183 100644
--- a/apps/web/messages/uk/settings.json
+++ b/apps/web/messages/uk/settings.json
@@ -201,12 +201,17 @@
"memoryHint": "Пам'ятати останні повідомлення в межах гілки.",
"memoryCount": "Пам'ятати останні N повідомлень",
"memoryCountPlaceholder": "напр. 20",
- "keyWarning": "Скопіюйте ключ зараз. З міркувань безпеки він показується один раз і його не можна отримати пізніше.",
+ "keyWarning": "Скопіюйте зараз. Ключ показується один раз.",
+ "apiKeyHint": "Ключ, яким агент підтверджує запити",
+ "keyOnCreate": "Видається під час створення агента, показується один раз.",
+ "currentKey": "Поточний ключ",
+ "currentKeyHint": "Зберігається лише початок ключа.",
+ "showKey": "Показати ключ",
+ "hideKey": "Приховати ключ",
"copyKey": "Скопіювати ключ",
"dismiss": "Закрити",
"regenerateTitle": "Перегенерувати API-ключ",
"regenerateConfirm": "Перегенерувати ключ",
- "keyRegenerated": "Ключ перегенеровано",
"apiKey": "API-ключ",
"apiKeyValue": "API-ключ {start}…",
"runHistory": "Історія запусків",
@@ -224,7 +229,7 @@
"moreActions": "Інші дії",
"createdOn": "Створено {date}",
"runsSubtitle": "@{username} · запуски за згадками і делегуванням",
- "regenerateMessage": "Для <v>{name}</v> буде видано новий ключ, а поточний одразу перестане працювати. Кожне з'єднання, що ним користується, зламається, доки його не оновлять новим ключем.",
+ "regenerateMessage": "Поточний ключ <v>{name}</v> перестане працювати одразу. Оновіть новим ключем усе, що ним користується.",
"deleteMessage": "<v>{name}</v> та його API-ключ буде видалено, а сам агент прибереться з усіх задач, де він був виконавцем чи делегатом. Цю дію не можна скасувати.",
"actionCount": "{count, plural, one {# дія} few {# дії} many {# дій} other {# дії}}",
"toolCount": "{count, plural, one {# інструмент} few {# інструменти} many {# інструментів} other {# інструмента}}",
diff --git a/apps/web/messages/zh-CN/settings.json b/apps/web/messages/zh-CN/settings.json
index bfacd294..326047ac 100644
--- a/apps/web/messages/zh-CN/settings.json
+++ b/apps/web/messages/zh-CN/settings.json
@@ -201,12 +201,17 @@
"memoryHint": "在对话线程中回顾最近的消息。",
"memoryCount": "记住最近 N 条消息",
"memoryCountPlaceholder": "例如:20",
- "keyWarning": "请立即复制密钥。为确保安全,密钥只显示一次,之后无法再次获取。",
+ "keyWarning": "请立即复制。密钥只显示一次。",
+ "apiKeyHint": "智能体用于验证请求的密钥",
+ "keyOnCreate": "创建智能体时生成,只显示一次。",
+ "currentKey": "当前密钥",
+ "currentKeyHint": "只保存密钥开头几位字符。",
+ "showKey": "显示密钥",
+ "hideKey": "隐藏密钥",
"copyKey": "复制密钥",
"dismiss": "关闭",
"regenerateTitle": "重新生成 API 密钥",
"regenerateConfirm": "重新生成密钥",
- "keyRegenerated": "密钥已重新生成",
"apiKey": "API 密钥",
"apiKeyValue": "API 密钥 {start}…",
"runHistory": "运行记录",
@@ -224,7 +229,7 @@
"moreActions": "更多操作",
"createdOn": "创建于 {date}",
"runsSubtitle": "@{username} · 因提及或委派触发的运行",
- "regenerateMessage": "将为 <v>{name}</v> 签发新密钥,当前密钥会立即失效。所有使用当前密钥的连接都必须更新。",
+ "regenerateMessage": "<v>{name}</v> 的当前密钥会立即失效。请用新密钥更新所有使用它的地方。",
"deleteMessage": "<v>{name}</v> 及其 API 密钥将被删除,并从所有指派或委派给它的工作项中移除。此操作无法撤销。",
"actionCount": "{count, plural, other {# 个操作}}",
"toolCount": "{count, plural, other {# 个工具}}",
diff --git a/apps/web/src/features/settings/components/ai-agents/AgentExpandedLayout.tsx b/apps/web/src/features/settings/components/ai-agents/AgentExpandedLayout.tsx
index bfe62d0c..1400631a 100644
--- a/apps/web/src/features/settings/components/ai-agents/AgentExpandedLayout.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/AgentExpandedLayout.tsx
@@ -13,12 +13,10 @@ export const AGENT_EXPANDED_WIDTH = 'max-w-[860px]';
// scroll root so the nav can spy on which section is in view and jump to one on click.
export default function AgentExpandedLayout({
navSections,
- banner,
onExpand,
children,
}: {
navSections: SectionNavItem[];
- banner?: ReactNode;
// Ensure a section is open before scrolling to it (jumping to a collapsed section
// would land on just its header).
onExpand: (id: string) => void;
@@ -47,7 +45,6 @@ export default function AgentExpandedLayout({
ref={containerRef}
className="min-h-0 flex-1 overflow-y-auto px-4 pt-5 pb-10 sm:px-6 sm:pt-2"
>
- {banner && <div className={`mx-auto mb-6 w-full ${AGENT_EXPANDED_WIDTH}`}>{banner}</div>}
<div className={`mx-auto flex w-full gap-10 ${AGENT_EXPANDED_WIDTH}`}>
<SectionNav
sections={navSections}
diff --git a/apps/web/src/features/settings/components/ai-agents/AgentKeyBanner.tsx b/apps/web/src/features/settings/components/ai-agents/AgentKeyBanner.tsx
deleted file mode 100644
index 33567b4b..00000000
--- a/apps/web/src/features/settings/components/ai-agents/AgentKeyBanner.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { useState } from 'react';
-import { Check, Copy, X } from 'lucide-react';
-import { Button } from '@/components/ui/button';
-import { Input } from '@/components/ui/input';
-import { useTranslations } from 'next-intl';
-
-// Inline, one-time reveal of a new external agent's plaintext API key, shown at the
-// top of the sheet form right after create. The secret is never stored in list
-// state — it is only available here and cannot be retrieved again. Dismissable.
-export default function AgentKeyBanner({
- apiKey,
- onDismiss,
-}: {
- apiKey: string;
- onDismiss: () => void;
-}) {
- const t = useTranslations('settings.agents');
- const [copied, setCopied] = useState(false);
-
- async function copy() {
- try {
- await navigator.clipboard.writeText(apiKey);
- setCopied(true);
- setTimeout(() => setCopied(false), 1500);
- } catch {
- // Clipboard can be blocked (no permission / insecure origin); ignore.
- }
- }
-
- return (
- <div className="space-y-2 rounded-md border border-primary/40 bg-primary/5 p-3">
- <div className="flex items-start justify-between gap-2">
- <p className="text-xs text-muted-foreground">{t('keyWarning')}</p>
- <button
- type="button"
- onClick={onDismiss}
- className="shrink-0 text-muted-foreground hover:text-foreground"
- title={t('dismiss')}
- >
- <X className="size-4" />
- </button>
- </div>
- <div className="flex items-center gap-2">
- <Input
- readOnly
- value={apiKey}
- className="font-mono text-xs"
- onFocus={(e) => e.currentTarget.select()}
- />
- <Button
- type="button"
- variant="outline"
- size="icon"
- className="shrink-0"
- title={t('copyKey')}
- onClick={copy}
- >
- {copied ? <Check className="size-4" /> : <Copy className="size-4" />}
- </Button>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/features/settings/components/ai-agents/AgentKeyRevealModal.tsx b/apps/web/src/features/settings/components/ai-agents/AgentKeyRevealModal.tsx
deleted file mode 100644
index 94e19066..00000000
--- a/apps/web/src/features/settings/components/ai-agents/AgentKeyRevealModal.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { useState } from 'react';
-import { Check, Copy } from 'lucide-react';
-import Modal from '@/components/common/overlay/Modal';
-import { Button } from '@/components/ui/button';
-import { Input } from '@/components/ui/input';
-import { useTranslations } from 'next-intl';
-
-// One-time reveal of an agent's plaintext API key, shown right after create or
-// regenerate. The secret is passed in and never stored in list state — it is only
-// available here, and cannot be retrieved again.
-export default function AgentKeyRevealModal({
- title,
- apiKey,
- onClose,
-}: {
- title: string;
- apiKey: string;
- onClose: () => void;
-}) {
- const t = useTranslations('settings.agents');
- const tCommon = useTranslations('common');
- const [copied, setCopied] = useState(false);
-
- async function copy() {
- try {
- await navigator.clipboard.writeText(apiKey);
- setCopied(true);
- setTimeout(() => setCopied(false), 1500);
- } catch {
- // Clipboard can be blocked (no permission / insecure origin); ignore.
- }
- }
-
- return (
- <Modal title={title} onClose={onClose}>
- <div className="space-y-4">
- <p className="text-sm text-muted-foreground">{t('keyWarning')}</p>
- <div className="flex items-center gap-2">
- <Input
- readOnly
- value={apiKey}
- className="font-mono text-xs"
- onFocus={(e) => e.currentTarget.select()}
- />
- <Button
- variant="outline"
- size="icon"
- className="shrink-0"
- title={t('copyKey')}
- onClick={copy}
- >
- {copied ? <Check className="size-4" /> : <Copy className="size-4" />}
- </Button>
- </div>
- <div className="flex justify-end">
- <Button onClick={onClose}>{tCommon('done')}</Button>
- </div>
- </div>
- </Modal>
- );
-}
diff --git a/apps/web/src/features/settings/components/ai-agents/AgentKeyValue.tsx b/apps/web/src/features/settings/components/ai-agents/AgentKeyValue.tsx
new file mode 100644
index 00000000..3a11e480
--- /dev/null
+++ b/apps/web/src/features/settings/components/ai-agents/AgentKeyValue.tsx
@@ -0,0 +1,60 @@
+import { useState } from 'react';
+import { Check, Copy, Eye, EyeOff } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { useTranslations } from 'next-intl';
+
+// Bullets stand in for the hidden part of the key: a fixed count, so the key's real
+// length stays private.
+const HIDDEN = '•'.repeat(24);
+
+// A plaintext API key, hidden behind bullets until revealed and copyable either way.
+// The first characters stay visible so the key can be told apart from another one
+// without exposing the secret.
+export default function AgentKeyValue({ apiKey }: { apiKey: string }) {
+ const t = useTranslations('settings.agents');
+ const [shown, setShown] = useState(false);
+ const [copied, setCopied] = useState(false);
+
+ async function copy() {
+ try {
+ await navigator.clipboard.writeText(apiKey);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ } catch {
+ // Clipboard can be blocked (no permission / insecure origin); ignore.
+ }
+ }
+
+ return (
+ <div className="flex items-center gap-2">
+ <code
+ dir="ltr"
+ className="min-w-0 flex-1 truncate rounded-md bg-background/60 px-3 py-2 font-mono text-xs"
+ >
+ {shown ? apiKey : `${apiKey.slice(0, 6)}${HIDDEN}`}
+ </code>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-8 shrink-0"
+ aria-label={shown ? t('hideKey') : t('showKey')}
+ title={shown ? t('hideKey') : t('showKey')}
+ onClick={() => setShown((v) => !v)}
+ >
+ {shown ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ className="size-8 shrink-0"
+ aria-label={t('copyKey')}
+ title={t('copyKey')}
+ onClick={copy}
+ >
+ {copied ? <Check className="size-4" /> : <Copy className="size-4" />}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/components/ai-agents/AgentSheetForm.tsx b/apps/web/src/features/settings/components/ai-agents/AgentSheetForm.tsx
index 623907c3..e625d0ca 100644
--- a/apps/web/src/features/settings/components/ai-agents/AgentSheetForm.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/AgentSheetForm.tsx
@@ -26,7 +26,6 @@ import { Button } from '@/components/ui/button';
import { AgentCapabilityList } from './AgentCapabilityList';
import SettingsAiAgentFields from './SettingsAiAgentFields';
import { AGENT_EXPANDED_WIDTH } from './AgentExpandedLayout';
-import AgentKeyBanner from './AgentKeyBanner';
import {
initialAgentValue,
isAgentFormValid,
@@ -42,27 +41,26 @@ import { useTranslations } from 'next-intl';
// creates one; once created (onCreated lifts it to the sheet) the same form switches
// to editing that agent without remounting, so the entered values stay. The kind can
// be chosen on create but not changed after. A new external agent's key is revealed
-// once, inline at the top, via revealedKey. An internal agent's enabled skills are
-// managed once the agent exists (they are linked through a separate endpoint).
+// once in the API key section. An internal agent's enabled skills are managed once
+// the agent exists (they are linked through a separate endpoint).
export function AgentSheetForm({
projectKey,
agent,
expanded = false,
onCreated,
- revealedKey,
- onDismissKey,
}: {
projectKey: string;
agent: AiAgent | null;
expanded?: boolean;
- onCreated: (agent: AiAgent, apiKey: string | null) => void;
- revealedKey: string | null;
- onDismissKey: () => void;
+ onCreated: (agent: AiAgent) => void;
}) {
const t = useTranslations('settings.agents');
const tCommon = useTranslations('common');
const [value, setValue] = useState<AgentFormValue>(() => initialAgentValue(agent ?? undefined));
const isCreate = agent == null;
+ // The plaintext key issued in this sheet, by the create or by a regenerate. It is
+ // shown once in the API key section and cannot be read back from the server.
+ const [revealedKey, setRevealedKey] = useState<string | null>(null);
// While creating, the username is derived from the name until the user edits it.
// Clearing the username field resumes auto-generation.
const [usernameEdited, setUsernameEdited] = useState(false);
@@ -177,7 +175,8 @@ export function AgentSheetForm({
if (res.agent.kind === 'internal' && canManageTools && toolIds && toolIds.length > 0) {
await setAgentTools.mutateAsync({ agentId: res.agent.id, agentToolIds: toolIds });
}
- onCreated(res.agent, res.apiKey);
+ setRevealedKey(res.apiKey);
+ onCreated(res.agent);
} else {
await updateAgent.mutateAsync({ id: agent.id, patch: toUpdatePatch(value) });
if (agent.kind === 'internal' && canManageSkills && skillIds !== null) {
@@ -243,9 +242,6 @@ export function AgentSheetForm({
)
) : null;
- const banner =
- revealedKey !== null ? <AgentKeyBanner apiKey={revealedKey} onDismiss={onDismissKey} /> : null;
-
// The full-width internal editor owns its scroll container (it holds the section
// nav's scroll spy). Every other case stacks in a single column here. Once the
// agent exists the chat takes the other half of the sheet and the form fills its
@@ -273,7 +269,8 @@ export function AgentSheetForm({
agent={agent}
skillsContent={skillsContent}
toolsContent={toolsContent}
- banner={banner}
+ revealedKey={revealedKey}
+ onRevealedKey={setRevealedKey}
/>
);
@@ -289,10 +286,7 @@ export function AgentSheetForm({
fields
) : (
<div className="min-h-0 flex-1 overflow-y-auto px-4 pt-5 pb-6 sm:px-6">
- <div className={`mx-auto w-full space-y-6 ${contentWidth}`}>
- {banner}
- {fields}
- </div>
+ <div className={`mx-auto w-full space-y-6 ${contentWidth}`}>{fields}</div>
</div>
)}
<div className="border-t border-border/60 px-4 py-3 sm:px-6">
diff --git a/apps/web/src/features/settings/components/ai-agents/AgentTokenSection.tsx b/apps/web/src/features/settings/components/ai-agents/AgentTokenSection.tsx
new file mode 100644
index 00000000..fca716f1
--- /dev/null
+++ b/apps/web/src/features/settings/components/ai-agents/AgentTokenSection.tsx
@@ -0,0 +1,119 @@
+import { useEffect, useRef, useState } from 'react';
+import { KeyRound, TriangleAlert, X } from 'lucide-react';
+import type { AiAgent } from '@/lib/api';
+import { useRegenerateAiAgentKey } from '@/services/aiAgents.service';
+import { Button } from '@/components/ui/button';
+import { useSettingsCan } from '../../context/settingsPermission';
+import SettingsConfirmDeleteDialog from '../crud/SettingsConfirmDeleteDialog';
+import { AgentFormSection } from './AgentFormSection';
+import AgentKeyValue from './AgentKeyValue';
+import { useTranslations } from 'next-intl';
+
+// The API key of an external agent. The server keeps only a hash and the key's first
+// characters, so the secret exists for the one moment it is issued: the section shows
+// the key just issued by a create or a regenerate, and once that is dismissed only
+// the stored prefix and the way to issue a new key.
+export default function AgentTokenSection({
+ projectKey,
+ agent,
+ revealedKey,
+ onRevealedKey,
+ ...section
+}: {
+ projectKey: string;
+ // The saved agent, for its key prefix. Null while creating: no key exists yet.
+ agent: AiAgent | null;
+ // The plaintext key issued in this sheet, or null once dismissed.
+ revealedKey: string | null;
+ onRevealedKey: (apiKey: string | null) => void;
+ id: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const t = useTranslations('settings.agents');
+ const can = useSettingsCan();
+ const regenerateKey = useRegenerateAiAgentKey(projectKey);
+ const [confirming, setConfirming] = useState(false);
+ const wrapRef = useRef<HTMLDivElement>(null);
+ const { onOpenChange } = section;
+
+ // A key is worthless if it scrolls past unseen, so issuing one opens this section
+ // and brings it into view. Tracked by value: onOpenChange is a new function every
+ // render, so this effect reruns constantly and must not re-open a section the user
+ // has since collapsed.
+ const openedForKey = useRef<string | null>(null);
+ useEffect(() => {
+ if (revealedKey === null || openedForKey.current === revealedKey) return;
+ openedForKey.current = revealedKey;
+ onOpenChange(true);
+ // The section is expanding in this frame; wait for it before measuring.
+ requestAnimationFrame(() => wrapRef.current?.scrollIntoView({ block: 'center' }));
+ }, [revealedKey, onOpenChange]);
+
+ return (
+ <div ref={wrapRef}>
+ <AgentFormSection {...section} icon={KeyRound} title={t('apiKey')} hint={t('apiKeyHint')}>
+ {revealedKey !== null ? (
+ <div className="space-y-2.5 rounded-md bg-warning/5 p-3">
+ <div className="flex items-start gap-2">
+ <TriangleAlert className="mt-0.5 size-4 shrink-0 text-warning" />
+ <p className="min-w-0 flex-1 text-xs">{t('keyWarning')}</p>
+ <button
+ type="button"
+ onClick={() => onRevealedKey(null)}
+ className="shrink-0 text-muted-foreground hover:text-foreground"
+ aria-label={t('dismiss')}
+ title={t('dismiss')}
+ >
+ <X className="size-4" />
+ </button>
+ </div>
+ <AgentKeyValue apiKey={revealedKey} />
+ </div>
+ ) : agent === null ? (
+ <p className="text-xs text-muted-foreground">{t('keyOnCreate')}</p>
+ ) : (
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="min-w-0">
+ <span className="block text-sm font-medium">{t('currentKey')}</span>
+ <span className="block text-xs text-muted-foreground">{t('currentKeyHint')}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <code dir="ltr" className="rounded-md bg-muted px-2.5 py-1.5 font-mono text-xs">
+ {agent.apiKeyStart ?? '—'}
+ <span className="text-muted-foreground">••••••••</span>
+ </code>
+ {can('edit') && (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setConfirming(true)}
+ disabled={regenerateKey.isPending}
+ >
+ {t('regenerateConfirm')}
+ </Button>
+ )}
+ </div>
+ </div>
+ )}
+ </AgentFormSection>
+
+ {confirming && agent && (
+ <SettingsConfirmDeleteDialog
+ title={t('regenerateTitle')}
+ confirmLabel={t('regenerateConfirm')}
+ message={t.rich('regenerateMessage', {
+ name: agent.name,
+ v: (chunks) => <span className="font-medium">{chunks}</span>,
+ })}
+ onClose={() => setConfirming(false)}
+ onConfirm={async () => {
+ const res = await regenerateKey.mutateAsync(agent.id);
+ setConfirming(false);
+ onRevealedKey(res.apiKey);
+ }}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentFields.tsx b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentFields.tsx
index 7bb4ef9c..99bcc0fe 100644
--- a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentFields.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentFields.tsx
@@ -15,6 +15,7 @@ import { type AgentFormValue, grantedToolCount } from '../../utils/agentForm';
import { AgentFormSection } from './AgentFormSection';
import AgentExpandedLayout from './AgentExpandedLayout';
import AgentAccessSection from './AgentAccessSection';
+import AgentTokenSection from './AgentTokenSection';
import AgentModelSection from './AgentModelSection';
import AgentActionsSection from './AgentActionsSection';
import AgentTriggersSection from './AgentTriggersSection';
@@ -22,10 +23,11 @@ import { AgentInstructionsField } from './AgentInstructionsField';
import AgentRunnerSection from './AgentRunnerSection';
import { useTranslations } from 'next-intl';
-// Which sections open when the form first renders: only Access, so the form opens as
-// a short list of sections instead of a wall of fields. Basics is not in it because
-// it never collapses.
-const DEFAULT_OPEN: Record<string, boolean> = { access: true };
+// Which sections open when the form first renders, so it opens as a short list of
+// sections instead of a wall of fields. Basics is not in it because it never
+// collapses; the API key section is, because an external agent is unusable until its
+// key is in the operator's hands.
+const DEFAULT_OPEN: Record<string, boolean> = { access: true, token: true };
// The agent form: the sections an agent of this kind has, in a stacked column or, for
// a full-width internal agent, beside a section nav. `kindLocked` fixes the kind on
@@ -46,7 +48,8 @@ export default function SettingsAiAgentFields({
agent,
skillsContent,
toolsContent,
- banner,
+ revealedKey,
+ onRevealedKey,
}: {
value: AgentFormValue;
onChange: (patch: Partial<AgentFormValue>) => void;
@@ -68,9 +71,10 @@ export default function SettingsAiAgentFields({
skillsContent?: ReactNode | null;
// The Tools section body (configured custom tools), built the same way.
toolsContent?: ReactNode | null;
- // Optional strip rendered above the form (the revealed-key banner on create),
- // used by the full-width internal layout which owns its own scroll container.
- banner?: ReactNode;
+ // The plaintext key issued in this sheet (external agents only), shown once in the
+ // API key section, and the way to drop it or replace it after a regenerate.
+ revealedKey: string | null;
+ onRevealedKey: (apiKey: string | null) => void;
}) {
const t = useTranslations('settings.agents');
const tCommon = useTranslations('common');
@@ -153,6 +157,17 @@ export default function SettingsAiAgentFields({
/>
);
+ const tokenSection = (
+ <AgentTokenSection
+ key="token"
+ {...sectionProps('token')}
+ projectKey={projectKey}
+ agent={agent}
+ revealedKey={revealedKey}
+ onRevealedKey={onRevealedKey}
+ />
+ );
+
const runnerSection = (
<AgentRunnerSection key="runner" {...sectionProps('runner')} agent={agent} />
);
@@ -313,7 +328,6 @@ export default function SettingsAiAgentFields({
return (
<AgentExpandedLayout
navSections={navSections}
- banner={banner}
onExpand={(id) => setOpenSections((s) => ({ ...s, [id]: true }))}
>
{basicsSection}
@@ -333,6 +347,7 @@ export default function SettingsAiAgentFields({
{basicsSection}
{value.kind === 'external' ? (
<>
+ {tokenSection}
{accessSection}
{triggersSection}
{runnerSection}
diff --git a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentRow.tsx b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentRow.tsx
index c74a3285..b3fcb688 100644
--- a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentRow.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentRow.tsx
@@ -1,12 +1,4 @@
-import {
- Bot,
- History,
- KeyRound,
- MessageSquare,
- MoreHorizontal,
- Pencil,
- Trash2,
-} from 'lucide-react';
+import { Bot, History, MessageSquare, MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
import type { AiAgent } from '@/lib/api';
import { formatShortDate } from '@/utils/dates';
import { AgentRunnerStatus } from '@/components/common/agent-chat/AgentRunnerStatus';
@@ -28,15 +20,14 @@ import { useTranslations } from 'next-intl';
// One agent as a table row: the Agent cell holds the name, @username, kind badge,
// and created date; the Configuration cell shows an internal agent's meta line
// (model, capability/tool/skill counts) or an external agent's runner presence and
-// non-secret key prefix. Row actions (history/chat/regenerate/edit/delete) sit in
-// the last cell. The plaintext key is never here, only apiKeyStart identifies the
-// key. `providerLabel` maps a provider key to its catalog label.
+// non-secret key prefix. Row actions (history/chat/edit/delete) sit in the last
+// cell; the key itself is managed in the agent's sheet. `providerLabel` maps a
+// provider key to its catalog label.
export function SettingsAiAgentRow({
agent,
providerLabel,
onChat,
onRuns,
- onRegenerate,
onEdit,
onDelete,
}: {
@@ -44,15 +35,13 @@ export function SettingsAiAgentRow({
providerLabel: (key: string) => string;
onChat: () => void;
onRuns: () => void;
- onRegenerate: () => void;
onEdit: () => void;
onDelete: () => void;
}) {
const t = useTranslations('settings.agents');
const can = useSettingsCan();
const canHistory = can('read');
- const canRegenerate = agent.kind === 'external' && can('edit');
- const hasMenu = canHistory || canRegenerate || can('delete');
+ const hasMenu = canHistory || can('delete');
return (
<TableRow className="group/item">
@@ -128,13 +117,7 @@ export function SettingsAiAgentRow({
{t('testChat')}
</DropdownMenuItem>
)}
- {canRegenerate && (
- <DropdownMenuItem className="min-h-11 sm:min-h-8" onSelect={onRegenerate}>
- <KeyRound />
- {t('regenerateConfirm')}
- </DropdownMenuItem>
- )}
- {can('delete') && (canHistory || canRegenerate) && <DropdownMenuSeparator />}
+ {can('delete') && canHistory && <DropdownMenuSeparator />}
{can('delete') && (
<DropdownMenuItem
className="min-h-11 sm:min-h-8"
diff --git a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx
index dd9421a3..5ef52b90 100644
--- a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx
@@ -3,6 +3,7 @@
import { useState } from 'react';
import { Bot, X } from 'lucide-react';
import type { AiAgent } from '@/lib/api';
+import { useAiAgentsQuery } from '@/services/aiAgents.service';
import {
Sheet,
SheetClose,
@@ -64,19 +65,16 @@ function SheetBody({
// The agent just created in this sheet, if any. Once set, the form switches from
// create to edit for it without remounting.
const [createdAgent, setCreatedAgent] = useState<AiAgent | null>(null);
- // A new external agent's plaintext key, revealed once inline after create.
- const [revealedKey, setRevealedKey] = useState<string | null>(null);
+ // The create response is a snapshot; re-read the row from the list so a key
+ // regenerated in this sheet updates the prefix it shows.
+ const agents = useAiAgentsQuery(projectKey).data ?? [];
+ const created = createdAgent && (agents.find((a) => a.id === createdAgent.id) ?? createdAgent);
- const agent = initialAgent ?? createdAgent;
+ const agent = initialAgent ?? created;
// Held here so the transcript and thread survive re-renders. No agent yet during
// create → id 0; the chat is only reachable once the agent exists.
const chat = useAgentChat(projectKey, agent?.id ?? 0, agent?.kind === 'external');
- function onCreated(created: AiAgent, apiKey: string | null) {
- setCreatedAgent(created);
- setRevealedKey(apiKey);
- }
-
// The sheet is always full width: an existing agent shows the form and the chat side
// by side; while creating one there is nothing to chat with, so the form takes the
// full width on its own.
@@ -124,9 +122,7 @@ function SheetBody({
projectKey={projectKey}
agent={agent}
expanded
- onCreated={onCreated}
- revealedKey={revealedKey}
- onDismissKey={() => setRevealedKey(null)}
+ onCreated={setCreatedAgent}
/>
</div>
diff --git a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgents.tsx b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgents.tsx
index f7eaca8f..ecdc4744 100644
--- a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgents.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgents.tsx
@@ -1,17 +1,12 @@
import { useState } from 'react';
import type { AiAgent, ProjectDetail } from '@/lib/api';
-import {
- useAiAgentsQuery,
- useDeleteAiAgent,
- useRegenerateAiAgentKey,
-} from '@/services/aiAgents.service';
+import { useAiAgentsQuery, useDeleteAiAgent } from '@/services/aiAgents.service';
import { useIntegrationCatalogQuery } from '@/services/integrations.service';
import { Table, TableBody, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { EmptyState } from '@/components/common/page/EmptyState';
import ListSkeleton from '@/components/common/skeleton/ListSkeleton';
import SettingsConfirmDeleteDialog from '../crud/SettingsConfirmDeleteDialog';
import { SettingsAiAgentRow } from './SettingsAiAgentRow';
-import AgentKeyRevealModal from './AgentKeyRevealModal';
import { SettingsAiAgentSheet } from './SettingsAiAgentSheet';
import { SettingsAiAgentRunsSheet } from './SettingsAiAgentRunsSheet';
import { integrationLabel } from '../../utils/integrationLabels';
@@ -20,9 +15,8 @@ import { useTranslations } from 'next-intl';
// Project settings tab for AI agents: bot users that issues can be delegated to.
// An external agent is driven through the API; an internal agent runs on the
// built-in runtime and carries provider/model/instructions/tools. Creating and
-// editing happen in the same full-width sheet; creating an external agent reveals
-// its key once, inline, then stays open to keep editing. Regenerating a key (an
-// existing external agent only) reveals the new plaintext secret once.
+// editing happen in the same full-width sheet, which also owns an external agent's
+// API key: the sheet reveals it once on create and is where it is regenerated.
export default function SettingsAiAgents({ project }: { project: ProjectDetail }) {
const t = useTranslations('settings.agents');
const tCommon = useTranslations('common');
@@ -30,7 +24,6 @@ export default function SettingsAiAgents({ project }: { project: ProjectDetail }
const agentsQuery = useAiAgentsQuery(projectKey);
const agents = agentsQuery.data ?? [];
const deleteAgent = useDeleteAiAgent(projectKey);
- const regenerateKey = useRegenerateAiAgentKey(projectKey);
// The integration catalog maps a provider key to a readable label for the meta row.
const catalog = useIntegrationCatalogQuery(projectKey).data ?? [];
@@ -40,19 +33,10 @@ export default function SettingsAiAgents({ project }: { project: ProjectDetail }
// The agent whose run history sidebar is open.
const [runsAgent, setRunsAgent] = useState<AiAgent | null>(null);
const [deleting, setDeleting] = useState<AiAgent | null>(null);
- // The agent pending a key regeneration (awaiting confirmation).
- const [regenerating, setRegenerating] = useState<AiAgent | null>(null);
- // The plaintext key from a regenerate, revealed once.
- const [regeneratedKey, setRegeneratedKey] = useState<string | null>(null);
const sheetAgent =
sheet?.agentId != null ? (agents.find((a) => a.id === sheet.agentId) ?? null) : null;
- async function regenerate(agent: AiAgent) {
- const res = await regenerateKey.mutateAsync(agent.id);
- setRegeneratedKey(res.apiKey);
- }
-
return (
<>
{agentsQuery.isPending ? (
@@ -92,7 +76,6 @@ export default function SettingsAiAgents({ project }: { project: ProjectDetail }
providerLabel={(key: string) => integrationLabel(catalog, key)}
onChat={() => setSheet({ agentId: a.id })}
onRuns={() => setRunsAgent(a)}
- onRegenerate={() => setRegenerating(a)}
onEdit={() => setSheet({ agentId: a.id })}
onDelete={() => setDeleting(a)}
/>
@@ -115,31 +98,6 @@ export default function SettingsAiAgents({ project }: { project: ProjectDetail }
onClose={() => setRunsAgent(null)}
/>
- {regenerating && (
- <SettingsConfirmDeleteDialog
- title={t('regenerateTitle')}
- confirmLabel={t('regenerateConfirm')}
- message={t.rich('regenerateMessage', {
- name: regenerating.name,
- v: (chunks) => <span className="font-medium">{chunks}</span>,
- })}
- onClose={() => setRegenerating(null)}
- onConfirm={async () => {
- const agent = regenerating;
- setRegenerating(null);
- await regenerate(agent);
- }}
- />
- )}
-
- {regeneratedKey !== null && (
- <AgentKeyRevealModal
- title={t('keyRegenerated')}
- apiKey={regeneratedKey}
- onClose={() => setRegeneratedKey(null)}
- />
- )}
-
{deleting && (
<SettingsConfirmDeleteDialog
title={t('delete')}
diff --git a/apps/web/src/services/aiAgents.service.ts b/apps/web/src/services/aiAgents.service.ts
index 940d4c5a..e894fe9b 100644
--- a/apps/web/src/services/aiAgents.service.ts
+++ b/apps/web/src/services/aiAgents.service.ts
@@ -116,8 +116,12 @@ export function useUpdateAiAgent(projectKey: string | null) {
}
export function useRegenerateAiAgentKey(projectKey: string | null) {
+ const qc = useQueryClient();
return useMutation({
mutationFn: (id: number) => api.regenerateAiAgentKey(projectKey!, id),
+ onSuccess: () => {
+ if (projectKey) void qc.invalidateQueries({ queryKey: qk.aiAgents(projectKey) });
+ },
});
}