Skip to content

feat(portal): allow editing Azure AI Foundry model - #1411

Open
Vv (dcaiwei) wants to merge 4 commits into
microsoft:mainfrom
dcaiwei:candidate/scope-1386
Open

Vv (dcaiwei) wants to merge 4 commits into
microsoft:mainfrom
dcaiwei:candidate/scope-1386

Conversation

@dcaiwei

Copy link
Copy Markdown

Summary

  • expose only the non-secret Azure AI Foundry model name on key detail responses
  • allow users to update or clear the model while preserving the endpoint and API key
  • mark validation pending and revalidate the deployment after a model change
  • add focused frontend/backend tests, a synthetic Storybook demo, and documentation

Fixes #1386

Demo

Azure AI Foundry model edited from gpt-4.1 to gpt-4.1-mini with synthetic data, followed by background validation.

9.22.mp4

Testing

  • pnpm exec vitest run packages/shared/src/token-manager/types.test.ts apps/token-manager/src/foundry-model.test.ts apps/portal/src/pages/TokenDetail.test.ts — passed (14 tests)
  • pnpm --filter shared build — passed
  • pnpm --filter telemetry build — passed
  • pnpm --filter token-manager build — passed
  • pnpm --filter portal lint — passed
  • pnpm headers:check — passed
  • git diff --check — passed

Documentation and compatibility

Updated docs/architecture/token-manager.md.

The API changes are additive and backward-compatible. No database migration or dependency change is required.

Checklist

  • CLI parity considered — key administration has no corresponding CLI surface today.
  • Added a Storybook story for the updated Portal interaction.
  • No database migration is required.
  • No dependency or notice changes are required.

AI assistance was used while preparing this change. The implementation and test results were reviewed locally before submission.

@dcaiwei

Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Unresolved backend consistency, validation, and data-safety issues must be addressed before approval.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 2 High severity · 1 Medium severity

Open (3)
What changed in this PR

Enables editing Azure AI Foundry model names while preserving credentials and triggering revalidation.

Changes:

  • Adds backend model projection, updates, and validation handling.
  • Adds Portal editing UI, tests, and Storybook demo.
  • Updates shared types and documentation.
File Reviewed change
packages/​shared/​src/​token-manager/​types.ts Extends shared key and update request types.
docs/​architecture/​token-manager.md Documents model editing and validation behavior.
apps/​token-manager/​src/​routes.ts Handles model updates and background validation.
apps/​token-manager/​src/​foundry-model.ts Projects and updates Foundry model data.
apps/​token-manager/​src/​foundry-model.test.ts Tests Foundry model helpers.
apps/​portal/​src/​types.ts Adds frontend model types.
apps/​portal/​src/​pages/​TokenDetail.tsx Adds model editing controls and polling behavior.
apps/​portal/​src/​pages/​TokenDetail.test.ts Tests update request construction.
apps/​portal/​src/​pages/​TokenDetail.stories.tsx Adds a synthetic editing demo.
apps/​portal/​src/​pages/​token-detail-utils.ts Builds normalized update requests.
apps/​portal/​src/​lib/​api.ts Documents the expanded update API.

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread apps/token-manager/src/routes.ts Resolved
Comment thread apps/token-manager/src/routes.ts Resolved
Comment thread apps/token-manager/src/foundry-model.ts Resolved
@cedricvidal

Cedric Vidal (cedricvidal) commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Vv (@dcaiwei) thank you for your contribution!

Before vs. after for Azure AI Foundry key handling:

Aspect Before PR After PR
Secret model field Embedded in opaque secret JSON, not surfaced as a separate field Projected as a non-secret model field
API response No model property exposed in detail responses model included for Azure AI Foundry tokens
Editing behavior Could not update deployment/model independently PUT /api/v1/keys/:id accepts model for Azure AI Foundry
Secret mutation Would require rewriting the whole secret blob Only rewrites the model property, preserving endpoint/API key
Portal UX No model/deployment input Shows “Deployment / Model name” only for Azure AI Foundry keys
Validation Stale validation result could remain after model change Resets to unknown and revalidates immediately after model update

Example shape:

Before:

  • stored secret: { "endpoint": "...", "apiKey": "...", "model": "gpt-4.1" }
  • UI/API: no explicit model field exposed

After:

  • stored secret: still { "endpoint": "...", "apiKey": "...", "model": "gpt-4.1" }
  • API/UI: model: "gpt-4.1" is surfaced and editable without exposing endpoint or apiKey

Wassim Chegham (@manekinekko) Josh Duffney (@duffney) this looks like something we should do. Would you be able to look into it?

@cedricvidal

Copy link
Copy Markdown
Collaborator

Vv (@dcaiwei) checks are failing, would you be able to fix CI and address Copilot reviews?

