Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-ui): move identity documents to large edit dialogs
Josué4e99ee327096
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 1fa37ab6b..d505c0fda 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -8929,7 +8929,7 @@ td.cu-registry-description {.cu-identity-section {display: grid;gap: var(--cu-space-3);- grid-template-rows: auto auto minmax(0, 1fr);+ grid-template-rows: auto minmax(0, 1fr);flex: 1;min-height: 0;border: 0;@@ -8974,6 +8974,31 @@ td.cu-registry-description {min-height: 0;}+.cu-identity-preview {+ min-height: min(42rem, calc(100vh - 24rem));+ overflow: auto;+ padding: var(--cu-space-4);+ border: 1px solid var(--cu-border-subtle);+ border-radius: var(--cu-radius-sm);+ background: var(--cu-surface);+}++.cu-identity-preview__loading,+.cu-identity-preview__empty {+ color: var(--cu-text-muted);+}++.cu-identity-dialog-editor {+ display: flex;+ flex-direction: column;+ gap: var(--cu-space-2);+ min-height: min(60vh, 40rem);+}++.cu-identity-dialog-editor .cu-markdown-editor {+ min-height: min(52vh, 34rem);+}+.cu-detail-flow-panel + .cu-card:has(.cu-identity-panel) {display: flex;flex-direction: column;diff --git a/control-ui/components/HostIdentityTab/index.tsx b/control-ui/components/HostIdentityTab/index.tsxindex 2fa3c4bdb..d8ac50462 100644--- a/control-ui/components/HostIdentityTab/index.tsx+++ b/control-ui/components/HostIdentityTab/index.tsx@@ -1,19 +1,15 @@'use client'import React, { useCallback, useEffect, useRef, useState } from 'react'-import { useConfirmDialog } from '@components/ConfirmDialog'+import { SingleValueEditDialog } from '@clerum/frontend-components'+import { MarkdownContent } from '@components/MarkdownContent'import { MarkdownEditor } from '@components/MarkdownEditor'import { TabBar } from '@components/TabBar'import { useToast } from '@components/Toast'-import { IconCheck, IconRefresh } from '@components/icons'+import { IconPencil, IconRefresh } from '@components/icons'import { Button } from '@components/ui'import { getHostPersonalization, updateHostPersonalization } from '@lib/api'-import {- EMPTY_IDENTITY_FIELDS,- FIELD_MAX_BYTES,- IDENTITY_FIELDS,- IDENTITY_FIELD_ORDER,-} from './constants'+import { EMPTY_IDENTITY_FIELDS, FIELD_MAX_BYTES, IDENTITY_FIELDS } from './constants'import type {HostIdentityTabProps,HostIdentityTabState,@@ -36,7 +32,6 @@ function fieldsFromPayload(payload: IdentityFields): IdentityFields {export function HostIdentityTab({ hostName, onActionsChange }: HostIdentityTabProps) {const { showToast } = useToast()- const { choose, confirmDialog } = useConfirmDialog()const loadRequestId = useRef(0)const [state, setState] = useState<HostIdentityTabState>({activeField: 'identity',@@ -48,16 +43,14 @@ export function HostIdentityTab({ hostName, onActionsChange }: HostIdentityTabPrresourceVersion: '',saving: false,})+ const [editing, setEditing] = useState(false)+ const [editBytes, setEditBytes] = useState(0)const stateRef = useRef(state)stateRef.current = stateconst activeConfig =IDENTITY_FIELDS.find(field => field.key === state.activeField) ?? IDENTITY_FIELDS[0]const activeValue = state.fields[activeConfig.key]- const activeBytes = fieldBytes(activeValue)- const activeDirty = activeValue !== state.initial[activeConfig.key]- const activeTooLarge = activeBytes > FIELD_MAX_BYTES- const anyDirty = IDENTITY_FIELD_ORDER.some(key => state.fields[key] !== state.initial[key])const loadIdentityFiles = useCallback(async () => {const requestId = loadRequestId.current + 1@@ -91,56 +84,55 @@ export function HostIdentityTab({ hostName, onActionsChange }: HostIdentityTabPr}}, [loadIdentityFiles])- function setField(key: IdentityFieldKey, value: string) {- setState(prev => ({- ...prev,- fields: { ...prev.fields, [key]: value },- }))+ useEffect(() => {+ onActionsChange?.(null)+ return () => onActionsChange?.(null)+ }, [onActionsChange])++ function openEditor() {+ setState(prev => ({ ...prev, error: '', reloadHint: false }))+ setEditBytes(fieldBytes(activeValue))+ setEditing(true)}- const discardEdits = useCallback(() => {- setState(prev => ({- ...prev,- fields: { ...prev.initial },- error: prev.reloadHint ? prev.error : '',- }))- }, [])+ function closeEditor() {+ if (state.saving) return+ setEditing(false)+ setState(prev => ({ ...prev, error: '', reloadHint: false }))+ }- const saveActiveField = useCallback(async (): Promise<boolean> => {+ async function saveActiveField(value: string): Promise<void> {const current = stateRef.currentconst currentConfig =IDENTITY_FIELDS.find(field => field.key === current.activeField) ?? IDENTITY_FIELDS[0]- const currentValue = current.fields[currentConfig.key]- if (- currentValue === current.initial[currentConfig.key] ||- fieldBytes(currentValue) > FIELD_MAX_BYTES ||- current.reloadHint- ) {- return false- }+ if (value === current.fields[currentConfig.key] || fieldBytes(value) > FIELD_MAX_BYTES) return+ const nextFields = { ...current.fields, [currentConfig.key]: value }setState(prev => ({ ...prev, error: '', saving: true }))try {const result = await updateHostPersonalization(hostName, {- agents: current.fields.agents,- identity: current.fields.identity,+ agents: nextFields.agents,+ identity: nextFields.identity,resourceVersion: current.resourceVersion,- soul: current.fields.soul,- user: current.fields.user,+ soul: nextFields.soul,+ user: nextFields.user,})setState(prev => ({...prev,- initial: { ...prev.fields },+ error: '',+ fields: nextFields,+ initial: { ...nextFields },+ reloadHint: false,resourceVersion: result.resourceVersion,saving: false,}))- showToast('Identity files saved.', { tone: 'success' })- return true+ setEditing(false)+ showToast(`${currentConfig.fileName} saved.`, { tone: 'success' })} catch (error) {const err = error as { message?: string; status?: number }const isConflict = err.status === 409 || /409/.test(err.message ?? '')const message = isConflict- ? 'Someone else updated these identity files. Reload before saving again.'+ ? 'Someone else updated these identity files. Reload the latest version and reapply this draft.': err.message || 'Save failed'setState(prev => ({...prev,@@ -149,77 +141,10 @@ export function HostIdentityTab({ hostName, onActionsChange }: HostIdentityTabPrsaving: false,}))showToast(message, { tone: 'error' })- return false}- }, [hostName, showToast])-- const setActiveField = useCallback(- async (key: IdentityFieldKey) => {- if (key === state.activeField) return- if (!anyDirty) {- setState(prev => ({ ...prev, activeField: key }))- return- }-- const outcome = await choose({- cancelLabel: 'Cancel',- confirmLabel: 'Save',- discardLabel: 'Discard all',- message: 'Save or discard your identity edits before changing files.',- title: 'Unsaved identity edits',- })- if (outcome === 'confirm') {- if (!(await saveActiveField())) return- } else if (outcome === 'discard') {- discardEdits()- } else {- return- }- setState(prev => ({ ...prev, activeField: key }))- },- [anyDirty, choose, discardEdits, saveActiveField, state.activeField]- )-- useEffect(() => {- if (!onActionsChange) return- onActionsChange(- anyDirty ? (- <>- <Button- disabled={!activeDirty || activeTooLarge || state.saving || state.reloadHint}- onClick={() => void saveActiveField()}- size="sm"- type="button"- variant="primary"- >- <IconCheck width={14} height={14} />- {state.saving ? 'Saving' : 'Save'}- </Button>- <Button- disabled={state.saving}- onClick={discardEdits}- size="sm"- type="button"- variant="ghost"- >- Discard all- </Button>- </>- ) : null- )- return () => onActionsChange(null)- }, [- activeDirty,- activeTooLarge,- anyDirty,- discardEdits,- onActionsChange,- saveActiveField,- state.reloadHint,- state.saving,- ])+ }- if (state.loading) {+ if (state.loading && !editing) {return (<div className="cu-identity-skeleton" aria-label="Loading identity files"><div className="cu-identity-skeleton__tabs" />@@ -236,31 +161,8 @@ export function HostIdentityTab({ hostName, onActionsChange }: HostIdentityTabPr<p className="cu-identity-panel__intro">Admin-managed identity files are readable by the agent but blocked from agent writes.</p>- {!onActionsChange && anyDirty ? (- <div className="cu-identity-panel__local-actions">- <Button- disabled={!activeDirty || activeTooLarge || state.saving || state.reloadHint}- onClick={() => void saveActiveField()}- size="sm"- type="button"- variant="primary"- >- <IconCheck width={14} height={14} />- {state.saving ? 'Saving' : 'Save'}- </Button>- <Button- disabled={state.saving}- onClick={discardEdits}- size="sm"- type="button"- variant="ghost"- >- Discard all- </Button>- </div>- ) : null}- {state.error && state.reloadHint ? (- <div className="cu-banner cu-banner--error">+ {state.error && !editing ? (+ <div className="cu-banner cu-banner--error" role="alert">{state.error}<ButtonclassName="cu-identity-reload"@@ -278,7 +180,7 @@ export function HostIdentityTab({ hostName, onActionsChange }: HostIdentityTabPractiveValue={state.activeField}ariaLabel="Identity file sections"className="cu-tabs--compact cu-identity-tabs"- onChange={setActiveField}+ onChange={key => setState(prev => ({ ...prev, activeField: key, error: '' }))}options={IDENTITY_FIELDS.map(field => ({label: field.label,value: field.key,@@ -287,31 +189,69 @@ export function HostIdentityTab({ hostName, onActionsChange }: HostIdentityTabPr<div className="cu-identity-section"><div className="cu-identity-section__header">- <div className="cu-identity-section__title-row">+ <div><h3 className="cu-identity-section__title">{activeConfig.fileName}</h3>- <span aria-hidden={!anyDirty} className="cu-identity-dirty" data-hidden={!anyDirty}>- Unsaved edits- </span>+ <p className="cu-identity-section__meta">{activeConfig.help}</p></div>+ <Button onClick={openEditor} size="sm" type="button" variant="secondary">+ <IconPencil width={14} height={14} />+ Edit+ </Button></div>- <p className="cu-field__hint">{activeConfig.help}</p>+ <MarkdownContent+ ariaLabel={`Rendered ${activeConfig.label} document`}+ className="cu-identity-preview cu-gfs-markdown-preview__content"+ emptyMessage="This identity document is empty."+ source={activeValue}+ />+ </div>- <div className="cu-identity-editor">- <MarkdownEditor- ariaLabel={`${activeConfig.label} markdown`}- className="cu-identity-editor__markdown"- invalid={activeTooLarge}- onChange={value => setField(activeConfig.key, value)}- placeholder={activeConfig.placeholder}- value={activeValue}- />- <div className={activeTooLarge ? 'cu-field__error' : 'cu-field__hint'}>- {activeBytes.toLocaleString()} bytes / {FIELD_MAX_BYTES.toLocaleString()} max+ <SingleValueEditDialog+ closeButtonLabel={`Close ${activeConfig.fileName} editor`}+ description={activeConfig.help}+ discardLabel="Cancel"+ error={state.error || undefined}+ initialValue={activeValue}+ isValid={editBytes <= FIELD_MAX_BYTES && !state.reloadHint}+ onDismiss={closeEditor}+ onSave={value => void saveActiveField(value)}+ open={editing}+ pending={state.saving || state.loading}+ renderEditor={({ value, onChange, disabled }) => (+ <div className="cu-identity-dialog-editor">+ <MarkdownEditor+ ariaLabel={`${activeConfig.label} markdown`}+ className="cu-identity-editor__markdown"+ invalid={editBytes > FIELD_MAX_BYTES}+ onChange={next => {+ setEditBytes(fieldBytes(next))+ onChange(next)+ }}+ placeholder={activeConfig.placeholder}+ value={value}+ />+ <div className={editBytes > FIELD_MAX_BYTES ? 'cu-field__error' : 'cu-field__hint'}>+ {editBytes.toLocaleString()} bytes / {FIELD_MAX_BYTES.toLocaleString()} max+ </div>+ {state.reloadHint ? (+ <Button+ disabled={disabled}+ onClick={() => void loadIdentityFiles()}+ size="sm"+ type="button"+ variant="secondary"+ >+ <IconRefresh width={14} height={14} />+ Reload latest and reapply draft+ </Button>+ ) : null}</div>- </div>- </div>- {confirmDialog}+ )}+ saveLabel="Save document"+ size="large"+ title={`Edit ${activeConfig.fileName}`}+ /></section>)}diff --git a/control-ui/components/MarkdownContent/index.tsx b/control-ui/components/MarkdownContent/index.tsxnew file mode 100644index 000000000..d6606dda9--- /dev/null+++ b/control-ui/components/MarkdownContent/index.tsx@@ -0,0 +1,77 @@+'use client'++import { Fragment, useMemo } from 'react'+import type { ReactNode } from 'react'+import { parseVanillaMarkdown } from '@lib/vanillaMarkdown'+import type { MarkdownBlock, MarkdownInlineNode } from '@lib/vanillaMarkdown.types'++type MarkdownContentProps = {+ ariaLabel: string+ className: string+ emptyMessage: string+ source: string+}++function renderInlineNodes(nodes: MarkdownInlineNode[]): ReactNode[] {+ return nodes.map(node => {+ if (node.kind === 'text') return <Fragment key={node.id}>{node.value}</Fragment>+ if (node.kind === 'code') return <code key={node.id}>{node.value}</code>+ const children = renderInlineNodes(node.children)+ if (node.kind === 'strong') return <strong key={node.id}>{children}</strong>+ if (node.kind === 'emphasis') return <em key={node.id}>{children}</em>+ if (node.kind === 'strikethrough') return <s key={node.id}>{children}</s>+ return node.href ? (+ <a href={node.href} key={node.id} rel="noreferrer" target="_blank">+ {children}+ </a>+ ) : (+ <span key={node.id}>{children}</span>+ )+ })+}++function renderHeading(block: Extract<MarkdownBlock, { kind: 'heading' }>): ReactNode {+ const children = renderInlineNodes(block.children)+ if (block.level === 1) return <h1 key={block.id}>{children}</h1>+ if (block.level === 2) return <h2 key={block.id}>{children}</h2>+ if (block.level === 3) return <h3 key={block.id}>{children}</h3>+ if (block.level === 4) return <h4 key={block.id}>{children}</h4>+ if (block.level === 5) return <h5 key={block.id}>{children}</h5>+ return <h6 key={block.id}>{children}</h6>+}++function renderBlock(block: MarkdownBlock): ReactNode {+ if (block.kind === 'heading') return renderHeading(block)+ if (block.kind === 'paragraph') return <p key={block.id}>{renderInlineNodes(block.children)}</p>+ if (block.kind === 'blockquote') {+ return <blockquote key={block.id}>{renderInlineNodes(block.children)}</blockquote>+ }+ if (block.kind === 'divider') return <hr key={block.id} />+ if (block.kind === 'code') {+ return (+ <pre key={block.id}>+ <code data-language={block.language ?? undefined}>{block.value}</code>+ </pre>+ )+ }+ const items = block.items.map(item => <li key={item.id}>{renderInlineNodes(item.children)}</li>)+ return block.ordered ? <ol key={block.id}>{items}</ol> : <ul key={block.id}>{items}</ul>+}++export function MarkdownContent({+ ariaLabel,+ className,+ emptyMessage,+ source,+}: MarkdownContentProps): React.JSX.Element {+ const blocks = useMemo(() => parseVanillaMarkdown(source), [source])+ return (+ <article aria-label={ariaLabel} className={className}>+ {blocks.length > 0 ? (+ blocks.map(renderBlock)+ ) : (+ <p className="cu-gfs-markdown-preview__empty">{emptyMessage}</p>+ )}+ </article>+ )+}diff --git a/control-ui/components/__tests__/HostIdentityTab.test.tsx b/control-ui/components/__tests__/HostIdentityTab.test.tsxindex cc6a15c33..fe698b9cd 100644--- a/control-ui/components/__tests__/HostIdentityTab.test.tsx+++ b/control-ui/components/__tests__/HostIdentityTab.test.tsx@@ -10,24 +10,22 @@ vi.mock('../../lib/api', () => ({updateHostPersonalization: vi.fn(),}))-afterEach(() => {- cleanup()-})+afterEach(cleanup)++const initialFiles = {+ agents: '## Agent instructions',+ identity: '## Mission\n\nProtect identity.',+ resourceVersion: '1',+ soul: '## Values',+ user: '## User context',+}describe('HostIdentityTab', () => {beforeEach(() => {vi.clearAllMocks()+ vi.mocked(api.getHostPersonalization).mockResolvedValue(initialFiles)})- const findMarkdownEditor = (name: RegExp) =>- screen.findByLabelText(name, undefined, { timeout: 10000 })-- async function expectMarkdownEditorValue(name: RegExp, value: string) {- const editor = await findMarkdownEditor(name)- await waitFor(() => expect(screen.getByLabelText(name)).toHaveValue(value), { timeout: 10000 })- return editor- }-function renderTab(onActionsChange?: (actions: React.ReactNode | null) => void) {return render(<ToastProvider>@@ -36,264 +34,134 @@ describe('HostIdentityTab', () => {)}- function renderHeaderTab() {- function HeaderMode() {- const [actions, setActions] = React.useState<React.ReactNode>(null)- return (- <ToastProvider>- <div aria-label="Header actions">{actions}</div>- <HostIdentityTab hostName="foo" onActionsChange={setActions} />- </ToastProvider>- )- }-- return render(<HeaderMode />)+ async function openIdentityEditor() {+ await screen.findByRole('article', { name: 'Rendered Identity document' })+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ const dialog = await screen.findByRole('dialog', { name: 'Edit IDENTITY.md' })+ await within(dialog).findByLabelText('Identity markdown', undefined, { timeout: 10000 })+ return dialog}- it('renders the four section tabs and displays the editor for each section', async () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: 'a',- identity: 'id',- resourceVersion: '1',- soul: 's',- user: 'u',- })+ it('renders each document as read content with an Edit action beside its title', async () => {renderTab()- expect(await screen.findByRole('tab', { name: 'Identity' })).toBeInTheDocument()- await expectMarkdownEditorValue(/Identity markdown/i, 'id')++ const identity = await screen.findByRole('article', { name: 'Rendered Identity document' })+ await waitFor(() => expect(identity).toHaveTextContent('Mission'), { timeout: 10000 })+ expect(screen.getByRole('heading', { name: 'IDENTITY.md' })).toBeInTheDocument()+ expect(screen.queryByLabelText('Identity markdown')).toBeNull()+fireEvent.click(screen.getByRole('tab', { name: 'Soul' }))- await expectMarkdownEditorValue(/Soul markdown/i, 's')- fireEvent.click(screen.getByRole('tab', { name: 'Agent instructions' }))- await expectMarkdownEditorValue(/Agent instructions markdown/i, 'a')- fireEvent.click(screen.getByRole('tab', { name: 'User context' }))- await expectMarkdownEditorValue(/User context markdown/i, 'u')- }, 15_000)+ const soul = await screen.findByRole('article', { name: 'Rendered Soul document' })+ await waitFor(() => expect(soul).toHaveTextContent('Values'), { timeout: 10000 })+ expect(screen.getByRole('heading', { name: 'SOUL.md' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument()+ })- it('shows a loading skeleton while the initial request is pending', () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockReturnValue(- new Promise(() => undefined)- )+ it('opens the current Markdown editor in the large shared dialog and cancels without saving', async () => {renderTab()- expect(screen.getByLabelText(/loading identity files/i)).toBeInTheDocument()- })+ const dialog = await openIdentityEditor()+ expect(dialog).toHaveClass('eft-dialog--large')+ expect(within(dialog).getByLabelText('Identity markdown')).toHaveValue(initialFiles.identity)- it('shows the markdown editor directly for the active section', async () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: '',- identity: '## Mission\n\n- Protect identity',- resourceVersion: '1',- soul: '',- user: '',+ fireEvent.change(within(dialog).getByLabelText('Identity markdown'), {+ target: { value: 'draft' },})- renderTab()- await expectMarkdownEditorValue(/Identity markdown/i, '## Mission\n\n- Protect identity')- expect(screen.queryByRole('button', { name: /save/i })).not.toBeInTheDocument()+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))++ expect(screen.queryByRole('dialog', { name: 'Edit IDENTITY.md' })).toBeNull()+ expect(screen.getByRole('article', { name: 'Rendered Identity document' })).toHaveTextContent(+ 'Protect identity.'+ )+ expect(api.updateHostPersonalization).not.toHaveBeenCalled()})- it('enables Save after edit without marking valid content invalid, and calls update API', async () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: '',- identity: 'old',- resourceVersion: '1',- soul: '',- user: '',- })- ;(api.updateHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- resourceVersion: '2',- })+ it('saves one document through the aggregate Host payload and current resourceVersion', async () => {+ vi.mocked(api.updateHostPersonalization).mockResolvedValue({ resourceVersion: '2' })renderTab()- const idEl = await findMarkdownEditor(/Identity markdown/i)- fireEvent.change(idEl, { target: { value: 'new' } })- const saveBtn = screen.getByRole('button', { name: /save/i })- expect(saveBtn).not.toBeDisabled()- expect(idEl).not.toHaveClass('cu-input--invalid')+ const dialog = await openIdentityEditor()+ fireEvent.change(within(dialog).getByLabelText('Identity markdown'), {+ target: { value: '## Updated mission' },+ })+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save document' }))- fireEvent.click(saveBtn)await waitFor(() =>expect(api.updateHostPersonalization).toHaveBeenCalledWith('foo', {- agents: '',- identity: 'new',+ agents: initialFiles.agents,+ identity: '## Updated mission',resourceVersion: '1',- soul: '',- user: '',+ soul: initialFiles.soul,+ user: initialFiles.user,}))+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ expect(screen.getByRole('article', { name: 'Rendered Identity document' })).toHaveTextContent(+ 'Updated mission'+ )+ expect(screen.getByText('IDENTITY.md saved.')).toBeInTheDocument()})- it('uses a success toast after a successful save', async () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: '',- identity: 'old',- resourceVersion: '1',- soul: '',- user: '',- })- ;(api.updateHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- resourceVersion: '2',- })- renderTab()- fireEvent.change(await findMarkdownEditor(/Identity markdown/i), {- target: { value: 'new' },- })- fireEvent.click(screen.getByRole('button', { name: /save/i }))- await waitFor(() => expect(screen.getByText(/^Identity files saved\.?$/i)).toBeInTheDocument())- })-- it('requires discarding or saving before changing identity files', async () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: 'agents old',- identity: 'identity old',- resourceVersion: '1',- soul: 'soul old',- user: 'user old',- })+ it('retains a failed draft in place for correction and retry', async () => {+ vi.mocked(api.updateHostPersonalization).mockRejectedValue(new Error('Save failed upstream'))renderTab()- const identityEditor = await findMarkdownEditor(/Identity markdown/i)- fireEvent.change(identityEditor, { target: { value: 'identity new' } })- fireEvent.click(screen.getByRole('tab', { name: 'Soul' }))-- const dialog = screen.getByRole('alertdialog', { name: /unsaved identity edits/i })- expect(dialog).toBeInTheDocument()- expect(screen.getByText(/save or discard your identity edits/i)).toBeInTheDocument()- fireEvent.click(within(dialog).getByRole('button', { name: 'Discard all' }))-- await expectMarkdownEditorValue(/Soul markdown/i, 'soul old')- fireEvent.click(screen.getByRole('tab', { name: 'Identity' }))- await expectMarkdownEditorValue(/Identity markdown/i, 'identity old')- expect(screen.getByText(/unsaved edits/i)).toHaveAttribute('data-hidden', 'true')- expect(screen.queryByRole('button', { name: /save/i })).not.toBeInTheDocument()+ const dialog = await openIdentityEditor()+ const editor = within(dialog).getByLabelText('Identity markdown')+ fireEvent.change(editor, { target: { value: 'retry me' } })+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save document' }))++ expect(await within(dialog).findByRole('alert')).toHaveTextContent('Save failed upstream')+ expect(editor).toHaveValue('retry me')+ expect(screen.getByRole('dialog', { name: 'Edit IDENTITY.md' })).toBeInTheDocument()})- it('keeps edits and the active file when the unsaved-edits prompt is dismissed', async () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: '',- identity: 'identity old',- resourceVersion: '1',- soul: 'soul old',- user: '',- })+ it('reloads a conflict and reapplies the retained draft with the new resourceVersion', async () => {+ vi.mocked(api.updateHostPersonalization)+ .mockRejectedValueOnce(Object.assign(new Error('HTTP 409'), { status: 409 }))+ .mockResolvedValueOnce({ resourceVersion: '3' })+ vi.mocked(api.getHostPersonalization)+ .mockResolvedValueOnce(initialFiles)+ .mockResolvedValueOnce({+ ...initialFiles,+ identity: 'server revision',+ soul: 'server soul',+ resourceVersion: '2',+ })renderTab()- const identityEditor = await findMarkdownEditor(/Identity markdown/i)- fireEvent.change(identityEditor, { target: { value: 'identity new' } })- fireEvent.click(screen.getByRole('tab', { name: 'Soul' }))- expect(screen.getByRole('alertdialog')).toBeInTheDocument()-- fireEvent.keyDown(window, { key: 'Escape' })-- await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull())- expect(screen.getByLabelText(/Identity markdown/i)).toHaveValue('identity new')- expect(screen.queryByLabelText(/Soul markdown/i)).toBeNull()- })+ const dialog = await openIdentityEditor()+ const editor = within(dialog).getByLabelText('Identity markdown')+ fireEvent.change(editor, { target: { value: 'my retained draft' } })+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save document' }))- it('saves edited content before switching identity files', async () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: '',- identity: 'identity old',- resourceVersion: '1',- soul: 'soul old',- user: '',- })- ;(api.updateHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- resourceVersion: '2',- })- renderTab()- fireEvent.change(await findMarkdownEditor(/Identity markdown/i), {- target: { value: 'identity new' },- })- fireEvent.click(screen.getByRole('tab', { name: 'Soul' }))- fireEvent.click(within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Save' }))+ expect(await within(dialog).findByRole('alert')).toHaveTextContent(/reload the latest version/i)+ fireEvent.click(within(dialog).getByRole('button', { name: 'Reload latest and reapply draft' }))+ await waitFor(() => expect(api.getHostPersonalization).toHaveBeenCalledTimes(2))+ await waitFor(() => expect(editor).toHaveValue('my retained draft'))+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save document' }))await waitFor(() =>- expect(api.updateHostPersonalization).toHaveBeenCalledWith(- 'foo',- expect.objectContaining({ identity: 'identity new' })- )+ expect(api.updateHostPersonalization).toHaveBeenLastCalledWith('foo', {+ agents: initialFiles.agents,+ identity: 'my retained draft',+ resourceVersion: '2',+ soul: 'server soul',+ user: initialFiles.user,+ }))- await expectMarkdownEditorValue(/Soul markdown/i, 'soul old')})- it('keeps the current file selected when saving before a switch fails', async () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: '',- identity: 'identity old',- resourceVersion: '1',- soul: 'soul old',- user: '',- })- ;(api.updateHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockRejectedValue(- Object.assign(new Error('HTTP 409'), { status: 409 })- )+ it('disables Save and marks the editor invalid above the 64 KiB limit', async () => {renderTab()- fireEvent.change(await findMarkdownEditor(/Identity markdown/i), {- target: { value: 'identity new' },- })- fireEvent.click(screen.getByRole('tab', { name: 'Soul' }))- fireEvent.click(within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Save' }))+ const dialog = await openIdentityEditor()+ const editor = within(dialog).getByLabelText('Identity markdown')+ fireEvent.change(editor, { target: { value: 'x'.repeat(64 * 1024 + 1) } })- await waitFor(() =>- expect(screen.getAllByText(/someone else updated/i).length).toBeGreaterThan(0)- )- expect(screen.getByLabelText(/Identity markdown/i)).toHaveValue('identity new')- expect(screen.queryByLabelText(/Soul markdown/i)).toBeNull()+ expect(editor.closest('.cu-markdown-editor')).toHaveClass('cu-markdown-editor--invalid')+ expect(within(dialog).getByRole('button', { name: 'Save document' })).toBeDisabled()})- it('registers dirty-file actions in header mode without re-registering per keystroke', async () => {+ it('keeps host-page header actions empty because edit is document-local', async () => {const onActionsChange = vi.fn()- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: '',- identity: 'identity old',- resourceVersion: '1',- soul: '',- user: '',- })renderTab(onActionsChange)- const editor = await findMarkdownEditor(/Identity markdown/i)- fireEvent.change(editor, { target: { value: 'identity one' } })- await waitFor(() => expect(onActionsChange).toHaveBeenCalled())- const callsAfterFirstEdit = onActionsChange.mock.calls.length-- fireEvent.change(editor, { target: { value: 'identity two' } })- expect(onActionsChange).toHaveBeenCalledTimes(callsAfterFirstEdit)-- cleanup()- renderHeaderTab()- const headerEditor = await screen.findByLabelText(/Identity markdown/i)- fireEvent.change(headerEditor, { target: { value: 'identity header edit' } })- await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument())- })-- it('disables Save and marks the textarea invalid when the active field exceeds 64 KiB', async () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: '',- identity: '',- resourceVersion: '1',- soul: '',- user: '',- })- renderTab()- const editor = await findMarkdownEditor(/Identity markdown/i)- fireEvent.change(editor, {- target: { value: 'x'.repeat(64 * 1024 + 1) },- })- expect(editor.closest('.cu-markdown-editor')).toHaveClass('cu-markdown-editor--invalid')- expect(screen.getByRole('button', { name: /save/i })).toBeDisabled()- })-- it('on 409 surfaces a reload prompt and error toast', async () => {- ;(api.getHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({- agents: '',- identity: '',- resourceVersion: '1',- soul: '',- user: '',- })- ;(api.updateHostPersonalization as unknown as ReturnType<typeof vi.fn>).mockRejectedValue(- Object.assign(new Error('HTTP 409: resourceVersion mismatch'), { status: 409 })- )- renderTab()- fireEvent.change(await findMarkdownEditor(/Identity markdown/i), { target: { value: 'y' } })- fireEvent.click(screen.getByRole('button', { name: /save/i }))- await waitFor(() => expect(screen.getAllByText(/reload/i).length).toBeGreaterThan(0))- expect(screen.getAllByText(/someone else updated these identity files/i).length).toBe(2)+ await screen.findByRole('article', { name: 'Rendered Identity document' })+ expect(onActionsChange).toHaveBeenCalledWith(null)})})diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 8c1d392f1..61b277dec 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.621",+ "version": "0.1.622","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.621",+ "version": "0.1.622","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.jsonindex c92638a06..51b56ac9e 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.621",+ "version": "0.1.622","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",