Skip to content

feat(design): add provider abstraction with Gemini support - #998

Closed
SkipSupreme wants to merge 1 commit into
garrytan:mainfrom
SkipSupreme:design-gemini-provider
Closed

SkipSupreme wants to merge 1 commit into
garrytan:mainfrom
SkipSupreme:design-gemini-provider

Conversation

@SkipSupreme

Copy link
Copy Markdown

Summary

Adds a DesignProvider interface 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 in design/src/auth.ts mean any external consumer of resolveApiKey / saveApiKey / requireApiKey keeps 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-3

DALL-E 3 output

Native 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_generation tool (post org verification)

gpt-4o image_generation output

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)

Gemini 3 Pro Image output

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 calls
  • 9 existing call sites (generate, variants, iterate, evolve, check, design-to-code, diff, memory, cli) migrated from inline fetch to getProvider().generateImage() / .vision()
  • GSTACK_DESIGN_PROVIDER=gemini|openai env 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_MODEL env overrides, read lazily per-call for testability

Capability flags reflect real API differences, not fiction

  • supportsImageRef() — Gemini natively accepts a reference image for image-to-image (evolve.ts). OpenAI's image_generation tool doesn't, so the OpenAI path falls back to vision-then-generate. Flag is true for Gemini, false for OpenAI.
  • 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; iterate.ts already does this.

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, but it's a single deliberate change worth calling out.

  2. ProviderError.retryable now normalized across all failure paths. Both providers funnel every thrown value through a normalizeError() helper that guarantees callers see a ProviderError with a correct retryable flag for: 429, any 5xx, AbortError (timeout), and raw transport failures (DNS / TLS / ECONNRESET / "Failed to fetch"). Previously raw TypeError from fetch() could bypass variants.ts retry logic and diff.ts graceful-degradation. This is a behavior improvement for the migrated consumers.

  3. Gemini.generateImage always returns a synthetic responseId (gemini-{ms}) because Gemini has no response_id concept. The previous fallback pattern was dead code.

  4. Default vision model is gemini-2.5-flash, image gen defaults to gemini-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 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 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 (mocks globalThis.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-existing serve / feedback-roundtrip / gallery tests)
  • bun build --compile design/src/cli.ts --outfile design/dist/design — clean compile, 61 MB binary, 112 ms
  • Real end-to-end: used this build to generate the 22 mockups linked above. Gemini path exercised at real workload.
  • Reviewer smoke test: GSTACK_DESIGN_PROVIDER=openai $D generate "test" (legacy path, should behave exactly as before) and GSTACK_DESIGN_PROVIDER=gemini $D generate "test" (new default)

Real end-to-end API tests belong in the EVALS=1 tier alongside test/gemini-e2e.test.ts and test/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.

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]>
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.

1 participant