Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: four external-review fixes for Teams channel setup UX
Jose Ramirezd0c8c994613a
diff --git a/channel-reader/package-lock.json b/channel-reader/package-lock.jsonindex 2a210ef10..a2bb6529a 100644--- a/channel-reader/package-lock.json+++ b/channel-reader/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-channel-reader",- "version": "0.1.100",+ "version": "0.1.101","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-channel-reader",- "version": "0.1.100",+ "version": "0.1.101","license": "SEE LICENSE IN LICENSE","dependencies": {"@kubernetes/client-node": "^1.0.0",diff --git a/channel-reader/package.json b/channel-reader/package.jsonindex 641e0db93..92b6e2a83 100644--- a/channel-reader/package.json+++ b/channel-reader/package.json@@ -1,6 +1,6 @@{"name": "clerum-channel-reader",- "version": "0.1.100",+ "version": "0.1.101","description": "Watches CommunicationChannel CRDs and fetches messages from Telegram, Email, and Slack","main": "dist/main.js","engines": {diff --git a/channel-reader/src/main.ts b/channel-reader/src/main.tsindex 5ae35a2ac..98b3e377a 100644--- a/channel-reader/src/main.ts+++ b/channel-reader/src/main.ts@@ -1642,7 +1642,14 @@ export class ChannelReader {// TeamsAdapter has no ephemeral concept, so the notice is a normal message.// Thread it under the triggering message so an unconnected user does not// produce a top-level post in a shared channel.- await adapter.sendMessage(channelId, content, msg.messageId)+ //+ // The reply target is the thread ROOT, the same target replyTargetMessageId+ // picks for every other Teams reply. threadId is the root activity id+ // (providerReplyToMessageId) and messageId is the leaf activity that just+ // arrived; replying to the leaf does not attach the notice to the+ // conversation, which is the whole mitigation here. The fallback is for a+ // direct chat, which has no separate root.+ await adapter.sendMessage(channelId, content, msg.threadId || msg.messageId)} else if (msg.channelType === 'telegram') {// No reply id: the spec fixes this as sendMessage(channelId, content) for// Telegram, with no threading. Group and supergroup chats do have adiff --git a/channel-reader/src/progressFormatter.ts b/channel-reader/src/progressFormatter.tsindex 53aeb4dbc..7aa18286d 100644--- a/channel-reader/src/progressFormatter.ts+++ b/channel-reader/src/progressFormatter.ts@@ -34,8 +34,11 @@ export function describeToolError(errorSummary: string | undefined): string {return 'unavailable (authentication problem). Ask your administrator.'}if (/timed out|timeout|etimedout|deadline/.test(raw)) return 'unavailable (timed out).'- if (/rate limit|429|too many requests/.test(raw)) return 'unavailable (rate limited).'- if (/not found|404|no such/.test(raw)) return 'unavailable (not found).'+ // \b-anchored for the same reason as 401/403 above: bare "429" matched inside+ // "4291ms" and bare "404" inside "4041ms", so a duration classified as a rate+ // limit or a missing resource.+ if (/rate limit|\b429\b|too many requests/.test(raw)) return 'unavailable (rate limited).'+ if (/not found|\b404\b|no such/.test(raw)) return 'unavailable (not found).'// Checked before the invalid-input category below: when a message carries// both a size-limit signal and generic "invalid" wording (e.g. "invalid// request, payload too large"), the size limit is the more specific anddiff --git a/channel-reader/test/progressFormatter.test.ts b/channel-reader/test/progressFormatter.test.tsindex 50b98b0e2..c4623d6b9 100644--- a/channel-reader/test/progressFormatter.test.ts+++ b/channel-reader/test/progressFormatter.test.ts@@ -76,6 +76,20 @@ describe('describeToolError', () => {expect(describeToolError('429 Too Many Requests')).toBe('unavailable (rate limited).')})+ it('does not misclassify a duration containing 429 as a rate limit', () => {+ // Bare `429` matched inside "4291ms"; \b429\b must not.+ expect(describeToolError('operation finished in 4291ms')).toBe('unavailable.')+ })++ it('classifies an HTTP 404 as not found', () => {+ expect(describeToolError('HTTP/1.1 404 Not Found')).toBe('unavailable (not found).')+ })++ it('does not misclassify a duration containing 404 as not found', () => {+ // Bare `404` matched inside "4041ms"; \b404\b must not.+ expect(describeToolError('operation finished in 4041ms')).toBe('unavailable.')+ })+it('falls back to generic for anything unrecognised', () => {expect(describeToolError('kaboom {"secret":"hunter2"}')).toBe('unavailable.')})diff --git a/channel-reader/test/unresolvedSenderNotice.test.ts b/channel-reader/test/unresolvedSenderNotice.test.tsindex d103d4699..5afbd613d 100644--- a/channel-reader/test/unresolvedSenderNotice.test.ts+++ b/channel-reader/test/unresolvedSenderNotice.test.ts@@ -354,21 +354,37 @@ describe('unresolved sender notice', () => {})describe('unresolved sender notice on Teams', () => {- it('sends a threaded notice to an unresolved Teams sender', async () => {- const { deliver, sendMessage } = buildReader({+ it('threads the notice under the conversation ROOT, not the activity that triggered it', async () => {+ const { buildMessage, deliverBatch, sendMessage } = buildReader({medium: 'teams',profileUiUrl: 'https://profile.test',})- await deliver()+ // Root and leaf deliberately differ. A Teams channel message carries the+ // root activity id as threadId (providerReplyToMessageId) and the activity+ // that just arrived as messageId; a truthiness assertion passes for either,+ // which is why the previous version of this test could not fail.+ await deliverBatch([+ { ...buildMessage('C1', 'U1'), messageId: 'leaf-activity', threadId: 'root-activity' },+ ])expect(sendMessage).toHaveBeenCalledTimes(1)const [channelId, content, replyToMessageId] = sendMessage.mock.calls[0]expect(channelId).toBe('C1')expect(content).toContain('https://profile.test')// Threading is the whole mitigation for Teams having no ephemeral concept:- // a top-level post would announce the notice to the entire channel.- expect(replyToMessageId).toBeTruthy()+ // a reply against the leaf does not attach to the conversation, and a+ // top-level post announces the notice to the entire channel.+ expect(replyToMessageId).toBe('root-activity')+ })++ it('falls back to the message id in a direct chat, which has no separate root', async () => {+ const { buildMessage, deliverBatch, sendMessage } = buildReader({ medium: 'teams' })++ await deliverBatch([{ ...buildMessage('C1', 'U1'), messageId: 'leaf-activity' }])++ expect(sendMessage).toHaveBeenCalledTimes(1)+ expect(sendMessage.mock.calls[0][2]).toBe('leaf-activity')})it('sends the Teams notice at most once per user per conversation', async () => {diff --git a/control-ui/app/communication-channels/[name]/edit/page.tsx b/control-ui/app/communication-channels/[name]/edit/page.tsxindex 11d68d28a..99d117607 100644--- a/control-ui/app/communication-channels/[name]/edit/page.tsx+++ b/control-ui/app/communication-channels/[name]/edit/page.tsx@@ -44,10 +44,11 @@ import {import { canGenerateSlackAppManifest, slackAppManifest } from '@lib/slackAppManifest'import {LOCAL_TEAMS_ENDPOINT_ORIGIN,+ TEAMS_APP_NAME_MAX_LENGTH,buildTeamsAppCreateCommand,canGenerateTeamsCommand,- isValidTeamsBotName,- toTeamsBotNameInput,+ teamsAppNameError,+ teamsPlaceholderEndpoint,} from '@lib/teamsSetup'type ChannelProvider = CommunicationChannelProvider@@ -273,27 +274,48 @@ export default function EditCommunicationChannelPage() {teamsRequestUrl && !canGenerateTeamsCommand(teamsRequestUrl)? buildTeamsAppCreateCommand({botName: draft?.teamsAppName || '',- endpoint: `${LOCAL_TEAMS_ENDPOINT_ORIGIN}${teamsRequestUrl}`,+ endpoint: teamsPlaceholderEndpoint(teamsRequestUrl),}): null// hasTeamsConfigForRequestUrl is satisfied by CLIENT_ID or TENANT_ID alone,// so teamsAppCreateCommand can render with a blank Name -- which// buildTeamsAppCreateCommand fills with the literal placeholder <bot-name>.- // Gate Copy on a valid name the same way the create page does, so that+ // Gate Copy on a usable name the same way the create page does, so that// placeholder is never handed over as if it were runnable.- const teamsBotNameIsValid = isValidTeamsBotName(draft?.teamsAppName || '')+ const teamsBotNameError = teamsAppNameError(draft?.teamsAppName || '')- async function persistDraft(nextDraft: DraftState, successMessage: string) {+ /**+ * The single validation boundary for this page: every path that persists a+ * full spec goes through here, Save and deleteConversation alike. Validating+ * in handleSave instead let deleteConversation persist a value Save refuses.+ *+ * It validates the SPEC, not the draft, because the spec is what is sent: an+ * empty name is omitted by buildCommunicationChannelSpec rather than written+ * as an empty string, which is exactly what the server accepts.+ *+ * Returns false when nothing was persisted, so callers do not navigate away+ * from an unsaved page -- neither on a rejected value nor on a failed PUT.+ */+ async function persistDraft(nextDraft: DraftState, successMessage: string): Promise<boolean> {+ const spec = buildCommunicationChannelSpec(nextDraft)+ const teamsAppName = spec.teamsSettings?.appName+ const nameError = teamsAppName === undefined ? null : teamsAppNameError(teamsAppName)+ if (nameError) {+ setSaveError(nameError)+ return false+ }setSaving(true)setSaveError('')try {await apiSend('PUT', `/api/v1/admin/communication-channels/${encodeURIComponent(name)}`, {- spec: buildCommunicationChannelSpec(nextDraft),+ spec,})setDraft(nextDraft)showToast(successMessage, { tone: 'success' })+ return true} catch (error) {setSaveError(error instanceof Error ? error.message : 'Failed to save communication channel')+ return false} finally {setSaving(false)}@@ -302,17 +324,8 @@ export default function EditCommunicationChannelPage() {async function handleSave(event: React.FormEvent<HTMLFormElement>) {event.preventDefault()if (!draft || saving) return- // buildCommunicationChannelSpec writes teamsAppName into spec.teamsSettings.appName- // whenever it is non-empty, regardless of which provider tab is active, so an- // invalid value typed on the Teams tab must block Save here rather than only- // gating the Teams-tab Copy button (which a user editing another tab never sees).- if (draft.teamsAppName.trim() && !isValidTeamsBotName(draft.teamsAppName)) {- setSaveError(- 'Teams bot name must start with a letter and use lowercase letters, numbers, and hyphens.'- )- return- }- await persistDraft(draft, `Communication channel ${name} updated.`)+ const saved = await persistDraft(draft, `Communication channel ${name} updated.`)+ if (!saved) returnbackToChannels()}@@ -706,20 +719,20 @@ export default function EditCommunicationChannelPage() {current? {...current,- teamsAppName: toTeamsBotNameInput(event.target.value),+ teamsAppName: event.target.value,// Typed, so no longer just an inherited label.teamsAppNameFromAnnotation: false,}: current)}- placeholder="evenfire-bot"+ placeholder="Evenfire Bot"disabled={saving}autoComplete="off"/><span className="cu-field__hint">- Name shown in the Teams bot creation output and Profile UI setup- instructions.+ Display name shown in the Teams bot creation output and Profile UI setup+ instructions, up to {TEAMS_APP_NAME_MAX_LENGTH} characters.</span></div><div className="cu-field">@@ -796,7 +809,7 @@ export default function EditCommunicationChannelPage() {size="sm"className="cu-command-block__copy"onClick={copyTeamsAppCreateCommand}- disabled={saving || !teamsBotNameIsValid}+ disabled={saving || Boolean(teamsBotNameError)}aria-label="Copy Teams bot create command"><IconCopy width={15} height={15} />@@ -832,7 +845,7 @@ export default function EditCommunicationChannelPage() {size="sm"className="cu-command-block__copy"onClick={copyTeamsAppCreatePlaceholderCommand}- disabled={saving || !teamsBotNameIsValid}+ disabled={saving || Boolean(teamsBotNameError)}aria-label="Copy Teams bot create command"><IconCopy width={15} height={15} />diff --git a/control-ui/app/communication-channels/new/page.tsx b/control-ui/app/communication-channels/new/page.tsxindex b1226ada7..818cb4082 100644--- a/control-ui/app/communication-channels/new/page.tsx+++ b/control-ui/app/communication-channels/new/page.tsx@@ -37,10 +37,11 @@ import { canGenerateSlackAppManifest, slackAppManifest } from '@lib/slackAppManiimport { toKebabCase, toKebabInput } from '@lib/string'import {LOCAL_TEAMS_ENDPOINT_ORIGIN,+ TEAMS_APP_NAME_MAX_LENGTH,buildTeamsAppCreateCommand,canGenerateTeamsCommand,- isValidTeamsBotName,- toTeamsBotNameInput,+ teamsAppNameError,+ teamsPlaceholderEndpoint,} from '@lib/teamsSetup'type HostItem = {@@ -214,7 +215,7 @@ export default function CreateCommunicationChannelPage() {if (!teamsWebhookUrl || canGenerateTeamsCommand(teamsWebhookUrl)) return nullreturn buildTeamsAppCreateCommand({botName: draft.teamsAppName,- endpoint: `${LOCAL_TEAMS_ENDPOINT_ORIGIN}${teamsWebhookUrl}`,+ endpoint: teamsPlaceholderEndpoint(teamsWebhookUrl),})}, [draft.teamsAppName, teamsWebhookUrl])// Slack's order is manifest first, credentials second: the bot token only exists@@ -237,7 +238,7 @@ export default function CreateCommunicationChannelPage() {if (!appName || !slackRequestUrl || !canGenerateSlackAppManifest(slackRequestUrl)) return nullreturn slackAppManifest(appName, slackRequestUrl)}, [draft.slackBotHandle, slackRequestUrl])- const teamsBotNameIsValid = isValidTeamsBotName(draft.teamsAppName)+ const teamsBotNameError = teamsAppNameError(draft.teamsAppName)useEffect(() => {setCanUseBrowserWebhookOrigin(true)@@ -403,8 +404,8 @@ export default function CreateCommunicationChannelPage() {return}if (activeProvider === 'teams') {- if (!isValidTeamsBotName(draft.teamsAppName)) {- setError('Name must start with a letter and use lowercase letters, numbers, and hyphens.')+ if (teamsBotNameError) {+ setError(teamsBotNameError)return}if (!UUID_RE.test(draft.teamsAppId.trim())) {@@ -727,7 +728,7 @@ export default function CreateCommunicationChannelPage() {</p></div><Field- description="Use lowercase letters, numbers, and hyphens. The name must start with a letter."+ description={`Display name for the bot, up to ${TEAMS_APP_NAME_MAX_LENGTH} characters. Spaces and capitals are fine.`}htmlFor="teams-app-name"label="Name"required@@ -738,13 +739,13 @@ export default function CreateCommunicationChannelPage() {onChange={event =>setDraft(current => ({...current,- teamsAppName: toTeamsBotNameInput(event.target.value),+ teamsAppName: event.target.value,}))}- placeholder="evenfire-bot"+ placeholder="Evenfire Bot"disabled={saving}autoComplete="off"- invalid={Boolean(draft.teamsAppName) && !teamsBotNameIsValid}+ invalid={Boolean(draft.teamsAppName) && Boolean(teamsBotNameError)}/></Field><ol className="cu-teams-setup__instructions">@@ -768,7 +769,7 @@ export default function CreateCommunicationChannelPage() {size="sm"className="cu-command-block__copy"onClick={copyTeamsAppCreateCommand}- disabled={saving || !teamsBotNameIsValid}+ disabled={saving || Boolean(teamsBotNameError)}aria-label="Copy Teams bot create command"><IconCopy width={15} height={15} />@@ -798,7 +799,7 @@ export default function CreateCommunicationChannelPage() {size="sm"className="cu-command-block__copy"onClick={copyTeamsAppCreatePlaceholderCommand}- disabled={saving || !teamsBotNameIsValid}+ disabled={saving || Boolean(teamsBotNameError)}aria-label="Copy Teams bot create command"><IconCopy width={15} height={15} />diff --git a/control-ui/components/__tests__/CreateCommunicationChannelPage.test.tsx b/control-ui/components/__tests__/CreateCommunicationChannelPage.test.tsxindex d15b92b0b..e9e3999e3 100644--- a/control-ui/components/__tests__/CreateCommunicationChannelPage.test.tsx+++ b/control-ui/components/__tests__/CreateCommunicationChannelPage.test.tsx@@ -243,10 +243,13 @@ describe('CreateCommunicationChannelPage — provider setup', () => {const botNameInput = screen.getByLabelText(/^Name/)fireEvent.change(botNameInput, {- target: { value: 'Evenfire Bot!' },+ target: { value: 'Evenfire Bot' },})- expect(botNameInput).toHaveValue('evenfire-bot')+ // appName is a free-form display name on both the CRD and control-api, and+ // the Teams CLI documents --name the same way, so what the operator types+ // is what the command must carry.+ expect(botNameInput).toHaveValue('Evenfire Bot')expect(screen.getByText(/The command writes CLIENT_ID, TENANT_ID and CLIENT_SECRET into/i)).toBeInTheDocument()@@ -254,7 +257,8 @@ describe('CreateCommunicationChannelPage — provider setup', () => {const command = screen.getByText(/teams app create/).closest('pre')expect(command).toHaveTextContent('teams app create')- expect(command).toHaveTextContent('--name "evenfire-bot"')+ // Quoted, so a display name with a space stays one argument.+ expect(command).toHaveTextContent('--name "Evenfire Bot"')expect(command).toHaveTextContent('--endpoint "https://webhook.example.com/webhooks/teams/')expect(command).toHaveTextContent('--env .env')expect(screen.getByLabelText(/^CLIENT_ID/)).toBeInTheDocument()@@ -280,7 +284,7 @@ describe('CreateCommunicationChannelPage — provider setup', () => {await fillStep1AndContinue()fireEvent.click(screen.getByRole('radio', { name: 'Microsoft Teams' }))fireEvent.change(screen.getByLabelText(/^Name/), {- target: { value: 'Evenfire Bot!' },+ target: { value: 'Evenfire Bot' },})const panel = document.querySelector('.cu-channel-provider-panel')@@ -289,13 +293,37 @@ describe('CreateCommunicationChannelPage — provider setup', () => {)const command = screen.getByText(/teams app create/).closest('pre')- expect(command).toHaveTextContent('--name "evenfire-bot"')+ expect(command).toHaveTextContent('--name "Evenfire Bot"')// Pin the literal placeholder origin: this is what the operator is being// told to replace by hand.expect(command).toHaveTextContent('--endpoint "https://<public-webhook-origin>/webhooks/teams/')expect(screen.getByRole('button', { name: 'Copy Teams bot create command' })).toBeEnabled()})+ it('treats an http webhook origin as unusable, since Microsoft requires https', async () => {+ // Microsoft needs a publicly reachable HTTPS messaging endpoint, so an http+ // origin has to land in the warning branch -- and that branch must still+ // render a usable command, not the marker origin glued onto an absolute+ // http URL.+ vi.stubEnv('NEXT_PUBLIC_WORKFLOW_APPROVAL_READER_BASE_URL', 'http://webhook.example.com')+ render(+ <ToastProvider>+ <CreateCommunicationChannelPage />+ </ToastProvider>+ )++ await fillStep1AndContinue()+ fireEvent.click(screen.getByRole('radio', { name: 'Microsoft Teams' }))+ fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: 'Evenfire Bot' } })++ const panel = document.querySelector('.cu-channel-provider-panel')+ expect(panel?.textContent ?? '').toMatch(/no public webhook origin/i)++ const command = screen.getByText(/teams app create/).closest('pre')+ expect(command).toHaveTextContent('--endpoint "https://<public-webhook-origin>/webhooks/teams/')+ expect(command?.textContent ?? '').not.toContain('http://webhook.example.com')+ })+it('validates Teams CLIENT_ID and TENANT_ID before submission', async () => {render(<ToastProvider>@@ -323,6 +351,56 @@ describe('CreateCommunicationChannelPage — provider setup', () => {expect(api.apiSend).not.toHaveBeenCalled()})+ it('requires a Teams bot name before submitting', async () => {+ render(+ <ToastProvider>+ <CreateCommunicationChannelPage />+ </ToastProvider>+ )++ await fillStep1AndContinue()+ fireEvent.click(screen.getByRole('radio', { name: 'Microsoft Teams' }))+ fireEvent.change(screen.getByLabelText('CLIENT_SECRET'), { target: { value: 'secret' } })+ fireEvent.change(screen.getByLabelText(/^CLIENT_ID/), {+ target: { value: '7e9cdb6c-87e8-4b1e-b291-76f7b8bdbe82' },+ })+ fireEvent.change(screen.getByLabelText(/^TENANT_ID/), {+ target: { value: '21e08d37-8d53-4144-87cb-557b8298aed3' },+ })+ fireEvent.click(screen.getByRole('button', { name: 'Create channel' }))++ // The name is free-form, but it is not optional: control-api rejects an+ // appName that is present and empty, and the whole setup command is built+ // around it.+ expect(await screen.findByText('Teams bot name is required.')).toBeInTheDocument()+ expect(api.apiSend).not.toHaveBeenCalled()+ })++ it('rejects a Teams bot name past the 80 character server limit', async () => {+ render(+ <ToastProvider>+ <CreateCommunicationChannelPage />+ </ToastProvider>+ )++ await fillStep1AndContinue()+ fireEvent.click(screen.getByRole('radio', { name: 'Microsoft Teams' }))+ fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: 'a'.repeat(81) } })+ fireEvent.change(screen.getByLabelText('CLIENT_SECRET'), { target: { value: 'secret' } })+ fireEvent.change(screen.getByLabelText(/^CLIENT_ID/), {+ target: { value: '7e9cdb6c-87e8-4b1e-b291-76f7b8bdbe82' },+ })+ fireEvent.change(screen.getByLabelText(/^TENANT_ID/), {+ target: { value: '21e08d37-8d53-4144-87cb-557b8298aed3' },+ })+ fireEvent.click(screen.getByRole('button', { name: 'Create channel' }))++ expect(+ await screen.findByText('Teams bot name must be 80 characters or fewer.')+ ).toBeInTheDocument()+ expect(api.apiSend).not.toHaveBeenCalled()+ })+it('submits Teams settings and credentials with UUID values', async () => {render(<ToastProvider>@@ -333,7 +411,7 @@ describe('CreateCommunicationChannelPage — provider setup', () => {await fillStep1AndContinue()fireEvent.click(screen.getByRole('radio', { name: 'Microsoft Teams' }))fireEvent.change(screen.getByLabelText(/^Name/), {- target: { value: 'evenfire-bot' },+ target: { value: 'Evenfire Bot' },})fireEvent.change(screen.getByLabelText(/^CLIENT_ID/), {target: { value: '7e9cdb6c-87e8-4b1e-b291-76f7b8bdbe82' },@@ -355,7 +433,8 @@ describe('CreateCommunicationChannelPage — provider setup', () => {spec: expect.objectContaining({hostRef: 'agent-a',teamsSettings: {- appName: 'evenfire-bot',+ // Persisted exactly as typed: no kebab-casing on the way to the spec.+ appName: 'Evenfire Bot',appId: '7e9cdb6c-87e8-4b1e-b291-76f7b8bdbe82',tenantId: '21e08d37-8d53-4144-87cb-557b8298aed3',replyOnlyWhenMentioned: true,diff --git a/control-ui/components/__tests__/EditCommunicationChannelPage.test.tsx b/control-ui/components/__tests__/EditCommunicationChannelPage.test.tsxindex 9e4a95436..1f39d9522 100644--- a/control-ui/components/__tests__/EditCommunicationChannelPage.test.tsx+++ b/control-ui/components/__tests__/EditCommunicationChannelPage.test.tsx@@ -725,15 +725,15 @@ describe('EditCommunicationChannelPage Teams setup command', () => {})/**- * The create page normalizes the Name field through toTeamsBotNameInput on- * every keystroke and blocks submit on isValidTeamsBotName. This page used to- * write event.target.value raw and never validated the field on Save, so a- * value Create would have rejected -- e.g. one with a space, or one that- * starts with a digit, which toTeamsBotNameInput's kebab-casing does not fix- * -- persisted straight to spec.teamsSettings.appName.+ * spec.teamsSettings.appName is a free-form DISPLAY name: the CRD declares it+ * with no pattern (unlike tenantId right below it), control-api checks only+ * non-empty and 80 characters (unlike appId, which carries a UUID regex), and+ * the Teams CLI documents --name the same way. A kebab rule invented in the UI+ * mangled legitimate names as they were typed and, worse, locked an operator out+ * of saving ANY change on a channel whose stored name predated it.*/describe('EditCommunicationChannelPage Teams name validation', () => {- it('normalizes the Name field into the Teams CLI shape as the operator types, and offers a valid placeholder', async () => {+ it('keeps a free-form display name exactly as typed', async () => {mockChannel('teams-channel', { teamsSettings: { appName: '' } })await renderLoadedPage()@@ -741,20 +741,37 @@ describe('EditCommunicationChannelPage Teams name validation', () => {await user.click(await screen.findByRole('radio', { name: /microsoft teams/i }))const nameInput = screen.getByLabelText(/^name$/i) as HTMLInputElement- // The old placeholder, "Your Teams Bot", is itself a value the field- // should reject: it has spaces and capitals.- expect(nameInput.placeholder).toBe('evenfire-bot')+ // The placeholder is a display name, so it does not imply a kebab rule.+ expect(nameInput.placeholder).toBe('Evenfire Bot')- await user.type(nameInput, 'Evenfire Bot!')+ await user.type(nameInput, 'My Bot')- expect(nameInput).toHaveValue('evenfire-bot')+ expect(nameInput).toHaveValue('My Bot')})- it('blocks Save and does not persist a Teams bot name that is still invalid after normalization', async () => {- // Kebab-casing lowercases and strips disallowed characters, but it does not- // enforce a leading letter, so a name typed as "123 Bot" survives- // normalization as "123-bot" -- non-empty, but still invalid because it- // starts with a digit. Save must catch what normalization does not.+ it('saves an unrelated field on a channel whose stored name has a space', async () => {+ // The regression the invented rule caused: `My Bot` is a legitimate stored+ // appName, and the gate validated the whole hydrated draft, so this channel+ // could not save CLIENT_ID, access, or anything else until the name was+ // rewritten.+ mockChannel('teams-channel', { teamsSettings: { appName: 'My Bot' } })+ await renderLoadedPage()++ const user = userEvent.setup()+ await user.click(await screen.findByRole('radio', { name: /microsoft teams/i }))++ await user.type(screen.getByLabelText(/^CLIENT_ID/), '7e9cdb6c-87e8-4b1e-b291-76f7b8bdbe82')+ fireEvent.click(screen.getByRole('button', { name: 'Save changes' }))++ await waitFor(() => expect(api.apiSend).toHaveBeenCalled())+ const [, , body] = vi.mocked(api.apiSend).mock.calls[0] as [string, string, { spec: unknown }]+ const teamsSettings = (body.spec as { teamsSettings: { appName: string; appId: string } })+ .teamsSettings+ expect(teamsSettings.appName).toBe('My Bot')+ expect(teamsSettings.appId).toBe('7e9cdb6c-87e8-4b1e-b291-76f7b8bdbe82')+ })++ it('blocks Save and does not persist a Teams bot name past the server limit', async () => {mockChannel('teams-channel', { teamsSettings: { appName: 'evenfire' } })await renderLoadedPage()@@ -763,21 +780,20 @@ describe('EditCommunicationChannelPage Teams name validation', () => {const nameInput = screen.getByLabelText(/^name$/i) as HTMLInputElementawait user.clear(nameInput)- await user.type(nameInput, '123 Bot')- expect(nameInput).toHaveValue('123-bot')+ // Pasted rather than typed: 81 keystrokes through userEvent is slow, and the+ // field holds what it is given either way.+ fireEvent.change(nameInput, { target: { value: 'a'.repeat(81) } })fireEvent.click(screen.getByRole('button', { name: 'Save changes' }))expect(- await screen.findByText(- 'Teams bot name must start with a letter and use lowercase letters, numbers, and hyphens.'- )+ await screen.findByText('Teams bot name must be 80 characters or fewer.')).toBeInTheDocument()expect(api.apiSend).not.toHaveBeenCalled()expect(navigation.push).not.toHaveBeenCalled()})- it('saves a valid Teams bot name typed over the previous value', async () => {+ it('saves a display name typed over the previous value', async () => {mockChannel('teams-channel', { teamsSettings: { appName: 'evenfire' } })await renderLoadedPage()@@ -786,14 +802,71 @@ describe('EditCommunicationChannelPage Teams name validation', () => {const nameInput = screen.getByLabelText(/^name$/i) as HTMLInputElementawait user.clear(nameInput)- await user.type(nameInput, 'evenfire-bot-2')+ await user.type(nameInput, 'Evenfire Bot 2')fireEvent.click(screen.getByRole('button', { name: 'Save changes' }))await waitFor(() => expect(api.apiSend).toHaveBeenCalled())const [, , body] = vi.mocked(api.apiSend).mock.calls[0] as [string, string, { spec: unknown }]expect((body.spec as { teamsSettings: { appName: string } }).teamsSettings.appName).toBe(- 'evenfire-bot-2'+ 'Evenfire Bot 2')})})++/**+ * deleteConversation persists a full spec through persistDraft without going+ * anywhere near handleSave, so a check that lived only in handleSave let it+ * write a value Save would refuse. Validation lives on persistDraft, the one+ * boundary both paths cross.+ */+describe('EditCommunicationChannelPage conversation delete validation', () => {+ const TEAMS_CONVERSATION = {+ channelId: '19:[email protected]',+ tenantId: '21e08d37-8d53-4144-87cb-557b8298aed3',+ conversationType: 'channel',+ title: 'General',+ confirmedAt: '2026-07-10T12:00:00Z',+ }++ async function openTeamsTabWithConversation(appName: string) {+ mockChannel('teams-channel', {+ teamsSettings: { appName, appId: '', tenantId: '' },+ teams: [TEAMS_CONVERSATION],+ })+ await renderLoadedPage()+ const user = userEvent.setup()+ await user.click(await screen.findByRole('radio', { name: /microsoft teams/i }))+ return user+ }++ it('deletes a conversation through the same validation as Save', async () => {+ const user = await openTeamsTabWithConversation('My Bot')++ await user.click(screen.getByRole('button', { name: 'Delete General' }))+ await user.click(await screen.findByRole('button', { name: 'Delete conversation' }))++ await waitFor(() => expect(api.apiSend).toHaveBeenCalled())+ const [, , body] = vi.mocked(api.apiSend).mock.calls[0] as [string, string, { spec: unknown }]+ const spec = body.spec as { teams: unknown[]; teamsSettings: { appName: string } }+ expect(spec.teams).toEqual([])+ expect(spec.teamsSettings.appName).toBe('My Bot')+ })++ it('refuses to delete a conversation while the Name field holds a value Save would refuse', async () => {+ const user = await openTeamsTabWithConversation('evenfire')++ const nameInput = screen.getByLabelText(/^name$/i) as HTMLInputElement+ await user.clear(nameInput)+ fireEvent.change(nameInput, { target: { value: 'a'.repeat(81) } })++ await user.click(screen.getByRole('button', { name: 'Delete General' }))+ await user.click(await screen.findByRole('button', { name: 'Delete conversation' }))++ expect(+ await screen.findByText('Teams bot name must be 80 characters or fewer.')+ ).toBeInTheDocument()+ // The whole point: this path used to persist a spec Save rejects.+ expect(api.apiSend).not.toHaveBeenCalled()+ })+})diff --git a/control-ui/lib/__tests__/teamsSetup.test.ts b/control-ui/lib/__tests__/teamsSetup.test.tsindex 17278121c..58d10a470 100644--- a/control-ui/lib/__tests__/teamsSetup.test.ts+++ b/control-ui/lib/__tests__/teamsSetup.test.ts@@ -1,11 +1,25 @@import { describe, expect, it } from 'vitest'-import { buildTeamsAppCreateCommand, canGenerateTeamsCommand } from '../teamsSetup'+import {+ LOCAL_TEAMS_ENDPOINT_ORIGIN,+ TEAMS_APP_NAME_MAX_LENGTH,+ buildTeamsAppCreateCommand,+ canGenerateTeamsCommand,+ teamsAppNameError,+ teamsPlaceholderEndpoint,+} from '../teamsSetup'describe('canGenerateTeamsCommand', () => {it('accepts an absolute https URL', () => {expect(canGenerateTeamsCommand('https://webhook.dev.example.com/webhooks/teams/x')).toBe(true)})+ it('rejects an http origin, which Microsoft cannot use as a messaging endpoint', () => {+ // Mirrored from the Slack helper, which accepts http. Teams requires a+ // publicly reachable HTTPS endpoint, so an http origin has to render the+ // invalid-origin warning rather than a command that registers a dead bot.+ expect(canGenerateTeamsCommand('http://webhook.dev.example.com/webhooks/teams/x')).toBe(false)+ })+it('rejects a bare path, which is what a non-app deployment produces', () => {expect(canGenerateTeamsCommand('/webhooks/teams/x')).toBe(false)})@@ -15,6 +29,50 @@ describe('canGenerateTeamsCommand', () => {})})+describe('teamsPlaceholderEndpoint', () => {+ it('prefixes a bare path with the marker origin', () => {+ expect(teamsPlaceholderEndpoint('/webhooks/teams/x')).toBe(+ `${LOCAL_TEAMS_ENDPOINT_ORIGIN}/webhooks/teams/x`+ )+ })++ it('drops the origin of a rejected http URL instead of concatenating onto it', () => {+ // Now that canGenerateTeamsCommand rejects http, this branch also receives+ // ABSOLUTE urls. Concatenation would render+ // https://<public-webhook-origin>http://webhook.example.com/webhooks/teams/x.+ expect(teamsPlaceholderEndpoint('http://webhook.example.com/webhooks/teams/x')).toBe(+ `${LOCAL_TEAMS_ENDPOINT_ORIGIN}/webhooks/teams/x`+ )+ })+})++describe('teamsAppNameError', () => {+ it('accepts a free-form display name with spaces and capitals', () => {+ // The CRD declares appName with no pattern and control-api checks only+ // emptiness and length, so this is a legitimate stored value.+ expect(teamsAppNameError('My Bot')).toBeNull()+ })++ it('accepts a kebab-cased name too', () => {+ expect(teamsAppNameError('evenfire-bot')).toBeNull()+ })++ it('rejects an empty name', () => {+ expect(teamsAppNameError('')).toBe('Teams bot name is required.')+ expect(teamsAppNameError(' ')).toBe('Teams bot name is required.')+ })++ it('accepts a name of exactly the server limit', () => {+ expect(teamsAppNameError('a'.repeat(TEAMS_APP_NAME_MAX_LENGTH))).toBeNull()+ })++ it('rejects a name past the server limit', () => {+ expect(teamsAppNameError('a'.repeat(TEAMS_APP_NAME_MAX_LENGTH + 1))).toBe(+ 'Teams bot name must be 80 characters or fewer.'+ )+ })+})+describe('buildTeamsAppCreateCommand', () => {it('renders the command with the bot name and endpoint', () => {const cmd = buildTeamsAppCreateCommand({@@ -25,4 +83,12 @@ describe('buildTeamsAppCreateCommand', () => {expect(cmd).toContain('--endpoint "https://webhook.dev.example.com/webhooks/teams/x"')expect(cmd).toContain('--env .env')})++ it('quotes a display name with spaces, so it survives as one argument', () => {+ const cmd = buildTeamsAppCreateCommand({+ botName: 'My Bot',+ endpoint: 'https://webhook.dev.example.com/webhooks/teams/x',+ })+ expect(cmd).toContain('--name "My Bot"')+ })})diff --git a/control-ui/lib/teamsSetup.ts b/control-ui/lib/teamsSetup.tsindex 156b9584e..ed6826dfb 100644--- a/control-ui/lib/teamsSetup.ts+++ b/control-ui/lib/teamsSetup.ts@@ -1,5 +1,3 @@-import { toKebabInput } from './string'-/*** Placeholder origin shown in guidance copy, and used to build a placeholder* command, when the deployment has no public webhook address to substitute.@@ -9,36 +7,63 @@ import { toKebabInput } from './string'*/export const LOCAL_TEAMS_ENDPOINT_ORIGIN = 'https://<public-webhook-origin>'-const TEAMS_BOT_NAME_RE = /^[a-z][a-z0-9-]{1,62}[a-z0-9]$/+/**+ * Longest `spec.teamsSettings.appName` control-api accepts+ * (validateCommunicationChannelSpec).+ */+export const TEAMS_APP_NAME_MAX_LENGTH = 80/**- * Teams CLI `--name` constraint: lowercase letters, numbers, and hyphens,- * starting with a letter. Shared by the create and edit pages so both gate- * Copy on the same rule instead of one silently drifting from the other.+ * The one rule for a Teams app name, mirroring the server contract exactly:+ * non-empty after trimming, at most TEAMS_APP_NAME_MAX_LENGTH characters.+ *+ * It is a free-form DISPLAY name, so spaces and capitals are legitimate: the+ * CRD declares `appName` as a plain string with no pattern (unlike `tenantId`+ * right below it, which does carry one), control-api checks only emptiness and+ * length (unlike `appId`, which carries a UUID regex), and the Teams CLI+ * documents `--name` as "App/bot name" with `--name "My Bot"` as its own+ * example. A stricter UI rule would reject names Teams and the server both+ * accept, and would block saving a channel whose stored name predates the rule.+ *+ * Returns the message to show, or null when the value is acceptable. Callers+ * share this one function so no page can drift onto its own rule.*/-export function isValidTeamsBotName(value: string): boolean {- return TEAMS_BOT_NAME_RE.test(value.trim())+export function teamsAppNameError(value: string): string | null {+ const trimmed = value.trim()+ if (!trimmed) return 'Teams bot name is required.'+ if (trimmed.length > TEAMS_APP_NAME_MAX_LENGTH) {+ return `Teams bot name must be ${TEAMS_APP_NAME_MAX_LENGTH} characters or fewer.`+ }+ return null}/**- * Normalizes free-typed input into the Teams CLI `--name` shape as the user- * types, so the field can never hold something isValidTeamsBotName rejects- * except through an empty or in-progress value. Shared by the create and edit- * pages so both normalize on the same rule instead of one drifting from the- * other -- which is how the edit page persisted a raw, unvalidated name.+ * The Teams CLI needs an absolute endpoint, and Microsoft requires a publicly+ * reachable HTTPS one: a bot registered against `http://` cannot receive+ * activities. A deployment with no NEXT_PUBLIC_WORKFLOW_APPROVAL_READER_BASE_URL+ * and a hostname that does not start with `app.` produces a bare path, which+ * would point a bot at a host that does not exist. Unlike+ * canGenerateSlackAppManifest, this deliberately does not accept `http://`.*/-export function toTeamsBotNameInput(value: string): string {- return toKebabInput(value).slice(0, 64)+export function canGenerateTeamsCommand(endpoint: string | null | undefined): boolean {+ return /^https:\/\//i.test(endpoint ?? '')}/**- * The Teams CLI needs an absolute endpoint. A deployment with no- * NEXT_PUBLIC_WORKFLOW_APPROVAL_READER_BASE_URL and a hostname that does not- * start with `app.` produces a bare path, which would register a bot pointing- * at a host that does not exist. Mirrors canGenerateSlackAppManifest.+ * Endpoint to render when canGenerateTeamsCommand said no: the marker origin+ * plus the reader path, for the operator to substitute by hand.+ *+ * The rejected value is usually a bare path (the minikube case), but it can+ * also be an absolute `http://` URL, from an http+ * NEXT_PUBLIC_WORKFLOW_APPROVAL_READER_BASE_URL or from browsing an `app.` host+ * over http. Concatenating that onto the marker would render+ * `https://<public-webhook-origin>http://host/path`, so the origin is dropped+ * and only the path is kept.*/-export function canGenerateTeamsCommand(endpoint: string | null | undefined): boolean {- return /^https?:\/\//i.test(endpoint ?? '')+export function teamsPlaceholderEndpoint(endpoint: string): string {+ const origin = endpoint.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i)+ const path = origin ? endpoint.slice(origin[0].length) : endpoint+ return `${LOCAL_TEAMS_ENDPOINT_ORIGIN}${path.startsWith('/') ? path : `/${path}`}`}/**diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex a229d7083..45902cdb2 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.421",+ "version": "0.1.422","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.421",+ "version": "0.1.422","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 58e9ccfbd..fd327fd2e 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.421",+ "version": "0.1.422","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",