@dcaiwei

Copy link
Copy Markdown
Author

Cedric Vidal (@cedricvidal) Thanks for the review. I’ve pushed a follow-up that addresses the failing build and all three Copilot findings:

  • fixed the Portal type error by guarding against an unavailable token;
  • persist the MongoDB validation state as unknown before writing the updated Foundry secret, so a partial cross-store update cannot leave the key looking valid;
  • guard background validation updates with the edit’s updatedAt revision so stale results are discarded;
  • degrade Foundry detail responses to metadata-only when Key Vault is temporarily unavailable;
  • added focused route/helper tests and updated the Token Manager architecture docs.

Focused validation passes: 17 tests, Token Manager build, Portal typecheck/production build, and git diff --check.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this. Being able to edit the deployment without re-entering the key is a real gap, and marking the key unknown before the Key Vault write is the right call. Tests, the token-manager build, and the Portal typecheck all pass locally.

One blocking issue: the Portal sends model on every save of a Foundry key, so a plain metadata edit rewrites the secret and resets validation. It can also wipe the stored model if the earlier Key Vault read failed. Details are inline, plus two smaller notes on how the background validation result is guarded.

Comment on lines +23 to +25
...(type === "azure-ai-foundry"
? { model: foundryModel.trim() || null }
: {}),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This sends model on every save of a Foundry key, even if the user only toggled enabled or edited the comment. The server treats any model field as a change, so a plain metadata edit rewrites the Key Vault secret, sets the key to unknown (so it can't be acquired), and revalidates it.

It can also lose data. withFoundryModel is best-effort, so if the Key Vault read fails on GET, token.model comes back undefined and the field shows "Provider default". If the user then saves anything, we send model: null and wipe the stored deployment name.

Can we send model only when it differs from what was loaded? For example, pass currentModel: token.model in here and include model only when foundryModel.trim() !== (currentModel ?? ""). A test for the "unchanged model, other field edited" case would cover it.

}

let foundrySecretValue: string | undefined;
if (body.model !== undefined) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

To protect API clients too (not just the Portal), could the server skip the rewrite when the requested model matches what's already stored? buildFoundryModelSecret already parses the current secret, so it could return a "no change" signal, and then we skip setSecret, the unknown reset, and the revalidation.

