Repository navigation
feat(design): add provider abstraction with Gemini support - #998
Closed
SkipSupreme wants to merge 1 commit into
Closed
SkipSupreme wants to merge 1 commit into
SkipSupreme wants to merge 1 commit into
Conversation
Refactor the design tool to support multiple AI providers behind a
DesignProvider interface. Adds Google Gemini (gemini-3-pro-image-preview,
aka Nano Banana 2) as the new default provider, with OpenAI (gpt-4o image
generation + vision) available as a legacy option.
## Provider resolution
1. GSTACK_DESIGN_PROVIDER env var ("gemini" | "openai", case/whitespace
tolerant; unknown values warn and fall through)
2. Auto-detect: prefer Gemini if a Gemini key is available, else OpenAI
3. Cached for the process lifetime via a module-level singleton; reset
via providers/factory.resetProvider() (used by tests)
## New files
- design/src/providers/provider.ts — DesignProvider interface, request/
response option types, ProviderError class, ProviderName type, shared
GEMINI_KEY_URL / OPENAI_KEY_URL constants
- design/src/providers/factory.ts — getProvider() resolver
- design/src/providers/openai.ts — OpenAIProvider (Responses API image
generation + Chat Completions vision)
- design/src/providers/gemini.ts — GeminiProvider (generateContent for
both image and vision modalities)
- design/test/providers.test.ts — 33 smoke tests (mocks globalThis.fetch,
covers request shape, response parsing, error surfaces, behavioral
invariants, transport-failure normalization)
## Migrated call sites (9)
generate.ts, variants.ts, iterate.ts, evolve.ts, check.ts,
design-to-code.ts, diff.ts, memory.ts, cli.ts
Each now imports getProvider() from ./providers/factory instead of
building fetch calls inline.
## Capability flags — real differences, not fiction
- supportsImageRef(): Gemini natively accepts a reference image for
image-to-image (evolve.ts). OpenAI's image_generation tool does not,
so the OpenAI path falls back to vision-then-generate.
- supportsThreading(): OpenAI uses previous_response_id from the
Responses API. Gemini has no equivalent and THROWS if a caller passes
previousResponseId (loud failure beats silent one). Callers must
check supportsThreading() first.
## Size mapping
OpenAI-style "1536x1024" size strings are mapped to the nearest Gemini
aspect ratio via a static 10-entry nearest-neighbor table (1:1, 2:3,
3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9). Unparseable sizes fall back
to "16:9".
## Auth
design/src/auth.ts now exports resolveGeminiKey / saveGeminiKey alongside
resolveOpenAIKey / saveOpenAIKey, backed by a shared readKeyFromFile /
saveKeyToFile helper pair. Legacy resolveApiKey / saveApiKey /
requireApiKey stay as @deprecated shims that delegate to the OpenAI path
so any consumer outside design/ keeps working.
Gemini key resolution order: ~/.gstack/gemini.json → GEMINI_API_KEY →
GOOGLE_API_KEY → null.
## Setup flow
cli.ts setup prompts for Gemini first (the new default), accepts sk-
prefixed keys as OpenAI and anything else as Gemini. Existing users with
a saved OpenAI key are given a one-line path to add Gemini alongside.
## Error contract (ProviderError)
ProviderError.retryable is advisory metadata flagged to true on
transient errors: 429, any 5xx, AbortError (timeout), and raw transport
failures (DNS/TLS/socket/ECONNRESET/Failed to fetch). Providers do NOT
retry — the flag is a hint callers can use to drive backoff. All four
fetch call sites (image+vision × 2 providers) funnel through a per-file
normalizeError() helper that:
- passes through existing ProviderError untouched (org verify,
no-image-data, etc. keep their original status/message)
- wraps AbortError as "{context} request timed out after {timeoutMs}ms"
- wraps any other thrown value (raw TypeError, network failures,
unexpected exceptions) as "{context} transport error: {message}"
Callers (variants.ts retry logic, diff.ts graceful degradation) can now
rely on always seeing a ProviderError, not a bare TypeError.
## Behavior changes worth flagging to reviewers
1. OpenAI vision content ordering normalized. Previously diff.ts put the
text part before the images, while check.ts / evolve.ts / memory.ts /
design-to-code.ts put text after images. Standardized on
images-first-then-text (the majority pattern). GPT-4o handles both
orderings correctly.
2. Gemini.generateImage throws on previousResponseId (instead of silently
ignoring) to prevent caller confusion when porting OpenAI code paths.
3. Gemini.generateImage always returns a synthetic responseId
(`gemini-{timestamp}`) because Gemini has no response_id concept. The
previous `data.responseId || synthetic` fallback was dead code.
4. Gemini default vision model is `gemini-2.5-flash` (cheap, fast) while
image generation defaults to `gemini-3-pro-image-preview` (Nano Banana 2).
Both are env-overridable via GSTACK_GEMINI_IMAGE_MODEL and
GSTACK_GEMINI_VISION_MODEL, read lazily per-call for testability.
## Test coverage
- 33 smoke tests in design/test/providers.test.ts, all passing
(97ms total runtime, no real network calls)
- 60 total design tests pass (no regressions in the 27 pre-existing
serve / feedback-roundtrip / gallery tests)
- bun build --compile design/src/cli.ts compiles cleanly to a 61MB binary
Real end-to-end API calls are intentionally not covered here — they
belong in the EVALS=1 tier alongside test/gemini-e2e.test.ts and
test/codex-e2e.test.ts.
## Known tech debt deferred to a follow-up PR
Both providers implement a `fetch + AbortController + timeout + error-
text truncation + ProviderError throw` pattern four times (image+vision
× 2 providers). A shared `postJson` helper could collapse ~60 lines but
would need per-provider error-mapping callbacks that the simplify pass
judged would make the call sites harder to read. Left as inline
duplication; revisit in a follow-up once a third provider lands or a
second consumer needs the same shape.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
9 tasks done
4 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds a
DesignProviderinterface to the design tool and implements it for Google Gemini (gemini-3-pro-image-preview, aka Nano Banana 2) alongside the existing OpenAI path. Gemini becomes the new default provider; OpenAI stays available as a legacy option. Back-compat shims indesign/src/auth.tsmean any external consumer ofresolveApiKey/saveApiKey/requireApiKeykeeps working.Why — three-day evolution, same brief
I built this while generating 22 mockups for a separate project (browser-based drone ground control station, dark + amber). I ran the same design brief through three providers on three consecutive days. Here's the evolution — every image is the same brief, same prompt style, picked as each provider's best output from its batch (not cherry-picked worst cases):
Day 1 —
dall-e-3Native size 1792×1024. Artistic interpretation of "cockpit UI" — looks like a mid-2010s sci-fi concept render. Text on panels is unreadable / hallucinated. Layout rules ignored. Not a production interface.
Day 1 afternoon —
gpt-4o+image_generationtool (post org verification)Native size 2752×1536 (way bigger file — ~8 MB per render). Better composition, but typography still renders as AI-font mush, map doesn't look like a real tile system, and the interactive chrome (flight mode pills, connection indicators, buttons) all read as "AI art of a UI" rather than "UI." This is what the existing gstack design tool ships with today.
Day 2 —
gemini-3-pro-image-preview(Nano Banana 2)Native size 1264×848. 7× smaller file than the gpt-4o render at the same display width because the output actually compresses well — less noise, cleaner edges, fewer high-frequency artifacts. Typography is legible. The terrain map looks like satellite imagery. Panel hierarchy is intentional. This is a mockup you can hand to an implementer.
14 of the 22 mockups in that batch were production-ready on first render. For the same $5 spend I was previously getting one or two usable gpt-4o renders out of a batch and re-rolling the rest.
What's new
design/src/providers/{provider,factory,openai,gemini}.ts— interface + resolver + two implementations (~580 lines)design/test/providers.test.ts— 33 hermetic smoke tests, no real network callsgenerate,variants,iterate,evolve,check,design-to-code,diff,memory,cli) migrated from inlinefetchtogetProvider().generateImage()/.vision()GSTACK_DESIGN_PROVIDER=gemini|openaienv var to force a choice (case and whitespace tolerant; unknown values warn and fall through to auto-detect)GSTACK_GEMINI_IMAGE_MODEL/GSTACK_GEMINI_VISION_MODELenv overrides, read lazily per-call for testabilityCapability flags reflect real API differences, not fiction
supportsImageRef()— Gemini natively accepts a reference image for image-to-image (evolve.ts). OpenAI'simage_generationtool doesn't, so the OpenAI path falls back to vision-then-generate. Flag istruefor Gemini,falsefor OpenAI.supportsThreading()— OpenAI usesprevious_response_idfrom the Responses API. Gemini has no equivalent and throws if a caller passespreviousResponseId— loud failure beats silent one. Callers must checksupportsThreading()first;iterate.tsalready does this.Behavior changes worth flagging to reviewers
OpenAI vision content ordering normalized. Previously
diff.tsput the text part before the images whilecheck.ts/evolve.ts/memory.ts/design-to-code.tsput text after images. Standardized on images-first-then-text (the majority pattern). GPT-4o handles both orderings correctly, but it's a single deliberate change worth calling out.ProviderError.retryablenow normalized across all failure paths. Both providers funnel every thrown value through anormalizeError()helper that guarantees callers see aProviderErrorwith a correctretryableflag for: 429, any 5xx, AbortError (timeout), and raw transport failures (DNS / TLS / ECONNRESET / "Failed to fetch"). Previously rawTypeErrorfromfetch()could bypassvariants.tsretry logic anddiff.tsgraceful-degradation. This is a behavior improvement for the migrated consumers.Gemini.generateImagealways returns a synthetic responseId (gemini-{ms}) because Gemini has no response_id concept. The previous fallback pattern was dead code.Default vision model is
gemini-2.5-flash, image gen defaults togemini-3-pro-image-preview. Cheap vision for the quality checker, Nano Banana 2 for the actual generation. Both env-overridable.Deferred to a follow-up PR
Both providers implement a
fetch + AbortController + timeout + error-text truncation + ProviderError throwpattern four times (image + vision × 2 providers). A sharedpostJsonhelper could collapse ~60 lines but would need per-provider error-mapping callbacks that would make the call sites harder to read. Left as inline duplication for now; happy to land it in a follow-up once there's a third provider or a second consumer needs the same shape.Test plan
bun test design/test/providers.test.ts— 33 pass, 0 fail, 97ms (mocksglobalThis.fetch, covers request shape / response parsing / error surfaces / behavioral invariants / transport-failure normalization / AbortError timeout path for both providers)bun test design/test/— 60 pass, 0 fail (no regressions in the 27 pre-existingserve/feedback-roundtrip/gallerytests)bun build --compile design/src/cli.ts --outfile design/dist/design— clean compile, 61 MB binary, 112 msGSTACK_DESIGN_PROVIDER=openai $D generate "test"(legacy path, should behave exactly as before) andGSTACK_DESIGN_PROVIDER=gemini $D generate "test"(new default)Real end-to-end API tests belong in the
EVALS=1tier alongsidetest/gemini-e2e.test.tsandtest/codex-e2e.test.ts— happy to add a follow-up PR scoping those out if you want.Assets branch (3 comparison PNGs + readme):
SkipSupreme:pr-assets-design-gemini-provider. Safe to delete once this PR is reviewed.