Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(control-ui): stage channel credentials with parent save

Josuéc958ba70156b
diff --git a/control-ui/app/communication-channels/[name]/edit/page.tsx b/control-ui/app/communication-channels/[name]/edit/page.tsx
index 8e2590f3e..0fb35afe1 100644
--- a/control-ui/app/communication-channels/[name]/edit/page.tsx
+++ b/control-ui/app/communication-channels/[name]/edit/page.tsx
@@ -5,6 +5,7 @@ import { useParams, useRouter } from 'next/navigation'
import { AuthGate } from '@components/AuthGate'
import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'
import { ChannelCredentialsPanel } from '@components/ChannelCredentialsPanel'
+import type { CredentialEditStates, CredentialKey } from '@components/ChannelCredentialsPanel/types'
import { CommunicationChannelAccessSelector } from '@components/CommunicationChannelAccessSelector'
import { CommunicationChannelConversationsTable } from '@components/CommunicationChannelConversations'
import type { CommunicationChannelConversation } from '@components/CommunicationChannelConversations/types'
@@ -21,6 +22,11 @@ import { IconCopy } from '@components/icons'
import { Button } from '@components/ui'
import { CONTROL_ROUTES } from '@constants/routes'
import { apiGet, apiSend, isSilentApiError } from '@lib/api'
+import {
+ buildCredentialOperationPlan,
+ cleanCredentialStates,
+ credentialStateIsDirty,
+} from '@lib/channelCredentialSave'
import type { ChannelType } from '@lib/channelTypes'
import { copyTextToClipboard } from '@lib/clipboard'
import {
@@ -119,6 +125,8 @@ export default function EditCommunicationChannelPage() {
const [item, setItem] = useState<CommunicationChannelItem | null>(null)
const [draft, setDraft] = useState<DraftState | null>(null)
+ const [savedDraft, setSavedDraft] = useState<DraftState | null>(null)
+ const [credentialEditStates, setCredentialEditStates] = useState<CredentialEditStates>({})
const [activeTab, setActiveTab] = useState<ChannelProvider>('telegram')
const [hosts, setHosts] = useState<HostItem[]>([])
// Which credential keys the channel's Secret actually holds. Undefined until
@@ -159,6 +167,7 @@ export default function EditCommunicationChannelPage() {
return
}
setStoredCredentialKeys(keys)
+ return keys
} catch (error) {
// A silent error is an expired session: the app is already redirecting,
// so a banner about credentials would just be noise on the way out.
@@ -195,7 +204,10 @@ export default function EditCommunicationChannelPage() {
? hostsResponse
: hostsResponse.items || hostsResponse.hosts || []
setItem(nextItem)
- setDraft(createCommunicationChannelDraft(nextItem))
+ const nextDraft = createCommunicationChannelDraft(nextItem)
+ setDraft(nextDraft)
+ setSavedDraft(nextDraft)
+ setCredentialEditStates({})
setActiveTab(communicationChannelInitialTab(nextItem))
setHosts(nextHosts)
} catch (error) {
@@ -216,6 +228,28 @@ export default function EditCommunicationChannelPage() {
}, [name, loadCredentialKeys])
const visibleChannelTypes = useMemo<ChannelType[]>(() => [activeTab], [activeTab])
+ const validCredentialChannelTypes = useMemo<ChannelType[]>(() => {
+ if (!draft) return []
+ const spec = buildCommunicationChannelSpec(draft)
+ return [
+ ...(spec.telegram || spec.telegramSettings ? (['telegram'] as const) : []),
+ ...(spec.slack || spec.slackSettings ? (['slack'] as const) : []),
+ ...(spec.teams || spec.teamsSettings ? (['teams'] as const) : []),
+ ...(spec.email ? (['email'] as const) : []),
+ ]
+ }, [draft])
+ const specDirty = useMemo(
+ () =>
+ Boolean(
+ draft &&
+ savedDraft &&
+ JSON.stringify(buildCommunicationChannelSpec(draft)) !==
+ JSON.stringify(buildCommunicationChannelSpec(savedDraft))
+ ),
+ [draft, savedDraft]
+ )
+ const credentialsDirty = Object.values(credentialEditStates).some(credentialStateIsDirty)
+ const formDirty = specDirty || credentialsDirty
const activeConversations = draft ? conversationsForProvider(activeTab, draft) : []
// Gated on the DRAFT, not the persisted item. Slack's own order is manifest
// first, credentials second: the bot token only exists after the app has been
@@ -312,6 +346,7 @@ export default function EditCommunicationChannelPage() {
spec,
})
setDraft(nextDraft)
+ setSavedDraft(nextDraft)
showToast(successMessage, { tone: 'success' })
return true
} catch (error) {
@@ -325,9 +360,100 @@ export default function EditCommunicationChannelPage() {
async function handleSave(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
if (!draft || saving) return
- const saved = await persistDraft(draft, `Communication channel ${name} updated.`)
- if (!saved) return
- backToChannels()
+ const spec = buildCommunicationChannelSpec(draft)
+ const teamsName = spec.teamsSettings?.appName
+ const nameError = teamsName === undefined ? null : teamsAppNameError(teamsName)
+ const plan = buildCredentialOperationPlan(credentialEditStates, validCredentialChannelTypes)
+ if (nameError || plan.invalidLabels.length) {
+ setSaveError(
+ nameError || `Credential changes are no longer valid for: ${plan.invalidLabels.join(', ')}.`
+ )
+ return
+ }
+ if (!specDirty && plan.operations.length === 0) return
+
+ setSaving(true)
+ setSaveError('')
+ try {
+ if (specDirty) {
+ await apiSend('PUT', `/api/v1/admin/communication-channels/${encodeURIComponent(name)}`, {
+ spec,
+ })
+ }
+
+ const channelResponse = await apiGet(
+ `/api/v1/admin/communication-channels/${encodeURIComponent(name)}`
+ )
+ const authoritativeItem = extractChannel(channelResponse, name)
+ if (!authoritativeItem) throw new Error(`Communication channel ${name} was not found.`)
+ const authoritativeDraft = createCommunicationChannelDraft(authoritativeItem)
+ const authoritativeSpec = buildCommunicationChannelSpec(authoritativeDraft)
+ const authoritativeTypes: ChannelType[] = [
+ ...(authoritativeSpec.telegram || authoritativeSpec.telegramSettings
+ ? (['telegram'] as const)
+ : []),
+ ...(authoritativeSpec.slack || authoritativeSpec.slackSettings ? (['slack'] as const) : []),
+ ...(authoritativeSpec.teams || authoritativeSpec.teamsSettings ? (['teams'] as const) : []),
+ ...(authoritativeSpec.email ? (['email'] as const) : []),
+ ]
+ const validatedPlan = buildCredentialOperationPlan(credentialEditStates, authoritativeTypes)
+ if (validatedPlan.invalidLabels.length) {
+ setItem(authoritativeItem)
+ setDraft(authoritativeDraft)
+ setSavedDraft(authoritativeDraft)
+ setSaveError(
+ `Channel settings were saved, but credential changes are no longer valid for: ${validatedPlan.invalidLabels.join(', ')}.`
+ )
+ return
+ }
+
+ const successful: CredentialKey[] = []
+ const failedLabels: string[] = []
+ for (const operation of validatedPlan.operations) {
+ try {
+ if (operation.kind === 'replace') {
+ await apiSend(
+ 'PUT',
+ `/api/v1/admin/communication-channels/${encodeURIComponent(name)}/credentials`,
+ { [operation.key]: operation.value }
+ )
+ } else {
+ await apiSend(
+ 'DELETE',
+ `/api/v1/admin/communication-channels/${encodeURIComponent(name)}/credentials/${encodeURIComponent(operation.key)}`
+ )
+ }
+ successful.push(operation.key)
+ } catch {
+ failedLabels.push(operation.label)
+ }
+ }
+
+ const [refreshedChannel] = await Promise.all([
+ apiGet(`/api/v1/admin/communication-channels/${encodeURIComponent(name)}`),
+ loadCredentialKeys(name),
+ ])
+ const refreshedItem = extractChannel(refreshedChannel, name) ?? authoritativeItem
+ const refreshedDraft = createCommunicationChannelDraft(refreshedItem)
+ setItem(refreshedItem)
+ setDraft(refreshedDraft)
+ setSavedDraft(refreshedDraft)
+ setCredentialEditStates(current => cleanCredentialStates(current, successful))
+
+ if (failedLabels.length) {
+ setSaveError(
+ `Channel settings were saved, but some credential changes failed: ${failedLabels.join(', ')}. Retry Save to apply the remaining changes.`
+ )
+ return
+ }
+ setCredentialEditStates({})
+ showToast(`Communication channel ${name} updated.`, { tone: 'success' })
+ backToChannels()
+ } catch (error) {
+ setSaveError(error instanceof Error ? error.message : 'Failed to save communication channel')
+ } finally {
+ setSaving(false)
+ }
}
async function deleteConversation(conversation: CommunicationChannelConversation) {
@@ -871,6 +997,11 @@ export default function EditCommunicationChannelPage() {
storedKeys={storedCredentialKeys}
storedKeysError={credentialKeysError}
onRetryStoredKeys={() => void loadCredentialKeys(name)}
+ editStates={credentialEditStates}
+ onEditStateChange={(key, state) =>
+ setCredentialEditStates(current => ({ ...current, [key]: state }))
+ }
+ saving={saving}
/>
</section>
@@ -918,7 +1049,11 @@ export default function EditCommunicationChannelPage() {
>
Cancel
</button>
- <button type="submit" className="cu-btn cu-btn--primary" disabled={saving}>
+ <button
+ type="submit"
+ className="cu-btn cu-btn--primary"
+ disabled={saving || !formDirty}
+ >
{saving ? 'Saving...' : 'Save changes'}
</button>
</div>
diff --git a/control-ui/components/ChannelCredentialsPanel/index.tsx b/control-ui/components/ChannelCredentialsPanel/index.tsx
index 095ef2559..ba0b7c105 100644
--- a/control-ui/components/ChannelCredentialsPanel/index.tsx
+++ b/control-ui/components/ChannelCredentialsPanel/index.tsx
@@ -1,6 +1,7 @@
'use client'
import React, { useEffect, useMemo, useRef, useState } from 'react'
+import { SecretEditField } from '@clerum/frontend-components'
import { IconCheck, IconPencil, IconTrash } from '@components/icons'
import { cn } from '@lib/cn'
import { apiSend } from '../../lib/api'
@@ -77,6 +78,9 @@ export function ChannelCredentialsPanel({
presentation = 'panel',
readOnly = false,
visibleChannelTypes,
+ editStates,
+ onEditStateChange,
+ saving: parentSaving = false,
}: ChannelCredentialsPanelProps) {
const { showToast } = useToast()
const [draft, setDraft] = useState<CredentialDraft>(emptyDraft)
@@ -128,6 +132,7 @@ export function ChannelCredentialsPanel({
// read is not pending: leaving it here disabled the whole panel forever,
// under a placeholder describing a request that had already finished.
const keysPending = !pending && storedSignature === null && !storedKeysReadFailed
+ const staged = !pending && Boolean(editStates && onEditStateChange)
// Reset local state when the target CC changes so values typed for CC A
// are not saved against CC B if the parent swaps `ccName` without unmounting.
@@ -260,7 +265,7 @@ export function ChannelCredentialsPanel({
}
}
- const disabled = saving
+ const disabled = saving || parentSaving
const fieldsDisabled = disabled || (!pending && !ccName)
const isInline = presentation === 'inline'
@@ -321,6 +326,29 @@ export function ChannelCredentialsPanel({
<div className="cu-form-stack">
{fields.map(field => {
const stored = isKeyStored(field.key)
+ if (staged) {
+ return (
+ <SecretEditField
+ key={field.key}
+ id={`channel-cred-${field.key}`}
+ label={field.label}
+ existingValue={stored}
+ state={editStates?.[field.key] ?? { status: 'untouched' }}
+ onStateChange={state => onEditStateChange?.(field.key, state)}
+ placeholder={
+ keysPending
+ ? PENDING_PLACEHOLDER
+ : storedKeysReadFailed
+ ? UNKNOWN_PLACEHOLDER
+ : field.placeholder
+ }
+ helpText={field.helpText}
+ disabled={fieldsDisabled || readOnly || keysPending}
+ clearLabel={`Clear ${field.label}`}
+ restoreLabel={`Restore ${field.label}`}
+ />
+ )
+ }
return (
<div key={field.key} className="cu-field cu-field--compact">
<label htmlFor={`channel-cred-${field.key}`}>{field.label}</label>
diff --git a/control-ui/components/ChannelCredentialsPanel/types.ts b/control-ui/components/ChannelCredentialsPanel/types.ts
index 6ff89b36d..57c6df669 100644
--- a/control-ui/components/ChannelCredentialsPanel/types.ts
+++ b/control-ui/components/ChannelCredentialsPanel/types.ts
@@ -1,3 +1,4 @@
+import type { SecretEditState } from '@clerum/frontend-components'
import type { ChannelType } from '../../lib/channelTypes'
export type { ChannelType }
@@ -34,6 +35,9 @@ export type CredentialDraft = {
'email-password'?: string
}
+export type CredentialKey = keyof CredentialDraft
+export type CredentialEditStates = Partial<Record<CredentialKey, SecretEditState>>
+
export type ChannelCredentialsPanelProps = {
/** CommunicationChannel resource name. The Secret is keyed by this value
* server-side (`cc-<ccName>-credentials` in the `channels` namespace). */
@@ -82,6 +86,13 @@ export type ChannelCredentialsPanelProps = {
/** Re-runs the stored-key read. Only meaningful alongside
* `storedKeysError` — the panel does not own that request. */
onRetryStoredKeys?: () => void
+ /** Parent-owned edit state for existing channels. When supplied, credential
+ * changes are staged here and persisted only by the parent form's Save. */
+ editStates?: CredentialEditStates
+ /** Updates one staged credential without performing a network request. */
+ onEditStateChange?: (key: CredentialKey, state: SecretEditState) => void
+ /** Disables staged controls while the parent save coordinator is running. */
+ saving?: boolean
/** Render masked provider fields without rotation/delete controls. */
readOnly?: boolean
}
diff --git a/control-ui/components/__tests__/ChannelCredentialsPanel.test.tsx b/control-ui/components/__tests__/ChannelCredentialsPanel.test.tsx
index 458db2694..d369640ff 100644
--- a/control-ui/components/__tests__/ChannelCredentialsPanel.test.tsx
+++ b/control-ui/components/__tests__/ChannelCredentialsPanel.test.tsx
@@ -1,6 +1,7 @@
import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { apiSend } from '../../lib/api'
import { ChannelCredentialsPanel } from '../ChannelCredentialsPanel'
import type { CredentialDraft } from '../ChannelCredentialsPanel/types'
import { ToastProvider } from '../Toast'
@@ -490,3 +491,73 @@ describe('ChannelCredentialsPanel — where the Slack credentials live', () => {
expect(hintFor('Slack Bot User OAuth Token')).toMatch(/OAuth & Permissions/i)
})
})
+
+describe('ChannelCredentialsPanel — parent-owned edit staging', () => {
+ it('keeps an existing value blank and identifies it as preserved', () => {
+ renderPanel({
+ ccName: 'cc-stage',
+ visibleChannelTypes: ['telegram'],
+ storedKeys: ['telegram-bot-token'],
+ editStates: {},
+ onEditStateChange: vi.fn(),
+ })
+ expect(credentialInput('Telegram Bot Token')).toHaveValue('')
+ expect(screen.getByText('A value is stored. Leave this field blank to keep it.')).toBeVisible()
+ })
+
+ it('stages a replacement without performing a credential request', () => {
+ const onEditStateChange = vi.fn()
+ renderPanel({
+ ccName: 'cc-stage',
+ visibleChannelTypes: ['telegram'],
+ storedKeys: ['telegram-bot-token'],
+ editStates: {},
+ onEditStateChange,
+ })
+ fireEvent.change(credentialInput('Telegram Bot Token'), { target: { value: 'next-token' } })
+ expect(onEditStateChange).toHaveBeenCalledWith('telegram-bot-token', {
+ status: 'replaced',
+ value: 'next-token',
+ })
+ expect(apiSend).not.toHaveBeenCalled()
+ })
+
+ it('stages clear and restore transitions without performing a request', () => {
+ const onEditStateChange = vi.fn()
+ renderPanel({
+ ccName: 'cc-stage',
+ visibleChannelTypes: ['telegram'],
+ storedKeys: ['telegram-bot-token'],
+ editStates: {},
+ onEditStateChange,
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Clear Telegram Bot Token' }))
+ expect(onEditStateChange).toHaveBeenLastCalledWith('telegram-bot-token', {
+ status: 'cleared',
+ })
+ expect(apiSend).not.toHaveBeenCalled()
+ })
+
+ it('renders a retained replacement draft supplied by the parent', () => {
+ renderPanel({
+ ccName: 'cc-stage',
+ visibleChannelTypes: ['telegram'],
+ storedKeys: ['telegram-bot-token'],
+ editStates: { 'telegram-bot-token': { status: 'replaced', value: 'retry-token' } },
+ onEditStateChange: vi.fn(),
+ })
+ expect(credentialInput('Telegram Bot Token')).toHaveValue('retry-token')
+ })
+
+ it('disables staged fields while the parent save coordinator runs', () => {
+ renderPanel({
+ ccName: 'cc-stage',
+ visibleChannelTypes: ['telegram'],
+ storedKeys: [],
+ editStates: {},
+ onEditStateChange: vi.fn(),
+ saving: true,
+ })
+ expect(credentialInput('Telegram Bot Token')).toBeDisabled()
+ })
+})
diff --git a/control-ui/components/__tests__/EditCommunicationChannelPage.test.tsx b/control-ui/components/__tests__/EditCommunicationChannelPage.test.tsx
index 9b2ab5e20..1f6f7383c 100644
--- a/control-ui/components/__tests__/EditCommunicationChannelPage.test.tsx
+++ b/control-ui/components/__tests__/EditCommunicationChannelPage.test.tsx
@@ -195,7 +195,7 @@ describe('EditCommunicationChannelPage channel credentials', () => {
})
}
- it('masks only the keys the channel Secret holds, not every field', async () => {
+ it('marks only the keys the channel Secret holds, without returning their values', async () => {
// The channel has a Secret, but it holds a Telegram token only. Inferring
// per-field state from the Secret's existence rendered both Slack fields as
// populated, so a half-configured channel read as configured.
@@ -208,8 +208,11 @@ describe('EditCommunicationChannelPage channel credentials', () => {
await renderLoadedPage()
await waitFor(() => {
- expect(screen.getByLabelText('Telegram Bot Token')).toHaveValue('**********')
+ expect(
+ screen.getByText('A value is stored. Leave this field blank to keep it.')
+ ).toBeVisible()
})
+ expect(screen.getByLabelText('Telegram Bot Token')).toHaveValue('')
fireEvent.click(screen.getByRole('radio', { name: 'Slack' }))
const signingSecret = screen.getByLabelText('Slack Signing Secret') as HTMLInputElement
@@ -230,9 +233,7 @@ describe('EditCommunicationChannelPage channel credentials', () => {
})
await renderLoadedPage()
- await waitFor(() => {
- expect(screen.getByLabelText('Edit Telegram Bot Token')).toBeEnabled()
- })
+ await waitFor(() => expect(screen.getByLabelText('Telegram Bot Token')).toBeEnabled())
const telegramToken = screen.getByLabelText('Telegram Bot Token') as HTMLInputElement
expect(telegramToken.value).toBe('')
expect(telegramToken.placeholder).toBe('123456789:ABCDEF…')
@@ -265,8 +266,8 @@ describe('EditCommunicationChannelPage channel credentials', () => {
expect(telegramToken.placeholder).toBe('Stored value unknown')
// Rotation still works: a PUT overwrites whatever is there and needs to
// know nothing about it. Deleting an invisible key does not.
- expect(screen.getByLabelText('Edit Telegram Bot Token')).toBeEnabled()
- expect(screen.getByLabelText('Delete Telegram Bot Token')).toBeDisabled()
+ expect(telegramToken).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'Clear Telegram Bot Token' })).toBeDisabled()
// The page itself still loaded: the read failure is scoped to the panel.
expect(screen.getByLabelText(/Telegram bot handle/)).toHaveValue('@ops_bot')
})
@@ -294,7 +295,9 @@ describe('EditCommunicationChannelPage channel credentials', () => {
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
await waitFor(() => {
- expect(screen.getByLabelText('Telegram Bot Token')).toHaveValue('**********')
+ expect(
+ screen.getByText('A value is stored. Leave this field blank to keep it.')
+ ).toBeVisible()
})
expect(credentialReadCount(TELEGRAM_ONLY_CHANNEL)).toBe(2)
expect(screen.queryByText(STORED_KEYS_ERROR)).not.toBeInTheDocument()
@@ -318,7 +321,7 @@ describe('EditCommunicationChannelPage channel credentials', () => {
).toBeInTheDocument()
const telegramToken = screen.getByLabelText('Telegram Bot Token') as HTMLInputElement
expect(telegramToken.placeholder).toBe('Stored value unknown')
- expect(screen.getByLabelText('Edit Telegram Bot Token')).toBeEnabled()
+ expect(telegramToken).toBeEnabled()
})
})
diff --git a/control-ui/lib/__tests__/channelCredentialSave.test.ts b/control-ui/lib/__tests__/channelCredentialSave.test.ts
new file mode 100644
index 000000000..9f31ef72a
--- /dev/null
+++ b/control-ui/lib/__tests__/channelCredentialSave.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest'
+import {
+ buildCredentialOperationPlan,
+ cleanCredentialStates,
+ credentialStateIsDirty,
+} from '../channelCredentialSave'
+
+describe('channel credential parent-save planning', () => {
+ it.each([
+ [undefined, false],
+ [{ status: 'untouched' } as const, false],
+ [{ status: 'restored' } as const, false],
+ [{ status: 'cleared' } as const, true],
+ [{ status: 'replaced', value: 'next' } as const, true],
+ ])('classifies %j dirty state as %s', (state, expected) => {
+ expect(credentialStateIsDirty(state)).toBe(expected)
+ })
+
+ it('builds deterministic replace and clear operations in field order', () => {
+ expect(
+ buildCredentialOperationPlan(
+ {
+ 'slack-bot-token': { status: 'cleared' },
+ 'telegram-bot-token': { status: 'replaced', value: ' telegram-next ' },
+ 'slack-signing-secret': { status: 'replaced', value: 'slack-next' },
+ },
+ ['telegram', 'slack']
+ ).operations
+ ).toEqual([
+ {
+ kind: 'replace',
+ key: 'telegram-bot-token',
+ label: 'Telegram Bot Token',
+ value: 'telegram-next',
+ },
+ {
+ kind: 'replace',
+ key: 'slack-signing-secret',
+ label: 'Slack Signing Secret',
+ value: 'slack-next',
+ },
+ { kind: 'clear', key: 'slack-bot-token', label: 'Slack Bot User OAuth Token' },
+ ])
+ })
+
+ it('treats untouched and restored values as preserve operations', () => {
+ const plan = buildCredentialOperationPlan(
+ {
+ 'telegram-bot-token': { status: 'untouched' },
+ 'slack-signing-secret': { status: 'restored' },
+ },
+ ['telegram', 'slack']
+ )
+ expect(plan).toEqual({ operations: [], invalidLabels: [] })
+ })
+
+ it('rejects blank replacements without retaining the value in an error', () => {
+ const plan = buildCredentialOperationPlan(
+ { 'telegram-bot-token': { status: 'replaced', value: ' ' } },
+ ['telegram']
+ )
+ expect(plan.operations).toEqual([])
+ expect(plan.invalidLabels).toEqual(['Telegram Bot Token'])
+ expect(JSON.stringify(plan)).not.toContain('telegram-next')
+ })
+
+ it('rejects operations whose provider is absent from the proposed channel', () => {
+ const plan = buildCredentialOperationPlan({ 'slack-bot-token': { status: 'cleared' } }, [
+ 'telegram',
+ ])
+ expect(plan.operations).toEqual([])
+ expect(plan.invalidLabels).toEqual(['Slack Bot User OAuth Token'])
+ })
+
+ it('cleans only successful fields after a partial save', () => {
+ const states = cleanCredentialStates(
+ {
+ 'telegram-bot-token': { status: 'replaced', value: 'secret-one' },
+ 'slack-signing-secret': { status: 'cleared' },
+ },
+ ['telegram-bot-token']
+ )
+ expect(states['telegram-bot-token']).toEqual({ status: 'untouched' })
+ expect(states['slack-signing-secret']).toEqual({ status: 'cleared' })
+ })
+})
diff --git a/control-ui/lib/channelCredentialSave.ts b/control-ui/lib/channelCredentialSave.ts
new file mode 100644
index 000000000..7160d255c
--- /dev/null
+++ b/control-ui/lib/channelCredentialSave.ts
@@ -0,0 +1,51 @@
+import type { SecretEditState } from '@clerum/frontend-components'
+import { CHANNEL_CREDENTIAL_FIELDS } from '@components/ChannelCredentialsPanel/constants'
+import type { CredentialEditStates, CredentialKey } from '@components/ChannelCredentialsPanel/types'
+import type { ChannelType } from './channelTypes'
+
+export type CredentialOperation =
+ | { kind: 'replace'; key: CredentialKey; label: string; value: string }
+ | { kind: 'clear'; key: CredentialKey; label: string }
+
+export function credentialStateIsDirty(state: SecretEditState | undefined): boolean {
+ return state?.status === 'replaced' || state?.status === 'cleared'
+}
+
+export function buildCredentialOperationPlan(
+ states: CredentialEditStates,
+ validChannelTypes: readonly ChannelType[]
+): { operations: CredentialOperation[]; invalidLabels: string[] } {
+ const valid = new Set(validChannelTypes)
+ const operations: CredentialOperation[] = []
+ const invalidLabels: string[] = []
+
+ for (const field of CHANNEL_CREDENTIAL_FIELDS) {
+ const state = states[field.key]
+ if (!credentialStateIsDirty(state)) continue
+ if (!valid.has(field.channelType)) {
+ invalidLabels.push(field.label)
+ continue
+ }
+ if (state?.status === 'replaced') {
+ const value = state.value.trim()
+ if (value) operations.push({ kind: 'replace', key: field.key, label: field.label, value })
+ else invalidLabels.push(field.label)
+ } else if (state?.status === 'cleared') {
+ operations.push({ kind: 'clear', key: field.key, label: field.label })
+ }
+ }
+ return { operations, invalidLabels }
+}
+
+export function cleanCredentialStates(
+ states: CredentialEditStates,
+ successfulKeys: readonly CredentialKey[]
+): CredentialEditStates {
+ const successful = new Set(successfulKeys)
+ return Object.fromEntries(
+ Object.entries(states).map(([key, state]) => [
+ key,
+ successful.has(key as CredentialKey) ? { status: 'untouched' } : state,
+ ])
+ ) as CredentialEditStates
+}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index cf27ff65c..08b7a16b4 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.614",
+ "version": "0.1.615",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.614",
+ "version": "0.1.615",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index df7dcf033..cf3bcb7fa 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.614",
+ "version": "0.1.615",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",