Comment thread apps/token-manager/src/routes.ts Outdated
.then(async (validation) => {
const now = new Date();
await collection.updateOne(
{ _id: result._id, updatedAt: updateRevision },

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Guarding on updatedAt: updateRevision correctly drops stale results, but any later PUT bumps updatedAt, including one that only changes the comment. If that happens before validation finishes, the result is thrown away and the key stays unknown (not acquirable) until someone validates it manually.

Could we use a dedicated field, e.g. a validationRevision set only when the model changes, so metadata-only edits don't cancel an in-flight validation? Or at least note the manual-revalidate fallback in the docs.

if (foundrySecretValue) {
// Persist the fail-safe pending state before changing Key Vault. If the
// secret write fails, the key cannot remain valid with stale capabilities.
await store.setSecret(result.secretName, foundrySecretValue);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Two quick model edits can race: A marks pending, B marks pending, B writes Key Vault, then A writes Key Vault. B's validation passes the revision guard and marks the key valid for B's model, while Key Vault now holds A's. It's unlikely in practice, but worth a comment, or have the background job validate the value read back from Key Vault instead of the captured foundrySecretValue.

Comment thread apps/portal/src/pages/TokenDetail.tsx Outdated
placeholder="e.g. gpt-4.1-mini"
/>
<p className="text-xs text-muted-foreground">
Clear this field to use the default model.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Small thing: the default isn't the same everywhere. The validator probes gpt-4.1, but apps/api/src/llm-token.ts uses LLM_MODEL || "gpt-4.1". Something like "Clear to use the provider default (gpt-4.1)" would be clearer, or leave it as is if LLM_MODEL is expected to vary per deployment.

@manekinekko Wassim Chegham (manekinekko) added area: portal Scope web portal, pages, and user-facing components. language: javascript Work involving JavaScript code, tooling, or dependencies. topic: security Security protections, vulnerabilities, and risk reduction. topic: testing Test coverage, test infrastructure, and validation quality. topic: ui Portal, visual presentation, layout, and interface components. type: documentation Documentation additions, corrections, and improvements. type: enhancement New functionality or improvements to existing behavior. area: shared Shared package: types, DB models, and queue/blob/redis clients used by all apps. labels Oct 1, 2026
@cedricvidal Cedric Vidal (cedricvidal) added the community-contribution Pull requests submitted by external community contributors. label Oct 7, 2026
@cedricvidal

Copy link
Copy Markdown
Collaborator

Hello Vv (@dcaiwei) , this is a useful contrib, would love to merge it. Let me know if the feedback I gave make sense

@dcaiwei

Vv (dcaiwei) commented Oct 15, 2026 •

Copy link
Copy Markdown
Author

Cedric Vidal (@cedricvidal) Thanks for the detailed review. I've pushed d4c1a50 to address the blocking metadata-save issue and the follow-up notes:

  • The Portal sends model only when the trimmed input differs from the loaded value. An omitted model after a failed Key Vault read therefore stays omitted on a metadata-only save; explicitly clearing a loaded override still sends null.
  • The server independently compares against a fresh Key Vault read. An unchanged model skips the secret write, validation reset, and background validation.
  • Background model validation now uses a UUID validationRevision that changes only with the model, so metadata edits do not discard an in-flight result and same-millisecond edits cannot share a revision.
  • Validation reads the stored credential back with the local cache bypassed. I also documented the remaining cross-store race, as suggested: this does not serialize concurrent MongoDB/Key Vault writes; overlapping model edits may still require confirming the final stored model and manually revalidating after writes finish.
  • The UI now says "configured default model", and the docs explain the validator/runtime defaults.

Validation: 125 relevant tests passed; shared, telemetry, Token Manager, and Portal production builds passed; license-header and diff checks passed. Both new Storybook interactions were exercised in headless Edge, including the missing-model projection case; both metadata-only PUT requests omitted model.

For transparency, the full local Windows suite was also attempted and is not green (38 test files failed, including Portal alias resolution and POSIX-path assertions). Root lint cannot find eslint locally, while Portal typechecking passes. Docker integration tests could not run because the local engine is unavailable. The new CI run currently reports action_required with zero jobs started; Secret Scan and Pull Request Labeler report the same status. Repository-side action is needed before the new workflows can execute, so CI has not yet validated this commit.

Could you take another look when CI completes? AI assistance was used for this follow-up; the diff and the validation results above were checked locally.

@manekinekko

Copy link
Copy Markdown
Member

Hi Vv (@dcaiwei), sorry your last follow-up went unanswered. Thanks for documenting the changes addressing the metadata-save findings and clearly separating local validation from the CI approval blocker. We still owe you a review of the updated revision and a check of the workflow approval status. I appreciate your patience.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for addressing the metadata-only save and revision issues, and for documenting the remaining cross-store limitation. The changed-only payload, server-side no-op check, and dedicated validation revision are substantial improvements.

I reviewed d4c1a50 and still think this needs changes before merging. The three blocking findings are inline:

  1. Old manual/scheduled validation can overwrite the result for a newer model, making an invalid stored model look valid again.
  2. Clicking Validate replaces the Portal detail cache with a response that omits the model projection, so an existing override appears to be the default and cannot be cleared from that state.
  3. Detail refetches overwrite unsaved model input, while Cancel retains that input for the next edit.

Please also address failure/recovery feedback. If the Key Vault write fails after Mongo has been marked unknown, the Portal's update mutation shows no error and does not refresh the failed-save state. The editor stays open without explaining what happened, and the cached status can remain valid despite the persisted pending state. Preserve the draft, show the error, and reconcile the server state. Background readback failures need a terminal, revision-guarded error state as noted inline.

Regression coverage: the focused existing tests pass, but TokenDetail.test.ts covers payload construction rather than the rendered page. AzureAiFoundryModelEdit has no play function, and the metadata-only page plays are not registered in the existing ui-only Vitest story harness; I found no CI Storybook interaction runner at this head. Please add automated rendered coverage for edit/clear -> pending -> result, Validate preserving the model, refetch during editing, Cancel, and failed-save recovery, plus manual/scheduler validation racing a model edit. Five scratch component/handler cases reproduced the reported draft, cache, validation, and error-feedback behavior.

Documentation/API: the architecture docs are helpful, but the claim that a partial update cannot leave an unvalidated deployment available is too strong until all validation writers participate in the revision guard. Document partial-failure recovery and distinguish no override from unreadable model data. The generic KeyInput/KeyResponse OpenAPI schemas also do not advertise the new Foundry-only model string/null contract; the API proxy forwards the field correctly, so this is a documentation gap rather than field stripping. No CLI key/model-update command was found at this head: that is a pre-existing parity gap widened by this Portal action, so please make its intended scope explicit rather than treating it as a newly broken CLI command.

Validation: 43 focused tests passed across the route, Foundry helper, vault store, validators, and Portal payload helper. Portal tsc -b and shared/telemetry/token-manager builds passed using Node 22.22.0. I inspected the rendered desktop/light Storybook form; its local Save request returned an unhandled PUT 404, so I am not treating that browser session as successful end-to-end save/clear validation or attributing the local failure to production code.

No exploitable security vulnerability was confirmed in the affected credential paths. The stale-validation finding is a correctness/availability issue, not a claim of credential disclosure. I did not run live Azure/provider calls, live multi-instance MongoDB/Key Vault concurrency tests, or a complete accessibility audit. The previously documented two-PUT secret-write-order race is not being re-reported as a new finding.

await collection.updateOne(
{
_id: result._id,
validationRevision: result.validationRevision,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[P1] Apply the credential revision guard to every validation writer. This protects the new PUT background job, but the manual validation route below still writes by _id alone, as do the scheduled success/error writes in token-scheduler.ts.

I reproduced this with the actual handlers: start manual validation of model A and pause its result; save model B and let its new validation return invalid; then complete A's older validation with valid. Mongo now says valid with inference capability while Key Vault still contains B. That makes the failed stored model eligible for acquisition again.

Please guard manual and scheduled writes using the revision captured for the credential they validated, including error writes, and ensure their reads are fresh across model edits/multiple instances rather than using a stale local secret cache. Add manual-versus-edit and scheduler-versus-edit regression cases. The old writers predate this PR, but mutable model credentials need them to participate in the new safety invariant.

) : (
<p className="text-sm">
{token.model || (
<span className="text-muted-foreground">Provider default</span>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[P2] Preserve the model projection after clicking Validate. The manual-validation response in routes.ts returns { ...token, ...update } from Mongo without withFoundryModel, and validateMutation.onSuccess replaces this page's cached detail document with that response.

Load a key with an override, click Validate, then Edit: the label becomes "Provider default" and the model editor is empty, although the override remains in Key Vault. Once validation is valid, this query no longer polls, and saving the empty input omits model, so it cannot express clearing the still-stored override from that state. I confirmed the missing route response property and rendered cache/editor behavior in separate scratch tests.

Please return the same non-secret projection from responses that replace the detail document, or refetch the complete detail after validation. Add a rendered Validate -> Edit/clear regression test.

setExpiresAt(token.expiresAt ? new Date(token.expiresAt).toISOString().slice(0, 16) : "");
setComment(token.comment ?? "");
setFoundryModel(token.model ?? "");
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[P2] Preserve dirty model input on refetch and discard it on Cancel. This effect runs whenever a changed detail result arrives, including when pending validation finishes or a focus refetch brings a changed timestamp. I reproduced typing an unsaved model and receiving a changed detail response: this assignment replaces the draft with the stored model.

The opposite happens on Cancel: Edit -> type another model -> Cancel -> Edit retains the supposedly cancelled model, since those buttons only toggle editing. A later Save can submit it.

Please initialize an editing snapshot on entry, avoid overwriting a dirty draft during background updates, and reset it explicitly on Cancel. Add rendered regression coverage for both flows. The metadata fields share the existing lifecycle pattern, but the new credential editor makes the behavior consequential for model selection.

}
);
})
.catch((err) => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[P2] Persist a revision-guarded error state when background readback/validation fails. After the model write succeeds, a rejected fresh Key Vault read reaches this catch and only logs. Mongo remains unknown, so the Portal continues polling without explaining the failure until another validator succeeds; a disabled key is not picked up by the periodic scheduler.

Please transition the matching, non-deleted credential revision to a terminal error/recovery state without letting an older failure overwrite a newer edit. Keep the logging, but also make the failure actionable to the user. Add a readback-rejection test that checks the persisted status and Portal recovery behavior. This catch-path finding is from source inspection rather than a live Key Vault fault-injection test.

placeholder="e.g. gpt-4.1-mini"
/>
<p className="text-xs text-muted-foreground">
Clear to use the configured default model.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Non-blocking: make default/unavailable-model wording precise. "Configured default model" here and "Provider default" in the read-only view describe different things. Clearing the override validates gpt-4.1, while runtime inference may use LLM_MODEL; the architecture docs already explain that mismatch, but the UI does not.

Also, a failed model projection currently looks exactly like a known absent override. Please distinguish "no override" from "unable to read the override" rather than asserting a default after a read failure, and use wording that accurately describes the validation/runtime fallback. Connect this help text to the input with aria-describedby.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: portal Scope web portal, pages, and user-facing components. area: shared Shared package: types, DB models, and queue/blob/redis clients used by all apps. community-contribution Pull requests submitted by external community contributors. language: javascript Work involving JavaScript code, tooling, or dependencies. topic: security Security protections, vulnerabilities, and risk reduction. topic: testing Test coverage, test infrastructure, and validation quality. topic: ui Portal, visual presentation, layout, and interface components. type: documentation Documentation additions, corrections, and improvements. type: enhancement New functionality or improvements to existing behavior.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow editing Azure AI Foundry model

4 participants