Skip to content

feat(vertex): add Vertex AI provider with Service Account/ADC auth and live model listing - #809

Open
Razor573 wants to merge 6 commits into
wangzan101:mainfrom
Razor573:pr/vertex-ai-provider
Open

Razor573 wants to merge 6 commits into
wangzan101:mainfrom
Razor573:pr/vertex-ai-provider

Conversation

@Razor573

Copy link
Copy Markdown
Contributor

Summary

Adds Vertex AI as a first-class model provider in Mika, supporting Google Cloud Service Account JSON (RS256 JWT exchange with automatic caching/refresh) and Application Default Credentials / OAuth2 bearer tokens against the Vertex AI generateContent API.

What's included

  • Auth & Endpoints (core/oauth/VertexAuth.kt):
    • VertexServiceAccount: parses Service Account JSON (client_email, private_key, project_id, token_uri), builds & signs RS256 JWTs, and exchanges them for short-lived OAuth2 bearer tokens.
    • VertexTokenProvider: implements BearerToken with thread-safe in-memory token caching, early expiry refresh, and single-flight refresh on 401.
    • VertexEndpoints: builds regional (https://{location}-aiplatform.googleapis.com) and global (https://aiplatform.googleapis.com) generateContent and publisher-model listing URLs.
  • Vertex AI Adapter & Shared Codec (core/model/VertexModel.kt, core/model/GeminiCodec.kt):
    • VertexModel: implements ChatModel over Vertex AI generateContent with Authorization: Bearer <token>, 401 refresh-and-retry, 429/5xx error classification, multimodal images, tool calls, and reasoning effort.
    • GeminiCodec: shared request/response codec for generateContent payloads used by VertexModel.
  • Live + Curated Model Catalog (core/model/ModelCatalog.kt):
    • Live paginated catalog.vertex(...) listing from Vertex AI publisher models (global with automatic us-central1 fallback), filtering out non-chat models (imagen, veo, embedding, chirp, lyria, etc.).
    • Merged with CURATED_VERTEX_MODELS: Gemini 4 Hydrogen (gemini-4-hydrogen), Gemini 3.8 Flash (gemini-3.8-flash), and Gemini 3.5 Flash-Lite (gemini-3.5-flash-lite), plus custom model ID fallback via manual entry.
  • App Wiring & Encrypted Storage (app/.../settings/ProviderStore.kt, ProviderPresets.kt, ProviderKeySites.kt, ReasoningOptions.kt, AllowanceRoute.kt, ui/ModelSetupScreen.kt, ui/ModelsScreen.kt):
    • Added ProviderConfig.Kind.Vertex and the Vertex AI preset (https://aiplatform.googleapis.com).
    • Credentials (Service Account JSON or bearer token) are stored exclusively in ProviderStore's encrypted KeyCipher / Android Keystore storage (provider-keys.json), never in plaintext providers.json.
    • Optional projectId and location fields on Provider (automatically falls back to project_id embedded in the Service Account JSON and global location).
    • Regenerated README.md and docs/readme/README.zh-CN.md via ./gradlew updateReadme.
  • Tests:
    • VertexAuthTest, VertexModelTest (including curated model assertions), GeminiCodecTest.

Adaptations for upstream main

  • Based directly on upstream wangzan101/Mika:main (9c7aabd8) with zero fork-specific code (no branding/package changes, no Antigravity, no unrelated UI rewrites).
  • Removed fork-only CallOptions / forceToolCall wiring from VertexModel and GeminiCodec so this PR is completely standalone and cleanly compiles against upstream ChatModel.
  • Added probe fallback in ProviderStore.buildModel so Service Account JSON works both during pre-save "Test & Save" probes and after saving in encrypted storage.

How to test

  1. Run unit tests:
    ./gradlew :core:test --tests "*VertexAuthTest*" --tests "*VertexModelTest*" --tests "*GeminiCodecTest*" --tests "*ModelCatalogTest*" --tests "*Readme*"
    python3 tools/i18n/translations.py check
  2. In the app: Settings › Models › Add Provider › Vertex AI, paste either a Google Cloud Service Account JSON or an OAuth2/ADC bearer token, tap Test & Save, verify live + curated models (gemini-4-hydrogen, gemini-3.8-flash, gemini-3.5-flash-lite) and manual custom model ID entry, and run a chat/tool call.

Copilot AI balanced review requested due to automatic review settings November 22, 2026 16:06

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T16:11:43.708605Z f3e9638 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f3e9638a24

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

ProviderConfig.Kind.Vertex -> {
val p = provider(cfg.providerId)
val raw = apiKey.orEmpty().trim()
val token: BearerToken = if (raw.startsWith("{")) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve service-account JSON before selecting the token provider

When a user pastes a service-account JSON, probe() and apiKey() first pass it through KeyPoolManager.parseKeys(), which splits on commas and newlines. raw here is therefore a field fragment rather than the JSON object, so this branch selects BearerToken.fixed and sends that fragment as a bearer token instead of using VertexTokenProvider; initial testing and subsequent chats with service-account credentials fail. Preserve or detect the raw JSON before key-pool parsing.

Useful? React with 👍 / 👎.

val parsedProject = if (raw.startsWith("{")) {
runCatching { VertexServiceAccount.parse(raw).projectId }.getOrDefault("")
} else ""
val project = p?.projectId?.trim().orEmpty().ifBlank { parsedProject }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Collect a project ID for pasted OAuth bearer tokens

When a user supplies an OAuth/ADC bearer token instead of service-account JSON, parsedProject is empty and a newly connected provider keeps the blank default projectId; the setup UI has no field that populates it. This passes an empty ID to VertexModel, whose constructor rejects it before making a request, so bearer-token users cannot test or use models. Collect a project ID or provide another reliable source for it.

Useful? React with 👍 / 👎.

.withHeaders(headers)
.removeHeader("x-goog-api-key")
.headerOrReject("Authorization", "Bearer $accessToken")
.headerOrReject("x-goog-user-project", cleanProjectId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid forcing a quota-project header without its permission

If a service-account caller has permission to invoke Vertex AI but lacks serviceusage.services.use on this project, setting x-goog-user-project makes Google treat it as the quota project and reject the request with 403, even though the project is already present in the resource URL. Omit this header unless a separate quota project is explicitly configured.

Useful? React with 👍 / 👎.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants