Compare commits
16 Commits
cursor/ope
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d501dbffdb | ||
|
|
b561446870 | ||
|
|
952cd42c0b | ||
|
|
fd92c2ac88 | ||
|
|
a30a12fe6c | ||
|
|
542f55704b | ||
|
|
761ea418d1 | ||
|
|
56e87b9d39 | ||
|
|
976564a0b6 | ||
|
|
100b708d93 | ||
|
|
3a90b0431c | ||
|
|
005b83218f | ||
|
|
0848e78cdb | ||
|
|
bc1fb094a4 | ||
|
|
5bccd8338b | ||
|
|
e09f076af8 |
@ -7,6 +7,7 @@ VITE_GOOGLE_GENERATIVE_AI_API_KEY=
|
||||
VITE_ALIBABA_API_KEY=
|
||||
VITE_OPENAI_API_KEY=
|
||||
VITE_ANTHROPIC_API_KEY=
|
||||
VITE_OPENCODE_API_KEY=
|
||||
VITE_XAI_API_KEY=
|
||||
|
||||
# Developer-only: write one JSON file per AI run to ./ai-logs/.
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -6,6 +6,7 @@ coverage/
|
||||
*.tsbuildinfo
|
||||
.eslintcache
|
||||
playwright-report/
|
||||
.playwright-mcp/
|
||||
test-results/
|
||||
.claude/
|
||||
|
||||
|
||||
@ -27,7 +27,7 @@ Use Bun for all package and script operations. Never use npm or manually edit `b
|
||||
- Keep editor mutations immutable; undo/redo snapshots depend on it.
|
||||
- This public repository owns only the editor. The production marketing site is maintained privately and deployed separately; never add its source, styles, assets, or production-only configuration here.
|
||||
- Never commit secrets, private screenshots, unlicensed assets, PSD/PSB files, or generated `dist/`.
|
||||
- AI provider keys are entered in the browser (stored in `localStorage`) with optional `.env.local` `VITE_*` fallback for local dev; only Moonshot uses the local CORS proxy. Never commit `.env.local` or deploy a keyed build.
|
||||
- AI provider keys are entered in the browser (stored in `localStorage`) with optional `.env.local` `VITE_*` fallback for local dev; Moonshot and OpenCode use a same-origin CORS proxy. Never commit `.env.local` or deploy a keyed build.
|
||||
- Use shadcn/Base UI and Hugeicons for editor chrome. Do not add a parallel UI or token system.
|
||||
- Update generated `src/components/ui/` files only with the shadcn CLI.
|
||||
- Use Conventional Commit messages and keep commits independently coherent.
|
||||
|
||||
@ -46,6 +46,14 @@ The Cloudflare custom domain is source-controlled in `wrangler.jsonc`. Do not
|
||||
attach this Worker to the apex domain, and do not add marketing-site source,
|
||||
styles, assets, or production-only configuration to this repository.
|
||||
|
||||
The Worker also runs the share API (`scripts/share-api.ts`) for short
|
||||
project share links. It stores opaque share payloads in the `SHARE_KV` KV
|
||||
namespace referenced in `wrangler.jsonc`; the API token therefore needs
|
||||
Workers KV Storage edit permission (included in the standard Edit Cloudflare
|
||||
Workers token template). The editor falls back to self-contained share links
|
||||
when the API is unavailable, so a deployment without the KV binding degrades
|
||||
gracefully.
|
||||
|
||||
Keep `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` available only to the
|
||||
`bun run deploy-only` command. The GitHub Actions workflow follows the same
|
||||
boundary: it builds without Cloudflare credentials and supplies them only to
|
||||
|
||||
11
README.md
11
README.md
@ -23,7 +23,7 @@ Projects live entirely in your browser — no Shotluma account or project backen
|
||||
|
||||
- **AI that designs, not renders** — the agent works through editor tool calls, so its output is a normal project: every element it creates is selectable and editable, and you can revise a single screen with the magic-cursor action instead of regenerating everything.
|
||||
- **Use your ChatGPT plan** — connect the Codex app or CLI to the hosted editor without giving Shotluma an API key.
|
||||
- **Bring your own model** — also works with Moonshot, Google, Qwen, OpenAI, Anthropic, xAI, and OpenRouter; pick provider and model per run.
|
||||
- **Bring your own model** — also works with Moonshot, Google, Qwen, OpenAI, Anthropic, xAI, OpenRouter, and OpenCode Zen/Go; pick provider and model per run.
|
||||
- **Full screenshot sets** — design a multi-screen story on portrait artboards, not one image at a time.
|
||||
- **Direct manipulation** — typography, gradients, shapes, images, mockups, alignment, stacking, and spacing are all hand-editable, with or without AI.
|
||||
- **Perspective device mockups** — drop a raw screenshot into a device frame with correct 3D geometry.
|
||||
@ -84,6 +84,7 @@ VITE_ALIBABA_API_KEY=
|
||||
VITE_OPENAI_API_KEY=
|
||||
VITE_ANTHROPIC_API_KEY=
|
||||
VITE_XAI_API_KEY=
|
||||
VITE_OPENCODE_API_KEY=
|
||||
```
|
||||
|
||||
Restart the dev server after changing `.env.local` keys. Pick the provider and model in the generation dialog — models with configurable reasoning also expose their effort levels there. If a selected provider has no key, the dialog offers **Enter API key** and disables generation until one is saved.
|
||||
@ -91,7 +92,7 @@ Restart the dev server after changing `.env.local` keys. Pick the provider and m
|
||||
How it works, and what to know:
|
||||
|
||||
- Codex runs go from the hosted browser to the paired loopback connector and then to Codex App Server. The connector exposes only the account, model, thread, turn, and Shotluma dynamic-tool RPC surface; Codex gets a read-only empty workspace with network access disabled.
|
||||
- Google, Qwen, OpenAI, Anthropic, xAI, and OpenRouter are called directly from the browser via the AI SDK. Moonshot works only on localhost through the local `/api/moonshot` CORS proxy.
|
||||
- Google, Qwen, OpenAI, Anthropic, xAI, and OpenRouter are called directly from the browser via the AI SDK. Moonshot works only on localhost through the local `/api/moonshot` CORS proxy. OpenCode Zen and Go use a same-origin `/api/opencode` proxy (Vite locally, Cloudflare Worker when hosted) because those APIs do not answer browser CORS preflight. Models without native vision send screenshots and previews through a second OpenCode vision model first.
|
||||
- When you start a run, your description and selected screenshots are sent to the selected provider or through Codex. Normal editing, persistence, and export never call any AI service. Provider limits or charges may apply.
|
||||
- Browser-stored keys are visible to same-origin JavaScript by design. Optional `VITE_*` keys are exposed only by the local dev server; production builds replace every provider env key with an empty value. Never commit `.env.local` (see [Self-hosting](#self-hosting)).
|
||||
- Prompts can be written in any language; generated canvas copy and summaries are in English.
|
||||
@ -109,7 +110,7 @@ For debugging, set `SHOTLUMA_AI_LOGGING=true` in `.env.local` to write one JSON
|
||||
| `bun run test` | Run the Vitest suite once |
|
||||
| `bun run test:coverage` | Tests with coverage thresholds |
|
||||
| `bun run build` | Type-check and build the production bundle |
|
||||
| `bun run preview` | Serve the production bundle locally, including the Moonshot proxy |
|
||||
| `bun run preview` | Serve the production bundle locally, including the Moonshot and OpenCode proxies |
|
||||
| `bun run audit` | Check dependencies for known vulnerabilities |
|
||||
| `bun run check` | All required local and CI quality gates |
|
||||
|
||||
@ -117,13 +118,13 @@ Changes to rendering, export, or AI behavior also need manual verification in th
|
||||
|
||||
## Self-hosting
|
||||
|
||||
`bun run build` produces a static app in `dist/`, including the downloadable Codex connector at `codex/shotluma-codex-bridge.mjs`. Provider env values are stripped from the bundle, so it can be hosted as a static site while users connect Codex or supply their own direct-provider keys in the browser.
|
||||
`bun run build` produces a static app in `dist/`, including the downloadable Codex connector at `codex/shotluma-codex-bridge.mjs`. Provider env values are stripped from the bundle, so it can be hosted as a static site while users connect Codex or supply their own direct-provider keys in the browser. OpenCode on a hosted origin also needs the `/api/opencode` Worker in `scripts/shotluma-worker.ts` (the official `app.shotluma.com` deploy includes it).
|
||||
|
||||
The official editor is deployed at `https://app.shotluma.com`. The marketing
|
||||
site at `https://shotluma.com` is maintained and deployed separately; its source
|
||||
and production configuration are not part of this repository.
|
||||
|
||||
Codex connection prompts pair against the deployment's own origin. Google, Qwen, OpenAI, Anthropic, xAI, and OpenRouter work with browser-entered keys. Moonshot
|
||||
Codex connection prompts pair against the deployment's own origin. Google, Qwen, OpenAI, Anthropic, xAI, OpenRouter, and OpenCode work with browser-entered keys. Moonshot
|
||||
remains local-only; offering it on a hosted deployment requires an authenticated
|
||||
proxy. A hosted workflow with shared credentials likewise needs a backend or
|
||||
short-lived credential exchange.
|
||||
|
||||
@ -32,8 +32,8 @@ Maintainers will acknowledge reports and coordinate a fix and disclosure on a be
|
||||
- `.env.local` is ignored by Git and must remain untracked.
|
||||
- Production builds replace provider env keys with empty values. Do not remove this build boundary or publish a manually altered keyed bundle.
|
||||
- Uploaded images and projects stay in IndexedDB during normal editing.
|
||||
- Screenshots selected for an AI run are sent to the selected provider. Google, Qwen, OpenAI, Anthropic, and xAI are contacted directly; Moonshot works only on localhost through the same-origin local CORS proxy. Opt-in overlay generation contacts OpenAI separately.
|
||||
- Screenshots selected for an AI run are sent to the selected provider. Google, Qwen, OpenAI, Anthropic, and xAI are contacted directly; Moonshot works only on localhost through the same-origin local CORS proxy. OpenCode Zen and Go use the same-origin `/api/opencode` proxy. Opt-in overlay generation contacts OpenAI separately.
|
||||
- Users are responsible for protecting provider keys and usage quotas.
|
||||
- A hosted deployment can use browser-entered keys with the direct providers. A deployment that supplies shared credentials or offers Moonshot requires a separate authenticated backend design.
|
||||
- A hosted deployment can use browser-entered keys with the direct providers and OpenCode. A deployment that supplies shared credentials or offers Moonshot requires a separate authenticated backend design.
|
||||
|
||||
If a key is accidentally exposed, revoke it at the provider immediately, remove it from the current files, and treat it as compromised even if the Git commit is later rewritten.
|
||||
|
||||
170
bun.lock
170
bun.lock
@ -56,7 +56,7 @@
|
||||
"@types/react": "latest",
|
||||
"@types/react-dom": "latest",
|
||||
"@vitejs/plugin-react": "latest",
|
||||
"@vitest/coverage-v8": "^4.1.6",
|
||||
"@vitest/coverage-v8": "^4.1.12",
|
||||
"eslint": "latest",
|
||||
"eslint-import-resolver-typescript": "^4.4.5",
|
||||
"eslint-plugin-import-x": "^4.17.1",
|
||||
@ -68,21 +68,29 @@
|
||||
"typescript": "5.9.3",
|
||||
"typescript-eslint": "latest",
|
||||
"vite": "latest",
|
||||
"vitest": "^4.1.6",
|
||||
"vitest": "^4.1.12",
|
||||
"wrangler": "4.118.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
"overrides": {
|
||||
"@hono/node-server": "2.0.10",
|
||||
"brace-expansion": "5.0.9",
|
||||
"fast-uri": "3.1.5",
|
||||
"hono": "4.12.34",
|
||||
"ip-address": "10.4.0",
|
||||
"js-yaml": "4.3.1",
|
||||
"@modelcontextprotocol/sdk": "1.32.1",
|
||||
"baseline-browser-mapping": "2.11.30",
|
||||
"brace-expansion": "5.0.12",
|
||||
"browserslist": "4.29.4",
|
||||
"fast-uri": "3.1.8",
|
||||
"hono": "4.13.13",
|
||||
"ip-address": "10.7.4",
|
||||
"js-yaml": "4.3.2",
|
||||
"nanoid": "3.3.18",
|
||||
"postcss": "8.5.25",
|
||||
"undici": "7.29.0",
|
||||
"postcss-selector-parser": "7.1.6",
|
||||
"proxy-addr": "2.0.8",
|
||||
"qs": "6.16.1",
|
||||
"sharp": "0.35.5",
|
||||
"source-map-js": "1.2.2",
|
||||
"undici": "7.29.1",
|
||||
},
|
||||
"packages": {
|
||||
"@ai-sdk/alibaba": ["@ai-sdk/alibaba@2.0.16", "", { "dependencies": { "@ai-sdk/openai-compatible": "3.0.14", "@ai-sdk/provider": "4.0.3", "@ai-sdk/provider-utils": "5.0.12" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-5m22ATiDlaJRKzgGIm2jXfBFbtOJ+PaUDUVzXLkU3Np2QisNVL6+kK28jQwEZLIj3vaef3c9gjoNt1CC7+qlGg=="],
|
||||
@ -353,57 +361,57 @@
|
||||
|
||||
"@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
|
||||
|
||||
"@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.2", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.1" }, "os": "darwin", "cpu": "arm64" }, "sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg=="],
|
||||
"@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg=="],
|
||||
|
||||
"@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.2", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.1" }, "os": "darwin", "cpu": "x64" }, "sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw=="],
|
||||
"@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.4" }, "os": "darwin", "cpu": "x64" }, "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw=="],
|
||||
|
||||
"@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.2", "", { "dependencies": { "@img/sharp-wasm32": "0.35.2" }, "os": "freebsd" }, "sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw=="],
|
||||
"@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.5", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "os": "freebsd" }, "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw=="],
|
||||
|
||||
"@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g=="],
|
||||
"@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw=="],
|
||||
|
||||
"@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ=="],
|
||||
"@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ=="],
|
||||
|
||||
"@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.1", "", { "os": "linux", "cpu": "arm" }, "sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg=="],
|
||||
"@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.4", "", { "os": "linux", "cpu": "arm" }, "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw=="],
|
||||
|
||||
"@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw=="],
|
||||
"@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A=="],
|
||||
|
||||
"@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng=="],
|
||||
"@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ=="],
|
||||
|
||||
"@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.1", "", { "os": "linux", "cpu": "none" }, "sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw=="],
|
||||
"@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.4", "", { "os": "linux", "cpu": "none" }, "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q=="],
|
||||
|
||||
"@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.1", "", { "os": "linux", "cpu": "s390x" }, "sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew=="],
|
||||
"@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ=="],
|
||||
|
||||
"@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.1", "", { "os": "linux", "cpu": "x64" }, "sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A=="],
|
||||
"@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.4", "", { "os": "linux", "cpu": "x64" }, "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw=="],
|
||||
|
||||
"@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw=="],
|
||||
"@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA=="],
|
||||
|
||||
"@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.1", "", { "os": "linux", "cpu": "x64" }, "sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg=="],
|
||||
"@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.4", "", { "os": "linux", "cpu": "x64" }, "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg=="],
|
||||
|
||||
"@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.2", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.1" }, "os": "linux", "cpu": "arm" }, "sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A=="],
|
||||
"@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.4" }, "os": "linux", "cpu": "arm" }, "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ=="],
|
||||
|
||||
"@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.2", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.1" }, "os": "linux", "cpu": "arm64" }, "sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA=="],
|
||||
"@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64" }, "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ=="],
|
||||
|
||||
"@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.2", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.1" }, "os": "linux", "cpu": "ppc64" }, "sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg=="],
|
||||
"@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.4" }, "os": "linux", "cpu": "ppc64" }, "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA=="],
|
||||
|
||||
"@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.2", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.1" }, "os": "linux", "cpu": "none" }, "sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA=="],
|
||||
"@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.4" }, "os": "linux", "cpu": "none" }, "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ=="],
|
||||
|
||||
"@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.2", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.1" }, "os": "linux", "cpu": "s390x" }, "sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA=="],
|
||||
"@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.4" }, "os": "linux", "cpu": "s390x" }, "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA=="],
|
||||
|
||||
"@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.2", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.1" }, "os": "linux", "cpu": "x64" }, "sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA=="],
|
||||
"@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.4" }, "os": "linux", "cpu": "x64" }, "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog=="],
|
||||
|
||||
"@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.2", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.1" }, "os": "linux", "cpu": "arm64" }, "sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg=="],
|
||||
"@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64" }, "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg=="],
|
||||
|
||||
"@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.2", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.1" }, "os": "linux", "cpu": "x64" }, "sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg=="],
|
||||
"@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.4" }, "os": "linux", "cpu": "x64" }, "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A=="],
|
||||
|
||||
"@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.2", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw=="],
|
||||
"@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.5", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ=="],
|
||||
|
||||
"@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.2", "", { "dependencies": { "@img/sharp-wasm32": "0.35.2" }, "cpu": "none" }, "sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g=="],
|
||||
"@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.5", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "cpu": "none" }, "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA=="],
|
||||
|
||||
"@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ=="],
|
||||
"@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q=="],
|
||||
|
||||
"@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog=="],
|
||||
"@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A=="],
|
||||
|
||||
"@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.2", "", { "os": "win32", "cpu": "x64" }, "sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ=="],
|
||||
"@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.5", "", { "os": "win32", "cpu": "x64" }, "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg=="],
|
||||
|
||||
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
|
||||
|
||||
@ -415,7 +423,7 @@
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
|
||||
|
||||
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
|
||||
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.1", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw=="],
|
||||
|
||||
"@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.6", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg=="],
|
||||
|
||||
@ -539,7 +547,7 @@
|
||||
|
||||
"@typescript-eslint/project-service": ["@typescript-eslint/project-service@8.65.0", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.65.0", "@typescript-eslint/types": "^8.65.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-SxnPhbTsGahizDgbu7oqFH/xVtzIqMd/s+WtnSxNxJZJpLbdT5IPdzg8EZxO3+PoKahXmwJLeNQOpKJb3/bi7Q=="],
|
||||
|
||||
"@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.64.0", "", { "dependencies": { "@typescript-eslint/types": "8.64.0", "@typescript-eslint/visitor-keys": "8.64.0" } }, "sha512-CXEaFdYXjSTgKhisNkwCcJwTP8Pl+fmRrEQrri4nm3vU743bALrxzLmq7fHG/7e6a5xO0lDYeURpZmBuhHk54w=="],
|
||||
"@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.65.0", "", { "dependencies": { "@typescript-eslint/types": "8.65.0", "@typescript-eslint/visitor-keys": "8.65.0" } }, "sha512-Esbl8OSYiVxBokYgWPf7VVWg/BE798wXhimnn9ML9Pt5qoDf8bfQlgjlKXR/k98+AcNzlLKYrpCcrcuZ9DZLgg=="],
|
||||
|
||||
"@typescript-eslint/tsconfig-utils": ["@typescript-eslint/tsconfig-utils@8.65.0", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-j6GzGqCiRdA7Qhur2VVmKZAkBLfnHFQfx4TaJGL9RMveZqCo48jSHHO0DTgizEnGhtWnqmbtCUSrqSkdiY/0Hg=="],
|
||||
|
||||
@ -549,7 +557,7 @@
|
||||
|
||||
"@typescript-eslint/typescript-estree": ["@typescript-eslint/typescript-estree@8.65.0", "", { "dependencies": { "@typescript-eslint/project-service": "8.65.0", "@typescript-eslint/tsconfig-utils": "8.65.0", "@typescript-eslint/types": "8.65.0", "@typescript-eslint/visitor-keys": "8.65.0", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-JboAE2swaYt4tb1fHhHTABE2K+OLy09XfcTbhnk4Pw96f9dd2e9iYsJ28gBggHlo5z5x1rkyWvcPoTuNTd4oGg=="],
|
||||
|
||||
"@typescript-eslint/utils": ["@typescript-eslint/utils@8.64.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.64.0", "@typescript-eslint/types": "8.64.0", "@typescript-eslint/typescript-estree": "8.64.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-aJUGVB3+U0htrrCjoA8qukw8cm8fNCGAxK/tVoS70k8aeb7DETKeFozRiVFIwEeN9WJLsjaP3ph8I60tY2XZoQ=="],
|
||||
"@typescript-eslint/utils": ["@typescript-eslint/utils@8.65.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.65.0", "@typescript-eslint/types": "8.65.0", "@typescript-eslint/typescript-estree": "8.65.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-gXiwIHsYreboxeJucHKPvgwl7dXt50mF8s1/c00cP/WoVTyWKFdtfhRWwZiXYFU5H2O8vVoSLNrexFZjYS/SGA=="],
|
||||
|
||||
"@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.65.0", "", { "dependencies": { "@typescript-eslint/types": "8.65.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-8C71BQkGjiMmXtop7pHVJu1l2NNShFdkCyD6a2ezzs5vU/L3LRtb69EtcteFwz0mYMPzIgOw0n6OV4VBUWZd7A=="],
|
||||
|
||||
@ -601,21 +609,21 @@
|
||||
|
||||
"@vitejs/plugin-react": ["@vitejs/plugin-react@6.0.3", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-vmFvco5/QuC2f9Oj+wTk0+9XeDFkHxSamwZKYc7MxYwKICfvUvlMhqKI0VuICPltGqh1neqBKDvO4kes1ya8vg=="],
|
||||
|
||||
"@vitest/coverage-v8": ["@vitest/coverage-v8@4.1.10", "", { "dependencies": { "@bcoe/v8-coverage": "^1.0.2", "@vitest/utils": "4.1.10", "ast-v8-to-istanbul": "^1.0.0", "istanbul-lib-coverage": "^3.2.2", "istanbul-lib-report": "^3.0.1", "istanbul-reports": "^3.2.0", "magicast": "^0.5.2", "obug": "^2.1.1", "std-env": "^4.0.0-rc.1", "tinyrainbow": "^3.1.0" }, "peerDependencies": { "@vitest/browser": "4.1.10", "vitest": "4.1.10" }, "optionalPeers": ["@vitest/browser"] }, "sha512-IM49HmthevbgAO4anp1hwtoT9wYe59w0LR00gr+eagHE+ZJ5lK4sLPeO0ubgoJcwLk6dehU3R24N+FbEEKDc8g=="],
|
||||
"@vitest/coverage-v8": ["@vitest/coverage-v8@4.1.12", "", { "dependencies": { "@bcoe/v8-coverage": "^1.0.2", "@vitest/utils": "4.1.12", "ast-v8-to-istanbul": "^1.0.0", "istanbul-lib-coverage": "^3.2.2", "istanbul-lib-report": "^3.0.1", "istanbul-reports": "^3.2.0", "magicast": "^0.5.2", "obug": "^2.1.1", "std-env": "^4.0.0-rc.1", "tinyrainbow": "^3.1.0" }, "peerDependencies": { "@vitest/browser": "4.1.12", "vitest": "4.1.12" }, "optionalPeers": ["@vitest/browser"] }, "sha512-6S7/iVknKglLAxMFxQGNppBI0iqJS2NgM6FBxavitj7KaDq/vywOWGf6dGu7F2L1Qy0G6S3uTp7aGshHrzK8JA=="],
|
||||
|
||||
"@vitest/expect": ["@vitest/expect@4.1.10", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.10", "@vitest/utils": "4.1.10", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA=="],
|
||||
"@vitest/expect": ["@vitest/expect@4.1.12", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.12", "@vitest/utils": "4.1.12", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-vFlTt+YEu9WBpNjdGayNmlMVzrWPi1+sv853/7t2FU7hpO5gAFBKHzQmkCq5Xjpr+evegF2994LQT3hF3mRlqQ=="],
|
||||
|
||||
"@vitest/mocker": ["@vitest/mocker@4.1.10", "", { "dependencies": { "@vitest/spy": "4.1.10", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow=="],
|
||||
"@vitest/mocker": ["@vitest/mocker@4.1.12", "", { "dependencies": { "@vitest/spy": "4.1.12", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-fKShNpKZzupWZuY0z7egydvL0sqW4INEZBEExMBMAa6izlENEVHwoXgdaTCaBZ5fwlr4xf2o1wXC83n9RpO+NA=="],
|
||||
|
||||
"@vitest/pretty-format": ["@vitest/pretty-format@4.1.10", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q=="],
|
||||
"@vitest/pretty-format": ["@vitest/pretty-format@4.1.12", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-XW9O8+Mxx4VpCtkYdMJLZQQwsVryP9wk7cPKDxtXFfwSak6yRh5+2fep/Y0XF/ElBvJHq8bcYdi6aeuai0opZA=="],
|
||||
|
||||
"@vitest/runner": ["@vitest/runner@4.1.10", "", { "dependencies": { "@vitest/utils": "4.1.10", "pathe": "^2.0.3" } }, "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg=="],
|
||||
"@vitest/runner": ["@vitest/runner@4.1.12", "", { "dependencies": { "@vitest/utils": "4.1.12", "pathe": "^2.0.3" } }, "sha512-NKlVKCr5QnCe8jijdMnmkpHHU+WTqiLFR6G0pHji9uRjXK9xJl1k1nTw6F3pOOj2PDcsDt2GKQMI7wIsaT491w=="],
|
||||
|
||||
"@vitest/snapshot": ["@vitest/snapshot@4.1.10", "", { "dependencies": { "@vitest/pretty-format": "4.1.10", "@vitest/utils": "4.1.10", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw=="],
|
||||
"@vitest/snapshot": ["@vitest/snapshot@4.1.12", "", { "dependencies": { "@vitest/pretty-format": "4.1.12", "@vitest/utils": "4.1.12", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-ko1y1Qgb/slzQ9mr+b89Cuqud8WG1TKtsPD8r7ZUBdvVOGt85Af2HwCqHujrhwJq95hs/9RM7fcAPg57o1vlzw=="],
|
||||
|
||||
"@vitest/spy": ["@vitest/spy@4.1.10", "", {}, "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw=="],
|
||||
"@vitest/spy": ["@vitest/spy@4.1.12", "", {}, "sha512-RGq9x4JNGNTZHEJxvN0oSiJjeSCExm0n2gZKKJZHY9cX5AVA6M7VJILBT3ZJ/tJ/0J9uWT7fETV9/btoi//vSg=="],
|
||||
|
||||
"@vitest/utils": ["@vitest/utils@4.1.10", "", { "dependencies": { "@vitest/pretty-format": "4.1.10", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA=="],
|
||||
"@vitest/utils": ["@vitest/utils@4.1.12", "", { "dependencies": { "@vitest/pretty-format": "4.1.12", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-Q3awXrwOfEV+qc3WmO5ONyE0yO7Q1gQ9/oyHxGLZ/pl7N3NO/ZztqQwKLuwMkV+CA1JYSIeO3gkHnRDIo4AVaA=="],
|
||||
|
||||
"@workflow/serde": ["@workflow/serde@4.1.0", "", {}, "sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ=="],
|
||||
|
||||
@ -647,7 +655,7 @@
|
||||
|
||||
"balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
|
||||
|
||||
"baseline-browser-mapping": ["baseline-browser-mapping@2.10.44", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-T3ghW+sl/ZJ8w1v/yQx3qvJ9040DWoLBz8JT/CILbAKcFyG9b2MRe75v6W5uXjv6uH1lumK2Kv46y2zSkcej0Q=="],
|
||||
"baseline-browser-mapping": ["baseline-browser-mapping@2.11.30", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-YJs6Pz17RMNv8HoyKREtCY38E3BV1nPkWVmIb+XN1uHC1Vqt3KZCH/uJH9ZKRoiKb/icZ6tvehyee6RZNbFfRA=="],
|
||||
|
||||
"bidi-js": ["bidi-js@1.0.3", "", { "dependencies": { "require-from-string": "^2.0.2" } }, "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw=="],
|
||||
|
||||
@ -655,11 +663,11 @@
|
||||
|
||||
"body-parser": ["body-parser@2.3.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="],
|
||||
|
||||
"brace-expansion": ["brace-expansion@5.0.9", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg=="],
|
||||
"brace-expansion": ["brace-expansion@5.0.12", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="],
|
||||
|
||||
"braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
|
||||
|
||||
"browserslist": ["browserslist@4.28.6", "", { "dependencies": { "baseline-browser-mapping": "^2.10.42", "caniuse-lite": "^1.0.30001803", "electron-to-chromium": "^1.5.389", "node-releases": "^2.0.51", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-FQBYNK15VMslhLHpA7+n+n1GOlF1kId2xcCg7/j95f24AOF6VDYMNH4mFxF7KuaTdv627faazpOAjFzMrfJOUw=="],
|
||||
"browserslist": ["browserslist@4.29.4", "", { "dependencies": { "baseline-browser-mapping": "^2.11.29", "caniuse-lite": "^1.0.30001816", "electron-to-chromium": "^1.5.459", "node-releases": "^2.0.59", "update-browserslist-db": "^1.3.4" }, "bin": { "browserslist": "cli.js" } }, "sha512-2TcbbiwXEq+N0kD36tykpCfyyQigUXmuwNQbnPp4Xk4PX9JOqVIKjJlIDjpH7uY6tmRGoAd+apeT1p60T8wsdA=="],
|
||||
|
||||
"bundle-name": ["bundle-name@4.1.0", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
|
||||
@ -671,7 +679,7 @@
|
||||
|
||||
"callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="],
|
||||
|
||||
"caniuse-lite": ["caniuse-lite@1.0.30001806", "", {}, "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw=="],
|
||||
"caniuse-lite": ["caniuse-lite@1.0.30001816", "", {}, "sha512-+8Yx7BXCoqk6IF8yTicjfUR6D/ldJzdlsodlEOiOSPmhK844WIgk67/zIQaGAOxNkZyyvBlrRFnLvqKIoqbAFw=="],
|
||||
|
||||
"chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="],
|
||||
|
||||
@ -751,7 +759,7 @@
|
||||
|
||||
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
|
||||
|
||||
"electron-to-chromium": ["electron-to-chromium@1.5.393", "", {}, "sha512-kiDJdIUawuEIcp9XoICKp1iTYDEbgguIPq526N1Q7jIQDeQ3CqoMx71025PI/7E48Ddtw2HuWsVjY7afEgNxmg=="],
|
||||
"electron-to-chromium": ["electron-to-chromium@1.5.459", "", {}, "sha512-4SC9HHSFjO/liAhifpdOL5hG9b4BP7/5G3y3UPZVO8trlAXr1CaUEEJL0gWK3kOcYcZrOA5rkwG45Gra/lTIgg=="],
|
||||
|
||||
"emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="],
|
||||
|
||||
@ -839,7 +847,7 @@
|
||||
|
||||
"fast-levenshtein": ["fast-levenshtein@2.0.6", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="],
|
||||
|
||||
"fast-uri": ["fast-uri@3.1.5", "", {}, "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw=="],
|
||||
"fast-uri": ["fast-uri@3.1.8", "", {}, "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg=="],
|
||||
|
||||
"fastq": ["fastq@1.20.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="],
|
||||
|
||||
@ -903,7 +911,7 @@
|
||||
|
||||
"hermes-parser": ["hermes-parser@0.25.1", "", { "dependencies": { "hermes-estree": "0.25.1" } }, "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA=="],
|
||||
|
||||
"hono": ["hono@4.12.34", "", {}, "sha512-GqXJqY/xJkJmuloTrnV1ZEXG3fqte+VjkUqoRNZXcrUidiUOP4fMSIHHY4tsqZBK++kVyWmt/AAfSUuy57/eSA=="],
|
||||
"hono": ["hono@4.13.13", "", {}, "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA=="],
|
||||
|
||||
"html-encoding-sniffer": ["html-encoding-sniffer@6.0.0", "", { "dependencies": { "@exodus/bytes": "^1.6.0" } }, "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg=="],
|
||||
|
||||
@ -927,7 +935,7 @@
|
||||
|
||||
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
|
||||
|
||||
"ip-address": ["ip-address@10.4.0", "", {}, "sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ=="],
|
||||
"ip-address": ["ip-address@10.7.4", "", {}, "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg=="],
|
||||
|
||||
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
|
||||
|
||||
@ -981,7 +989,7 @@
|
||||
|
||||
"js-tokens": ["js-tokens@10.0.0", "", {}, "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q=="],
|
||||
|
||||
"js-yaml": ["js-yaml@4.3.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ=="],
|
||||
"js-yaml": ["js-yaml@4.3.2", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="],
|
||||
|
||||
"jsdom": ["jsdom@29.1.1", "", { "dependencies": { "@asamuzakjp/css-color": "^5.1.11", "@asamuzakjp/dom-selector": "^7.1.1", "@bramus/specificity": "^2.4.2", "@csstools/css-syntax-patches-for-csstree": "^1.1.3", "@exodus/bytes": "^1.15.0", "css-tree": "^3.2.1", "data-urls": "^7.0.0", "decimal.js": "^10.6.0", "html-encoding-sniffer": "^6.0.0", "is-potential-custom-element-name": "^1.0.1", "lru-cache": "^11.3.5", "parse5": "^8.0.1", "saxes": "^6.0.0", "symbol-tree": "^3.2.4", "tough-cookie": "^6.0.1", "undici": "^7.25.0", "w3c-xmlserializer": "^5.0.0", "webidl-conversions": "^8.0.1", "whatwg-mimetype": "^5.0.0", "whatwg-url": "^16.0.1", "xml-name-validator": "^5.0.0" }, "peerDependencies": { "canvas": "^3.0.0" }, "optionalPeers": ["canvas"] }, "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q=="],
|
||||
|
||||
@ -1089,7 +1097,7 @@
|
||||
|
||||
"negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
|
||||
|
||||
"node-releases": ["node-releases@2.0.51", "", {}, "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ=="],
|
||||
"node-releases": ["node-releases@2.0.59", "", {}, "sha512-5qr2okC4ItAI0hG5SaV0HoYMpnM/Y6+Oqr7AmPYy/2uEoGvS+GbSKLeRxSS1uAdu59yz0ouzcuXievSgg///WA=="],
|
||||
|
||||
"npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="],
|
||||
|
||||
@ -1151,7 +1159,7 @@
|
||||
|
||||
"postcss": ["postcss@8.5.25", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw=="],
|
||||
|
||||
"postcss-selector-parser": ["postcss-selector-parser@7.1.4", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-HeP7D2wyhkR+XaK6v4W8oRF62Dsz4flyuczALJp61GckGm42u1saSSJ/0auvcBqxs3jMRFEcPK34At/0JBKdOg=="],
|
||||
"postcss-selector-parser": ["postcss-selector-parser@7.1.6", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw=="],
|
||||
|
||||
"powershell-utils": ["powershell-utils@0.1.0", "", {}, "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A=="],
|
||||
|
||||
@ -1163,11 +1171,11 @@
|
||||
|
||||
"prompts": ["prompts@2.4.2", "", { "dependencies": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q=="],
|
||||
|
||||
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
|
||||
"proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="],
|
||||
|
||||
"punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
|
||||
|
||||
"qs": ["qs@6.15.3", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A=="],
|
||||
"qs": ["qs@6.16.1", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg=="],
|
||||
|
||||
"queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
|
||||
|
||||
@ -1223,7 +1231,7 @@
|
||||
|
||||
"shadcn": ["shadcn@4.16.2", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/parser": "^7.28.0", "@babel/plugin-transform-typescript": "^7.28.0", "@babel/preset-typescript": "^7.27.1", "@dotenvx/dotenvx": "^1.48.4", "@modelcontextprotocol/sdk": "^1.26.0", "@types/validate-npm-package-name": "^4.0.2", "browserslist": "^4.26.2", "commander": "^14.0.0", "cosmiconfig": "^9.0.0", "dedent": "^1.6.0", "deepmerge": "^4.3.1", "diff": "^8.0.2", "execa": "^9.6.0", "fast-glob": "^3.3.3", "fs-extra": "^11.3.1", "fuzzysort": "^3.1.0", "kleur": "^4.1.5", "open": "^11.0.0", "ora": "^8.2.0", "postcss": "^8.5.6", "postcss-selector-parser": "^7.1.0", "prompts": "^2.4.2", "recast": "^0.23.11", "stringify-object": "^5.0.0", "tailwind-merge": "^3.0.1", "ts-morph": "^26.0.0", "tsconfig-paths": "^4.2.0", "undici": "^7.27.2", "validate-npm-package-name": "^7.0.1", "zod": "^3.24.1", "zod-to-json-schema": "^3.24.6" }, "bin": { "shadcn": "dist/index.js" } }, "sha512-M1AvZKFWcCzWRDoyApIqJMSLIpY8Ev4uBGuiPLSFmiTbixXhPmzotSTvLzFmBrfoIxG9aIg2dZOETblEaXGUnQ=="],
|
||||
|
||||
"sharp": ["sharp@0.35.2", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.4" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.2", "@img/sharp-darwin-x64": "0.35.2", "@img/sharp-freebsd-wasm32": "0.35.2", "@img/sharp-libvips-darwin-arm64": "1.3.1", "@img/sharp-libvips-darwin-x64": "1.3.1", "@img/sharp-libvips-linux-arm": "1.3.1", "@img/sharp-libvips-linux-arm64": "1.3.1", "@img/sharp-libvips-linux-ppc64": "1.3.1", "@img/sharp-libvips-linux-riscv64": "1.3.1", "@img/sharp-libvips-linux-s390x": "1.3.1", "@img/sharp-libvips-linux-x64": "1.3.1", "@img/sharp-libvips-linuxmusl-arm64": "1.3.1", "@img/sharp-libvips-linuxmusl-x64": "1.3.1", "@img/sharp-linux-arm": "0.35.2", "@img/sharp-linux-arm64": "0.35.2", "@img/sharp-linux-ppc64": "0.35.2", "@img/sharp-linux-riscv64": "0.35.2", "@img/sharp-linux-s390x": "0.35.2", "@img/sharp-linux-x64": "0.35.2", "@img/sharp-linuxmusl-arm64": "0.35.2", "@img/sharp-linuxmusl-x64": "0.35.2", "@img/sharp-webcontainers-wasm32": "0.35.2", "@img/sharp-win32-arm64": "0.35.2", "@img/sharp-win32-ia32": "0.35.2", "@img/sharp-win32-x64": "0.35.2" } }, "sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w=="],
|
||||
"sharp": ["sharp@0.35.5", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="],
|
||||
|
||||
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
|
||||
|
||||
@ -1245,7 +1253,7 @@
|
||||
|
||||
"source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
|
||||
|
||||
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
"source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
|
||||
|
||||
"stable-hash-x": ["stable-hash-x@0.2.0", "", {}, "sha512-o3yWv49B/o4QZk5ZcsALc6t0+eCelPc44zZsLtCQnZPDwFpDYSWcDnrv2TtMmMbQ7uKo3J0HTURCqckw23czNQ=="],
|
||||
|
||||
@ -1321,7 +1329,7 @@
|
||||
|
||||
"typescript-eslint": ["typescript-eslint@8.65.0", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.65.0", "@typescript-eslint/parser": "8.65.0", "@typescript-eslint/typescript-estree": "8.65.0", "@typescript-eslint/utils": "8.65.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-/ggrHAwyjENDusvyxbuqxAC2dTnZg/Z8F+fgQtYIz+L6n/9HfSlEZcFGV/NsMNa6CkGk0xUjUAFwC0vHOflvIA=="],
|
||||
|
||||
"undici": ["undici@7.29.0", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
|
||||
"undici": ["undici@7.29.1", "", {}, "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q=="],
|
||||
|
||||
"undici-types": ["undici-types@7.28.0", "", {}, "sha512-LJAfY+2w6HGeT8d8J1wNQsUGUEGio6NWWpwdwurQe4f6oojzCFuGLizl1KSve4irsTxyLly1QhEeE6iapdaIvQ=="],
|
||||
|
||||
@ -1335,7 +1343,7 @@
|
||||
|
||||
"unrs-resolver": ["unrs-resolver@1.12.2", "", { "dependencies": { "napi-postinstall": "^0.3.4" }, "optionalDependencies": { "@unrs/resolver-binding-android-arm-eabi": "1.12.2", "@unrs/resolver-binding-android-arm64": "1.12.2", "@unrs/resolver-binding-darwin-arm64": "1.12.2", "@unrs/resolver-binding-darwin-x64": "1.12.2", "@unrs/resolver-binding-freebsd-x64": "1.12.2", "@unrs/resolver-binding-linux-arm-gnueabihf": "1.12.2", "@unrs/resolver-binding-linux-arm-musleabihf": "1.12.2", "@unrs/resolver-binding-linux-arm64-gnu": "1.12.2", "@unrs/resolver-binding-linux-arm64-musl": "1.12.2", "@unrs/resolver-binding-linux-loong64-gnu": "1.12.2", "@unrs/resolver-binding-linux-loong64-musl": "1.12.2", "@unrs/resolver-binding-linux-ppc64-gnu": "1.12.2", "@unrs/resolver-binding-linux-riscv64-gnu": "1.12.2", "@unrs/resolver-binding-linux-riscv64-musl": "1.12.2", "@unrs/resolver-binding-linux-s390x-gnu": "1.12.2", "@unrs/resolver-binding-linux-x64-gnu": "1.12.2", "@unrs/resolver-binding-linux-x64-musl": "1.12.2", "@unrs/resolver-binding-openharmony-arm64": "1.12.2", "@unrs/resolver-binding-wasm32-wasi": "1.12.2", "@unrs/resolver-binding-win32-arm64-msvc": "1.12.2", "@unrs/resolver-binding-win32-ia32-msvc": "1.12.2", "@unrs/resolver-binding-win32-x64-msvc": "1.12.2" } }, "sha512-dmlRxBJJayXjqTwC+JtF1HhJmgf3ftQ3YejFcZrf4+KKtJv0qDsK1pjqaaVjG7wJ5NJ6UVP1OqRMQ71Z4C3rxQ=="],
|
||||
|
||||
"update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
|
||||
"update-browserslist-db": ["update-browserslist-db@1.3.4", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A=="],
|
||||
|
||||
"uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
|
||||
|
||||
@ -1349,7 +1357,7 @@
|
||||
|
||||
"vite": ["vite@8.1.5", "", { "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.5", "postcss": "^8.5.17", "rolldown": "~1.1.5", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.3.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw=="],
|
||||
|
||||
"vitest": ["vitest@4.1.10", "", { "dependencies": { "@vitest/expect": "4.1.10", "@vitest/mocker": "4.1.10", "@vitest/pretty-format": "4.1.10", "@vitest/runner": "4.1.10", "@vitest/snapshot": "4.1.10", "@vitest/spy": "4.1.10", "@vitest/utils": "4.1.10", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.10", "@vitest/browser-preview": "4.1.10", "@vitest/browser-webdriverio": "4.1.10", "@vitest/coverage-istanbul": "4.1.10", "@vitest/coverage-v8": "4.1.10", "@vitest/ui": "4.1.10", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw=="],
|
||||
"vitest": ["vitest@4.1.12", "", { "dependencies": { "@vitest/expect": "4.1.12", "@vitest/mocker": "4.1.12", "@vitest/pretty-format": "4.1.12", "@vitest/runner": "4.1.12", "@vitest/snapshot": "4.1.12", "@vitest/spy": "4.1.12", "@vitest/utils": "4.1.12", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.12", "@vitest/browser-preview": "4.1.12", "@vitest/browser-webdriverio": "^4.1.11", "@vitest/coverage-istanbul": "4.1.12", "@vitest/coverage-v8": "4.1.12", "@vitest/ui": "4.1.12", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-5eWdz2yb3ajxWF3C8C4TjkXl7FGm3n2E/VlazALrQHzK7nYMSGFnCZto0bbPNl77AwkOZVLk0YnBAejUu0NiWA=="],
|
||||
|
||||
"w3c-xmlserializer": ["w3c-xmlserializer@5.0.0", "", { "dependencies": { "xml-name-validator": "^5.0.0" } }, "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA=="],
|
||||
|
||||
@ -1425,7 +1433,7 @@
|
||||
|
||||
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
|
||||
|
||||
"@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="],
|
||||
"@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
|
||||
|
||||
"@modelcontextprotocol/sdk/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
|
||||
|
||||
@ -1451,27 +1459,19 @@
|
||||
|
||||
"@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin/@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.65.0", "", { "dependencies": { "@typescript-eslint/types": "8.65.0", "@typescript-eslint/visitor-keys": "8.65.0" } }, "sha512-Esbl8OSYiVxBokYgWPf7VVWg/BE798wXhimnn9ML9Pt5qoDf8bfQlgjlKXR/k98+AcNzlLKYrpCcrcuZ9DZLgg=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin/@typescript-eslint/utils": ["@typescript-eslint/utils@8.65.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.65.0", "@typescript-eslint/types": "8.65.0", "@typescript-eslint/typescript-estree": "8.65.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-gXiwIHsYreboxeJucHKPvgwl7dXt50mF8s1/c00cP/WoVTyWKFdtfhRWwZiXYFU5H2O8vVoSLNrexFZjYS/SGA=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.6", "", {}, "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw=="],
|
||||
|
||||
"@typescript-eslint/parser/@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.65.0", "", { "dependencies": { "@typescript-eslint/types": "8.65.0", "@typescript-eslint/visitor-keys": "8.65.0" } }, "sha512-Esbl8OSYiVxBokYgWPf7VVWg/BE798wXhimnn9ML9Pt5qoDf8bfQlgjlKXR/k98+AcNzlLKYrpCcrcuZ9DZLgg=="],
|
||||
|
||||
"@typescript-eslint/parser/@typescript-eslint/types": ["@typescript-eslint/types@8.65.0", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
|
||||
|
||||
"@typescript-eslint/project-service/@typescript-eslint/types": ["@typescript-eslint/types@8.65.0", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
|
||||
|
||||
"@typescript-eslint/scope-manager/@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.64.0", "", { "dependencies": { "@typescript-eslint/types": "8.64.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-mrtuL8Nsn6gi2H4mo5KMTp823M+3Q19Ew/i+Zlikq20tIMm99C3Ez0dCmkWWnxut20esQvTg8aUSEhMcAOXhEw=="],
|
||||
"@typescript-eslint/scope-manager/@typescript-eslint/types": ["@typescript-eslint/types@8.65.0", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
|
||||
|
||||
"@typescript-eslint/type-utils/@typescript-eslint/types": ["@typescript-eslint/types@8.65.0", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
|
||||
|
||||
"@typescript-eslint/type-utils/@typescript-eslint/utils": ["@typescript-eslint/utils@8.65.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.65.0", "@typescript-eslint/types": "8.65.0", "@typescript-eslint/typescript-estree": "8.65.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-gXiwIHsYreboxeJucHKPvgwl7dXt50mF8s1/c00cP/WoVTyWKFdtfhRWwZiXYFU5H2O8vVoSLNrexFZjYS/SGA=="],
|
||||
|
||||
"@typescript-eslint/typescript-estree/@typescript-eslint/types": ["@typescript-eslint/types@8.65.0", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
|
||||
|
||||
"@typescript-eslint/utils/@typescript-eslint/typescript-estree": ["@typescript-eslint/typescript-estree@8.64.0", "", { "dependencies": { "@typescript-eslint/project-service": "8.64.0", "@typescript-eslint/tsconfig-utils": "8.64.0", "@typescript-eslint/types": "8.64.0", "@typescript-eslint/visitor-keys": "8.64.0", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-Pztpsn1aCE1oWDvDEfUk31nngvvF7vUB5SwHFEaZIFpvw7WJtqUHHL4plBZDA9HfWJJjL13BdG0YrJInTUvoVA=="],
|
||||
"@typescript-eslint/utils/@typescript-eslint/types": ["@typescript-eslint/types@8.65.0", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
|
||||
|
||||
"@typescript-eslint/visitor-keys/@typescript-eslint/types": ["@typescript-eslint/types@8.65.0", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
|
||||
|
||||
@ -1523,8 +1523,6 @@
|
||||
|
||||
"type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
|
||||
|
||||
"typescript-eslint/@typescript-eslint/utils": ["@typescript-eslint/utils@8.65.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.65.0", "@typescript-eslint/types": "8.65.0", "@typescript-eslint/typescript-estree": "8.65.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-gXiwIHsYreboxeJucHKPvgwl7dXt50mF8s1/c00cP/WoVTyWKFdtfhRWwZiXYFU5H2O8vVoSLNrexFZjYS/SGA=="],
|
||||
|
||||
"wsl-utils/is-wsl": ["is-wsl@3.1.1", "", { "dependencies": { "is-inside-container": "^1.0.0" } }, "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw=="],
|
||||
|
||||
"@dotenvx/dotenvx/execa/get-stream": ["get-stream@6.0.1", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="],
|
||||
@ -1569,20 +1567,6 @@
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin/@typescript-eslint/scope-manager/@typescript-eslint/types": ["@typescript-eslint/types@8.65.0", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin/@typescript-eslint/utils/@typescript-eslint/types": ["@typescript-eslint/types@8.65.0", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
|
||||
|
||||
"@typescript-eslint/scope-manager/@typescript-eslint/visitor-keys/eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],
|
||||
|
||||
"@typescript-eslint/type-utils/@typescript-eslint/utils/@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.65.0", "", { "dependencies": { "@typescript-eslint/types": "8.65.0", "@typescript-eslint/visitor-keys": "8.65.0" } }, "sha512-Esbl8OSYiVxBokYgWPf7VVWg/BE798wXhimnn9ML9Pt5qoDf8bfQlgjlKXR/k98+AcNzlLKYrpCcrcuZ9DZLgg=="],
|
||||
|
||||
"@typescript-eslint/utils/@typescript-eslint/typescript-estree/@typescript-eslint/project-service": ["@typescript-eslint/project-service@8.64.0", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.64.0", "@typescript-eslint/types": "^8.64.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-tk4WpOJ6IEbGrVHaNmM0YRrwAD3exZlIK3iadQNAxh4YKk6jvUQ4ecq18n+v7+meh+cJ3j+D8nbk8sRKhlwLQg=="],
|
||||
|
||||
"@typescript-eslint/utils/@typescript-eslint/typescript-estree/@typescript-eslint/tsconfig-utils": ["@typescript-eslint/tsconfig-utils@8.64.0", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-2yo8rRNKuzbVWQp5kslhANqZ2uDAeROQHBRZNPu8JDsHmeFNj/XJJhX/FhNUWmkHHvoNsKa6+tHJiig87EzsQw=="],
|
||||
|
||||
"@typescript-eslint/utils/@typescript-eslint/typescript-estree/@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.64.0", "", { "dependencies": { "@typescript-eslint/types": "8.64.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-mrtuL8Nsn6gi2H4mo5KMTp823M+3Q19Ew/i+Zlikq20tIMm99C3Ez0dCmkWWnxut20esQvTg8aUSEhMcAOXhEw=="],
|
||||
|
||||
"ajv-formats/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
|
||||
|
||||
"conf/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
|
||||
@ -1591,12 +1575,6 @@
|
||||
|
||||
"pkg-up/find-up/locate-path": ["locate-path@3.0.0", "", { "dependencies": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" } }, "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A=="],
|
||||
|
||||
"typescript-eslint/@typescript-eslint/utils/@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.65.0", "", { "dependencies": { "@typescript-eslint/types": "8.65.0", "@typescript-eslint/visitor-keys": "8.65.0" } }, "sha512-Esbl8OSYiVxBokYgWPf7VVWg/BE798wXhimnn9ML9Pt5qoDf8bfQlgjlKXR/k98+AcNzlLKYrpCcrcuZ9DZLgg=="],
|
||||
|
||||
"typescript-eslint/@typescript-eslint/utils/@typescript-eslint/types": ["@typescript-eslint/types@8.65.0", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
|
||||
|
||||
"@typescript-eslint/utils/@typescript-eslint/typescript-estree/@typescript-eslint/visitor-keys/eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],
|
||||
|
||||
"pkg-up/find-up/locate-path/p-locate": ["p-locate@3.0.0", "", { "dependencies": { "p-limit": "^2.0.0" } }, "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ=="],
|
||||
|
||||
"pkg-up/find-up/locate-path/path-exists": ["path-exists@3.0.0", "", {}, "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ=="],
|
||||
|
||||
@ -17,10 +17,11 @@ Optional AI path
|
||||
Browser → local Shotluma bridge → Codex App Server → ChatGPT plan
|
||||
Browser → AI SDK provider → Google / Qwen / OpenAI / Anthropic / xAI / OpenRouter
|
||||
Browser → /api/moonshot/* → Vite proxy → Moonshot API
|
||||
Browser → /api/opencode/* → Vite or Cloudflare Worker proxy → OpenCode Zen/Go
|
||||
Browser → /api/ai-run-logs → Vite → ./ai-logs/*.json (developer opt-in)
|
||||
```
|
||||
|
||||
The core editor has no backend requirement. Hosted users can connect a Codex app or CLI already signed in with ChatGPT on the same computer; `app.shotluma.com` remains the application host. The browser talks to a paired loopback bridge, and the bridge talks to Codex App Server over stdio. The alternative AI path uses bring-your-own keys entered in the browser (`localStorage`), with optional `.env.local` `VITE_*` fallback served only during local development. Production builds replace all provider env values with empty strings. Google, Qwen, OpenAI, Anthropic, xAI, and OpenRouter are called directly; Moonshot is enabled only on localhost and uses a same-origin proxy because its API does not support the required browser CORS flow.
|
||||
The core editor has no backend requirement. Hosted users can connect a Codex app or CLI already signed in with ChatGPT on the same computer; `app.shotluma.com` remains the application host. The browser talks to a paired loopback bridge, and the bridge talks to Codex App Server over stdio. The alternative AI path uses bring-your-own keys entered in the browser (`localStorage`), with optional `.env.local` `VITE_*` fallback served only during local development. Production builds replace all provider env values with empty strings. Google, Qwen, OpenAI, Anthropic, xAI, and OpenRouter are called directly; Moonshot is enabled only on localhost and uses a same-origin proxy because its API does not support the required browser CORS flow. OpenCode Zen and Go share one API key and use the same-origin `/api/opencode` proxy (Vite in local dev, Cloudflare Worker when hosted) for the same CORS reason.
|
||||
|
||||
This public repository contains and deploys only the editor at
|
||||
`app.shotluma.com`. The marketing site at `shotluma.com` has a separate private
|
||||
@ -90,6 +91,43 @@ Persistence is browser-local:
|
||||
|
||||
Avoid putting credentials or provider responses into persisted project data.
|
||||
|
||||
### Share links
|
||||
|
||||
`src/app/share-link.ts` implements project sharing. The share payload is the
|
||||
whole project as deflate-raw-compressed JSON with every image inlined as a
|
||||
data URL (images are additionally capped at export resolution and re-encoded
|
||||
as WebP when that is smaller). Two link forms exist:
|
||||
|
||||
- `/s/<id>` (preferred): the payload is uploaded to the share API and only a
|
||||
short id travels in the link. `scripts/share-api.ts` is mounted into the
|
||||
`shotluma-app` Worker entry (`scripts/shotluma-worker.ts`) that also serves
|
||||
the editor assets (`assets.run_worker_first` routes `/api/share*` and
|
||||
`/s/*` through the script) and stores payloads opaquely in the `SHARE_KV`
|
||||
KV namespace with a 90-day TTL and a 10 MB cap. The id lives in the URL path because link-preview crawlers
|
||||
never send fragments: `GET /s/<id>` serves the editor's index.html with
|
||||
per-share Open Graph tags injected (project name plus a 1200 × 630 unfurl
|
||||
image that `src/app/share-preview.ts` renders client-side from the live
|
||||
artboards, using colors sampled from the rendered first screen for its
|
||||
backdrop, and uploads best-effort at share time). The app consumes the path
|
||||
on boot and rewrites the URL back to `/`. The equivalent `#s=<id>` fragment
|
||||
form is also consumed on boot as a compatibility format — it just cannot
|
||||
carry per-share OG tags because crawlers never send fragments. During local
|
||||
dev the Vite server proxies `/api/share` to the deployed Worker.
|
||||
- `#share=<base64url payload>` (fallback): when the share API is unreachable
|
||||
the link carries the payload itself, so sharing degrades gracefully instead
|
||||
of failing; such links can get very long and the dialog says so.
|
||||
|
||||
Opening either link imports the payload as a new, independent local project —
|
||||
inlined images become locally stored Blobs — so the recipient can edit or
|
||||
delete their copy without ever affecting the sender's project. This is the
|
||||
only place project data can leave the browser, and only when the user
|
||||
explicitly creates a share link. A share payload is untrusted input: decoding
|
||||
re-sanitizes AI screen markup and rich text, drops malformed slides, elements,
|
||||
and uploads, rejects unsafe image source schemes, and caps the decompressed
|
||||
size so a handcrafted link cannot act as a decompression bomb. The import path
|
||||
consumes the fragment exactly once and is cached module-wide because React
|
||||
StrictMode double-invokes the hydration effect in development.
|
||||
|
||||
Developer AI run logging is enabled only when `SHOTLUMA_AI_LOGGING=true`. The browser sends a versioned, bounded record to the local Vite middleware, which validates it and writes one JSON file per run to the git-ignored `ai-logs/` directory in the repository. Records include normalized total and per-step token usage, per-step tool and preview counts, visible text and reasoning output, tool activity, and coarse request sizes. Shotluma does not add input prompt text, screenshot payloads or names, credentials, or raw provider metadata to the records.
|
||||
|
||||
## Export
|
||||
@ -139,6 +177,11 @@ The AI feature is split into explicit layers:
|
||||
| `src/html-slide/device-attributes.ts` | `<shotluma-device>` placeholder parsing |
|
||||
| `src/ai/prompt-caching.ts` | OpenAI, Anthropic, and Qwen prompt-cache routing and breakpoints |
|
||||
| `src/ai/chat-tool-images.ts` | Image relay for providers whose chat tool results support text only |
|
||||
| `src/ai/describe-images.ts` | Replace image parts with text descriptions for models without vision |
|
||||
| `src/ai/opencode-models.ts` | Runtime OpenCode Zen/Go catalog, vision flags, and fallback picker |
|
||||
| `src/ai/opencode-client.ts` | OpenAI-compat chat client against the same-origin OpenCode proxy |
|
||||
| `scripts/opencode-proxy.ts` | URL rewrite and header allowlist for Zen/Go |
|
||||
| `scripts/shotluma-worker.ts` | Hosted Cloudflare Worker that proxies `/api/opencode/*` |
|
||||
| `src/ai/tools.ts` | Tool composition and generate/edit tool boundary |
|
||||
| `src/ai/*-tools.ts`, `src/ai/*-tool.ts` | Focused slide, media, text, update, inspection, and overlay-asset tools |
|
||||
| `src/ai/chroma-key.ts` | Pure soft chroma-key pixel math for overlay cutouts |
|
||||
@ -168,13 +211,15 @@ Rich text is built from structured highlight input. The model never writes raw H
|
||||
|
||||
The generate dialog covers input only. Once a run starts it closes and `src/components/AiRunBand.tsx` takes over as a band floating over the canvas: assistant prose and reasoning at reading size (accumulated per sentence by `src/ai/run-narration.ts`), a screen rail fed by the model's `declare_plan` call and reconciled against reality by `src/ai/run-plan.ts`, and an action count in place of a tool log. The band is also where a finished or failed run reports its result, so no run hands control back to the centered dialog.
|
||||
|
||||
`src/ai/provider-catalog.ts` owns the selectable providers, models, transport metadata, and model-specific reasoning-effort choices. `src/ai/provider-config.ts` resolves keys from browser `localStorage` (API keys dialog) with optional `.env.local` `VITE_*` fallback, and `src/ai/runner.ts` routes either to the Codex bridge or a lazily loaded native AI SDK provider. The runner passes portable efforts through the AI SDK's standardized `reasoning` option so each native provider can map it to its own API; OpenAI GPT-5.6 and Moonshot/Kimi K3 `max` go through OpenAI-compat `providerOptions` because the shared option has no `max`. The generate modal presents one model picker grouped by provider, with reasoning effort as secondary chips when the model supports it, a Codex connection tutorial, and an API keys dialog for key-based providers. Requests go directly from the local browser to Google, Alibaba/Qwen, OpenAI, Anthropic, xAI, or OpenRouter. Moonshot uses the OpenAI chat provider through the only Vite proxy route.
|
||||
`src/ai/provider-catalog.ts` owns the selectable providers, models, transport metadata, and model-specific reasoning-effort choices. `src/ai/provider-config.ts` resolves keys from browser `localStorage` (API keys dialog) with optional `.env.local` `VITE_*` fallback, and `src/ai/runner.ts` routes either to the Codex bridge or a lazily loaded native AI SDK provider. The runner passes portable efforts through the AI SDK's standardized `reasoning` option so each native provider can map it to its own API; OpenAI GPT-6 Astra, GPT-5.6, and Moonshot/Kimi K3 `max` go through OpenAI-compat `providerOptions` because the shared option has no `max`. The generate modal presents one model picker grouped by provider, with reasoning effort as secondary chips when the model supports it, a Codex connection tutorial, and an API keys dialog for key-based providers. Requests go directly from the local browser to Google, Alibaba/Qwen, OpenAI, Anthropic, xAI, or OpenRouter. Moonshot uses the OpenAI chat provider through the local Vite proxy. OpenCode Zen and Go share one API key, call chat-completions through `/api/opencode`, and describe images with a second vision model when the selected model has no native vision.
|
||||
|
||||
Codex pairing is deliberately not OAuth inside Shotluma. The setup prompt downloads the connector asset emitted with the hosted app, asks Codex to inspect it, and starts it as a detached user process. The browser stores a random pairing token and the exact app origin. The connector binds only `127.0.0.1:47447`, stores its matching configuration with user-only permissions, requires both the exact `Origin` header and bearer pairing token, and never reads Codex authentication files. It starts `codex app-server` over stdio and allowlists only account/rate-limit/model reads plus ephemeral thread and turn methods. Thread and turn requests are overwritten to use an empty read-only workspace, no approvals, and no network. The model can change the canvas only through the same `createEditorTools` dynamic tools used by direct providers.
|
||||
|
||||
The bridge uses Codex App Server's experimental dynamic-tool API. Keep bridge and web-client versions compatible, fail closed on unknown RPC methods, and retain the API-key provider path as a fallback while this integration is experimental.
|
||||
|
||||
OpenRouter is the one provider with a runtime model catalog: `src/ai/openrouter-models.ts` fetches the public OpenRouter `/models` endpoint (no key required), keeps only models that accept image input and support tool calling, caches the result in `localStorage` for an hour, and registers it with the static catalog so selections resolve everywhere. The curated OpenRouter shortlist in `provider-catalog.ts` doubles as the offline fallback, and the model picker adds a searchable browser over the fetched catalog. Requests use the OpenAI chat provider against `https://openrouter.ai/api/v1`.
|
||||
OpenRouter is one runtime model catalog: `src/ai/openrouter-models.ts` fetches the public OpenRouter `/models` endpoint (no key required), keeps only models that accept image input and support tool calling, caches the result in `localStorage` for an hour, and registers it with the static catalog so selections resolve everywhere. The curated OpenRouter shortlist in `provider-catalog.ts` doubles as the offline fallback, and the model picker adds a searchable browser over the fetched catalog. Requests use the OpenAI chat provider against `https://openrouter.ai/api/v1`.
|
||||
|
||||
OpenCode Zen and Go are the other runtime catalogs: `src/ai/opencode-models.ts` fetches each gateway's `/v1/models` list through the same-origin proxy, keeps every tool-capable model including those without vision, and caches for an hour. Text-only models stay selectable; `src/ai/describe-images.ts` sends screenshots and slide previews to a vision model from the same gateway (defaulting to a cheap one such as MiMo V2.5 Free on Zen or MiMo V2.5 on Go) and replaces the image parts with the description before the coding model runs.
|
||||
|
||||
Keys are intentionally browser-visible and stored unencrypted. Never commit `.env.local` or weaken the production-build stripping of provider env values. Use dedicated keys with restrictive quotas. A hosted deployment that must hide or share credentials needs an authenticated backend.
|
||||
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
Every step of a multi-step AI run re-reads the growing conversation history, so the input token count scales quadratically with the number of turns. Prompt caching converts most of that re-read cost into 90% discounted cache reads. The runner applies provider-specific cache routing:
|
||||
|
||||
- **Anthropic**: one fixed `cacheControl` breakpoint on the system instructions caches tools plus the static prompt, while a second breakpoint moves to the last message through `prepareStep` (`src/ai/prompt-caching.ts`). The fixed breakpoint protects the reusable prefix when a large parallel-tool turn exceeds Anthropic's moving lookback window.
|
||||
- **OpenAI**: a browser-session `promptCacheKey` is partitioned by model, mode, and overlay-tool availability. GPT-5.6 receives an explicit breakpoint after the stable instructions while implicit mode continues caching the growing tool loop. This allows cross-run static-prefix hits without giving up within-run history hits; the session id also shards traffic below OpenAI's per-key routing guidance.
|
||||
- **OpenAI**: a browser-session `promptCacheKey` is partitioned by model, mode, and overlay-tool availability. GPT-6 Astra and GPT-5.6 receive an explicit breakpoint after the stable instructions while implicit mode continues caching the growing tool loop. This allows cross-run static-prefix hits without giving up within-run history hits; the session id also shards traffic below OpenAI's per-key routing guidance.
|
||||
- **Alibaba/Qwen**: explicit `cacheControl` uses the same fixed-instruction plus moving-message pattern as Anthropic through the Alibaba provider namespace.
|
||||
- **Google Gemini**: implicit caching is automatic on 2.5+ models. No configuration needed; savings are passed through when request prefixes match.
|
||||
|
||||
@ -13,11 +13,24 @@ Generate mode does not spend a model turn re-reading canvas state already presen
|
||||
|
||||
Preview images are rendered at the editor's native 330 px width rather than upscaled, use OpenAI's low-detail vision path because exact geometry arrives separately, and are capped at three attempts per generated screen (four for edit mode's before/after checks). Mutations return only warnings involving the changed element; the preview is the one deduplicated slide-wide validation point. Measurement boxes remain rounded to one decimal (`src/ai/measure.ts`).
|
||||
|
||||
OpenAI Responses, Anthropic, Google, xAI, and Codex accept image-bearing tool results directly. OpenAI-compatible Chat Completions and Alibaba do not: before Moonshot, OpenRouter, or Qwen steps, `src/ai/chat-tool-images.ts` moves image files out of the tool-result JSON and into a following multimodal user message. Never allow base64 image data to be serialized as model-visible text.
|
||||
OpenAI Responses, Anthropic, Google, xAI, and Codex accept image-bearing tool results directly. OpenAI-compatible Chat Completions and Alibaba do not: before Moonshot, OpenRouter, Qwen, or chat-completions OpenCode steps, `src/ai/chat-tool-images.ts` moves image files out of the tool-result JSON and into a following multimodal user message. Never allow base64 image data to be serialized as model-visible text.
|
||||
|
||||
OpenCode models without native vision then go through `src/ai/describe-images.ts`: each remaining image part is sent to a vision-capable model on the same Zen or Go gateway, and the coding model receives the text description instead. Do not send raw images to a text-only OpenCode model.
|
||||
|
||||
## Security and provider boundary
|
||||
|
||||
The browser uses the AI SDK's native Google, Alibaba/Qwen, OpenAI, Anthropic, and xAI providers directly. OpenRouter is called directly through the OpenAI chat provider against `https://openrouter.ai/api/v1`. Moonshot uses the OpenAI chat provider through the local `/api/moonshot` CORS proxy.
|
||||
The browser uses the AI SDK's native Google, Alibaba/Qwen, OpenAI, Anthropic, and xAI providers directly. OpenRouter is called directly through the OpenAI chat provider against `https://openrouter.ai/api/v1`. Moonshot uses the OpenAI chat provider through the local `/api/moonshot` CORS proxy. OpenCode Zen and Go go through `/api/opencode/{zen|go}/v1` because `opencode.ai` does not answer browser CORS preflight.
|
||||
|
||||
OpenCode is a multi-dialect gateway, not an OpenAI-compatible one. Each model answers on exactly one endpoint, and calling any other returns a 400 or an `Endpoint is unavailable` 5xx rather than routing itself. `src/ai/opencode-dialects.ts` owns the mapping and `src/ai/opencode-client.ts` builds the matching provider:
|
||||
|
||||
| Dialect | Endpoint | Provider | Families |
|
||||
| --- | --- | --- | --- |
|
||||
| `responses` | `/v1/responses` | `@ai-sdk/openai` Responses | `gpt-*`, `grok-*`, `muse-spark-*` |
|
||||
| `messages` | `/v1/messages` | `@ai-sdk/anthropic` | `claude-*`, `qwen*`, `minimax-*` on Go only |
|
||||
| `google` | `/v1/models/<id>:…` | `@ai-sdk/google` | `gemini-*` |
|
||||
| `chat` | `/v1/chat/completions` | `@ai-sdk/openai` chat | everything else, including `minimax-*` on Zen |
|
||||
|
||||
Match `src/ai/opencode-dialects.ts` against the endpoint tables at <https://opencode.ai/docs/zen> and <https://opencode.ai/docs/go> whenever OpenCode adds a family; prefixes are matched rather than exact ids because `/v1/models` only reports ids and keeps growing. Chat completions is the default for an unrecognised id because every open-weight family lands there. The proxy header allowlist in `scripts/opencode-proxy.ts` must keep carrying `x-api-key`, `anthropic-version`, `anthropic-beta`, and `x-goog-api-key` alongside `authorization`, or the non-OpenAI dialects lose their credentials.
|
||||
|
||||
Codex is a separate no-API-key transport for hosted users. The browser pairs with `scripts/shotluma-codex-bridge.ts` on `127.0.0.1`; that process launches `codex app-server` over stdio and uses Codex's existing ChatGPT authentication. The user stays on `app.shotluma.com` and never needs a repository checkout or local Vite server.
|
||||
|
||||
@ -29,7 +42,7 @@ Codex is a separate no-API-key transport for hosted users. The browser pairs wit
|
||||
- `scripts/codex-bridge-asset-plugin.ts` must emit the reviewed connector source at `/codex/shotluma-codex-bridge.mjs` in both development and production builds. The copied setup prompt must use the current browser origin so normal hosted and self-hosted deployments pair only with themselves.
|
||||
- Open the ChatGPT desktop app with the documented `codex://threads/new?prompt=` deep link and URI-encode the complete setup prompt. Deep links prefill but do not submit the composer, so the tutorial must tell the user to press Send and retain the manual copy fallback.
|
||||
- Keys are intentionally visible to same-origin browser JavaScript. Never commit `.env.local`, reuse a shared production credential, or weaken the production build boundary. Recommend dedicated keys with restrictive quotas.
|
||||
- Do not add a proxy for providers whose browser API supports the required CORS flow. Moonshot is available only on localhost through `/api/moonshot`; a hosted deployment that offers Moonshot or must hide keys needs a separate authenticated backend design.
|
||||
- Do not add a proxy for providers whose browser API supports the required CORS flow. Moonshot is available only on localhost through `/api/moonshot`; a hosted deployment that offers Moonshot or must hide keys needs a separate authenticated backend design. OpenCode is the exception that is proxied in production as well: `scripts/shotluma-worker.ts` forwards `/api/opencode/*` to `opencode.ai`, copying only the allowlisted auth headers upstream without storing or logging the caller's key.
|
||||
- Never return secrets or raw data URLs in model-visible state.
|
||||
- Keep uploads browser-local except for screenshots and app logos explicitly included in an AI run.
|
||||
- In generate mode, collect app name and app logo separately from the app description and screenshots. Pass the name and logo asset id through the user message and attach the logo image. Instruct the model to place the logo with `add_image` in element runs and with an `<img src="asset:…">` tag in HTML screen runs — never as a device screenshot.
|
||||
@ -73,6 +86,10 @@ An opt-in generate-dialog toggle lets the model author whole screens as HTML doc
|
||||
|
||||
The controller adapter must update `slidesRef` synchronously before React state because multiple tool calls can read and write in one tick. Preserve the non-history adapter and create one checkpoint before a run so the entire generation remains one undo step.
|
||||
|
||||
A run belongs to exactly one project, and the slide/upload refs are shared across project switches. `useAiWorkflow` therefore owns the run lifecycle: the modal registers a cancel handle for the live run (`onRunStateChange`), controller writes are gated on that registration, and `cancelActiveRun` must be called before any path that swaps the refs to another project — the confirm dialog covers user-initiated switches, and `handleProjectReplaced` is the unconditional safety net. Never let a generation write into a project it was not started in.
|
||||
|
||||
Project switch, creation, and duplication during a live run go through the `AiRunCancelDialog` confirm; project deletion is disabled until the run ends; `beforeunload` warns only while a run is active. Saves during a run carry `PersistedProject.interruptedGeneration`, which is cleared by one save after the run ends and otherwise consumed on the next load with a one-time toast explaining the half-finished screens.
|
||||
|
||||
Clear selection before generation and preview capture. Any live overlay must carry `data-ai-overlay` and remain filtered from preview and export.
|
||||
|
||||
## Canvas and prompt contract
|
||||
@ -102,10 +119,12 @@ While a run is live, the editor shows `src/components/AiRunBand.tsx` — a float
|
||||
|
||||
In edit mode there is one target screen and no plan, so the rail is omitted and the band renders narrow. The run band is also the result and error surface — a finished run stays in place instead of handing back to the centered dialog.
|
||||
|
||||
Reasoning-effort choices belong to the model catalog. Offer only values supported by the selected model (never a provider-default option) and default to `high` when the model supports it, otherwise `medium`. Pass portable efforts through the AI SDK's top-level `reasoning` option. OpenAI GPT-5.6 (Luna/Terra/Sol) and Moonshot/Kimi K3 also offer `max`, which the runner sends via OpenAI-compat `providerOptions.openai.reasoningEffort` because the shared SDK option has no `max`. Do not duplicate provider-specific effort mapping in the UI. The generate modal exposes one model picker grouped by provider; reasoning effort appears as secondary chips only when the selected model supports it.
|
||||
Reasoning-effort choices belong to the model catalog. Offer only values supported by the selected model (never a provider-default option) and default to `high` when the model supports it, otherwise `medium`. Pass portable efforts through the AI SDK's top-level `reasoning` option. OpenAI GPT-6 Astra, GPT-5.6 (Luna/Terra/Sol), and Moonshot/Kimi K3 also offer `max`, which the runner sends via OpenAI-compat `providerOptions.openai.reasoningEffort` because the shared SDK option has no `max`. Do not duplicate provider-specific effort mapping in the UI. The generate modal exposes one model picker grouped by provider; reasoning effort appears as secondary chips only when the selected model supports it.
|
||||
|
||||
Reasoning **visibility** is a separate switch from reasoning **effort**, and providers are asymmetric about it. OpenAI's Responses API defaults `reasoningSummary` to `'detailed'` as soon as an effort is set, so thoughts stream without being asked for. Google does not: in `@ai-sdk/google`, `thinkingLevel` and `thinkingBudget` fall back to the mapped top-level `reasoning` value, but `includeThoughts` reads *only* from `providerOptions.google.thinkingConfig` with no fallback. Omit it and Gemini still thinks and still bills the tokens while withholding every thought summary — the run band stays empty for the whole run. `buildStreamRequestOptions` (`src/ai/prompt-caching.ts`) therefore always sends `thinkingConfig: { includeThoughts: true }` for Google, across all Gemini generations (the `thinkingLevel`/`thinkingBudget` split is generation-specific; `includeThoughts` is not). Keep that object limited to `includeThoughts`: adding `thinkingLevel` or `thinkingBudget` there would take full precedence over the portable `reasoning` option and silently discard the user's effort choice.
|
||||
|
||||
This matters more than a missing nicety because `prompt.ts` tells the model not to narrate its work turn by turn. Reasoning is therefore the only live prose during a run, and for a model that streams none, the tool-activity line in the run band is the only remaining signal — it is load-bearing, not decoration.
|
||||
|
||||
OpenRouter is the only provider with a runtime model catalog (`src/ai/openrouter-models.ts`): the public `/models` endpoint is fetched without a key, filtered to models that accept image input and support tool calling — both are hard requirements for a Shotluma run — and cached in `localStorage` for an hour. Loaded models are registered with `setDynamicOpenRouterModels` so catalog lookups resolve them; unknown OpenRouter ids synthesize a minimal option instead of throwing, while every other provider keeps failing fast on unknown models. Keep the curated OpenRouter shortlist in `provider-catalog.ts` working as the fetch fallback, keep the vision+tools filter intact, and offer reasoning effort only when the fetched model advertises the `reasoning` parameter.
|
||||
OpenRouter is a runtime model catalog (`src/ai/openrouter-models.ts`): the public `/models` endpoint is fetched without a key, filtered to models that accept image input and support tool calling — both are hard requirements for a Shotluma run — and cached in `localStorage` for an hour. Loaded models are registered with `setDynamicProviderModels` so catalog lookups resolve them; unknown OpenRouter ids synthesize a minimal option instead of throwing, while every other static provider keeps failing fast on unknown models. Keep the curated OpenRouter shortlist in `provider-catalog.ts` working as the fetch fallback, keep the vision+tools filter intact, and offer reasoning effort only when the fetched model advertises the `reasoning` parameter.
|
||||
|
||||
OpenCode Zen and Go are also runtime catalogs (`src/ai/opencode-models.ts`). Fetch `/v1/models` through the same-origin proxy, keep text-only tool models, and mark them `supportsVision: false`. The generate modal exposes a vision-fallback picker for those models. Unknown OpenCode ids synthesize like OpenRouter.
|
||||
|
||||
@ -15,6 +15,8 @@ Do not broaden a task through opportunistic rewrites. A prerequisite refactor is
|
||||
- Add a dependency only when platform APIs and current dependencies cannot solve the problem cleanly.
|
||||
- Prefer maintained, typed packages with compatible licenses and a narrow runtime footprint.
|
||||
- Run `bun audit` after dependency changes.
|
||||
- Keep the `overrides` entries on the lowest patched release; they exist only to replace versions that dependents still pin.
|
||||
- The audit script ignores `GHSA-vfj7-8cjw-p6xm` (`braces`), which has no patched release upstream and only reaches the project through the shadcn CLI. Remove the ignore once `braces` publishes a fix.
|
||||
- Do not remove the `@hono/node-server` override without testing shadcn add/apply, the build, and the audit.
|
||||
- Do not edit `dist/`, coverage output, lockfile internals, or shadcn-generated source manually.
|
||||
|
||||
|
||||
28
package.json
28
package.json
@ -2,19 +2,27 @@
|
||||
"name": "shotluma",
|
||||
"description": "An AI-first, local-first canvas editor for editable App Store screenshot sets.",
|
||||
"private": true,
|
||||
"version": "0.4.0",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"packageManager": "bun@1.3.9",
|
||||
"overrides": {
|
||||
"@hono/node-server": "2.0.10",
|
||||
"brace-expansion": "5.0.9",
|
||||
"fast-uri": "3.1.5",
|
||||
"hono": "4.12.34",
|
||||
"ip-address": "10.4.0",
|
||||
"js-yaml": "4.3.1",
|
||||
"@modelcontextprotocol/sdk": "1.32.1",
|
||||
"baseline-browser-mapping": "2.11.30",
|
||||
"brace-expansion": "5.0.12",
|
||||
"browserslist": "4.29.4",
|
||||
"fast-uri": "3.1.8",
|
||||
"hono": "4.13.13",
|
||||
"ip-address": "10.7.4",
|
||||
"js-yaml": "4.3.2",
|
||||
"nanoid": "3.3.18",
|
||||
"postcss": "8.5.25",
|
||||
"undici": "7.29.0"
|
||||
"postcss-selector-parser": "7.1.6",
|
||||
"proxy-addr": "2.0.8",
|
||||
"qs": "6.16.1",
|
||||
"sharp": "0.35.5",
|
||||
"source-map-js": "1.2.2",
|
||||
"undici": "7.29.1"
|
||||
},
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@ -31,7 +39,7 @@
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"audit": "bun audit",
|
||||
"audit": "bun audit --ignore=GHSA-vfj7-8cjw-p6xm",
|
||||
"check": "bun run structure && bun run lint && bun run test:coverage && bun run build && bun run audit"
|
||||
},
|
||||
"dependencies": {
|
||||
@ -86,7 +94,7 @@
|
||||
"@types/react": "latest",
|
||||
"@types/react-dom": "latest",
|
||||
"@vitejs/plugin-react": "latest",
|
||||
"@vitest/coverage-v8": "^4.1.6",
|
||||
"@vitest/coverage-v8": "^4.1.12",
|
||||
"eslint": "latest",
|
||||
"eslint-import-resolver-typescript": "^4.4.5",
|
||||
"eslint-plugin-import-x": "^4.17.1",
|
||||
@ -98,7 +106,7 @@
|
||||
"typescript": "5.9.3",
|
||||
"typescript-eslint": "latest",
|
||||
"vite": "latest",
|
||||
"vitest": "^4.1.6",
|
||||
"vitest": "^4.1.12",
|
||||
"wrangler": "4.118.0"
|
||||
}
|
||||
}
|
||||
|
||||
@ -17,6 +17,7 @@ describe('client provider environment', () => {
|
||||
expect(values.VITE_MOONSHOT_API_KEY).toBe('moonshot-public')
|
||||
expect(values.VITE_OPENAI_API_KEY).toBe('openai-public')
|
||||
expect(values.VITE_XAI_API_KEY).toBe('')
|
||||
expect(values.VITE_OPENCODE_API_KEY).toBe('')
|
||||
expect(values).not.toHaveProperty('MOONSHOT_API_KEY')
|
||||
})
|
||||
|
||||
@ -28,6 +29,7 @@ describe('client provider environment', () => {
|
||||
VITE_OPENAI_API_KEY: '',
|
||||
VITE_ANTHROPIC_API_KEY: '',
|
||||
VITE_XAI_API_KEY: '',
|
||||
VITE_OPENCODE_API_KEY: '',
|
||||
})
|
||||
expect(createClientProviderDefinitions(environment, 'build')).toMatchObject({
|
||||
'import.meta.env.VITE_MOONSHOT_API_KEY': '""',
|
||||
|
||||
@ -5,6 +5,7 @@ export const AI_PROVIDER_ENV_VARIABLES = [
|
||||
'VITE_OPENAI_API_KEY',
|
||||
'VITE_ANTHROPIC_API_KEY',
|
||||
'VITE_XAI_API_KEY',
|
||||
'VITE_OPENCODE_API_KEY',
|
||||
] as const
|
||||
|
||||
export type AiProviderEnvironmentVariable = typeof AI_PROVIDER_ENV_VARIABLES[number]
|
||||
|
||||
140
scripts/opencode-proxy.test.ts
Normal file
140
scripts/opencode-proxy.test.ts
Normal file
@ -0,0 +1,140 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
copyOpencodeProxyHeaders,
|
||||
isOpencodeProxyMethod,
|
||||
proxyOpencodeRequest,
|
||||
rewriteOpencodeProxyUrl,
|
||||
} from './opencode-proxy'
|
||||
|
||||
describe('OpenCode CORS proxy rewrite', () => {
|
||||
it('maps Zen and Go prefixes onto the public OpenCode origins', () => {
|
||||
expect(rewriteOpencodeProxyUrl(
|
||||
new URL('https://app.shotluma.com/api/opencode/zen/v1/chat/completions'),
|
||||
)?.toString()).toBe('https://opencode.ai/zen/v1/chat/completions')
|
||||
expect(rewriteOpencodeProxyUrl(
|
||||
new URL('https://app.shotluma.com/api/opencode/go/v1/models?foo=1'),
|
||||
)?.toString()).toBe('https://opencode.ai/zen/go/v1/models?foo=1')
|
||||
expect(rewriteOpencodeProxyUrl(
|
||||
new URL('https://app.shotluma.com/api/opencode/zen'),
|
||||
)?.toString()).toBe('https://opencode.ai/zen/')
|
||||
expect(rewriteOpencodeProxyUrl(
|
||||
new URL('https://app.shotluma.com/api/moonshot/v1/chat/completions'),
|
||||
)).toBeNull()
|
||||
expect(rewriteOpencodeProxyUrl(
|
||||
new URL('https://app.shotluma.com/api/opencode/go'),
|
||||
)?.toString()).toBe('https://opencode.ai/zen/go/')
|
||||
})
|
||||
|
||||
it('maps every dialect path each gateway serves', () => {
|
||||
expect(rewriteOpencodeProxyUrl(
|
||||
new URL('https://app.shotluma.com/api/opencode/go/v1/responses'),
|
||||
)?.toString()).toBe('https://opencode.ai/zen/go/v1/responses')
|
||||
expect(rewriteOpencodeProxyUrl(
|
||||
new URL('https://app.shotluma.com/api/opencode/zen/v1/messages'),
|
||||
)?.toString()).toBe('https://opencode.ai/zen/v1/messages')
|
||||
expect(rewriteOpencodeProxyUrl(
|
||||
new URL('https://app.shotluma.com/api/opencode/zen/v1/models/gemini-3.7-flash:streamGenerateContent'),
|
||||
)?.toString()).toBe('https://opencode.ai/zen/v1/models/gemini-3.7-flash:streamGenerateContent')
|
||||
})
|
||||
|
||||
it('does not treat a zen path as go', () => {
|
||||
expect(rewriteOpencodeProxyUrl(
|
||||
new URL('https://app.shotluma.com/api/opencode/zen/v1/models'),
|
||||
)?.toString()).toBe('https://opencode.ai/zen/v1/models')
|
||||
})
|
||||
})
|
||||
|
||||
describe('OpenCode CORS proxy headers and methods', () => {
|
||||
it('forwards only the allowlisted request headers', () => {
|
||||
const headers = copyOpencodeProxyHeaders(new Headers({
|
||||
authorization: 'Bearer test-key',
|
||||
'content-type': 'application/json',
|
||||
accept: 'text/event-stream',
|
||||
'x-opencode-session': 'shotluma-test-session',
|
||||
cookie: 'session=secret',
|
||||
host: 'app.shotluma.com',
|
||||
}))
|
||||
expect(Object.fromEntries(headers.entries())).toEqual({
|
||||
authorization: 'Bearer test-key',
|
||||
'content-type': 'application/json',
|
||||
accept: 'text/event-stream',
|
||||
'x-opencode-session': 'shotluma-test-session',
|
||||
})
|
||||
})
|
||||
|
||||
it('forwards the Anthropic and Google credentials the other dialects use', () => {
|
||||
const headers = copyOpencodeProxyHeaders(new Headers({
|
||||
'x-api-key': 'sk-test',
|
||||
'anthropic-version': '2023-06-01',
|
||||
'anthropic-beta': 'fine-grained-tool-streaming-2025-05-14',
|
||||
'x-goog-api-key': 'goog-test',
|
||||
origin: 'https://evil.example',
|
||||
}))
|
||||
expect(Object.fromEntries(headers.entries())).toEqual({
|
||||
'x-api-key': 'sk-test',
|
||||
'anthropic-version': '2023-06-01',
|
||||
'anthropic-beta': 'fine-grained-tool-streaming-2025-05-14',
|
||||
'x-goog-api-key': 'goog-test',
|
||||
})
|
||||
})
|
||||
|
||||
it('allows GET, POST, and OPTIONS only', () => {
|
||||
expect(isOpencodeProxyMethod('get')).toBe(true)
|
||||
expect(isOpencodeProxyMethod('POST')).toBe(true)
|
||||
expect(isOpencodeProxyMethod('OPTIONS')).toBe(true)
|
||||
expect(isOpencodeProxyMethod('PUT')).toBe(false)
|
||||
})
|
||||
|
||||
it('answers OPTIONS without contacting OpenCode', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const response = await proxyOpencodeRequest(new Request(
|
||||
'https://app.shotluma.com/api/opencode/zen/v1/models',
|
||||
{ method: 'OPTIONS' },
|
||||
))
|
||||
expect(response.status).toBe(204)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('rejects unsupported methods and unknown paths', async () => {
|
||||
expect((await proxyOpencodeRequest(new Request(
|
||||
'https://app.shotluma.com/api/opencode/zen/v1/models',
|
||||
{ method: 'DELETE' },
|
||||
))).status).toBe(405)
|
||||
expect((await proxyOpencodeRequest(new Request(
|
||||
'https://app.shotluma.com/api/moonshot/v1/models',
|
||||
{ method: 'GET' },
|
||||
))).status).toBe(404)
|
||||
})
|
||||
|
||||
it('forwards GET and POST to the rewritten OpenCode origin', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('ok', { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const getResponse = await proxyOpencodeRequest(new Request(
|
||||
'https://app.shotluma.com/api/opencode/go/v1/models',
|
||||
{ method: 'GET', headers: { authorization: 'Bearer test-key' } },
|
||||
))
|
||||
expect(getResponse.status).toBe(200)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const [getUrl, getInit] = fetchMock.mock.calls[0] as [URL, RequestInit]
|
||||
expect(getUrl.toString()).toBe('https://opencode.ai/zen/go/v1/models')
|
||||
expect(getInit.method).toBe('GET')
|
||||
expect(getInit.body).toBeUndefined()
|
||||
|
||||
await proxyOpencodeRequest(new Request(
|
||||
'https://app.shotluma.com/api/opencode/zen/v1/chat/completions',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: '{"model":"kimi-k3"}',
|
||||
},
|
||||
))
|
||||
const [, postInit] = fetchMock.mock.calls[1] as [URL, RequestInit & { duplex?: string }]
|
||||
expect(postInit.method).toBe('POST')
|
||||
expect(postInit.body).toBeDefined()
|
||||
expect(postInit.duplex).toBe('half')
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
91
scripts/opencode-proxy.ts
Normal file
91
scripts/opencode-proxy.ts
Normal file
@ -0,0 +1,91 @@
|
||||
export const OPENCODE_ZEN_UPSTREAM = 'https://opencode.ai/zen'
|
||||
export const OPENCODE_GO_UPSTREAM = 'https://opencode.ai/zen/go'
|
||||
|
||||
const GO_PREFIX = '/api/opencode/go'
|
||||
const ZEN_PREFIX = '/api/opencode/zen'
|
||||
|
||||
/**
|
||||
* OpenCode serves each model on one of four dialects, so the proxy has to carry
|
||||
* the auth and versioning headers of all of them: `authorization` for the
|
||||
* OpenAI Responses and Chat Completions endpoints, `x-api-key` plus the
|
||||
* `anthropic-*` headers for `/v1/messages`, and `x-goog-api-key` for the Gemini
|
||||
* endpoint. `x-opencode-session` carries the client session id OpenCode uses
|
||||
* for routing and prompt caching. Anything outside this list (cookies, origin,
|
||||
* client hints) is dropped so the proxy stays a pure credential passthrough.
|
||||
*/
|
||||
export const OPENCODE_FORWARDED_HEADERS = [
|
||||
'authorization',
|
||||
'content-type',
|
||||
'accept',
|
||||
'x-opencode-session',
|
||||
'x-api-key',
|
||||
'anthropic-version',
|
||||
'anthropic-beta',
|
||||
'x-goog-api-key',
|
||||
] as const
|
||||
|
||||
const joinUpstream = (origin: string, suffix: string): URL => {
|
||||
const base = `${origin.replace(/\/$/u, '')}/`
|
||||
const relative = suffix.replace(/^\//u, '')
|
||||
return new URL(relative, base)
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a same-origin OpenCode CORS-proxy path onto the Zen or Go upstream.
|
||||
* `/api/opencode/go` is matched before `/api/opencode/zen` so the prefixes
|
||||
* cannot overlap.
|
||||
*/
|
||||
export const rewriteOpencodeProxyUrl = (requestUrl: URL): URL | null => {
|
||||
const path = requestUrl.pathname
|
||||
const search = requestUrl.search
|
||||
if (path === GO_PREFIX || path.startsWith(`${GO_PREFIX}/`)) {
|
||||
const upstream = joinUpstream(OPENCODE_GO_UPSTREAM, path.slice(GO_PREFIX.length))
|
||||
upstream.search = search
|
||||
return upstream
|
||||
}
|
||||
if (path === ZEN_PREFIX || path.startsWith(`${ZEN_PREFIX}/`)) {
|
||||
const upstream = joinUpstream(OPENCODE_ZEN_UPSTREAM, path.slice(ZEN_PREFIX.length))
|
||||
upstream.search = search
|
||||
return upstream
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export const copyOpencodeProxyHeaders = (source: Headers): Headers => {
|
||||
const headers = new Headers()
|
||||
for (const name of OPENCODE_FORWARDED_HEADERS) {
|
||||
const value = source.get(name)
|
||||
if (value) headers.set(name, value)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
export const isOpencodeProxyMethod = (method: string): boolean => {
|
||||
const normalized = method.toUpperCase()
|
||||
return normalized === 'GET' || normalized === 'POST' || normalized === 'OPTIONS'
|
||||
}
|
||||
|
||||
export const proxyOpencodeRequest = async (request: Request): Promise<Response> => {
|
||||
if (request.method.toUpperCase() === 'OPTIONS') {
|
||||
return new Response(null, { status: 204 })
|
||||
}
|
||||
if (!isOpencodeProxyMethod(request.method)) {
|
||||
return new Response('Method not allowed', { status: 405 })
|
||||
}
|
||||
const upstream = rewriteOpencodeProxyUrl(new URL(request.url))
|
||||
if (!upstream) {
|
||||
return new Response('Not found', { status: 404 })
|
||||
}
|
||||
const method = request.method.toUpperCase()
|
||||
// Node's fetch types require `duplex` when forwarding a stream body.
|
||||
const init: RequestInit & { duplex?: 'half' } = {
|
||||
method,
|
||||
headers: copyOpencodeProxyHeaders(request.headers),
|
||||
redirect: 'manual',
|
||||
}
|
||||
if (method !== 'GET' && method !== 'HEAD') {
|
||||
init.body = request.body
|
||||
init.duplex = 'half'
|
||||
}
|
||||
return fetch(upstream, init)
|
||||
}
|
||||
234
scripts/share-api.ts
Normal file
234
scripts/share-api.ts
Normal file
@ -0,0 +1,234 @@
|
||||
/**
|
||||
* Share API for short project links, mounted into the `shotluma-app` Worker
|
||||
* entry (`scripts/shotluma-worker.ts`); `run_worker_first` routes only
|
||||
* `/api/share*` and `/s/*` through the Worker script for it.
|
||||
*
|
||||
* The API stores opaque, client-compressed share payloads in KV and hands
|
||||
* back a short id. It never inspects project content — decoding, validation,
|
||||
* and sanitization all stay in the browser (`src/app/share-link.ts`), and the
|
||||
* editor falls back to self-contained `#share=` links when this API is
|
||||
* unreachable. Alongside the payload the client may upload a rendered
|
||||
* Open Graph preview and the project name; `/s/<id>` serves the editor's
|
||||
* index.html with per-share OG tags injected so pasted links unfurl with the
|
||||
* project's own artwork.
|
||||
*/
|
||||
|
||||
type ShareKv = {
|
||||
get(key: string, type: 'arrayBuffer'): Promise<ArrayBuffer | null>
|
||||
get(key: string, type: 'text'): Promise<string | null>
|
||||
put(key: string, value: ArrayBuffer | string, options?: { expirationTtl?: number }): Promise<void>
|
||||
}
|
||||
|
||||
type RateLimiter = {
|
||||
limit(options: { key: string }): Promise<{ success: boolean }>
|
||||
}
|
||||
|
||||
export type ShareApiEnv = {
|
||||
SHARE_KV: ShareKv
|
||||
ASSETS: { fetch(request: Request): Promise<Response> }
|
||||
/** Optional Workers rate-limiting binding; writes are allowed when absent. */
|
||||
SHARE_RATE?: RateLimiter
|
||||
}
|
||||
|
||||
/** Must stay at or below the client cap so accepted uploads always fit KV. */
|
||||
const MAX_PAYLOAD_BYTES = 10 * 1024 * 1024
|
||||
const MAX_PREVIEW_BYTES = 2 * 1024 * 1024
|
||||
const MAX_TITLE_LENGTH = 120
|
||||
const SHARE_TTL_SECONDS = 60 * 60 * 24 * 90
|
||||
const SHARE_ID_PATTERN = /^[A-Za-z0-9_-]{6,32}$/
|
||||
const SHARE_API_PATH = '/api/share'
|
||||
const SHARE_PAGE_PREFIX = '/s/'
|
||||
|
||||
const previewKey = (id: string) => `preview:${id}`
|
||||
const metaKey = (id: string) => `meta:${id}`
|
||||
|
||||
const jsonResponse = (value: unknown, status = 200): Response =>
|
||||
new Response(JSON.stringify(value), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
|
||||
const methodNotAllowed = (allow: string): Response =>
|
||||
new Response('Method not allowed', { status: 405, headers: { allow } })
|
||||
|
||||
const invalidShareId = (): Response => jsonResponse({ error: 'The share id is invalid.' }, 400)
|
||||
|
||||
const createShareId = (): string => {
|
||||
// 9 random bytes → 12 base64url characters, no padding.
|
||||
const bytes = new Uint8Array(9)
|
||||
crypto.getRandomValues(bytes)
|
||||
let binary = ''
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte)
|
||||
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_')
|
||||
}
|
||||
|
||||
const escapeHtml = (value: string): string =>
|
||||
value
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll('\'', ''')
|
||||
|
||||
/** Rejects oversized uploads before buffering the body. */
|
||||
const declaredLengthExceeds = (request: Request, maxBytes: number): boolean => {
|
||||
const declared = Number(request.headers.get('content-length') ?? '0')
|
||||
return Number.isFinite(declared) && declared > maxBytes
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort write throttle per client IP. The binding is optional so a
|
||||
* deployment without it stays functional.
|
||||
*/
|
||||
const writeAllowed = async (request: Request, env: ShareApiEnv): Promise<boolean> => {
|
||||
if (!env.SHARE_RATE) return true
|
||||
const key = request.headers.get('cf-connecting-ip') ?? 'unknown'
|
||||
try {
|
||||
return (await env.SHARE_RATE.limit({ key })).success
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
const rateLimited = (): Response =>
|
||||
jsonResponse({ error: 'Too many shares — try again in a minute.' }, 429)
|
||||
|
||||
const storeShare = async (request: Request, env: ShareApiEnv): Promise<Response> => {
|
||||
if (declaredLengthExceeds(request, MAX_PAYLOAD_BYTES)) {
|
||||
return jsonResponse({ error: 'The share payload is too large.' }, 413)
|
||||
}
|
||||
if (!await writeAllowed(request, env)) return rateLimited()
|
||||
const payload = await request.arrayBuffer()
|
||||
if (payload.byteLength === 0) return jsonResponse({ error: 'The share payload is empty.' }, 400)
|
||||
if (payload.byteLength > MAX_PAYLOAD_BYTES) {
|
||||
return jsonResponse({ error: 'The share payload is too large.' }, 413)
|
||||
}
|
||||
const id = createShareId()
|
||||
await env.SHARE_KV.put(id, payload, { expirationTtl: SHARE_TTL_SECONDS })
|
||||
return jsonResponse({ id })
|
||||
}
|
||||
|
||||
const storeSharePreview = async (id: string, request: Request, env: ShareApiEnv): Promise<Response> => {
|
||||
if (declaredLengthExceeds(request, MAX_PREVIEW_BYTES)) {
|
||||
return jsonResponse({ error: 'The share preview is too large.' }, 413)
|
||||
}
|
||||
if (!await writeAllowed(request, env)) return rateLimited()
|
||||
const existing = await env.SHARE_KV.get(id, 'arrayBuffer')
|
||||
if (!existing) return jsonResponse({ error: 'This share link has expired or does not exist.' }, 404)
|
||||
|
||||
const title = (new URL(request.url).searchParams.get('title') ?? '').trim().slice(0, MAX_TITLE_LENGTH)
|
||||
const preview = await request.arrayBuffer()
|
||||
if (preview.byteLength > MAX_PREVIEW_BYTES) {
|
||||
return jsonResponse({ error: 'The share preview is too large.' }, 413)
|
||||
}
|
||||
if (preview.byteLength > 0) {
|
||||
await env.SHARE_KV.put(previewKey(id), preview, { expirationTtl: SHARE_TTL_SECONDS })
|
||||
}
|
||||
await env.SHARE_KV.put(metaKey(id), JSON.stringify({ title }), { expirationTtl: SHARE_TTL_SECONDS })
|
||||
return jsonResponse({ ok: true })
|
||||
}
|
||||
|
||||
const readShare = async (id: string, env: ShareApiEnv): Promise<Response> => {
|
||||
const payload = await env.SHARE_KV.get(id, 'arrayBuffer')
|
||||
if (!payload) return jsonResponse({ error: 'This share link has expired or does not exist.' }, 404)
|
||||
return new Response(payload, {
|
||||
headers: {
|
||||
'content-type': 'application/octet-stream',
|
||||
'cache-control': 'public, max-age=3600',
|
||||
'x-content-type-options': 'nosniff',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const readSharePreview = async (id: string, env: ShareApiEnv): Promise<Response> => {
|
||||
const preview = await env.SHARE_KV.get(previewKey(id), 'arrayBuffer')
|
||||
if (!preview) return new Response('Not found', { status: 404 })
|
||||
return new Response(preview, {
|
||||
headers: {
|
||||
'content-type': 'image/jpeg',
|
||||
'cache-control': 'public, max-age=3600',
|
||||
'x-content-type-options': 'nosniff',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const readShareTitle = async (id: string, env: ShareApiEnv): Promise<string> => {
|
||||
try {
|
||||
const meta = await env.SHARE_KV.get(metaKey(id), 'text')
|
||||
if (!meta) return ''
|
||||
const parsed = JSON.parse(meta) as { title?: unknown }
|
||||
return typeof parsed.title === 'string' ? parsed.title : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
// index.html ships static og:/twitter: tags for the editor itself. Crawlers
|
||||
// often honor the first tag they see, so the defaults must be removed before
|
||||
// the per-share tags are injected.
|
||||
const stripDefaultSocialTags = (html: string): string =>
|
||||
html.replace(/[ \t]*<meta (?:property="og:|name="twitter:)[^>]*>\n?/g, '')
|
||||
|
||||
/** Serves the editor with per-share OG tags so pasted links unfurl nicely. */
|
||||
const sharePage = async (id: string, url: URL, env: ShareApiEnv): Promise<Response> => {
|
||||
const assetResponse = await env.ASSETS.fetch(new Request(new URL('/', url).toString()))
|
||||
if (!assetResponse.ok) return assetResponse
|
||||
const html = stripDefaultSocialTags(await assetResponse.text())
|
||||
const title = await readShareTitle(id, env)
|
||||
const pageTitle = escapeHtml(title === '' ? 'Shared Shotluma project' : `${title} — Shotluma`)
|
||||
const tags = [
|
||||
'<meta property="og:site_name" content="Shotluma">',
|
||||
`<meta property="og:title" content="${pageTitle}">`,
|
||||
'<meta property="og:description" content="App Store screens shared with Shotluma. Open the link to get your own editable copy.">',
|
||||
'<meta property="og:type" content="website">',
|
||||
`<meta property="og:url" content="${url.origin}${SHARE_PAGE_PREFIX}${id}">`,
|
||||
`<meta property="og:image" content="${url.origin}${SHARE_API_PATH}/${id}/preview">`,
|
||||
'<meta property="og:image:width" content="1200">',
|
||||
'<meta property="og:image:height" content="630">',
|
||||
'<meta name="twitter:card" content="summary_large_image">',
|
||||
].join('\n')
|
||||
return new Response(html.replace('</head>', `${tags}\n</head>`), {
|
||||
headers: {
|
||||
'content-type': 'text/html; charset=utf-8',
|
||||
'cache-control': 'public, max-age=300',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const routeShareApi = (segments: string[], request: Request, env: ShareApiEnv): Promise<Response> | Response => {
|
||||
const [id, action] = segments
|
||||
if (!id || !SHARE_ID_PATTERN.test(id)) return invalidShareId()
|
||||
if (action === undefined) {
|
||||
return request.method === 'GET' ? readShare(id, env) : methodNotAllowed('GET')
|
||||
}
|
||||
if (action === 'preview' && segments.length === 2) {
|
||||
if (request.method === 'GET') return readSharePreview(id, env)
|
||||
if (request.method === 'POST') return storeSharePreview(id, request, env)
|
||||
return methodNotAllowed('GET, POST')
|
||||
}
|
||||
return new Response('Not found', { status: 404 })
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a share API or share page request; returns null for every other
|
||||
* request so the Worker entry can continue with its remaining routes.
|
||||
*/
|
||||
export const handleShareRequest = (
|
||||
request: Request,
|
||||
env: ShareApiEnv,
|
||||
): Promise<Response> | Response | null => {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === SHARE_API_PATH) {
|
||||
return request.method === 'POST' ? storeShare(request, env) : methodNotAllowed('POST')
|
||||
}
|
||||
if (url.pathname.startsWith(`${SHARE_API_PATH}/`)) {
|
||||
const segments = url.pathname.slice(SHARE_API_PATH.length + 1).split('/')
|
||||
return routeShareApi(segments, request, env)
|
||||
}
|
||||
if (url.pathname.startsWith(SHARE_PAGE_PREFIX)) {
|
||||
const id = url.pathname.slice(SHARE_PAGE_PREFIX.length)
|
||||
if (SHARE_ID_PATTERN.test(id) && request.method === 'GET') return sharePage(id, url, env)
|
||||
// Unknown /s/ paths behave like any other SPA route.
|
||||
}
|
||||
return null
|
||||
}
|
||||
22
scripts/shotluma-worker.ts
Normal file
22
scripts/shotluma-worker.ts
Normal file
@ -0,0 +1,22 @@
|
||||
import { proxyOpencodeRequest, rewriteOpencodeProxyUrl } from './opencode-proxy'
|
||||
import { handleShareRequest, type ShareApiEnv } from './share-api'
|
||||
|
||||
export type ShotlumaWorkerEnv = ShareApiEnv
|
||||
|
||||
/**
|
||||
* Single Worker entry for app.shotluma.com. It mounts the share API and
|
||||
* share pages (`scripts/share-api.ts`) and the hosted same-origin CORS proxy
|
||||
* for OpenCode Zen/Go — browser keys stay on the request; the worker only
|
||||
* rewrites the URL so app.shotluma.com can call an API that does not answer
|
||||
* OPTIONS preflight. Everything else is served from static assets.
|
||||
*/
|
||||
export default {
|
||||
async fetch(request: Request, env: ShotlumaWorkerEnv): Promise<Response> {
|
||||
const shareResponse = handleShareRequest(request, env)
|
||||
if (shareResponse) return shareResponse
|
||||
if (rewriteOpencodeProxyUrl(new URL(request.url))) {
|
||||
return proxyOpencodeRequest(request)
|
||||
}
|
||||
return env.ASSETS.fetch(request)
|
||||
},
|
||||
}
|
||||
1
share.bin
Normal file
1
share.bin
Normal file
@ -0,0 +1 @@
|
||||
{"result":null,"success":false,"errors":[{"code":10000,"message":"Authentication error"}],"messages":[]}
|
||||
63
src/App.tsx
63
src/App.tsx
@ -1,8 +1,10 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useAiWorkflow } from './ai/use-ai-workflow'
|
||||
import { AiRunCancelDialog } from './app/AiRunCancelDialog'
|
||||
import { AppHeader } from './app/AppHeader'
|
||||
import { loadInitialState } from './app/project-utils'
|
||||
import { ProjectDeleteDialog } from './app/ProjectDeleteDialog'
|
||||
import { ShareLinkDialog } from './app/ShareLinkDialog'
|
||||
import { useProjectWorkspace } from './app/use-project-workspace'
|
||||
import { useSlideExport } from './app/use-slide-export'
|
||||
import { APP_LOGO_URL } from './brand'
|
||||
@ -32,6 +34,7 @@ export default function App() {
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false)
|
||||
const [zoom, setZoom] = useState(0.9)
|
||||
const [toast, setToast] = useState<string | null>(null)
|
||||
const [shareDialogOpen, setShareDialogOpen] = useState(false)
|
||||
|
||||
const selectedElementId = selectedElementIds.at(-1) ?? null
|
||||
const clearSelection = useCallback(() => setSelectedElementIds([]), [])
|
||||
@ -56,12 +59,15 @@ export default function App() {
|
||||
clearSelection,
|
||||
setToast,
|
||||
})
|
||||
const { close: closeAi, handleActivity: handleAiActivity } = ai
|
||||
const { close: closeAi, handleActivity: handleAiActivity, cancelActiveRun: cancelAiRun, isRunActive: isAiRunActive } = ai
|
||||
const { commit, resetHistory } = history
|
||||
|
||||
const handleProjectReplaced = useCallback((project: {
|
||||
slides: Slide[]
|
||||
}) => {
|
||||
// Safety net: whatever replaced the project, a still-running generation
|
||||
// must never write into the incoming project's slides.
|
||||
cancelAiRun()
|
||||
const firstSlide = project.slides[0]
|
||||
setActiveSlideId(firstSlide?.id ?? '')
|
||||
clearSelection()
|
||||
@ -69,7 +75,7 @@ export default function App() {
|
||||
closeAi()
|
||||
resetHistory()
|
||||
if (project.slides.length === 0) setIsSidebarOpen(false)
|
||||
}, [clearSelection, closeAi, handleAiActivity, resetHistory])
|
||||
}, [cancelAiRun, clearSelection, closeAi, handleAiActivity, resetHistory])
|
||||
|
||||
const project = useProjectWorkspace({
|
||||
initialProjectName: initial.projectName,
|
||||
@ -81,8 +87,26 @@ export default function App() {
|
||||
uploadsRef,
|
||||
onProjectReplaced: handleProjectReplaced,
|
||||
setToast,
|
||||
isAiRunActive,
|
||||
})
|
||||
|
||||
// A project action requested while a generation is live first asks the user
|
||||
// to give up the run; the confirmed action runs after the run is cancelled.
|
||||
const [pendingProjectAction, setPendingProjectAction] = useState<{ run: () => void } | null>(null)
|
||||
const guardProjectAction = useCallback((action: () => void) => {
|
||||
if (isAiRunActive()) setPendingProjectAction({ run: action })
|
||||
else action()
|
||||
}, [isAiRunActive])
|
||||
|
||||
const { saveCurrentProject } = project
|
||||
const wasAiRunActiveRef = useRef(false)
|
||||
useEffect(() => {
|
||||
// Autosaves during a run carry the interrupted-generation marker; one save
|
||||
// after the run ends clears it so the next load shows no stale notice.
|
||||
if (wasAiRunActiveRef.current && !ai.runActive) void saveCurrentProject()
|
||||
wasAiRunActiveRef.current = ai.runActive
|
||||
}, [ai.runActive, saveCurrentProject])
|
||||
|
||||
const activeSlide = getActiveSlide(slides, activeSlideId)
|
||||
const selectedElement = activeSlide?.elements.find(
|
||||
(element) => element.id === selectedElementId,
|
||||
@ -217,10 +241,12 @@ export default function App() {
|
||||
canUndo={history.canUndo}
|
||||
canRedo={history.canRedo}
|
||||
aiDisabled={aiActionsDisabled}
|
||||
aiRunActive={ai.runActive}
|
||||
onProjectNameChange={project.setProjectName}
|
||||
onOpenProject={project.openProject}
|
||||
onCreateProject={project.createNewProject}
|
||||
onDuplicateProject={project.duplicateCurrentProject}
|
||||
onOpenProject={(projectId) => guardProjectAction(() => project.openProject(projectId))}
|
||||
onCreateProject={() => guardProjectAction(project.createNewProject)}
|
||||
onDuplicateProject={() => guardProjectAction(project.duplicateCurrentProject)}
|
||||
onShareProject={() => setShareDialogOpen(true)}
|
||||
onSaveProject={() => void project.saveCurrentProject(true)}
|
||||
onRequestProjectDeletion={() => project.setDeleteDialogOpen(true)}
|
||||
onUndo={history.undo}
|
||||
@ -313,6 +339,13 @@ export default function App() {
|
||||
<button onClick={() => setToast(null)}><X size={14} /></button>
|
||||
</div>
|
||||
)}
|
||||
<ShareLinkDialog
|
||||
open={shareDialogOpen}
|
||||
projectName={project.projectName}
|
||||
slides={slides}
|
||||
uploads={uploads}
|
||||
onOpenChange={setShareDialogOpen}
|
||||
/>
|
||||
<ProjectDeleteDialog
|
||||
open={project.deleteDialogOpen}
|
||||
deleting={project.deletingProject}
|
||||
@ -320,6 +353,20 @@ export default function App() {
|
||||
onOpenChange={project.setDeleteDialogOpen}
|
||||
onConfirm={() => void project.deleteCurrentProject()}
|
||||
/>
|
||||
<AiRunCancelDialog
|
||||
open={pendingProjectAction !== null}
|
||||
projectName={project.projectName}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setPendingProjectAction(null)
|
||||
}}
|
||||
onConfirm={() => {
|
||||
const pending = pendingProjectAction
|
||||
setPendingProjectAction(null)
|
||||
if (!pending) return
|
||||
cancelAiRun()
|
||||
pending.run()
|
||||
}}
|
||||
/>
|
||||
{ai.controller && ai.open && (
|
||||
<AiGenerateModal
|
||||
open={ai.open}
|
||||
@ -327,8 +374,12 @@ export default function App() {
|
||||
controller={ai.controller}
|
||||
{...(ai.targetSlide ? { targetSlide: ai.targetSlide } : {})}
|
||||
onPrepareRun={ai.prepareRun}
|
||||
onFinished={ai.handleFinished}
|
||||
onFinished={(result) => {
|
||||
ai.handleFinished(result.slidesCreated)
|
||||
if (result.appName) project.applyGeneratedProjectName(result.appName)
|
||||
}}
|
||||
onActivity={ai.handleActivity}
|
||||
onRunStateChange={ai.handleRunStateChange}
|
||||
/>
|
||||
)}
|
||||
<div className="mobile-blocker">
|
||||
|
||||
@ -222,6 +222,41 @@ describe('Codex App Server adapter', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('forwards GPT-6 Astra to the Codex thread and turn', async () => {
|
||||
const { client, requests } = createClient((method, _params, _signal, emit) => {
|
||||
if (method === 'account/read') {
|
||||
return { account: { type: 'chatgpt', email: null, planType: 'plus' } }
|
||||
}
|
||||
if (method === 'thread/start') return { thread: { id: 'thread-1' } }
|
||||
if (method === 'turn/start') {
|
||||
emit({
|
||||
method: 'turn/completed',
|
||||
params: { threadId: 'thread-1', turnId: 'turn-1', turn: { status: 'completed' } },
|
||||
})
|
||||
return { turn: { id: 'turn-1' } }
|
||||
}
|
||||
return {}
|
||||
})
|
||||
|
||||
await runCodexAppServerGeneration({
|
||||
...baseGenerationOptions(),
|
||||
selection: {
|
||||
provider: 'codex',
|
||||
model: 'codex/gpt-6-astra',
|
||||
reasoningEffort: 'max',
|
||||
},
|
||||
client,
|
||||
})
|
||||
|
||||
expect(requests.find((request) => request.method === 'thread/start')?.params).toMatchObject({
|
||||
model: 'gpt-6-astra',
|
||||
})
|
||||
expect(requests.find((request) => request.method === 'turn/start')?.params).toMatchObject({
|
||||
model: 'gpt-6-astra',
|
||||
effort: 'max',
|
||||
})
|
||||
})
|
||||
|
||||
it('interrupts a turn when cancellation lands before the turn id is assigned', async () => {
|
||||
const abortController = new AbortController()
|
||||
let markTurnStarted: (() => void) | null = null
|
||||
|
||||
216
src/ai/describe-images.test.ts
Normal file
216
src/ai/describe-images.test.ts
Normal file
@ -0,0 +1,216 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
collectMessageImages,
|
||||
describeMessageImages,
|
||||
imagePartKey,
|
||||
replaceMessageImages,
|
||||
toVisionFilePart,
|
||||
} from './describe-images'
|
||||
import type { FilePart, ModelMessage, UserModelMessage } from 'ai'
|
||||
|
||||
const filePart = (data: string, mediaType = 'image/png'): FilePart => ({
|
||||
type: 'file',
|
||||
mediaType,
|
||||
data,
|
||||
})
|
||||
|
||||
const userImages = (...parts: FilePart[]): UserModelMessage => ({
|
||||
role: 'user',
|
||||
content: [{ type: 'text', text: 'Screenshots:' }, ...parts],
|
||||
})
|
||||
|
||||
describe('describeMessageImages', () => {
|
||||
it('leaves messages without images unchanged', async () => {
|
||||
const messages: ModelMessage[] = [{ role: 'user', content: 'hello' }]
|
||||
expect(await describeMessageImages(messages, async () => 'nope')).toBe(messages)
|
||||
expect(collectMessageImages(messages)).toEqual([])
|
||||
})
|
||||
|
||||
it('replaces image files with text descriptions and skips tool payloads', async () => {
|
||||
const shot = filePart('data:image/png;base64,abc')
|
||||
const messages: ModelMessage[] = [
|
||||
userImages(shot),
|
||||
{
|
||||
role: 'tool',
|
||||
content: [{
|
||||
type: 'tool-result',
|
||||
toolCallId: 'call-1',
|
||||
toolName: 'render_slide_preview',
|
||||
output: {
|
||||
type: 'content',
|
||||
value: [{
|
||||
type: 'file',
|
||||
mediaType: 'image/jpeg',
|
||||
data: { type: 'data', data: 'preview-bytes' },
|
||||
}],
|
||||
},
|
||||
}],
|
||||
},
|
||||
]
|
||||
|
||||
const described = await describeMessageImages(messages, async (part) => {
|
||||
return part.mediaType === 'image/jpeg' ? 'preview layout' : 'app screenshot'
|
||||
})
|
||||
|
||||
expect(collectMessageImages(messages)).toHaveLength(1)
|
||||
expect(described[0]).toMatchObject({
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: 'Screenshots:' },
|
||||
{ type: 'text', text: 'Image description:\napp screenshot' },
|
||||
],
|
||||
})
|
||||
expect(described[1]).toBe(messages[1])
|
||||
})
|
||||
|
||||
it('describes identical payloads once and reports failures as text', async () => {
|
||||
const first = filePart('same-bytes')
|
||||
const second = filePart('same-bytes')
|
||||
const broken = filePart('broken')
|
||||
let calls = 0
|
||||
const described = await describeMessageImages(
|
||||
[userImages(first, second, broken)],
|
||||
async (part) => {
|
||||
calls += 1
|
||||
if (imagePartKey(part).includes('broken')) throw new Error('vision timeout')
|
||||
return ' shared view '
|
||||
},
|
||||
)
|
||||
|
||||
expect(calls).toBe(2)
|
||||
const content = (described[0] as UserModelMessage).content
|
||||
if (!Array.isArray(content)) throw new Error('expected parts')
|
||||
expect(content.map((part) => 'text' in part ? part.text : '')).toEqual([
|
||||
'Screenshots:',
|
||||
'Image description:\nshared view',
|
||||
'Image description:\nshared view',
|
||||
'[Image could not be described: vision timeout]',
|
||||
])
|
||||
})
|
||||
|
||||
it('reuses a shared cache across calls instead of re-describing per step', async () => {
|
||||
const shot = filePart('step-bytes')
|
||||
const cache = new Map<string, string>()
|
||||
let calls = 0
|
||||
const describeImage = async () => {
|
||||
calls += 1
|
||||
return 'described once'
|
||||
}
|
||||
|
||||
const first = await describeMessageImages([userImages(shot)], describeImage, cache)
|
||||
const second = await describeMessageImages([userImages(shot)], describeImage, cache)
|
||||
|
||||
expect(calls).toBe(1)
|
||||
for (const described of [first, second]) {
|
||||
const content = (described[0] as UserModelMessage).content
|
||||
if (!Array.isArray(content)) throw new Error('expected parts')
|
||||
expect(content[1]).toEqual({
|
||||
type: 'text',
|
||||
text: 'Image description:\ndescribed once',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('keys distinct binary payloads separately, including ArrayBuffers', async () => {
|
||||
const bytesPart = (bytes: number[]): FilePart => ({
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
data: new Uint8Array(bytes),
|
||||
})
|
||||
// Same length and first byte must not collide.
|
||||
expect(imagePartKey(bytesPart([9, 8, 7]))).not.toBe(imagePartKey(bytesPart([9, 0, 0])))
|
||||
const bufferPart = (bytes: number[]): FilePart => ({
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
data: new Uint8Array(bytes).buffer,
|
||||
})
|
||||
expect(imagePartKey(bufferPart([1, 2, 3]))).not.toBe(imagePartKey(bufferPart([1, 2, 4])))
|
||||
// An ArrayBuffer keys by content, matching its Uint8Array view.
|
||||
expect(imagePartKey(bufferPart([1, 2, 3]))).toBe(imagePartKey(bytesPart([1, 2, 3])))
|
||||
|
||||
const descriptions: string[] = []
|
||||
const described = await describeMessageImages(
|
||||
[userImages(bytesPart([9, 8, 7]), bytesPart([9, 0, 0]))],
|
||||
async () => {
|
||||
descriptions.push(`payload ${descriptions.length + 1}`)
|
||||
return descriptions[descriptions.length - 1] ?? ''
|
||||
},
|
||||
)
|
||||
expect(descriptions).toHaveLength(2)
|
||||
expect(described[0]).toMatchObject({
|
||||
content: [
|
||||
{ type: 'text', text: 'Screenshots:' },
|
||||
{ type: 'text', text: 'Image description:\npayload 1' },
|
||||
{ type: 'text', text: 'Image description:\npayload 2' },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('converts legacy image parts for the vision request', () => {
|
||||
const converted = toVisionFilePart({
|
||||
type: 'image',
|
||||
image: 'abc',
|
||||
mediaType: 'image/jpeg',
|
||||
})
|
||||
expect(converted).toEqual({
|
||||
type: 'file',
|
||||
mediaType: 'image/jpeg',
|
||||
data: { type: 'data', data: 'abc' },
|
||||
})
|
||||
expect(replaceMessageImages([], new Map())).toEqual([])
|
||||
})
|
||||
|
||||
it('covers image-part keys, empty descriptions, and tagged data wrappers', async () => {
|
||||
const url = new URL('https://example.test/shot.png')
|
||||
expect(toVisionFilePart({ type: 'file', mediaType: 'image/png', data: 'kept' })).toEqual({
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
data: 'kept',
|
||||
})
|
||||
expect(toVisionFilePart({
|
||||
type: 'image',
|
||||
image: url,
|
||||
})).toEqual({
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
data: { type: 'url', url },
|
||||
})
|
||||
expect(imagePartKey({
|
||||
type: 'file',
|
||||
mediaType: 'image/webp',
|
||||
data: { type: 'data', data: 'nested' },
|
||||
})).toContain('nested')
|
||||
expect(imagePartKey({
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
data: { type: 'url', url },
|
||||
})).toContain('example.test')
|
||||
expect(imagePartKey({
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
data: new Uint8Array([9, 8, 7]),
|
||||
})).toContain('bytes:3:')
|
||||
expect(imagePartKey({
|
||||
type: 'image',
|
||||
image: 'abc',
|
||||
mediaType: 'image/jpeg',
|
||||
})).toContain('abc')
|
||||
|
||||
const described = await describeMessageImages(
|
||||
[{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'image', image: 'abc', mediaType: 'image/jpeg' },
|
||||
{ type: 'file', mediaType: 'application/pdf', data: 'not-an-image' },
|
||||
],
|
||||
}],
|
||||
async () => ' ',
|
||||
)
|
||||
expect(described[0]).toMatchObject({
|
||||
content: [
|
||||
{ type: 'text', text: '[Image description was empty]' },
|
||||
{ type: 'file', mediaType: 'application/pdf', data: 'not-an-image' },
|
||||
],
|
||||
})
|
||||
})
|
||||
})
|
||||
167
src/ai/describe-images.ts
Normal file
167
src/ai/describe-images.ts
Normal file
@ -0,0 +1,167 @@
|
||||
import type { FilePart, ModelMessage, TextPart } from 'ai'
|
||||
|
||||
type LegacyImagePart = {
|
||||
type: 'image'
|
||||
image: unknown
|
||||
mediaType?: string
|
||||
}
|
||||
|
||||
type DescribeablePart = FilePart | LegacyImagePart
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null
|
||||
|
||||
const isFilePart = (part: unknown): part is FilePart =>
|
||||
isRecord(part) && part['type'] === 'file' && typeof part['mediaType'] === 'string'
|
||||
|
||||
const isLegacyImagePart = (part: unknown): part is LegacyImagePart =>
|
||||
isRecord(part) && part['type'] === 'image'
|
||||
|
||||
const isImageMediaType = (mediaType: string | undefined): boolean =>
|
||||
typeof mediaType === 'string' && mediaType.toLowerCase().startsWith('image/')
|
||||
|
||||
export const OPENCODE_VISION_PROMPT = `Describe this image for a designer who cannot see it.
|
||||
Focus on layout, visual hierarchy, colors, typography, exact visible copy, UI elements, icons, device frames, and spacing.
|
||||
Be concrete and complete. Do not suggest improvements.`
|
||||
|
||||
// Two FNV-1a variants over the full payload keep same-length images from
|
||||
// sharing a cache key without pulling in a hashing dependency.
|
||||
const hashBytes = (bytes: Uint8Array): string => {
|
||||
let a = 0x811c9dc5
|
||||
let b = 0x811c9dc5
|
||||
for (const byte of bytes) {
|
||||
a = Math.imul(a ^ byte, 0x01000193)
|
||||
b = Math.imul(b ^ byte, 0x85ebca77)
|
||||
}
|
||||
return `${(a >>> 0).toString(16)}-${(b >>> 0).toString(16)}`
|
||||
}
|
||||
|
||||
const serializeImageData = (data: unknown): string => {
|
||||
if (typeof data === 'string') return data
|
||||
if (data instanceof URL) return data.toString()
|
||||
if (isRecord(data) && data['type'] === 'data') return serializeImageData(data['data'])
|
||||
if (isRecord(data) && data['type'] === 'url') return serializeImageData(data['url'])
|
||||
if (data instanceof Uint8Array) return `bytes:${data.byteLength}:${hashBytes(data)}`
|
||||
if (data instanceof ArrayBuffer) return serializeImageData(new Uint8Array(data))
|
||||
return JSON.stringify(data)
|
||||
}
|
||||
|
||||
export const imagePartKey = (part: DescribeablePart): string => {
|
||||
if (isFilePart(part)) {
|
||||
return `${part.mediaType}:${serializeImageData(part.data)}`
|
||||
}
|
||||
return `image:${part.mediaType ?? 'image'}:${serializeImageData(part.image)}`
|
||||
}
|
||||
|
||||
const isDescribeablePart = (part: unknown): part is DescribeablePart => {
|
||||
if (isLegacyImagePart(part)) return true
|
||||
return isFilePart(part) && isImageMediaType(part.mediaType)
|
||||
}
|
||||
|
||||
const collectFromContent = (content: unknown, images: DescribeablePart[]): void => {
|
||||
if (!Array.isArray(content)) return
|
||||
for (const part of content as unknown[]) {
|
||||
if (isDescribeablePart(part)) images.push(part)
|
||||
}
|
||||
}
|
||||
|
||||
export const collectMessageImages = (
|
||||
messages: readonly ModelMessage[],
|
||||
): readonly DescribeablePart[] => {
|
||||
const images: DescribeablePart[] = []
|
||||
for (const message of messages) {
|
||||
if (message.role === 'tool') continue
|
||||
collectFromContent(message.content, images)
|
||||
}
|
||||
return images
|
||||
}
|
||||
|
||||
const toDescriptionPart = (description: string): TextPart => ({
|
||||
type: 'text',
|
||||
text: description.startsWith('[Image')
|
||||
? description
|
||||
: `Image description:\n${description}`,
|
||||
})
|
||||
|
||||
const replaceContentImages = (
|
||||
content: unknown,
|
||||
descriptions: ReadonlyMap<string, string>,
|
||||
): unknown => {
|
||||
if (!Array.isArray(content)) return content
|
||||
const parts = content as unknown[]
|
||||
const next = parts.map((part) => {
|
||||
if (!isDescribeablePart(part)) return part
|
||||
const description = descriptions.get(imagePartKey(part))
|
||||
if (description === undefined) return part
|
||||
return toDescriptionPart(description)
|
||||
})
|
||||
const changed = next.some((part, index) => part !== parts[index])
|
||||
return changed ? next : content
|
||||
}
|
||||
|
||||
export const replaceMessageImages = (
|
||||
messages: ModelMessage[],
|
||||
descriptions: ReadonlyMap<string, string>,
|
||||
): ModelMessage[] => {
|
||||
if (descriptions.size === 0) return messages
|
||||
const next = messages.map((message) => {
|
||||
if (message.role === 'tool') return message
|
||||
const content = replaceContentImages(message.content, descriptions)
|
||||
if (content === message.content) return message
|
||||
return { ...message, content } as ModelMessage
|
||||
})
|
||||
const changed = next.some((message, index) => message !== messages[index])
|
||||
return changed ? next : messages
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace image file parts with text descriptions so a text-only model can
|
||||
* still use screenshots and slide previews. Descriptions are cached by image
|
||||
* payload so repeated previews of the same bytes are described once. Pass a
|
||||
* shared `cache` to reuse descriptions across calls — each tool-loop step
|
||||
* re-prepares the full message history, and describe calls cost tens of
|
||||
* seconds each, so re-describing per step would stall every step.
|
||||
*/
|
||||
export const describeMessageImages = async (
|
||||
messages: ModelMessage[],
|
||||
describeImage: (part: FilePart) => Promise<string>,
|
||||
cache?: Map<string, string>,
|
||||
): Promise<ModelMessage[]> => {
|
||||
const images = collectMessageImages(messages)
|
||||
if (images.length === 0) return messages
|
||||
|
||||
const descriptions = cache ?? new Map<string, string>()
|
||||
for (const image of images) {
|
||||
const key = imagePartKey(image)
|
||||
if (descriptions.has(key)) continue
|
||||
try {
|
||||
const description = (await describeImage(toVisionFilePart(image))).trim()
|
||||
descriptions.set(
|
||||
key,
|
||||
description.length > 0 ? description : '[Image description was empty]',
|
||||
)
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
descriptions.set(key, `[Image could not be described: ${detail}]`)
|
||||
}
|
||||
}
|
||||
|
||||
return replaceMessageImages(messages, descriptions)
|
||||
}
|
||||
|
||||
export const toVisionFilePart = (part: DescribeablePart): FilePart => {
|
||||
if (isFilePart(part)) return part
|
||||
const mediaType = part.mediaType ?? 'image/png'
|
||||
const image = part.image
|
||||
if (image instanceof URL) {
|
||||
return { type: 'file', mediaType, data: { type: 'url', url: image } }
|
||||
}
|
||||
if (
|
||||
typeof image === 'string'
|
||||
|| image instanceof Uint8Array
|
||||
|| image instanceof ArrayBuffer
|
||||
) {
|
||||
return { type: 'file', mediaType, data: { type: 'data', data: image } }
|
||||
}
|
||||
return { type: 'file', mediaType, data: { type: 'data', data: serializeImageData(image) } }
|
||||
}
|
||||
@ -32,4 +32,13 @@ describe('buildHtmlInstructions', () => {
|
||||
it('shares the bundled font library with the element prompt', () => {
|
||||
expect(buildHtmlInstructions()).toContain('Bricolage Grotesque Variable')
|
||||
})
|
||||
|
||||
it('does not prescribe a bold design or favor saturated palettes', () => {
|
||||
const instructions = buildHtmlInstructions()
|
||||
|
||||
expect(instructions).toContain('design a cohesive set')
|
||||
expect(instructions).not.toContain('design a bold, cohesive set')
|
||||
expect(instructions).not.toContain('a saturated brand color or rich dark tone')
|
||||
expect(instructions).not.toContain('beats a timid neutral')
|
||||
})
|
||||
})
|
||||
|
||||
@ -15,7 +15,7 @@ export function buildHtmlInstructions(options: HtmlPromptOptions = {}): string {
|
||||
const { targetSlideId } = options
|
||||
const mission = targetSlideId
|
||||
? `Your job is to edit the existing App Store screen with id "${targetSlideId}" by revising its HTML according to the user's request.`
|
||||
: 'Your job is to design a bold, cohesive set of App Store screenshots for the app the user describes, authoring each screen as one complete HTML document.'
|
||||
: 'Your job is to design a cohesive set of App Store screenshots for the app the user describes, authoring each screen as one complete HTML document.'
|
||||
|
||||
const process = targetSlideId
|
||||
? `1. Call get_canvas_state first. It contains only the target screen — including its full current HTML — and the uploaded asset ids available to this run.
|
||||
@ -27,7 +27,7 @@ export function buildHtmlInstructions(options: HtmlPromptOptions = {}): string {
|
||||
: `1. Call get_canvas_state first. It shows the screens that already exist and the ids of every uploaded asset (screenshots and app logo).
|
||||
2. Do NOT modify or delete the user's existing screens. Only create NEW screens with add_html_screen.
|
||||
3. Decide how many screens to build yourself - typically 3 to 6, depending on how many screenshots were provided and how much story the app has to tell. Do not pad the set with filler screens.
|
||||
4. ART DIRECTION - commit to a concept before you build anything: a palette (background, text color, one accent - a saturated brand color or rich dark tone as a full-bleed background almost always beats a timid neutral), one font pairing from the list below, one highlight treatment, and a composition plan where no two adjacent screens share the same layout.
|
||||
4. ART DIRECTION - commit to a concept before you build anything. Study the uploaded screenshots first: unless the user asks for a different style, ADAPT THE APP'S OWN VISUAL STYLE - derive the palette (background, text color, one accent), mood, and shape language from the app's actual UI, logo, and subject so the set feels native to the app. Pick one font pairing from the list below, one highlight treatment to hold in reserve (see Design system rules for how sparingly to use it), and a composition plan that serves each screen's story role.
|
||||
5. Call declare_plan once the plan is fixed and BEFORE the first add_html_screen, listing the screens in build order with a short name and role each ("Hero", "Ritual" - labels, not sentences).
|
||||
6. Build each screen as ONE add_html_screen call carrying its complete markup, then verify it (see below) before moving to the next.
|
||||
|
||||
@ -94,8 +94,8 @@ After composing each screen, study the preview image: does the headline fit with
|
||||
${COPYWRITING_RULES}
|
||||
|
||||
## Design system rules
|
||||
Consistency lives in the SYSTEM, not in repeating one layout. Across every screen keep the same palette, the same font pairing, the same accent color, the same highlight treatment, and a consistent shape vocabulary - while the composition changes from screen to screen.
|
||||
- Style the 1-2 most meaningful words of most headlines differently: the accent color, or one pill/highlight treatment used consistently across the set. A flat single-color headline on every screen looks generic.
|
||||
Consistency comes first: across every screen keep the same palette, the same font pairing, the same accent color, the same highlight treatment, and a consistent shape vocabulary. Repeating a layout is fine when it serves the story - a cohesive set beats forced variety.
|
||||
- Emphasis inside a headline comes first from type: size jumps between lines, weight contrast, and where the line breaks. A word highlight (accent color or one pill/underline treatment) is a scarce device on top of that - at most two screens in the whole set get one: the hero, plus at most one screen where a claim or statistic earns it. Every other headline stays a single color. When you do highlight, do not reflexively take the closing words - pick the word that carries the claim wherever it sits, keep it to one or two words, leave the sentence-final period outside it, and use the same treatment both times.
|
||||
- Density lives inside the phone, sparsity outside: keep the canvas around the device to the headline, supporting copy, and a few deliberate accents.
|
||||
- A slight device rotation (transform: rotate(-8deg) to rotate(8deg)) adds energy; alternate the direction between screens.
|
||||
|
||||
|
||||
58
src/ai/opencode-client.test.ts
Normal file
58
src/ai/opencode-client.test.ts
Normal file
@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
OPENCODE_SESSION_ID,
|
||||
OPENCODE_SESSION_STORAGE_KEY,
|
||||
opencodeBaseUrl,
|
||||
opencodeRequestHeaders,
|
||||
readOpencodeSessionId,
|
||||
} from './opencode-client'
|
||||
import { opencodeRequestModelId } from './opencode-models'
|
||||
|
||||
const createMemoryStorage = (initial: Record<string, string> = {}) => {
|
||||
const entries = new Map(Object.entries(initial))
|
||||
return {
|
||||
entries,
|
||||
getItem: (key: string) => entries.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => {
|
||||
entries.set(key, value)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('OpenCode client routing', () => {
|
||||
it('builds same-origin proxy base URLs for Zen and Go', () => {
|
||||
expect(opencodeBaseUrl('opencode-zen', 'https://app.shotluma.com'))
|
||||
.toBe('https://app.shotluma.com/api/opencode/zen/v1')
|
||||
expect(opencodeBaseUrl('opencode-go', 'http://127.0.0.1:4173'))
|
||||
.toBe('http://127.0.0.1:4173/api/opencode/go/v1')
|
||||
})
|
||||
|
||||
it('sends the upstream model id rather than the catalog prefix', () => {
|
||||
expect(opencodeRequestModelId('opencode-go/glm-5.3', 'glm-5.3')).toBe('glm-5.3')
|
||||
expect(opencodeRequestModelId('opencode-zen/kimi-k3')).toBe('kimi-k3')
|
||||
})
|
||||
|
||||
it('identifies every request with a stable session header', () => {
|
||||
const headers = opencodeRequestHeaders()
|
||||
expect(headers['x-opencode-session']).toBe(OPENCODE_SESSION_ID)
|
||||
expect(opencodeRequestHeaders()['x-opencode-session']).toBe(OPENCODE_SESSION_ID)
|
||||
})
|
||||
|
||||
it('reuses a stored session id so it survives a full page reload', () => {
|
||||
const storage = createMemoryStorage({ [OPENCODE_SESSION_STORAGE_KEY]: 'shotluma-stored' })
|
||||
expect(readOpencodeSessionId(storage)).toBe('shotluma-stored')
|
||||
})
|
||||
|
||||
it('generates and persists a session id when storage is empty', () => {
|
||||
const storage = createMemoryStorage()
|
||||
const generated = readOpencodeSessionId(storage)
|
||||
expect(generated).toMatch(/^shotluma-/u)
|
||||
expect(storage.entries.get(OPENCODE_SESSION_STORAGE_KEY)).toBe(generated)
|
||||
expect(readOpencodeSessionId(storage)).toBe(generated)
|
||||
})
|
||||
|
||||
it('falls back to a per-page-load id when storage is unavailable', () => {
|
||||
expect(readOpencodeSessionId(null)).toMatch(/^shotluma-/u)
|
||||
expect(readOpencodeSessionId(null)).not.toBe(readOpencodeSessionId(null))
|
||||
})
|
||||
})
|
||||
119
src/ai/opencode-client.ts
Normal file
119
src/ai/opencode-client.ts
Normal file
@ -0,0 +1,119 @@
|
||||
import { generateText, type FilePart } from 'ai'
|
||||
import { uid } from '../utils'
|
||||
import { OPENCODE_VISION_PROMPT, toVisionFilePart } from './describe-images'
|
||||
import { opencodeModelDialect } from './opencode-dialects'
|
||||
import type { OpencodeProviderId } from './opencode-models'
|
||||
|
||||
export const OPENCODE_SESSION_STORAGE_KEY = 'shotluma-opencode-session'
|
||||
|
||||
type SessionIdStorage = Pick<Storage, 'getItem' | 'setItem'>
|
||||
|
||||
const getSessionStorage = (): SessionIdStorage | null => {
|
||||
try {
|
||||
return typeof sessionStorage === 'undefined' ? null : sessionStorage
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenCode Go and Zen expect a stable session id on every request so the
|
||||
* gateway can route traffic and reuse prompt caches:
|
||||
* https://opencode.ai/docs/go/#where-can-i-use-it
|
||||
*
|
||||
* sessionStorage keeps the id stable across full page reloads in one browser
|
||||
* tab while naturally sharding traffic across clients. Storage that is
|
||||
* unavailable or throws degrades to an id that only survives the page load.
|
||||
*/
|
||||
export const readOpencodeSessionId = (
|
||||
storage: SessionIdStorage | null = getSessionStorage(),
|
||||
): string => {
|
||||
if (!storage) return uid('shotluma')
|
||||
try {
|
||||
const stored = storage.getItem(OPENCODE_SESSION_STORAGE_KEY)
|
||||
if (stored) return stored
|
||||
} catch {
|
||||
return uid('shotluma')
|
||||
}
|
||||
const generated = uid('shotluma')
|
||||
try {
|
||||
storage.setItem(OPENCODE_SESSION_STORAGE_KEY, generated)
|
||||
} catch {
|
||||
// The id still serves this page load; only persistence is unavailable.
|
||||
}
|
||||
return generated
|
||||
}
|
||||
|
||||
export const OPENCODE_SESSION_ID = readOpencodeSessionId()
|
||||
|
||||
/** Identifies Shotluma traffic to the OpenCode gateways on every request. */
|
||||
export const opencodeRequestHeaders = (): Record<string, string> => ({
|
||||
'x-opencode-session': OPENCODE_SESSION_ID,
|
||||
})
|
||||
|
||||
export const opencodeBaseUrl = (
|
||||
providerId: OpencodeProviderId,
|
||||
origin: string,
|
||||
): string =>
|
||||
`${origin}/api/opencode/${providerId === 'opencode-go' ? 'go' : 'zen'}/v1`
|
||||
|
||||
/**
|
||||
* Build a language model for one OpenCode model on the dialect that gateway
|
||||
* serves it on. All four dialects share the same proxied base URL; only the
|
||||
* provider package and the path it appends differ.
|
||||
*/
|
||||
export const createOpencodeModel = async (options: {
|
||||
providerId: OpencodeProviderId
|
||||
modelId: string
|
||||
apiKey: string
|
||||
origin?: string
|
||||
}) => {
|
||||
const { providerId, modelId, apiKey } = options
|
||||
const baseURL = opencodeBaseUrl(providerId, options.origin ?? window.location.origin)
|
||||
switch (opencodeModelDialect(providerId, modelId)) {
|
||||
case 'responses': {
|
||||
const { createOpenAI } = await import('@ai-sdk/openai')
|
||||
return createOpenAI({ apiKey, baseURL, headers: opencodeRequestHeaders() }).responses(modelId)
|
||||
}
|
||||
case 'messages': {
|
||||
const { createAnthropic } = await import('@ai-sdk/anthropic')
|
||||
return createAnthropic({ apiKey, baseURL, headers: opencodeRequestHeaders() })(modelId)
|
||||
}
|
||||
case 'google': {
|
||||
const { createGoogle } = await import('@ai-sdk/google')
|
||||
return createGoogle({ apiKey, baseURL, headers: opencodeRequestHeaders() })(modelId)
|
||||
}
|
||||
case 'chat': {
|
||||
const { createOpenAI } = await import('@ai-sdk/openai')
|
||||
return createOpenAI({ apiKey, baseURL, headers: opencodeRequestHeaders() }).chat(modelId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const createOpencodeImageDescriber = (options: {
|
||||
providerId: OpencodeProviderId
|
||||
visionModelId: string
|
||||
apiKey: string
|
||||
signal?: AbortSignal
|
||||
}): ((part: FilePart) => Promise<string>) => {
|
||||
let modelPromise: ReturnType<typeof createOpencodeModel> | null = null
|
||||
return async (part) => {
|
||||
modelPromise ??= createOpencodeModel({
|
||||
providerId: options.providerId,
|
||||
modelId: options.visionModelId,
|
||||
apiKey: options.apiKey,
|
||||
})
|
||||
const { text } = await generateText({
|
||||
model: await modelPromise,
|
||||
messages: [{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: OPENCODE_VISION_PROMPT },
|
||||
toVisionFilePart(part),
|
||||
],
|
||||
}],
|
||||
...(options.signal ? { abortSignal: options.signal } : {}),
|
||||
})
|
||||
return text
|
||||
}
|
||||
}
|
||||
61
src/ai/opencode-dialects.test.ts
Normal file
61
src/ai/opencode-dialects.test.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
opencodeDialectNeedsChatToolImageRelay,
|
||||
opencodeModelDialect,
|
||||
opencodeSelectionDialect,
|
||||
} from './opencode-dialects'
|
||||
|
||||
describe('OpenCode dialect routing', () => {
|
||||
it('routes GPT, Grok, and Muse Spark to the Responses endpoint', () => {
|
||||
expect(opencodeModelDialect('opencode-zen', 'gpt-5.6-terra')).toBe('responses')
|
||||
expect(opencodeModelDialect('opencode-go', 'gpt-5.6-luna')).toBe('responses')
|
||||
expect(opencodeModelDialect('opencode-go', 'grok-4.5')).toBe('responses')
|
||||
expect(opencodeModelDialect('opencode-zen', 'grok-4.6')).toBe('responses')
|
||||
expect(opencodeModelDialect('opencode-go', 'muse-spark-1.2-contributor'))
|
||||
.toBe('responses')
|
||||
})
|
||||
|
||||
it('routes Claude and Qwen to the Anthropic messages endpoint', () => {
|
||||
expect(opencodeModelDialect('opencode-zen', 'claude-sonnet-5')).toBe('messages')
|
||||
expect(opencodeModelDialect('opencode-zen', 'qwen3.7-max')).toBe('messages')
|
||||
expect(opencodeModelDialect('opencode-go', 'qwen3.8-max')).toBe('messages')
|
||||
})
|
||||
|
||||
it('routes Gemini to the Google endpoint', () => {
|
||||
expect(opencodeModelDialect('opencode-zen', 'gemini-3.7-flash')).toBe('google')
|
||||
})
|
||||
|
||||
it('keeps the open-weight families and unknown ids on chat completions', () => {
|
||||
expect(opencodeModelDialect('opencode-zen', 'kimi-k3')).toBe('chat')
|
||||
expect(opencodeModelDialect('opencode-go', 'mimo-v2.5')).toBe('chat')
|
||||
expect(opencodeModelDialect('opencode-go', 'glm-5.3')).toBe('chat')
|
||||
expect(opencodeModelDialect('opencode-zen', 'deepseek-v4-pro')).toBe('chat')
|
||||
expect(opencodeModelDialect('opencode-zen', 'hy3-free')).toBe('chat')
|
||||
expect(opencodeModelDialect('opencode-go', 'some-future-open-model')).toBe('chat')
|
||||
})
|
||||
|
||||
it('splits MiniMax by gateway because Zen and Go disagree', () => {
|
||||
expect(opencodeModelDialect('opencode-zen', 'minimax-m2.5')).toBe('chat')
|
||||
expect(opencodeModelDialect('opencode-go', 'minimax-m3')).toBe('messages')
|
||||
})
|
||||
|
||||
it('resolves a selection and ignores non-OpenCode providers', () => {
|
||||
expect(opencodeSelectionDialect({
|
||||
provider: 'opencode-go',
|
||||
model: 'opencode-go/gpt-5.6-luna',
|
||||
})).toBe('responses')
|
||||
expect(opencodeSelectionDialect({
|
||||
provider: 'opencode-zen',
|
||||
model: 'opencode-zen/kimi-k3',
|
||||
})).toBe('chat')
|
||||
expect(opencodeSelectionDialect({ provider: 'openai', model: 'gpt-5.6-terra' }))
|
||||
.toBeNull()
|
||||
})
|
||||
|
||||
it('relays tool images only on the chat-completions dialect', () => {
|
||||
expect(opencodeDialectNeedsChatToolImageRelay('chat')).toBe(true)
|
||||
expect(opencodeDialectNeedsChatToolImageRelay('responses')).toBe(false)
|
||||
expect(opencodeDialectNeedsChatToolImageRelay('messages')).toBe(false)
|
||||
expect(opencodeDialectNeedsChatToolImageRelay('google')).toBe(false)
|
||||
})
|
||||
})
|
||||
74
src/ai/opencode-dialects.ts
Normal file
74
src/ai/opencode-dialects.ts
Normal file
@ -0,0 +1,74 @@
|
||||
import {
|
||||
isOpencodeProviderId,
|
||||
opencodeRequestModelId,
|
||||
type OpencodeProviderId,
|
||||
} from './opencode-models'
|
||||
import { getAiModel, type AiModelSelection } from './provider-catalog'
|
||||
|
||||
/**
|
||||
* OpenCode Zen and Go are multi-dialect gateways: every model answers on exactly
|
||||
* one endpoint, and the wrong one fails with a 400 or an "Endpoint is
|
||||
* unavailable" 5xx instead of falling back. The table mirrors the endpoint
|
||||
* columns published at https://opencode.ai/docs/zen and https://opencode.ai/docs/go.
|
||||
*/
|
||||
export type OpencodeDialect = 'responses' | 'messages' | 'google' | 'chat'
|
||||
|
||||
const PREFIX_DIALECTS: readonly (readonly [string, OpencodeDialect])[] = [
|
||||
['gpt-', 'responses'],
|
||||
['grok-', 'responses'],
|
||||
['muse-spark-', 'responses'],
|
||||
['claude-', 'messages'],
|
||||
['qwen', 'messages'],
|
||||
['gemini-', 'google'],
|
||||
]
|
||||
|
||||
/** MiniMax is the one family the two gateways route differently. */
|
||||
const GATEWAY_PREFIX_DIALECTS: Record<
|
||||
OpencodeProviderId,
|
||||
readonly (readonly [string, OpencodeDialect])[]
|
||||
> = {
|
||||
'opencode-zen': [['minimax-', 'chat']],
|
||||
'opencode-go': [['minimax-', 'messages']],
|
||||
}
|
||||
|
||||
const matchPrefix = (
|
||||
modelId: string,
|
||||
table: readonly (readonly [string, OpencodeDialect])[],
|
||||
): OpencodeDialect | null => {
|
||||
for (const [prefix, dialect] of table) {
|
||||
if (modelId.startsWith(prefix)) return dialect
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the endpoint dialect for an upstream OpenCode model id. Prefixes are
|
||||
* used rather than a fixed id list because `/v1/models` keeps gaining entries;
|
||||
* the open-weight families (DeepSeek, GLM, Kimi, MiMo, Hy3, Laguna, Nemotron,
|
||||
* Big Pickle, and the free tier) all answer on chat completions, which makes it
|
||||
* the correct default for an unrecognised id.
|
||||
*/
|
||||
export const opencodeModelDialect = (
|
||||
providerId: OpencodeProviderId,
|
||||
modelId: string,
|
||||
): OpencodeDialect =>
|
||||
matchPrefix(modelId, GATEWAY_PREFIX_DIALECTS[providerId])
|
||||
?? matchPrefix(modelId, PREFIX_DIALECTS)
|
||||
?? 'chat'
|
||||
|
||||
/** The dialect a selection resolves to, or `null` for a non-OpenCode provider. */
|
||||
export const opencodeSelectionDialect = (
|
||||
selection: AiModelSelection,
|
||||
): OpencodeDialect | null => {
|
||||
if (!isOpencodeProviderId(selection.provider)) return null
|
||||
const model = getAiModel(selection)
|
||||
return opencodeModelDialect(
|
||||
selection.provider,
|
||||
opencodeRequestModelId(model.id, model.providerModelId),
|
||||
)
|
||||
}
|
||||
|
||||
/** Only the chat-completions dialect rejects images inside tool results. */
|
||||
export const opencodeDialectNeedsChatToolImageRelay = (
|
||||
dialect: OpencodeDialect,
|
||||
): boolean => dialect === 'chat'
|
||||
171
src/ai/opencode-models.test.ts
Normal file
171
src/ai/opencode-models.test.ts
Normal file
@ -0,0 +1,171 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
formatOpencodeModelLabel,
|
||||
loadAllOpencodeModels,
|
||||
loadOpencodeModels,
|
||||
opencodeCatalogId,
|
||||
opencodeModelsUrl,
|
||||
opencodeModelSupportsVision,
|
||||
parseOpencodeModels,
|
||||
pickOpencodeVisionModel,
|
||||
readCachedOpencodeModels,
|
||||
toOpencodeModelOption,
|
||||
} from './opencode-models'
|
||||
import {
|
||||
getAiProvider,
|
||||
getDynamicProviderModels,
|
||||
setDynamicProviderModels,
|
||||
} from './provider-catalog'
|
||||
|
||||
const createMemoryStorage = (entries: Record<string, string> = {}) => {
|
||||
const store = new Map(Object.entries(entries))
|
||||
return {
|
||||
getItem: (key: string) => store.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => {
|
||||
store.set(key, value)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setDynamicProviderModels('opencode-zen', [])
|
||||
setDynamicProviderModels('opencode-go', [])
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('OpenCode model catalog', () => {
|
||||
it('formats labels and marks known text-only models', () => {
|
||||
expect(formatOpencodeModelLabel('gpt-5.6-luna')).toBe('GPT 5.6 Luna')
|
||||
expect(formatOpencodeModelLabel('kimi-k3')).toBe('Kimi K3')
|
||||
expect(formatOpencodeModelLabel('mimo-v2.5-pro')).toBe('MiMo V2.5 Pro')
|
||||
expect(formatOpencodeModelLabel('big-pickle')).toBe('Big Pickle')
|
||||
expect(opencodeModelSupportsVision('kimi-k3')).toBe(true)
|
||||
expect(opencodeModelSupportsVision('glm-5.3')).toBe(false)
|
||||
expect(opencodeCatalogId('opencode-go', 'glm-5.3')).toBe('opencode-go/glm-5.3')
|
||||
})
|
||||
|
||||
it('parses the live /models list and keeps text-only tool models', () => {
|
||||
const models = parseOpencodeModels('opencode-go', {
|
||||
data: [
|
||||
{ id: 'glm-5.3' },
|
||||
{ id: 'kimi-k3' },
|
||||
{ id: 'kimi-k3' },
|
||||
{ id: '' },
|
||||
'nope',
|
||||
],
|
||||
})
|
||||
expect(models.map((model) => model.id)).toEqual([
|
||||
'opencode-go/glm-5.3',
|
||||
'opencode-go/kimi-k3',
|
||||
])
|
||||
expect(toOpencodeModelOption('opencode-go', 'glm-5.3')).toMatchObject({
|
||||
providerModelId: 'glm-5.3',
|
||||
supportsVision: false,
|
||||
reasoningEfforts: ['low', 'medium', 'high'],
|
||||
})
|
||||
expect(toOpencodeModelOption('opencode-zen', 'kimi-k3').supportsVision).toBeUndefined()
|
||||
expect(parseOpencodeModels('opencode-zen', null)).toEqual([])
|
||||
})
|
||||
|
||||
it('picks a cheap vision fallback and honors an explicit preference', () => {
|
||||
const models = [
|
||||
toOpencodeModelOption('opencode-zen', 'glm-5.2'),
|
||||
toOpencodeModelOption('opencode-zen', 'gpt-5-nano'),
|
||||
toOpencodeModelOption('opencode-zen', 'claude-sonnet-5'),
|
||||
]
|
||||
expect(pickOpencodeVisionModel('opencode-zen', models)?.id).toBe(
|
||||
'opencode-zen/gpt-5-nano',
|
||||
)
|
||||
expect(pickOpencodeVisionModel(
|
||||
'opencode-zen',
|
||||
models,
|
||||
'opencode-zen/claude-sonnet-5',
|
||||
)?.id).toBe('opencode-zen/claude-sonnet-5')
|
||||
expect(pickOpencodeVisionModel(
|
||||
'opencode-go',
|
||||
[toOpencodeModelOption('opencode-go', 'glm-5.3')],
|
||||
)).toBeUndefined()
|
||||
expect(pickOpencodeVisionModel(
|
||||
'opencode-go',
|
||||
[toOpencodeModelOption('opencode-go', 'kimi-k3')],
|
||||
)?.id).toBe('opencode-go/kimi-k3')
|
||||
expect(formatOpencodeModelLabel('unknown-xyz')).toBe('Unknown Xyz')
|
||||
expect(parseOpencodeModels('opencode-zen', { data: 'nope' })).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('loadOpencodeModels', () => {
|
||||
it('serves a fresh cache without fetching', async () => {
|
||||
const cachedModel = toOpencodeModelOption('opencode-zen', 'kimi-k3')
|
||||
const storage = createMemoryStorage({
|
||||
'shotluma-opencode-zen-models': JSON.stringify({
|
||||
fetchedAt: 500,
|
||||
models: [cachedModel],
|
||||
}),
|
||||
})
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await loadOpencodeModels('opencode-zen', { now: 600, storage })
|
||||
expect(result).toEqual({ models: [cachedModel], source: 'cache' })
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(getDynamicProviderModels('opencode-zen')).toEqual([cachedModel])
|
||||
expect(readCachedOpencodeModels('opencode-zen', 600, storage)).toEqual([cachedModel])
|
||||
})
|
||||
|
||||
it('fetches, caches, and registers the remote catalog', async () => {
|
||||
const storage = createMemoryStorage()
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ data: [{ id: 'glm-5.2' }, { id: 'kimi-k3' }] }),
|
||||
}))
|
||||
|
||||
const result = await loadOpencodeModels('opencode-zen', { now: 42, storage })
|
||||
expect(result.source).toBe('remote')
|
||||
expect(result.models.map((model) => model.id)).toEqual([
|
||||
'opencode-zen/glm-5.2',
|
||||
'opencode-zen/kimi-k3',
|
||||
])
|
||||
expect(getDynamicProviderModels('opencode-zen')).toEqual(result.models)
|
||||
})
|
||||
|
||||
it('falls back to the curated shortlist when the fetch fails', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 503 }))
|
||||
|
||||
const result = await loadOpencodeModels('opencode-go', { now: 42, storage: null })
|
||||
expect(result.source).toBe('fallback')
|
||||
expect(result.models).toBe(getAiProvider('opencode-go').models)
|
||||
})
|
||||
|
||||
it('ignores stale or invalid cache and coalesces remote loads', async () => {
|
||||
const storage = createMemoryStorage({
|
||||
'shotluma-opencode-zen-models': '{not-json',
|
||||
'shotluma-opencode-go-models': JSON.stringify({
|
||||
fetchedAt: 1,
|
||||
models: [toOpencodeModelOption('opencode-go', 'kimi-k3')],
|
||||
}),
|
||||
})
|
||||
expect(readCachedOpencodeModels('opencode-zen', 10, storage)).toBeNull()
|
||||
expect(readCachedOpencodeModels('opencode-go', 60 * 60 * 1000 + 2, storage)).toBeNull()
|
||||
expect(opencodeModelsUrl('opencode-zen', 'https://app.shotluma.com'))
|
||||
.toBe('https://app.shotluma.com/api/opencode/zen/v1/models')
|
||||
expect(opencodeModelsUrl('opencode-go', 'null'))
|
||||
.toBe('https://opencode.ai/zen/go/v1/models')
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ data: [{ id: 'kimi-k3' }] }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const [first, second, all] = await Promise.all([
|
||||
loadOpencodeModels('opencode-zen', { now: 42, storage: null }),
|
||||
loadOpencodeModels('opencode-zen', { now: 42, storage: null }),
|
||||
loadAllOpencodeModels({ now: 42, storage: null }),
|
||||
])
|
||||
expect(first.source).toBe('remote')
|
||||
expect(second.source).toBe('remote')
|
||||
expect(all).toHaveLength(2)
|
||||
// One request per gateway, not one per caller.
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
361
src/ai/opencode-models.ts
Normal file
361
src/ai/opencode-models.ts
Normal file
@ -0,0 +1,361 @@
|
||||
import {
|
||||
OPENROUTER_REASONING_EFFORTS,
|
||||
getAiProvider,
|
||||
setDynamicProviderModels,
|
||||
type AiModelOption,
|
||||
type AiProviderId,
|
||||
} from './provider-catalog'
|
||||
|
||||
export type OpencodeGateway = 'zen' | 'go'
|
||||
|
||||
export const OPENCODE_PROVIDERS = [
|
||||
'opencode-zen',
|
||||
'opencode-go',
|
||||
] as const satisfies readonly AiProviderId[]
|
||||
|
||||
export type OpencodeProviderId = (typeof OPENCODE_PROVIDERS)[number]
|
||||
|
||||
export const isOpencodeProviderId = (
|
||||
value: unknown,
|
||||
): value is OpencodeProviderId =>
|
||||
value === 'opencode-zen' || value === 'opencode-go'
|
||||
|
||||
export const OPENCODE_MODELS_TTL_MS = 60 * 60 * 1000
|
||||
|
||||
// Bounds the catalog request so a stalled gateway falls back to the curated
|
||||
// shortlist instead of leaving the model browser loading forever.
|
||||
export const OPENCODE_MODELS_REQUEST_TIMEOUT_MS = 10_000
|
||||
|
||||
const STORAGE_KEYS: Record<OpencodeProviderId, string> = {
|
||||
'opencode-zen': 'shotluma-opencode-zen-models',
|
||||
'opencode-go': 'shotluma-opencode-go-models',
|
||||
}
|
||||
|
||||
const GATEWAY_BY_PROVIDER: Record<OpencodeProviderId, OpencodeGateway> = {
|
||||
'opencode-zen': 'zen',
|
||||
'opencode-go': 'go',
|
||||
}
|
||||
|
||||
/**
|
||||
* Models.dev reports these OpenCode ids as text-only; the runner describes
|
||||
* images for them instead of attaching them. Unknown live ids default to
|
||||
* vision-capable so screenshots reach new models untouched — a wrong default
|
||||
* fails loudly at the provider instead of silently flattening images to text.
|
||||
*/
|
||||
const OPENCODE_TEXT_ONLY_MODELS = new Set([
|
||||
'big-pickle',
|
||||
'deepseek-v4-flash',
|
||||
'deepseek-v4-flash-free',
|
||||
'deepseek-v4-pro',
|
||||
'glm-5',
|
||||
'glm-5.1',
|
||||
'glm-5.2',
|
||||
'glm-5.3',
|
||||
'gpt-5.3-codex-spark',
|
||||
'hy3',
|
||||
'hy3-free',
|
||||
'hy3-preview',
|
||||
'laguna-s-2.1-free',
|
||||
'minimax-m2.5',
|
||||
'minimax-m2.7',
|
||||
'nemotron-3-ultra-free',
|
||||
'nemotron-3.5-lightning-free',
|
||||
'qwen3.7-max',
|
||||
])
|
||||
|
||||
const OPENCODE_LABEL_OVERRIDES: Record<string, string> = {
|
||||
'big-pickle': 'Big Pickle',
|
||||
hy3: 'Hy3',
|
||||
'hy3-free': 'Hy3 Free',
|
||||
'hy3-preview': 'Hy3 Preview',
|
||||
'mimo-v2.5': 'MiMo V2.5',
|
||||
'mimo-v2.5-free': 'MiMo V2.5 Free',
|
||||
'mimo-v2.5-pro': 'MiMo V2.5 Pro',
|
||||
'mimo-v2-omni': 'MiMo V2 Omni',
|
||||
'mimo-v2-pro': 'MiMo V2 Pro',
|
||||
}
|
||||
|
||||
const DEFAULT_VISION_MODEL_IDS: Record<OpencodeProviderId, readonly string[]> = {
|
||||
'opencode-zen': [
|
||||
'opencode-zen/mimo-v2.5-free',
|
||||
'opencode-zen/gpt-5-nano',
|
||||
'opencode-zen/gemini-3.5-flash-lite',
|
||||
'opencode-zen/gpt-5.4-nano',
|
||||
],
|
||||
'opencode-go': [
|
||||
'opencode-go/mimo-v2.5',
|
||||
'opencode-go/gpt-5.6-luna',
|
||||
'opencode-go/minimax-m3',
|
||||
],
|
||||
}
|
||||
|
||||
const TOKEN_LABELS: Record<string, string> = {
|
||||
claude: 'Claude',
|
||||
deepseek: 'DeepSeek',
|
||||
gemini: 'Gemini',
|
||||
glm: 'GLM',
|
||||
gpt: 'GPT',
|
||||
grok: 'Grok',
|
||||
kimi: 'Kimi',
|
||||
laguna: 'Laguna',
|
||||
minimax: 'MiniMax',
|
||||
mimo: 'MiMo',
|
||||
muse: 'Muse',
|
||||
nemotron: 'Nemotron',
|
||||
qwen: 'Qwen',
|
||||
}
|
||||
|
||||
export const formatOpencodeModelLabel = (modelId: string): string => {
|
||||
const override = OPENCODE_LABEL_OVERRIDES[modelId]
|
||||
if (override) return override
|
||||
return modelId.split('-').map((token) => {
|
||||
const mapped = TOKEN_LABELS[token]
|
||||
if (mapped) return mapped
|
||||
if (/[0-9]/.test(token)) return token.toUpperCase()
|
||||
if (token.length === 0) return token
|
||||
return `${token[0]?.toUpperCase() ?? ''}${token.slice(1)}`
|
||||
}).join(' ')
|
||||
}
|
||||
|
||||
export const opencodeModelSupportsVision = (modelId: string): boolean =>
|
||||
!OPENCODE_TEXT_ONLY_MODELS.has(modelId)
|
||||
|
||||
export const opencodeCatalogId = (
|
||||
providerId: OpencodeProviderId,
|
||||
modelId: string,
|
||||
): string => `${providerId}/${modelId}`
|
||||
|
||||
export const opencodeProviderModelId = (catalogId: string): string =>
|
||||
catalogId.replace(/^opencode-(?:zen|go)\//, '')
|
||||
|
||||
/** The upstream id to send for a catalog entry, preferring the stored mapping. */
|
||||
export const opencodeRequestModelId = (
|
||||
catalogId: string,
|
||||
providerModelId?: string,
|
||||
): string => providerModelId ?? opencodeProviderModelId(catalogId)
|
||||
|
||||
const gatewayLabel = (providerId: OpencodeProviderId): string =>
|
||||
providerId === 'opencode-go' ? 'OpenCode Go' : 'OpenCode Zen'
|
||||
|
||||
const describeOpencodeModel = (
|
||||
providerId: OpencodeProviderId,
|
||||
supportsVision: boolean,
|
||||
): string => {
|
||||
const gateway = gatewayLabel(providerId)
|
||||
if (supportsVision) return `${gateway} · vision and tools`
|
||||
return `${gateway} · no native vision · a vision model describes images first`
|
||||
}
|
||||
|
||||
export const toOpencodeModelOption = (
|
||||
providerId: OpencodeProviderId,
|
||||
modelId: string,
|
||||
): AiModelOption => {
|
||||
const supportsVision = opencodeModelSupportsVision(modelId)
|
||||
return {
|
||||
id: opencodeCatalogId(providerId, modelId),
|
||||
providerModelId: modelId,
|
||||
label: formatOpencodeModelLabel(modelId),
|
||||
description: describeOpencodeModel(providerId, supportsVision),
|
||||
reasoningEfforts: OPENROUTER_REASONING_EFFORTS,
|
||||
...(supportsVision ? {} : { supportsVision: false }),
|
||||
}
|
||||
}
|
||||
|
||||
const parseModelId = (value: unknown): string | null => {
|
||||
if (!value || typeof value !== 'object') return null
|
||||
const id = (value as Record<string, unknown>)['id']
|
||||
return typeof id === 'string' && id.length > 0 ? id : null
|
||||
}
|
||||
|
||||
/** Parse an OpenAI-compatible `/models` list into OpenCode catalog options. */
|
||||
export const parseOpencodeModels = (
|
||||
providerId: OpencodeProviderId,
|
||||
payload: unknown,
|
||||
): AiModelOption[] => {
|
||||
if (!payload || typeof payload !== 'object') return []
|
||||
const data = (payload as Record<string, unknown>)['data']
|
||||
if (!Array.isArray(data)) return []
|
||||
const seen = new Set<string>()
|
||||
const models: AiModelOption[] = []
|
||||
for (const entry of data) {
|
||||
const modelId = parseModelId(entry)
|
||||
if (!modelId || seen.has(modelId)) continue
|
||||
seen.add(modelId)
|
||||
models.push(toOpencodeModelOption(providerId, modelId))
|
||||
}
|
||||
return models.sort((left, right) => left.label.localeCompare(right.label))
|
||||
}
|
||||
|
||||
export const listOpencodeVisionModels = (
|
||||
models: readonly AiModelOption[],
|
||||
): readonly AiModelOption[] =>
|
||||
models.filter((model) => model.supportsVision !== false)
|
||||
|
||||
export const pickOpencodeVisionModel = (
|
||||
providerId: OpencodeProviderId,
|
||||
models: readonly AiModelOption[],
|
||||
preferredId?: string,
|
||||
): AiModelOption | undefined => {
|
||||
const visionModels = listOpencodeVisionModels(models)
|
||||
if (visionModels.length === 0) return undefined
|
||||
if (preferredId) {
|
||||
const preferred = visionModels.find((model) => model.id === preferredId)
|
||||
if (preferred) return preferred
|
||||
}
|
||||
for (const candidateId of DEFAULT_VISION_MODEL_IDS[providerId]) {
|
||||
const match = visionModels.find((model) => model.id === candidateId)
|
||||
if (match) return match
|
||||
}
|
||||
return visionModels[0]
|
||||
}
|
||||
|
||||
type CachedOpencodeModels = {
|
||||
fetchedAt: number
|
||||
models: AiModelOption[]
|
||||
}
|
||||
|
||||
const parseCachedModels = (raw: string | null): CachedOpencodeModels | null => {
|
||||
if (!raw) return null
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(raw)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!parsed || typeof parsed !== 'object') return null
|
||||
const record = parsed as Record<string, unknown>
|
||||
if (typeof record['fetchedAt'] !== 'number' || !Array.isArray(record['models'])) {
|
||||
return null
|
||||
}
|
||||
const models = record['models'].filter((entry): entry is AiModelOption => {
|
||||
if (!entry || typeof entry !== 'object') return false
|
||||
const model = entry as Record<string, unknown>
|
||||
return typeof model['id'] === 'string'
|
||||
&& typeof model['label'] === 'string'
|
||||
&& typeof model['description'] === 'string'
|
||||
})
|
||||
return { fetchedAt: record['fetchedAt'], models }
|
||||
}
|
||||
|
||||
type ModelStorage = Pick<Storage, 'getItem' | 'setItem'>
|
||||
|
||||
const getBrowserStorage = (): ModelStorage | null => {
|
||||
try {
|
||||
if (typeof localStorage === 'undefined') return null
|
||||
return localStorage
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const opencodeModelsUrl = (
|
||||
providerId: OpencodeProviderId,
|
||||
origin: string = typeof window === 'undefined' ? '' : window.location.origin,
|
||||
): string => {
|
||||
const gateway = GATEWAY_BY_PROVIDER[providerId]
|
||||
if (origin && origin !== 'null') {
|
||||
return `${origin}/api/opencode/${gateway}/v1/models`
|
||||
}
|
||||
return gateway === 'go'
|
||||
? 'https://opencode.ai/zen/go/v1/models'
|
||||
: 'https://opencode.ai/zen/v1/models'
|
||||
}
|
||||
|
||||
export const readCachedOpencodeModels = (
|
||||
providerId: OpencodeProviderId,
|
||||
now: number,
|
||||
storage: ModelStorage | null = getBrowserStorage(),
|
||||
): AiModelOption[] | null => {
|
||||
if (!storage) return null
|
||||
let cached: CachedOpencodeModels | null
|
||||
try {
|
||||
cached = parseCachedModels(storage.getItem(STORAGE_KEYS[providerId]))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!cached || cached.models.length === 0) return null
|
||||
if (now - cached.fetchedAt > OPENCODE_MODELS_TTL_MS) return null
|
||||
return cached.models
|
||||
}
|
||||
|
||||
const writeCachedOpencodeModels = (
|
||||
providerId: OpencodeProviderId,
|
||||
models: AiModelOption[],
|
||||
now: number,
|
||||
storage: ModelStorage | null,
|
||||
): void => {
|
||||
if (!storage) return
|
||||
try {
|
||||
storage.setItem(
|
||||
STORAGE_KEYS[providerId],
|
||||
JSON.stringify({ fetchedAt: now, models } satisfies CachedOpencodeModels),
|
||||
)
|
||||
} catch {
|
||||
// A full or blocked storage only loses the cache, not the feature.
|
||||
}
|
||||
}
|
||||
|
||||
export type OpencodeModelsResult = {
|
||||
models: readonly AiModelOption[]
|
||||
source: 'remote' | 'cache' | 'fallback'
|
||||
}
|
||||
|
||||
const pendingFetches = new Map<OpencodeProviderId, Promise<OpencodeModelsResult>>()
|
||||
|
||||
const fetchRemoteModels = async (
|
||||
providerId: OpencodeProviderId,
|
||||
now: number,
|
||||
storage: ModelStorage | null,
|
||||
): Promise<OpencodeModelsResult> => {
|
||||
const response = await fetch(opencodeModelsUrl(providerId), {
|
||||
signal: AbortSignal.timeout(OPENCODE_MODELS_REQUEST_TIMEOUT_MS),
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`OpenCode models request failed: ${response.status}`)
|
||||
}
|
||||
const models = parseOpencodeModels(providerId, await response.json() as unknown)
|
||||
if (models.length === 0) throw new Error('OpenCode models response was empty')
|
||||
writeCachedOpencodeModels(providerId, models, now, storage)
|
||||
setDynamicProviderModels(providerId, models)
|
||||
return { models, source: 'remote' }
|
||||
}
|
||||
|
||||
/**
|
||||
* Load an OpenCode gateway catalog: fresh cache, then the proxied `/models`
|
||||
* list, then the curated shortlist. Successful loads register the models so
|
||||
* selections resolve everywhere. Never rejects.
|
||||
*/
|
||||
export const loadOpencodeModels = (
|
||||
providerId: OpencodeProviderId,
|
||||
options?: {
|
||||
now?: number
|
||||
storage?: ModelStorage | null
|
||||
},
|
||||
): Promise<OpencodeModelsResult> => {
|
||||
const now = options?.now ?? Date.now()
|
||||
const storage = options?.storage === undefined ? getBrowserStorage() : options.storage
|
||||
|
||||
const cached = readCachedOpencodeModels(providerId, now, storage)
|
||||
if (cached) {
|
||||
setDynamicProviderModels(providerId, cached)
|
||||
return Promise.resolve({ models: cached, source: 'cache' })
|
||||
}
|
||||
|
||||
const pending = pendingFetches.get(providerId)
|
||||
?? fetchRemoteModels(providerId, now, storage)
|
||||
.catch((): OpencodeModelsResult => ({
|
||||
models: getAiProvider(providerId).models,
|
||||
source: 'fallback',
|
||||
}))
|
||||
.finally(() => {
|
||||
pendingFetches.delete(providerId)
|
||||
})
|
||||
pendingFetches.set(providerId, pending)
|
||||
return pending
|
||||
}
|
||||
|
||||
export const loadAllOpencodeModels = (options?: {
|
||||
now?: number
|
||||
storage?: ModelStorage | null
|
||||
}): Promise<readonly OpencodeModelsResult[]> =>
|
||||
Promise.all(OPENCODE_PROVIDERS.map((providerId) => loadOpencodeModels(providerId, options)))
|
||||
@ -1,3 +1,4 @@
|
||||
import { opencodeSelectionDialect } from './opencode-dialects'
|
||||
import {
|
||||
getAiStreamReasoningOptions,
|
||||
type AiModelSelection,
|
||||
@ -34,12 +35,19 @@ export type AiStreamRequestOptions = {
|
||||
* still thinks and still bills those tokens while withholding every thought
|
||||
* summary — the run band then has no live prose to show for the whole run.
|
||||
*
|
||||
* OpenCode's Gemini models run on the same Google provider through the gateway,
|
||||
* so they need the same option to stream thoughts.
|
||||
*
|
||||
* Keep this object limited to `includeThoughts`. Adding `thinkingLevel` or
|
||||
* `thinkingBudget` here would take full precedence over the portable `reasoning`
|
||||
* option and silently discard the user's effort choice.
|
||||
*/
|
||||
const GOOGLE_THOUGHT_OPTIONS = { thinkingConfig: { includeThoughts: true } } as const
|
||||
|
||||
const usesGoogleGeneration = (selection: AiModelSelection): boolean =>
|
||||
selection.provider === 'google'
|
||||
|| opencodeSelectionDialect(selection) === 'google'
|
||||
|
||||
/**
|
||||
* Combine the reasoning-effort options with OpenAI's request-wide cache
|
||||
* routing. Implicit mode intentionally stays enabled: its moving breakpoint
|
||||
@ -57,7 +65,7 @@ export const buildStreamRequestOptions = (
|
||||
promptCacheKey: string,
|
||||
): AiStreamRequestOptions => {
|
||||
const reasoningOptions = getAiStreamReasoningOptions(selection)
|
||||
if (selection.provider === 'google') {
|
||||
if (usesGoogleGeneration(selection)) {
|
||||
return {
|
||||
...(reasoningOptions && 'reasoning' in reasoningOptions
|
||||
? { reasoning: reasoningOptions.reasoning }
|
||||
|
||||
@ -26,6 +26,17 @@ describe('AI prompt language', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('AI prompt art direction', () => {
|
||||
it('does not prescribe a bold design or favor saturated palettes', () => {
|
||||
const instructions = buildInstructions()
|
||||
|
||||
expect(instructions).toContain('design a cohesive set')
|
||||
expect(instructions).not.toContain('design a bold, cohesive set')
|
||||
expect(instructions).not.toContain('a saturated brand color or a rich dark tone')
|
||||
expect(instructions).not.toContain('beats a timid neutral')
|
||||
})
|
||||
})
|
||||
|
||||
describe('AI prompt branding', () => {
|
||||
it('requires logo placement via add_image in generate mode', () => {
|
||||
const instructions = buildInstructions()
|
||||
|
||||
@ -48,7 +48,7 @@ export function buildInstructions(options: AiPromptOptions = {}): string {
|
||||
const { targetSlideId, enableOverlayAssets } = options
|
||||
const mission = targetSlideId
|
||||
? `Your job is to edit the existing App Store screen with id "${targetSlideId}" according to the user's request.`
|
||||
: 'Your job is to design a bold, cohesive set of App Store screenshots for the app the user describes.'
|
||||
: 'Your job is to design a cohesive set of App Store screenshots for the app the user describes.'
|
||||
const process = targetSlideId
|
||||
? `1. Call get_canvas_state first. It contains only the target screen and the uploaded asset ids available to this run.
|
||||
2. Work ONLY on slide "${targetSlideId}". You cannot create or delete slides, and you must not attempt to access another slide id.
|
||||
@ -59,9 +59,10 @@ export function buildInstructions(options: AiPromptOptions = {}): string {
|
||||
: `1. The user message already lists every screenshot and logo asset available to this run. Do NOT modify or delete existing slides; create only NEW slides for this design.
|
||||
2. Decide how many screens to build yourself - typically 3 to 6, depending on how many screenshots were provided and how much story the app has to tell. Do not pad the set with filler screens just to hit a number.
|
||||
3. ART DIRECTION - commit to a concept before you build anything:
|
||||
- Palette: background, text color, one accent. Be confident - a saturated brand color or a rich dark tone as a full-bleed background almost always beats a timid neutral. Take cues from the app's own screenshots, logo, and subject.
|
||||
- Study the uploaded screenshots first. Unless the user asks for a different style, ADAPT THE APP'S OWN VISUAL STYLE: derive the palette, mood, and shape language from the app's actual UI, logo, and subject so the set feels native to the app rather than imposed on it.
|
||||
- Palette: background, text color, one accent - taken from that app style.
|
||||
- One font pairing (a display face for headlines, a quieter face for supporting copy) and ONE highlight treatment.
|
||||
- A composition plan: assign every slide an archetype from the library below. No two adjacent slides may use the same archetype, and a set should use at least 3 different ones.
|
||||
- A composition plan: assign every slide an archetype from the library below, chosen to serve each slide's story role.
|
||||
4. In your FIRST tool turn, call declare_plan and add_slides together, in that order and exactly once each. Their screen lists must match. add_slides creates every planned screen at once and returns all ids in build order.
|
||||
5. In the next turn, build using those returned ids. Emit each slide's full planned composition as ONE batched turn (see "Batch your tool calls"), then run the verify routine before moving on.`
|
||||
const layoutContext = targetSlideId
|
||||
@ -76,7 +77,7 @@ export function buildInstructions(options: AiPromptOptions = {}): string {
|
||||
: 'After the LAST slide, do not re-render screens that already passed their preview. Their latest previews remain in the conversation; request another preview only if a later change affected that screen.'
|
||||
const consistency = targetSlideId
|
||||
? 'Keep the screen consistent with its existing visual system unless the user explicitly requests a redesign.'
|
||||
: 'Consistency lives in the SYSTEM, not in repeating one layout. Across every slide keep the same palette, the same font pairing, the same accent color, the same highlight treatment, the same device screenTheme, and a consistent shape vocabulary - while the composition changes from slide to slide via the archetypes.'
|
||||
: 'Consistency comes first: across every slide keep the same palette, the same font pairing, the same accent color, the same highlight treatment, the same device screenTheme, and a consistent shape vocabulary. Repeating an archetype is fine when it serves the story - a cohesive set beats forced variety.'
|
||||
const brandRule = targetSlideId
|
||||
? 'If the user provides an app name or logo for this edit, use them only when the requested change calls for branding updates.'
|
||||
: `BRANDING is required when the user provides an app name and/or logo:
|
||||
@ -193,7 +194,7 @@ ${finalReview}
|
||||
## Design system rules
|
||||
${consistency}
|
||||
- Backgrounds: the same treatment on every slide, or a single deliberate progression (e.g. darkening, or cycling through a fixed palette) - never random colors per slide. Solid fills, linear/radial gradients, or uploaded images with an overlay; subtle dots, grid, diagonal, or wave patterns are available.
|
||||
- Typography should feel designed, not typed. add_text and update_element accept a "highlights" array that styles individual words inside a text: a different color, a background pill (backgroundColor + backgroundOpacity + borderRadius + padding), bold/italic/underline contrast, or reduced opacity for de-emphasis. In most headlines, set the 1-2 most meaningful words apart — typically in the accent color, or with a highlight pill for one hero moment or a statistic. A flat single-color headline on every slide looks generic. Pick ONE highlight treatment and keep it consistent across the set.
|
||||
- Typography should feel designed, not typed. Emphasis comes first from type itself: size jumps between lines, weight contrast, and where you break the line. add_text and update_element also accept a "highlights" array that styles individual words inside a text (a different color, a background pill via backgroundColor + backgroundOpacity + borderRadius + padding, bold/italic/underline contrast, or reduced opacity) - treat that as a scarce device, not a default. At most two slides in the whole set carry a word highlight: the hero, plus at most one slide where a claim or statistic genuinely earns it. Every other headline stays a single color. When you do highlight, do not reflexively take the closing words - pick the word that actually carries the claim wherever it sits, keep it to one or two words, and leave the sentence-final period outside the highlight. Use the same treatment for both.
|
||||
- Use the expanded vector library intentionally: geometric forms, stars/bursts, blobs/arches, rings, lines, arrows, and waves. Decorative elements should clarify flow or establish rhythm, not fill empty space at random. A large blob, arch, or wave running behind a device and off the canvas edge adds depth cheaply.
|
||||
- Use Hugeicons (add_icon) for feature bullets, status indicators, social proof marks, rating stars, and UI-style accents. Icons render as crisp vector SVG at any size. Common uses: a check or badge-check icon next to a feature line, a star icon for ratings, a lock/shield icon for security claims, a rocket or zap icon for performance messaging. Keep icon sizing consistent within a slide (e.g. all feature-row icons at width 6-8) and pick a single color for the set (usually the accent color or white). NEVER use emoji characters on canvas — always use add_icon instead.
|
||||
- Text can use a colored box, padding, rounded corners, outline, and shadow. Reserve these treatments for labels, statistics, or one deliberate hero treatment; ordinary body copy should remain clean.
|
||||
|
||||
@ -11,8 +11,11 @@ import {
|
||||
getAiStreamReasoningOptions,
|
||||
getDefaultAiModel,
|
||||
getDynamicOpenRouterModels,
|
||||
getAiProviderKeyFields,
|
||||
isAiProviderId,
|
||||
modelSupportsVision,
|
||||
setDynamicOpenRouterModels,
|
||||
setDynamicProviderModels,
|
||||
toAiSdkReasoningEffort,
|
||||
} from './provider-catalog'
|
||||
|
||||
@ -27,6 +30,8 @@ describe('AI provider catalog', () => {
|
||||
'anthropic',
|
||||
'xai',
|
||||
'openrouter',
|
||||
'opencode-zen',
|
||||
'opencode-go',
|
||||
])
|
||||
expect(AI_PROVIDERS.map((provider) => provider.envVar)).toEqual([
|
||||
'',
|
||||
@ -37,10 +42,12 @@ describe('AI provider catalog', () => {
|
||||
'VITE_ANTHROPIC_API_KEY',
|
||||
'VITE_XAI_API_KEY',
|
||||
'VITE_OPENROUTER_API_KEY',
|
||||
'VITE_OPENCODE_API_KEY',
|
||||
'VITE_OPENCODE_API_KEY',
|
||||
])
|
||||
expect(AI_PROVIDERS.filter((provider) => provider.transport === 'proxy').map(
|
||||
(provider) => provider.id,
|
||||
)).toEqual(['moonshot'])
|
||||
)).toEqual(['moonshot', 'opencode-zen', 'opencode-go'])
|
||||
expect(getAiProvider('codex')).toMatchObject({
|
||||
auth: 'chatgpt',
|
||||
transport: 'bridge',
|
||||
@ -49,6 +56,26 @@ describe('AI provider catalog', () => {
|
||||
id: 'codex/gpt-5.6-terra',
|
||||
providerModelId: 'gpt-5.6-terra',
|
||||
})
|
||||
expect(getAiProvider('codex').models.map((model) => model.id)).toEqual([
|
||||
'codex/gpt-5.6-terra',
|
||||
'codex/gpt-6-astra',
|
||||
'codex/gpt-5.6-sol',
|
||||
'codex/gpt-5.6-luna',
|
||||
])
|
||||
expect(getAiProvider('openai').models.map((model) => model.id)).toEqual([
|
||||
'gpt-5.6-terra',
|
||||
'gpt-6-astra',
|
||||
'gpt-5.6-sol',
|
||||
'gpt-5.6-luna',
|
||||
])
|
||||
expect(getAiModel({ provider: 'codex', model: 'codex/gpt-6-astra' })).toMatchObject({
|
||||
providerModelId: 'gpt-6-astra',
|
||||
reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'],
|
||||
})
|
||||
expect(getAiModel({ provider: 'openai', model: 'gpt-6-astra' })).toMatchObject({
|
||||
label: 'GPT-6 Astra',
|
||||
reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'],
|
||||
})
|
||||
expect(getAiProvider('xai').models.map((model) => model.id)).toEqual([
|
||||
'grok-4.6',
|
||||
'grok-4.5',
|
||||
@ -153,6 +180,7 @@ describe('AI provider catalog', () => {
|
||||
['low', 'medium', 'high', 'xhigh', 'max'],
|
||||
['low', 'medium', 'high', 'xhigh', 'max'],
|
||||
['low', 'medium', 'high', 'xhigh', 'max'],
|
||||
['low', 'medium', 'high', 'xhigh', 'max'],
|
||||
])
|
||||
expect(getAiProvider('moonshot').models[0]?.reasoningEfforts).toEqual([
|
||||
'low',
|
||||
@ -178,6 +206,16 @@ describe('AI provider catalog', () => {
|
||||
model: 'gpt-5.6-sol',
|
||||
reasoningEffort: 'xhigh',
|
||||
})).toBe('xhigh')
|
||||
expect(getAiSdkReasoningEffort({
|
||||
provider: 'openai',
|
||||
model: 'gpt-6-astra',
|
||||
reasoningEffort: 'minimal',
|
||||
})).toBe('high')
|
||||
expect(getAiSdkReasoningEffort({
|
||||
provider: 'openai',
|
||||
model: 'gpt-6-astra',
|
||||
reasoningEffort: 'max',
|
||||
})).toBe('max')
|
||||
expect(getAiSdkReasoningEffort({
|
||||
provider: 'openai',
|
||||
model: 'gpt-5.6-luna',
|
||||
@ -219,4 +257,47 @@ describe('AI provider catalog', () => {
|
||||
providerOptions: { openai: { reasoningEffort: 'max' } },
|
||||
})
|
||||
})
|
||||
|
||||
it('shares one OpenCode key field and synthesizes runtime catalog models', () => {
|
||||
const opencodeField = getAiProviderKeyFields().find((field) => field.id === 'opencode')
|
||||
expect(opencodeField).toMatchObject({
|
||||
label: 'OpenCode',
|
||||
envVar: 'VITE_OPENCODE_API_KEY',
|
||||
providerIds: ['opencode-zen', 'opencode-go'],
|
||||
})
|
||||
expect(modelSupportsVision(getAiModel({
|
||||
provider: 'opencode-go',
|
||||
model: 'opencode-go/glm-5.3',
|
||||
}))).toBe(false)
|
||||
expect(modelSupportsVision(getAiModel({
|
||||
provider: 'opencode-zen',
|
||||
model: 'opencode-zen/kimi-k3',
|
||||
}))).toBe(true)
|
||||
|
||||
const synthesized = getAiModel({
|
||||
provider: 'opencode-go',
|
||||
model: 'opencode-go/new-model',
|
||||
})
|
||||
expect(synthesized).toEqual({
|
||||
id: 'opencode-go/new-model',
|
||||
label: 'opencode-go/new-model',
|
||||
description: 'OpenCode Go model',
|
||||
})
|
||||
const dynamicModel = {
|
||||
id: 'opencode-go/new-model',
|
||||
label: 'New Go Model',
|
||||
description: 'fetched',
|
||||
supportsVision: false,
|
||||
}
|
||||
setDynamicProviderModels('opencode-go', [dynamicModel])
|
||||
expect(getAiModel({
|
||||
provider: 'opencode-go',
|
||||
model: 'opencode-go/new-model',
|
||||
})).toBe(dynamicModel)
|
||||
expect(findAiModelById('opencode-go/new-model')).toEqual({
|
||||
provider: getAiProvider('opencode-go'),
|
||||
model: dynamicModel,
|
||||
})
|
||||
setDynamicProviderModels('opencode-go', [])
|
||||
})
|
||||
})
|
||||
|
||||
@ -7,6 +7,8 @@ export type AiProviderId =
|
||||
| 'anthropic'
|
||||
| 'xai'
|
||||
| 'openrouter'
|
||||
| 'opencode-zen'
|
||||
| 'opencode-go'
|
||||
|
||||
export type AiReasoningEffort =
|
||||
| 'minimal'
|
||||
@ -23,6 +25,7 @@ export type AiModelSelection = {
|
||||
provider: AiProviderId
|
||||
model: string
|
||||
reasoningEffort?: AiReasoningEffort
|
||||
visionModel?: string
|
||||
}
|
||||
|
||||
export type AiModelOption = {
|
||||
@ -31,6 +34,13 @@ export type AiModelOption = {
|
||||
label: string
|
||||
description: string
|
||||
reasoningEfforts?: readonly AiReasoningEffort[]
|
||||
/** Omitted means the model accepts image input natively. */
|
||||
supportsVision?: boolean
|
||||
}
|
||||
|
||||
export type AiProviderKeyGroup = {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export type AiProviderOption = {
|
||||
@ -40,8 +50,12 @@ export type AiProviderOption = {
|
||||
auth: 'apiKey' | 'chatgpt'
|
||||
transport: 'bridge' | 'direct' | 'proxy'
|
||||
models: readonly AiModelOption[]
|
||||
keyGroup?: AiProviderKeyGroup
|
||||
}
|
||||
|
||||
export const modelSupportsVision = (model: AiModelOption): boolean =>
|
||||
model.supportsVision !== false
|
||||
|
||||
export const DEFAULT_AI_REASONING_EFFORT = 'high' as const satisfies AiReasoningEffort
|
||||
|
||||
export const AI_REASONING_EFFORT_LABELS: Record<AiReasoningEffort, string> = {
|
||||
@ -67,7 +81,7 @@ const STANDARD_REASONING_EFFORTS = [
|
||||
'xhigh',
|
||||
] as const satisfies readonly AiReasoningEffort[]
|
||||
|
||||
/** GPT-5.6 Luna / Terra / Sol: low … xhigh / max (`max` via providerOptions). */
|
||||
/** GPT-6 Astra and GPT-5.6: low … xhigh / max (`max` via providerOptions). */
|
||||
const OPENAI_REASONING_EFFORTS = [
|
||||
'low',
|
||||
'medium',
|
||||
@ -112,11 +126,18 @@ export const AI_PROVIDERS: readonly AiProviderOption[] = [
|
||||
description: 'Recommended · uses your ChatGPT plan, no API key',
|
||||
reasoningEfforts: OPENAI_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
id: 'codex/gpt-6-astra',
|
||||
providerModelId: 'gpt-6-astra',
|
||||
label: 'GPT-6 Astra',
|
||||
description: 'Most capable · uses your ChatGPT plan',
|
||||
reasoningEfforts: OPENAI_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
id: 'codex/gpt-5.6-sol',
|
||||
providerModelId: 'gpt-5.6-sol',
|
||||
label: 'GPT-5.6 Sol',
|
||||
description: 'Highest quality · uses your ChatGPT plan',
|
||||
description: 'Previous flagship · uses your ChatGPT plan',
|
||||
reasoningEfforts: OPENAI_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
@ -210,10 +231,16 @@ export const AI_PROVIDERS: readonly AiProviderOption[] = [
|
||||
description: 'Recommended · balanced quality and cost',
|
||||
reasoningEfforts: OPENAI_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
id: 'gpt-6-astra',
|
||||
label: 'GPT-6 Astra',
|
||||
description: 'Most capable for complex agentic work',
|
||||
reasoningEfforts: OPENAI_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.6-sol',
|
||||
label: 'GPT-5.6 Sol',
|
||||
description: 'Highest quality for agentic work',
|
||||
description: 'Previous flagship for agentic work',
|
||||
reasoningEfforts: OPENAI_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
@ -320,6 +347,86 @@ export const AI_PROVIDERS: readonly AiProviderOption[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'opencode-zen',
|
||||
label: 'OpenCode Zen',
|
||||
envVar: 'VITE_OPENCODE_API_KEY',
|
||||
auth: 'apiKey',
|
||||
transport: 'proxy',
|
||||
keyGroup: { id: 'opencode', label: 'OpenCode' },
|
||||
// Curated recommendations; the full tools catalog is fetched at runtime
|
||||
// (src/ai/opencode-models.ts) and this list doubles as the offline fallback.
|
||||
models: [
|
||||
{
|
||||
id: 'opencode-zen/gpt-5.6-terra',
|
||||
providerModelId: 'gpt-5.6-terra',
|
||||
label: 'GPT 5.6 Terra',
|
||||
description: 'Recommended · vision and tools',
|
||||
reasoningEfforts: OPENROUTER_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
id: 'opencode-zen/claude-sonnet-5',
|
||||
providerModelId: 'claude-sonnet-5',
|
||||
label: 'Claude Sonnet 5',
|
||||
description: 'Balanced quality and cost',
|
||||
reasoningEfforts: OPENROUTER_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
id: 'opencode-zen/kimi-k3',
|
||||
providerModelId: 'kimi-k3',
|
||||
label: 'Kimi K3',
|
||||
description: 'Open coding model with vision',
|
||||
reasoningEfforts: OPENROUTER_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
id: 'opencode-zen/glm-5.2',
|
||||
providerModelId: 'glm-5.2',
|
||||
label: 'GLM 5.2',
|
||||
description: 'No native vision · a vision model describes images first',
|
||||
reasoningEfforts: OPENROUTER_REASONING_EFFORTS,
|
||||
supportsVision: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'opencode-go',
|
||||
label: 'OpenCode Go',
|
||||
envVar: 'VITE_OPENCODE_API_KEY',
|
||||
auth: 'apiKey',
|
||||
transport: 'proxy',
|
||||
keyGroup: { id: 'opencode', label: 'OpenCode' },
|
||||
models: [
|
||||
{
|
||||
id: 'opencode-go/gpt-5.6-luna',
|
||||
providerModelId: 'gpt-5.6-luna',
|
||||
label: 'GPT 5.6 Luna',
|
||||
description: 'Recommended · vision and tools',
|
||||
reasoningEfforts: OPENROUTER_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
id: 'opencode-go/kimi-k3',
|
||||
providerModelId: 'kimi-k3',
|
||||
label: 'Kimi K3',
|
||||
description: 'Open coding model with vision',
|
||||
reasoningEfforts: OPENROUTER_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
id: 'opencode-go/mimo-v2.5',
|
||||
providerModelId: 'mimo-v2.5',
|
||||
label: 'MiMo V2.5',
|
||||
description: 'Fast open model with vision',
|
||||
reasoningEfforts: OPENROUTER_REASONING_EFFORTS,
|
||||
},
|
||||
{
|
||||
id: 'opencode-go/glm-5.3',
|
||||
providerModelId: 'glm-5.3',
|
||||
label: 'GLM 5.3',
|
||||
description: 'No native vision · a vision model describes images first',
|
||||
reasoningEfforts: OPENROUTER_REASONING_EFFORTS,
|
||||
supportsVision: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export const DEFAULT_AI_SELECTION: AiModelSelection = {
|
||||
@ -331,37 +438,93 @@ export const DEFAULT_AI_SELECTION: AiModelSelection = {
|
||||
export const isAiProviderId = (value: unknown): value is AiProviderId =>
|
||||
typeof value === 'string' && AI_PROVIDERS.some((provider) => provider.id === value)
|
||||
|
||||
export type AiProviderKeyField = {
|
||||
id: string
|
||||
label: string
|
||||
envVar: string
|
||||
providerIds: readonly AiProviderId[]
|
||||
}
|
||||
|
||||
/** One API-key field per credential, sharing Zen/Go under a single OpenCode key. */
|
||||
export const getAiProviderKeyFields = (): readonly AiProviderKeyField[] => {
|
||||
const fields: AiProviderKeyField[] = []
|
||||
const indexById = new Map<string, number>()
|
||||
for (const provider of AI_PROVIDERS) {
|
||||
if (provider.auth !== 'apiKey') continue
|
||||
const id = provider.keyGroup?.id ?? provider.id
|
||||
const existingIndex = indexById.get(id)
|
||||
if (existingIndex !== undefined) {
|
||||
const existing = fields[existingIndex]
|
||||
if (!existing) continue
|
||||
fields[existingIndex] = {
|
||||
...existing,
|
||||
providerIds: [...existing.providerIds, provider.id],
|
||||
}
|
||||
continue
|
||||
}
|
||||
indexById.set(id, fields.length)
|
||||
fields.push({
|
||||
id,
|
||||
label: provider.keyGroup?.label ?? provider.label,
|
||||
envVar: provider.envVar,
|
||||
providerIds: [provider.id],
|
||||
})
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenRouter models discovered at runtime (src/ai/openrouter-models.ts).
|
||||
* Registered here so catalog lookups resolve dynamic selections; the static
|
||||
* catalog stays the source of truth for every other provider.
|
||||
* Runtime catalogs (OpenRouter, OpenCode Zen/Go) register here so lookups
|
||||
* resolve dynamic selections. The static catalog stays the fallback.
|
||||
*/
|
||||
let dynamicOpenRouterModels: readonly AiModelOption[] = []
|
||||
const DYNAMIC_CATALOG_PROVIDERS = new Set<AiProviderId>([
|
||||
'openrouter',
|
||||
'opencode-zen',
|
||||
'opencode-go',
|
||||
])
|
||||
|
||||
const dynamicModelsByProvider: Partial<Record<AiProviderId, readonly AiModelOption[]>> = {}
|
||||
|
||||
export const setDynamicProviderModels = (
|
||||
providerId: AiProviderId,
|
||||
models: readonly AiModelOption[],
|
||||
): void => {
|
||||
dynamicModelsByProvider[providerId] = models
|
||||
}
|
||||
|
||||
export const getDynamicProviderModels = (
|
||||
providerId: AiProviderId,
|
||||
): readonly AiModelOption[] =>
|
||||
dynamicModelsByProvider[providerId] ?? []
|
||||
|
||||
export const setDynamicOpenRouterModels = (
|
||||
models: readonly AiModelOption[],
|
||||
): void => {
|
||||
dynamicOpenRouterModels = models
|
||||
setDynamicProviderModels('openrouter', models)
|
||||
}
|
||||
|
||||
export const getDynamicOpenRouterModels = (): readonly AiModelOption[] =>
|
||||
dynamicOpenRouterModels
|
||||
getDynamicProviderModels('openrouter')
|
||||
|
||||
const findOpenRouterModel = (modelId: string): AiModelOption | undefined =>
|
||||
getAiProvider('openrouter').models.find((option) => option.id === modelId)
|
||||
?? dynamicOpenRouterModels.find((option) => option.id === modelId)
|
||||
const findDynamicCatalogModel = (
|
||||
providerId: AiProviderId,
|
||||
modelId: string,
|
||||
): AiModelOption | undefined =>
|
||||
getAiProvider(providerId).models.find((option) => option.id === modelId)
|
||||
?? getDynamicProviderModels(providerId).find((option) => option.id === modelId)
|
||||
|
||||
/**
|
||||
* A dynamic selection may outlive the fetched catalog (e.g. the model list is
|
||||
* still loading); synthesize a minimal option so lookups never throw for the
|
||||
* dynamic provider. Reasoning support is unknown, so no effort is offered.
|
||||
*/
|
||||
const synthesizeOpenRouterModel = (modelId: string): AiModelOption => ({
|
||||
const synthesizeDynamicCatalogModel = (
|
||||
providerId: AiProviderId,
|
||||
modelId: string,
|
||||
): AiModelOption => ({
|
||||
id: modelId,
|
||||
label: modelId,
|
||||
description: 'OpenRouter model',
|
||||
description: `${getAiProvider(providerId).label} model`,
|
||||
})
|
||||
|
||||
export const isDynamicCatalogProvider = (providerId: AiProviderId): boolean =>
|
||||
DYNAMIC_CATALOG_PROVIDERS.has(providerId)
|
||||
|
||||
export const getAiProvider = (providerId: AiProviderId): AiProviderOption => {
|
||||
const provider = AI_PROVIDERS.find((option) => option.id === providerId)
|
||||
if (!provider) throw new Error(`Unknown AI provider: ${providerId}`)
|
||||
@ -375,9 +538,9 @@ export const getDefaultAiModel = (providerId: AiProviderId): AiModelOption => {
|
||||
}
|
||||
|
||||
export const getAiModel = (selection: AiModelSelection): AiModelOption => {
|
||||
if (selection.provider === 'openrouter') {
|
||||
return findOpenRouterModel(selection.model)
|
||||
?? synthesizeOpenRouterModel(selection.model)
|
||||
if (isDynamicCatalogProvider(selection.provider)) {
|
||||
return findDynamicCatalogModel(selection.provider, selection.model)
|
||||
?? synthesizeDynamicCatalogModel(selection.provider, selection.model)
|
||||
}
|
||||
const model = getAiProvider(selection.provider).models.find(
|
||||
(option) => option.id === selection.model,
|
||||
@ -395,9 +558,13 @@ export const findAiModelById = (
|
||||
const model = provider.models.find((option) => option.id === modelId)
|
||||
if (model) return { provider, model }
|
||||
}
|
||||
const dynamicModel = dynamicOpenRouterModels.find((option) => option.id === modelId)
|
||||
if (dynamicModel) {
|
||||
return { provider: getAiProvider('openrouter'), model: dynamicModel }
|
||||
for (const providerId of DYNAMIC_CATALOG_PROVIDERS) {
|
||||
const dynamicModel = getDynamicProviderModels(providerId).find(
|
||||
(option) => option.id === modelId,
|
||||
)
|
||||
if (dynamicModel) {
|
||||
return { provider: getAiProvider(providerId), model: dynamicModel }
|
||||
}
|
||||
}
|
||||
throw new Error(`Unknown AI model: ${modelId}`)
|
||||
}
|
||||
|
||||
@ -43,8 +43,9 @@ describe('AI provider configuration', () => {
|
||||
VITE_ANTHROPIC_API_KEY: 'anthropic-key',
|
||||
VITE_XAI_API_KEY: ' xai-key ',
|
||||
VITE_OPENROUTER_API_KEY: ' openrouter-key ',
|
||||
VITE_OPENCODE_API_KEY: ' opencode-key ',
|
||||
})).toEqual({
|
||||
codex: '',
|
||||
...createEmptyAiProviderKeys(),
|
||||
moonshot: 'moonshot-key',
|
||||
google: 'google-key',
|
||||
qwen: 'qwen-key',
|
||||
@ -52,6 +53,8 @@ describe('AI provider configuration', () => {
|
||||
anthropic: 'anthropic-key',
|
||||
xai: 'xai-key',
|
||||
openrouter: 'openrouter-key',
|
||||
'opencode-zen': 'opencode-key',
|
||||
'opencode-go': 'opencode-key',
|
||||
})
|
||||
})
|
||||
|
||||
@ -63,14 +66,8 @@ describe('AI provider configuration', () => {
|
||||
})
|
||||
|
||||
expect(keys).toEqual({
|
||||
codex: '',
|
||||
moonshot: '',
|
||||
google: '',
|
||||
qwen: '',
|
||||
...createEmptyAiProviderKeys(),
|
||||
openai: 'openai-key',
|
||||
anthropic: '',
|
||||
xai: '',
|
||||
openrouter: '',
|
||||
})
|
||||
expect(getAiProviderAvailability(keys)).toEqual({
|
||||
codex: false,
|
||||
@ -81,6 +78,8 @@ describe('AI provider configuration', () => {
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: false,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
})
|
||||
})
|
||||
|
||||
@ -94,6 +93,8 @@ describe('AI provider configuration', () => {
|
||||
anthropic: true,
|
||||
xai: true,
|
||||
openrouter: true,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
})).toEqual({
|
||||
provider: 'openai',
|
||||
model: 'gpt-5.6-terra',
|
||||
@ -108,6 +109,8 @@ describe('AI provider configuration', () => {
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: true,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
})).toEqual({
|
||||
provider: 'openrouter',
|
||||
model: 'anthropic/claude-sonnet-5',
|
||||
@ -122,6 +125,8 @@ describe('AI provider configuration', () => {
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: false,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
})).toEqual({
|
||||
provider: 'codex',
|
||||
model: 'codex/gpt-5.6-terra',
|
||||
@ -136,6 +141,8 @@ describe('AI provider configuration', () => {
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: false,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
})).toEqual({
|
||||
provider: 'moonshot',
|
||||
model: 'kimi-k3',
|
||||
@ -154,14 +161,9 @@ describe('AI provider configuration', () => {
|
||||
}
|
||||
|
||||
expect(mergeAiProviderKeys(environment, stored)).toEqual({
|
||||
codex: '',
|
||||
moonshot: '',
|
||||
...createEmptyAiProviderKeys(),
|
||||
google: 'env-google',
|
||||
qwen: '',
|
||||
openai: 'browser-openai',
|
||||
anthropic: '',
|
||||
xai: '',
|
||||
openrouter: '',
|
||||
})
|
||||
})
|
||||
|
||||
@ -176,6 +178,20 @@ describe('AI provider configuration', () => {
|
||||
...createEmptyAiProviderKeys(),
|
||||
openai: 'sk-test',
|
||||
})
|
||||
expect(parseStoredAiProviderKeys(JSON.stringify({
|
||||
opencode: ' zen-go-key ',
|
||||
}))).toEqual({
|
||||
...createEmptyAiProviderKeys(),
|
||||
'opencode-zen': 'zen-go-key',
|
||||
'opencode-go': 'zen-go-key',
|
||||
})
|
||||
expect(parseStoredAiProviderKeys(JSON.stringify({
|
||||
'opencode-zen': ' zen-only-key ',
|
||||
}))).toEqual({
|
||||
...createEmptyAiProviderKeys(),
|
||||
'opencode-zen': 'zen-only-key',
|
||||
'opencode-go': 'zen-only-key',
|
||||
})
|
||||
|
||||
const storage = createMemoryStorage()
|
||||
expect(writeStoredAiProviderKeys({
|
||||
@ -238,6 +254,8 @@ describe('AI provider configuration', () => {
|
||||
expect(isLocalAiProxyHostname('[::1]')).toBe(true)
|
||||
expect(isLocalAiProxyHostname('app.shotluma.com')).toBe(false)
|
||||
expect(getAiProviderTransportAvailability('app.shotluma.com').moonshot).toBe(false)
|
||||
expect(getAiProviderTransportAvailability('app.shotluma.com')['opencode-zen']).toBe(true)
|
||||
expect(getAiProviderTransportAvailability('app.shotluma.com')['opencode-go']).toBe(true)
|
||||
})
|
||||
|
||||
it('does not mark a stored Moonshot key as usable without the local proxy', () => {
|
||||
|
||||
@ -22,6 +22,7 @@ type AiProviderEnvironment = {
|
||||
VITE_ANTHROPIC_API_KEY?: unknown
|
||||
VITE_XAI_API_KEY?: unknown
|
||||
VITE_OPENROUTER_API_KEY?: unknown
|
||||
VITE_OPENCODE_API_KEY?: unknown
|
||||
}
|
||||
|
||||
export const AI_PROVIDER_KEYS_STORAGE_KEY = 'shotluma-ai-provider-keys'
|
||||
@ -40,20 +41,27 @@ export const createEmptyAiProviderKeys = (): AiProviderKeys => ({
|
||||
anthropic: '',
|
||||
xai: '',
|
||||
openrouter: '',
|
||||
'opencode-zen': '',
|
||||
'opencode-go': '',
|
||||
})
|
||||
|
||||
export const createAiProviderKeys = (
|
||||
environment: AiProviderEnvironment,
|
||||
): AiProviderKeys => ({
|
||||
codex: '',
|
||||
moonshot: readKey(environment.VITE_MOONSHOT_API_KEY),
|
||||
google: readKey(environment.VITE_GOOGLE_GENERATIVE_AI_API_KEY),
|
||||
qwen: readKey(environment.VITE_ALIBABA_API_KEY),
|
||||
openai: readKey(environment.VITE_OPENAI_API_KEY),
|
||||
anthropic: readKey(environment.VITE_ANTHROPIC_API_KEY),
|
||||
xai: readKey(environment.VITE_XAI_API_KEY),
|
||||
openrouter: readKey(environment.VITE_OPENROUTER_API_KEY),
|
||||
})
|
||||
): AiProviderKeys => {
|
||||
const opencode = readKey(environment.VITE_OPENCODE_API_KEY)
|
||||
return {
|
||||
codex: '',
|
||||
moonshot: readKey(environment.VITE_MOONSHOT_API_KEY),
|
||||
google: readKey(environment.VITE_GOOGLE_GENERATIVE_AI_API_KEY),
|
||||
qwen: readKey(environment.VITE_ALIBABA_API_KEY),
|
||||
openai: readKey(environment.VITE_OPENAI_API_KEY),
|
||||
anthropic: readKey(environment.VITE_ANTHROPIC_API_KEY),
|
||||
xai: readKey(environment.VITE_XAI_API_KEY),
|
||||
openrouter: readKey(environment.VITE_OPENROUTER_API_KEY),
|
||||
'opencode-zen': opencode,
|
||||
'opencode-go': opencode,
|
||||
}
|
||||
}
|
||||
|
||||
export const getAiProviderAvailability = (
|
||||
keys: AiProviderKeys,
|
||||
@ -66,6 +74,8 @@ export const getAiProviderAvailability = (
|
||||
anthropic: keys.anthropic.length > 0,
|
||||
xai: keys.xai.length > 0,
|
||||
openrouter: keys.openrouter.length > 0,
|
||||
'opencode-zen': keys['opencode-zen'].length > 0,
|
||||
'opencode-go': keys['opencode-go'].length > 0,
|
||||
})
|
||||
|
||||
const getBrowserHostname = (): string => {
|
||||
@ -95,6 +105,8 @@ export const getAiProviderTransportAvailability = (
|
||||
anthropic: true,
|
||||
xai: true,
|
||||
openrouter: true,
|
||||
'opencode-zen': true,
|
||||
'opencode-go': true,
|
||||
})
|
||||
|
||||
export const mergeAiProviderKeys = (
|
||||
@ -125,6 +137,11 @@ export const parseStoredAiProviderKeys = (raw: string | null): AiProviderKeys =>
|
||||
for (const providerId of PROVIDER_IDS) {
|
||||
keys[providerId] = readKey(record[providerId])
|
||||
}
|
||||
const sharedOpencode = readKey(record['opencode'])
|
||||
|| keys['opencode-zen']
|
||||
|| keys['opencode-go']
|
||||
keys['opencode-zen'] = sharedOpencode
|
||||
keys['opencode-go'] = sharedOpencode
|
||||
return keys
|
||||
}
|
||||
|
||||
@ -232,6 +249,7 @@ export const ENVIRONMENT_AI_PROVIDER_KEYS = createAiProviderKeys({
|
||||
VITE_ANTHROPIC_API_KEY: import.meta.env.VITE_ANTHROPIC_API_KEY,
|
||||
VITE_XAI_API_KEY: import.meta.env.VITE_XAI_API_KEY,
|
||||
VITE_OPENROUTER_API_KEY: import.meta.env.VITE_OPENROUTER_API_KEY,
|
||||
VITE_OPENCODE_API_KEY: import.meta.env.VITE_OPENCODE_API_KEY,
|
||||
})
|
||||
|
||||
export const AI_PROVIDER_AVAILABILITY = getResolvedAiProviderAvailability()
|
||||
|
||||
98
src/ai/runner.test.ts
Normal file
98
src/ai/runner.test.ts
Normal file
@ -0,0 +1,98 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { prepareGenerationMessages, type OpencodeVisionFallback } from './runner'
|
||||
import type { ModelMessage } from 'ai'
|
||||
|
||||
const textOnlyMessages: ModelMessage[] = [
|
||||
{ role: 'user', content: 'Design three slides' },
|
||||
]
|
||||
|
||||
const messagesWithUserImage: ModelMessage[] = [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: 'Screenshot:' },
|
||||
{ type: 'file', mediaType: 'image/png', data: 'data:image/png;base64,abc' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const messagesWithToolPreview: ModelMessage[] = [
|
||||
{ role: 'user', content: 'Design three slides' },
|
||||
{
|
||||
role: 'tool',
|
||||
content: [{
|
||||
type: 'tool-result',
|
||||
toolCallId: 'call-1',
|
||||
toolName: 'render_slide_preview',
|
||||
output: {
|
||||
type: 'content',
|
||||
value: [{
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
data: { type: 'data', data: 'preview-bytes' },
|
||||
}],
|
||||
},
|
||||
}],
|
||||
},
|
||||
]
|
||||
|
||||
const prepare = (
|
||||
messages: ModelMessage[],
|
||||
resolveVisionFallback: (() => OpencodeVisionFallback) | null,
|
||||
needsChatImageRelay = false,
|
||||
) => prepareGenerationMessages({
|
||||
messages,
|
||||
movingCacheProvider: null,
|
||||
needsChatImageRelay,
|
||||
resolveVisionFallback,
|
||||
visionAnnouncement: { sent: false },
|
||||
descriptionCache: new Map(),
|
||||
})
|
||||
|
||||
describe('prepareGenerationMessages', () => {
|
||||
it('never resolves the vision fallback for image-free requests', async () => {
|
||||
const resolveVisionFallback = vi.fn((): OpencodeVisionFallback => {
|
||||
throw new Error('no OpenCode vision model is available')
|
||||
})
|
||||
const prepared = await prepare(textOnlyMessages, resolveVisionFallback)
|
||||
expect(prepared).toBe(textOnlyMessages)
|
||||
expect(resolveVisionFallback).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces the missing-vision-model error once an image appears', async () => {
|
||||
const resolveVisionFallback = (): OpencodeVisionFallback => {
|
||||
throw new Error('no OpenCode vision model is available')
|
||||
}
|
||||
await expect(prepare(messagesWithUserImage, resolveVisionFallback))
|
||||
.rejects.toThrow('no OpenCode vision model is available')
|
||||
})
|
||||
|
||||
it('describes user images through the resolved fallback', async () => {
|
||||
const describeImage = vi.fn().mockResolvedValue('a login screen')
|
||||
const prepared = await prepare(messagesWithUserImage, () => ({
|
||||
describeImage,
|
||||
visionLabel: 'MiMo V2.5',
|
||||
}))
|
||||
expect(describeImage).toHaveBeenCalledTimes(1)
|
||||
expect(prepared[0]).toMatchObject({
|
||||
content: [
|
||||
{ type: 'text', text: 'Screenshot:' },
|
||||
{ type: 'text', text: 'Image description:\na login screen' },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('relays tool preview images for non-chat dialects when the fallback is active', async () => {
|
||||
const describeImage = vi.fn().mockResolvedValue('slide preview')
|
||||
const prepared = await prepare(messagesWithToolPreview, () => ({
|
||||
describeImage,
|
||||
visionLabel: 'MiMo V2.5',
|
||||
}), false)
|
||||
expect(describeImage).toHaveBeenCalledTimes(1)
|
||||
const relayedUserMessage = prepared[prepared.length - 1]
|
||||
expect(relayedUserMessage).toMatchObject({
|
||||
role: 'user',
|
||||
content: [{ type: 'text', text: 'Image description:\nslide preview' }],
|
||||
})
|
||||
})
|
||||
})
|
||||
171
src/ai/runner.ts
171
src/ai/runner.ts
@ -14,7 +14,21 @@ import { relayChatToolImages } from './chat-tool-images'
|
||||
import { runCodexAppServerGeneration } from './codex-app-server'
|
||||
import { readCodexConnection } from './codex-connection'
|
||||
import { scopeAiControllerToSlide, type AiEditorController } from './controller'
|
||||
import { collectMessageImages, describeMessageImages } from './describe-images'
|
||||
import { buildHtmlInstructions } from './html-prompt'
|
||||
import {
|
||||
createOpencodeImageDescriber,
|
||||
createOpencodeModel,
|
||||
} from './opencode-client'
|
||||
import {
|
||||
opencodeDialectNeedsChatToolImageRelay,
|
||||
opencodeSelectionDialect,
|
||||
} from './opencode-dialects'
|
||||
import {
|
||||
isOpencodeProviderId,
|
||||
opencodeRequestModelId,
|
||||
pickOpencodeVisionModel,
|
||||
} from './opencode-models'
|
||||
import { buildInstructions, buildUserMessage } from './prompt'
|
||||
import {
|
||||
buildStreamRequestOptions,
|
||||
@ -26,6 +40,8 @@ import {
|
||||
getAiModel,
|
||||
getAiProvider,
|
||||
getAiSdkReasoningEffort,
|
||||
getDynamicProviderModels,
|
||||
modelSupportsVision,
|
||||
type AiModelSelection,
|
||||
} from './provider-catalog'
|
||||
import {
|
||||
@ -107,7 +123,9 @@ const buildUserContent = (options: {
|
||||
|
||||
const createAiModel = async (selection: AiModelSelection) => {
|
||||
if (!getAiProviderTransportAvailability()[selection.provider]) {
|
||||
throw new Error('Moonshot requires the local Shotluma CORS proxy and is unavailable on this host')
|
||||
throw new Error(
|
||||
`${getAiProvider(selection.provider).label} requires the local Shotluma CORS proxy and is unavailable on this host`,
|
||||
)
|
||||
}
|
||||
const apiKey = getAiProviderKey(selection.provider)
|
||||
if (!apiKey) {
|
||||
@ -162,6 +180,15 @@ const createAiModel = async (selection: AiModelSelection) => {
|
||||
},
|
||||
}).chat(selection.model)
|
||||
}
|
||||
case 'opencode-zen':
|
||||
case 'opencode-go': {
|
||||
const model = getAiModel(selection)
|
||||
return createOpencodeModel({
|
||||
providerId: selection.provider,
|
||||
modelId: opencodeRequestModelId(model.id, model.providerModelId),
|
||||
apiKey,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -304,7 +331,99 @@ const collectStreamPart = <TOOLS extends ToolSet>(options: {
|
||||
*/
|
||||
export const NARRATION_WORD_DELAY_MS = 18
|
||||
|
||||
export const narrationSmoothing = () => smoothStream<ToolSet>({ delayInMs: NARRATION_WORD_DELAY_MS })
|
||||
export const narrationSmoothing = () =>
|
||||
smoothStream<ToolSet>({ delayInMs: NARRATION_WORD_DELAY_MS })
|
||||
|
||||
/**
|
||||
* OpenCode serves each model on one of four dialects, and only its
|
||||
* chat-completions models reject images inside tool results.
|
||||
*/
|
||||
const needsChatToolImageRelay = (selection: AiModelSelection): boolean => {
|
||||
const dialect = opencodeSelectionDialect(selection)
|
||||
if (dialect) return opencodeDialectNeedsChatToolImageRelay(dialect)
|
||||
return selection.provider === 'moonshot'
|
||||
|| selection.provider === 'openrouter'
|
||||
|| selection.provider === 'qwen'
|
||||
}
|
||||
|
||||
export type OpencodeVisionFallback = {
|
||||
describeImage: ReturnType<typeof createOpencodeImageDescriber>
|
||||
visionLabel: string
|
||||
}
|
||||
|
||||
const needsOpencodeVisionFallback = (selection: AiModelSelection): boolean =>
|
||||
isOpencodeProviderId(selection.provider) && !modelSupportsVision(getAiModel(selection))
|
||||
|
||||
const resolveOpencodeVisionDescriber = (options: {
|
||||
selection: AiModelSelection
|
||||
apiKey: string
|
||||
signal?: AbortSignal
|
||||
}): OpencodeVisionFallback | null => {
|
||||
if (!isOpencodeProviderId(options.selection.provider)) return null
|
||||
const model = getAiModel(options.selection)
|
||||
if (modelSupportsVision(model)) return null
|
||||
const catalog = [
|
||||
...getAiProvider(options.selection.provider).models,
|
||||
...getDynamicProviderModels(options.selection.provider),
|
||||
]
|
||||
const vision = pickOpencodeVisionModel(
|
||||
options.selection.provider,
|
||||
catalog,
|
||||
options.selection.visionModel,
|
||||
)
|
||||
if (!vision) {
|
||||
throw new Error(
|
||||
`${model.label} cannot see images, and no OpenCode vision model is available to describe them.`,
|
||||
)
|
||||
}
|
||||
return {
|
||||
visionLabel: vision.label,
|
||||
describeImage: createOpencodeImageDescriber({
|
||||
providerId: options.selection.provider,
|
||||
visionModelId: opencodeRequestModelId(vision.id, vision.providerModelId),
|
||||
apiKey: options.apiKey,
|
||||
...(options.signal ? { signal: options.signal } : {}),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The resolver runs only once a prepared step actually contains an image, so
|
||||
* a text-only OpenCode model without any vision fallback in the catalog can
|
||||
* still run image-free requests; the missing-fallback error surfaces the
|
||||
* moment a screenshot or slide preview enters the conversation.
|
||||
*/
|
||||
export const prepareGenerationMessages = async (options: {
|
||||
messages: ModelMessage[]
|
||||
movingCacheProvider: 'anthropic' | 'alibaba' | null
|
||||
needsChatImageRelay: boolean
|
||||
resolveVisionFallback: (() => OpencodeVisionFallback) | null
|
||||
onStatus?: (message: string) => void
|
||||
visionAnnouncement: { sent: boolean }
|
||||
descriptionCache: Map<string, string>
|
||||
}): Promise<ModelMessage[]> => {
|
||||
// Text-only models reject images anywhere, so the vision fallback also
|
||||
// needs tool-result images relayed into user messages before describing.
|
||||
const relayed = options.needsChatImageRelay || options.resolveVisionFallback !== null
|
||||
? relayChatToolImages(options.messages)
|
||||
: options.messages
|
||||
let next = relayed
|
||||
if (options.resolveVisionFallback && collectMessageImages(relayed).length > 0) {
|
||||
const visionFallback = options.resolveVisionFallback()
|
||||
if (!options.visionAnnouncement.sent) {
|
||||
options.visionAnnouncement.sent = true
|
||||
options.onStatus?.(`Describing images with ${visionFallback.visionLabel}…`)
|
||||
}
|
||||
next = await describeMessageImages(
|
||||
relayed,
|
||||
visionFallback.describeImage,
|
||||
options.descriptionCache,
|
||||
)
|
||||
}
|
||||
return options.movingCacheProvider
|
||||
? withMovingCacheBreakpoint(next, options.movingCacheProvider)
|
||||
: next
|
||||
}
|
||||
|
||||
const openAiGenerationStream = (options: {
|
||||
model: Awaited<ReturnType<typeof createAiModel>>
|
||||
@ -317,6 +436,7 @@ const openAiGenerationStream = (options: {
|
||||
signal?: AbortSignal
|
||||
onActivity?: (activity: AiToolActivity) => void
|
||||
onStepUsage?: (usage: LanguageModelUsage, toolNames: string[]) => void
|
||||
onStatus?: (message: string) => void
|
||||
}) => {
|
||||
const {
|
||||
model,
|
||||
@ -329,6 +449,7 @@ const openAiGenerationStream = (options: {
|
||||
signal,
|
||||
onActivity,
|
||||
onStepUsage,
|
||||
onStatus,
|
||||
} = options
|
||||
const runController = targetSlideId
|
||||
? scopeAiControllerToSlide(controller, targetSlideId)
|
||||
@ -352,9 +473,23 @@ const openAiGenerationStream = (options: {
|
||||
const movingCacheProvider = selection.provider === 'anthropic'
|
||||
? 'anthropic'
|
||||
: selection.provider === 'qwen' ? 'alibaba' : null
|
||||
const needsChatImageRelay = selection.provider === 'moonshot'
|
||||
|| selection.provider === 'openrouter'
|
||||
|| selection.provider === 'qwen'
|
||||
const needsChatImageRelay = needsChatToolImageRelay(selection)
|
||||
let cachedVisionFallback: OpencodeVisionFallback | null = null
|
||||
const resolveVisionFallback = needsOpencodeVisionFallback(selection)
|
||||
? (): OpencodeVisionFallback => {
|
||||
cachedVisionFallback ??= resolveOpencodeVisionDescriber({
|
||||
selection,
|
||||
apiKey: getAiProviderKey(selection.provider),
|
||||
...(signal ? { signal } : {}),
|
||||
})
|
||||
if (!cachedVisionFallback) {
|
||||
throw new Error(`${getAiModel(selection).label} has no vision fallback to describe images.`)
|
||||
}
|
||||
return cachedVisionFallback
|
||||
}
|
||||
: null
|
||||
const visionAnnouncement = { sent: false }
|
||||
const descriptionCache = new Map<string, string>()
|
||||
|
||||
return streamText({
|
||||
model,
|
||||
@ -375,18 +510,19 @@ const openAiGenerationStream = (options: {
|
||||
...requestOptions,
|
||||
// Anthropic and Alibaba require explicit message breakpoints. Keep one
|
||||
// moving forward so each step can reuse the growing tool-loop prefix.
|
||||
...(movingCacheProvider || needsChatImageRelay
|
||||
...(movingCacheProvider || needsChatImageRelay || resolveVisionFallback
|
||||
? {
|
||||
prepareStep: ({ messages }: { messages: ModelMessage[] }) => {
|
||||
const relayed = needsChatImageRelay
|
||||
? relayChatToolImages(messages)
|
||||
: messages
|
||||
return {
|
||||
messages: movingCacheProvider
|
||||
? withMovingCacheBreakpoint(relayed, movingCacheProvider)
|
||||
: relayed,
|
||||
}
|
||||
},
|
||||
prepareStep: async ({ messages }: { messages: ModelMessage[] }) => ({
|
||||
messages: await prepareGenerationMessages({
|
||||
messages,
|
||||
movingCacheProvider,
|
||||
needsChatImageRelay,
|
||||
resolveVisionFallback,
|
||||
...(onStatus ? { onStatus } : {}),
|
||||
visionAnnouncement,
|
||||
descriptionCache,
|
||||
}),
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
...(signal ? { abortSignal: signal } : {}),
|
||||
@ -499,6 +635,9 @@ const runDirectProviderGeneration = async (options: {
|
||||
...(htmlMode ? { htmlMode: true } : {}),
|
||||
...(signal ? { signal } : {}),
|
||||
...(onActivity ? { onActivity } : {}),
|
||||
onStatus: (message) => {
|
||||
onEvent({ type: 'status', message })
|
||||
},
|
||||
onStepUsage: (usage, toolNames) => {
|
||||
accumulator.steps.push({
|
||||
usage: toAiRunTokenUsage(usage),
|
||||
|
||||
@ -75,17 +75,25 @@ export function useAiWorkflow({
|
||||
const activitySequence = useRef(0)
|
||||
const followedSlideId = useRef<string | null>(null)
|
||||
const preRunSlideIds = useRef<Set<string>>(new Set())
|
||||
const [runActive, setRunActive] = useState(false)
|
||||
const runControlRef = useRef<{ cancel: () => void } | null>(null)
|
||||
const runActiveRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
setController(createAiController({
|
||||
getSlides: () => slidesRef.current,
|
||||
// Writes are gated on the registered run: after an external cancel (for
|
||||
// example a project switch) an in-flight tool result must not land in
|
||||
// whatever project the refs point to by then.
|
||||
setSlides: (updater) => {
|
||||
if (!runActiveRef.current) return
|
||||
const next = updater(slidesRef.current)
|
||||
slidesRef.current = next
|
||||
setSlides(next)
|
||||
},
|
||||
getUploads: () => uploadsRef.current,
|
||||
setUploads: (updater) => {
|
||||
if (!runActiveRef.current) return
|
||||
const next = updater(uploadsRef.current)
|
||||
uploadsRef.current = next
|
||||
setUploads(next)
|
||||
@ -93,6 +101,33 @@ export function useAiWorkflow({
|
||||
}))
|
||||
}, [setSlides, setUploads, slidesRef, uploadsRef])
|
||||
|
||||
const handleRunStateChange = useCallback((control: { cancel: () => void } | null) => {
|
||||
runControlRef.current = control
|
||||
runActiveRef.current = control !== null
|
||||
setRunActive(control !== null)
|
||||
}, [])
|
||||
|
||||
const isRunActive = useCallback(() => runActiveRef.current, [])
|
||||
|
||||
const cancelActiveRun = useCallback(() => {
|
||||
const control = runControlRef.current
|
||||
runControlRef.current = null
|
||||
runActiveRef.current = false
|
||||
setRunActive(false)
|
||||
control?.cancel()
|
||||
followedSlideId.current = null
|
||||
setActivity(null)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!runActive) return
|
||||
const warnBeforeUnload = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault()
|
||||
}
|
||||
window.addEventListener('beforeunload', warnBeforeUnload)
|
||||
return () => window.removeEventListener('beforeunload', warnBeforeUnload)
|
||||
}, [runActive])
|
||||
|
||||
const targetSlide = targetSlideId
|
||||
? slides.find((slide) => slide.id === targetSlideId)
|
||||
: undefined
|
||||
@ -196,6 +231,10 @@ export function useAiWorkflow({
|
||||
open,
|
||||
targetSlide,
|
||||
activity,
|
||||
runActive,
|
||||
isRunActive,
|
||||
cancelActiveRun,
|
||||
handleRunStateChange,
|
||||
handleActivity,
|
||||
prepareRun,
|
||||
openGenerator,
|
||||
|
||||
58
src/app/AiRunCancelDialog.tsx
Normal file
58
src/app/AiRunCancelDialog.tsx
Normal file
@ -0,0 +1,58 @@
|
||||
import { AiGenerative } from '../components/icons'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogMedia,
|
||||
AlertDialogTitle,
|
||||
} from '../components/ui/alert-dialog'
|
||||
|
||||
type AiRunCancelDialogProps = {
|
||||
open: boolean
|
||||
projectName: string
|
||||
onOpenChange: (open: boolean) => void
|
||||
onConfirm: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks before a project switch, creation, or duplication is allowed to end a
|
||||
* live AI generation. Dismissing keeps the run going; confirming cancels the
|
||||
* run and then performs the requested project action.
|
||||
*/
|
||||
export function AiRunCancelDialog({
|
||||
open,
|
||||
projectName,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
}: AiRunCancelDialogProps) {
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent className="ai-run-cancel-dialog">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogMedia><AiGenerative size={17} /></AlertDialogMedia>
|
||||
<AlertDialogTitle>Stop the AI generation?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
An AI generation is still running in “{projectName}”. Leaving now cancels it —
|
||||
finished screens are kept, the screen being built is lost.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel className="ai-run-cancel-keep">
|
||||
Keep generating
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="ai-run-cancel-confirm"
|
||||
variant="destructive"
|
||||
onClick={onConfirm}
|
||||
>
|
||||
Stop and continue
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
@ -42,10 +42,12 @@ const headerProps = {
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
aiDisabled: false,
|
||||
aiRunActive: false,
|
||||
onProjectNameChange: () => undefined,
|
||||
onOpenProject: () => undefined,
|
||||
onCreateProject: () => undefined,
|
||||
onDuplicateProject: () => undefined,
|
||||
onShareProject: () => undefined,
|
||||
onSaveProject: () => undefined,
|
||||
onRequestProjectDeletion: () => undefined,
|
||||
onUndo: () => undefined,
|
||||
@ -74,6 +76,18 @@ describe('App header', () => {
|
||||
expect(markup).not.toMatch(/aria-label="New project"[^>]*disabled/)
|
||||
})
|
||||
|
||||
it('offers sharing the project as a link from the project menu', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<AppHeader
|
||||
{...headerProps}
|
||||
saveStatus="saved"
|
||||
persistenceReady
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(markup).toContain('Share as link')
|
||||
})
|
||||
|
||||
it('disables the new-project button until persistence is ready', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<AppHeader
|
||||
@ -85,4 +99,24 @@ describe('App header', () => {
|
||||
|
||||
expect(markup).toMatch(/aria-label="New project"[^>]*disabled/)
|
||||
})
|
||||
|
||||
it('holds back project deletion while an AI generation is running', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<AppHeader
|
||||
{...headerProps}
|
||||
projects={[...headerProps.projects, {
|
||||
id: 'project-2',
|
||||
projectName: 'Second project',
|
||||
createdAt: 1_700_000_000_000,
|
||||
savedAt: 1_700_000_000_000,
|
||||
}]}
|
||||
aiRunActive
|
||||
saveStatus="saved"
|
||||
persistenceReady
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(markup).toContain('Delete waits for the AI run')
|
||||
expect(markup).not.toContain('Delete current project')
|
||||
})
|
||||
})
|
||||
|
||||
@ -7,6 +7,7 @@ import {
|
||||
Cloud,
|
||||
Copy,
|
||||
Download,
|
||||
Link01,
|
||||
Plus,
|
||||
Redo2,
|
||||
Save,
|
||||
@ -42,10 +43,13 @@ type AppHeaderProps = {
|
||||
canUndo: boolean
|
||||
canRedo: boolean
|
||||
aiDisabled: boolean
|
||||
/** True while an AI generation is running; project deletion is held back until it ends. */
|
||||
aiRunActive: boolean
|
||||
onProjectNameChange: (name: string) => void
|
||||
onOpenProject: (projectId: string) => void
|
||||
onCreateProject: () => void
|
||||
onDuplicateProject: () => void
|
||||
onShareProject: () => void
|
||||
onSaveProject: () => void
|
||||
onRequestProjectDeletion: () => void
|
||||
onUndo: () => void
|
||||
@ -59,18 +63,22 @@ function ProjectMenu({
|
||||
projects,
|
||||
currentProjectId,
|
||||
disabled,
|
||||
aiRunActive,
|
||||
onOpenProject,
|
||||
onCreateProject,
|
||||
onDuplicateProject,
|
||||
onShareProject,
|
||||
onSaveProject,
|
||||
onRequestProjectDeletion,
|
||||
}: Pick<
|
||||
AppHeaderProps,
|
||||
| 'projects'
|
||||
| 'currentProjectId'
|
||||
| 'aiRunActive'
|
||||
| 'onOpenProject'
|
||||
| 'onCreateProject'
|
||||
| 'onDuplicateProject'
|
||||
| 'onShareProject'
|
||||
| 'onSaveProject'
|
||||
| 'onRequestProjectDeletion'
|
||||
> & { disabled: boolean }) {
|
||||
@ -115,6 +123,10 @@ function ProjectMenu({
|
||||
<Copy size={15} />
|
||||
<span>Duplicate project</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="project-menu-action" disabled={disabled} onClick={onShareProject}>
|
||||
<Link01 size={15} />
|
||||
<span>Share as link</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="project-menu-action" disabled={disabled} onClick={onSaveProject}>
|
||||
@ -125,11 +137,11 @@ function ProjectMenu({
|
||||
<DropdownMenuItem
|
||||
className="project-menu-action"
|
||||
variant="destructive"
|
||||
disabled={disabled || projects.length <= 1}
|
||||
disabled={disabled || projects.length <= 1 || aiRunActive}
|
||||
onClick={onRequestProjectDeletion}
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
<span>Delete current project</span>
|
||||
<span>{aiRunActive ? 'Delete waits for the AI run' : 'Delete current project'}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
@ -204,10 +216,12 @@ export function AppHeader({
|
||||
canUndo,
|
||||
canRedo,
|
||||
aiDisabled,
|
||||
aiRunActive,
|
||||
onProjectNameChange,
|
||||
onOpenProject,
|
||||
onCreateProject,
|
||||
onDuplicateProject,
|
||||
onShareProject,
|
||||
onSaveProject,
|
||||
onRequestProjectDeletion,
|
||||
onUndo,
|
||||
@ -253,9 +267,11 @@ export function AppHeader({
|
||||
projects={projects}
|
||||
currentProjectId={currentProjectId}
|
||||
disabled={projectMenuDisabled}
|
||||
aiRunActive={aiRunActive}
|
||||
onOpenProject={onOpenProject}
|
||||
onCreateProject={onCreateProject}
|
||||
onDuplicateProject={onDuplicateProject}
|
||||
onShareProject={onShareProject}
|
||||
onSaveProject={onSaveProject}
|
||||
onRequestProjectDeletion={onRequestProjectDeletion}
|
||||
/>
|
||||
|
||||
156
src/app/ShareLinkDialog.tsx
Normal file
156
src/app/ShareLinkDialog.tsx
Normal file
@ -0,0 +1,156 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Check, Copy, Link01 } from '../components/icons'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogMedia,
|
||||
AlertDialogTitle,
|
||||
} from '../components/ui/alert-dialog'
|
||||
import { Button } from '../components/ui/button'
|
||||
import { createShareLink, SHARE_LINK_LENGTH_WARNING, type ShareLinkResult } from './share-link'
|
||||
import { createSharePreviewImage } from './share-preview'
|
||||
import type { Slide, UploadAsset } from '../types'
|
||||
|
||||
type ShareLinkDialogProps = {
|
||||
open: boolean
|
||||
projectName: string
|
||||
slides: Slide[]
|
||||
uploads: UploadAsset[]
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
// Share links can reach megabytes, so the dialog never renders the full URL —
|
||||
// a short preview stands in and the copy button hands over the real thing.
|
||||
const LINK_PREVIEW_LENGTH = 120
|
||||
|
||||
const formatLinkSize = (length: number) => (length >= 1024 * 1024
|
||||
? `${(length / (1024 * 1024)).toFixed(1)} MB`
|
||||
: `${Math.max(1, Math.round(length / 1024))} KB`)
|
||||
|
||||
type ShareRequestKey = readonly [string, Slide[], UploadAsset[]]
|
||||
|
||||
// Everything shown by the dialog is keyed to the inputs that produced it, so
|
||||
// a change to the project while the dialog is open (for example an AI run
|
||||
// mutating slides) immediately renders as pending instead of surfacing the
|
||||
// previous project's link or error.
|
||||
type ShareState = {
|
||||
key: ShareRequestKey
|
||||
result: ShareLinkResult | null
|
||||
failed: boolean
|
||||
copied: boolean
|
||||
copyFailed: boolean
|
||||
}
|
||||
|
||||
export function ShareLinkDialog({
|
||||
open,
|
||||
projectName,
|
||||
slides,
|
||||
uploads,
|
||||
onOpenChange,
|
||||
}: ShareLinkDialogProps) {
|
||||
const [state, setState] = useState<ShareState | null>(null)
|
||||
const key = useMemo<ShareRequestKey>(
|
||||
() => [projectName, slides, uploads],
|
||||
[projectName, slides, uploads],
|
||||
)
|
||||
const active = state !== null && state.key === key ? state : null
|
||||
const link = active?.result ?? null
|
||||
const failed = active?.failed ?? false
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
let cancelled = false
|
||||
const [name, keyedSlides, keyedUploads] = key
|
||||
createShareLink({ projectName: name, slides: keyedSlides, uploads: keyedUploads }, {
|
||||
createPreview: () => createSharePreviewImage(name, keyedSlides),
|
||||
})
|
||||
.then((result) => {
|
||||
if (!cancelled) setState({ key, result, failed: false, copied: false, copyFailed: false })
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setState({ key, result: null, failed: true, copied: false, copyFailed: false })
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open, key])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
if (!nextOpen) setState(null)
|
||||
onOpenChange(nextOpen)
|
||||
}
|
||||
|
||||
const copyLink = async () => {
|
||||
if (!link) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(link.url)
|
||||
setState((current) => current && { ...current, copied: true, copyFailed: false })
|
||||
} catch {
|
||||
setState((current) => current && { ...current, copyFailed: true })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={handleOpenChange}>
|
||||
<AlertDialogContent className="share-link-dialog">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogMedia><Link01 size={17} /></AlertDialogMedia>
|
||||
<AlertDialogTitle>Share as link</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
The link carries a full copy of “{projectName}”, images included.
|
||||
Whoever opens it gets their own local copy to edit or delete —
|
||||
without ever touching your project.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="share-link-dialog-body">
|
||||
{failed && <p className="share-link-dialog-error">The share link couldn’t be created.</p>}
|
||||
{!failed && !link && <p className="share-link-dialog-status">Preparing link …</p>}
|
||||
{link && (
|
||||
<>
|
||||
<div className="share-link-dialog-preview" aria-label="Share link preview">
|
||||
{link.url.length > LINK_PREVIEW_LENGTH ? `${link.url.slice(0, LINK_PREVIEW_LENGTH)}…` : link.url}
|
||||
</div>
|
||||
<p className="share-link-dialog-meta">
|
||||
{link.mode === 'short'
|
||||
? 'The shared copy is stored for 90 days; the project itself stays local.'
|
||||
: `${formatLinkSize(link.url.length)} link — the share service couldn’t be reached, so this link carries the full project data.${
|
||||
link.url.length > SHARE_LINK_LENGTH_WARNING
|
||||
? ' Some messengers truncate links this size.'
|
||||
: ''}`}
|
||||
</p>
|
||||
{active?.copyFailed && (
|
||||
<>
|
||||
<p className="share-link-dialog-error">
|
||||
Copying was blocked by the browser — select the link below instead.
|
||||
</p>
|
||||
<input
|
||||
className="share-link-dialog-fallback"
|
||||
value={link.url}
|
||||
readOnly
|
||||
aria-label="Share link"
|
||||
onFocus={(event) => event.currentTarget.select()}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel className="share-link-dialog-close">Close</AlertDialogCancel>
|
||||
<Button
|
||||
type="button"
|
||||
className="share-link-dialog-copy"
|
||||
disabled={!link}
|
||||
onClick={() => void copyLink()}
|
||||
>
|
||||
{active?.copied ? <><Check size={14} /> Copied</> : <><Copy size={14} /> Copy link</>}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
@ -1,8 +1,10 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
consumeInterruptedGeneration,
|
||||
DEFAULT_PROJECT_NAME,
|
||||
getUniqueProjectName,
|
||||
loadInitialState,
|
||||
resolveGeneratedProjectName,
|
||||
sortProjectSummaries,
|
||||
upsertProjectSummary,
|
||||
} from './project-utils'
|
||||
@ -105,3 +107,61 @@ describe('project utilities', () => {
|
||||
expect(getUniqueProjectName(projects, 'Launch')).toBe('Launch')
|
||||
})
|
||||
})
|
||||
|
||||
describe('generated project names', () => {
|
||||
const projects = [
|
||||
summary('current', 'New Project 2', 3),
|
||||
summary('other', 'Aurora', 2),
|
||||
summary('third', 'Aurora 2', 1),
|
||||
]
|
||||
|
||||
it('adopts the app name while the title is still auto-assigned', () => {
|
||||
expect(resolveGeneratedProjectName(projects, 'current', 'New Project 2', 'Lumen'))
|
||||
.toBe('Lumen')
|
||||
expect(resolveGeneratedProjectName(projects, 'current', 'New Project', 'Lumen'))
|
||||
.toBe('Lumen')
|
||||
expect(resolveGeneratedProjectName(projects, 'current', DEFAULT_PROJECT_NAME, 'Lumen'))
|
||||
.toBe('Lumen')
|
||||
expect(resolveGeneratedProjectName(projects, 'current', ' ', 'Lumen'))
|
||||
.toBe('Lumen')
|
||||
})
|
||||
|
||||
it('numbers the app name past the other projects that already use it', () => {
|
||||
expect(resolveGeneratedProjectName(projects, 'current', 'New Project 2', 'aurora'))
|
||||
.toBe('aurora 3')
|
||||
})
|
||||
|
||||
it('ignores the current project when deduplicating', () => {
|
||||
const named = [summary('current', 'New Project', 1)]
|
||||
|
||||
expect(resolveGeneratedProjectName(named, 'current', 'New Project', 'New Project'))
|
||||
.toBe('New Project')
|
||||
})
|
||||
|
||||
it('keeps a title the user typed', () => {
|
||||
expect(resolveGeneratedProjectName(projects, 'other', 'Aurora', 'Lumen')).toBe(null)
|
||||
expect(resolveGeneratedProjectName(projects, 'current', 'New Project Ideas', 'Lumen'))
|
||||
.toBe(null)
|
||||
})
|
||||
|
||||
it('keeps the title when no app name was entered', () => {
|
||||
expect(resolveGeneratedProjectName(projects, 'current', 'New Project 2', ' '))
|
||||
.toBe(null)
|
||||
})
|
||||
})
|
||||
|
||||
describe('consumeInterruptedGeneration', () => {
|
||||
it('returns null for a project without the marker', () => {
|
||||
expect(consumeInterruptedGeneration(persistedProject('p1', 'Aurora', 10))).toBe(null)
|
||||
})
|
||||
|
||||
it('strips the marker and keeps everything else', () => {
|
||||
const project = { ...persistedProject('p1', 'Aurora', 10), interruptedGeneration: true as const }
|
||||
|
||||
const cleared = consumeInterruptedGeneration(project)
|
||||
|
||||
expect(cleared).toEqual(persistedProject('p1', 'Aurora', 10))
|
||||
expect(cleared && 'interruptedGeneration' in cleared).toBe(false)
|
||||
expect(project.interruptedGeneration).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@ -32,6 +32,20 @@ export const upsertProjectSummary = (
|
||||
},
|
||||
])
|
||||
|
||||
/**
|
||||
* Returns a copy of the project without the interrupted-generation marker, or
|
||||
* null when the project carries none. The caller persists the cleared copy and
|
||||
* shows the one-time interruption notice, so the marker never fires twice.
|
||||
*/
|
||||
export const consumeInterruptedGeneration = (
|
||||
project: PersistedProject,
|
||||
): PersistedProject | null => {
|
||||
if (!project.interruptedGeneration) return null
|
||||
const { interruptedGeneration, ...cleared } = project
|
||||
void interruptedGeneration
|
||||
return cleared
|
||||
}
|
||||
|
||||
export const getUniqueProjectName = (
|
||||
projects: ProjectSummary[],
|
||||
desiredName: string,
|
||||
@ -44,6 +58,36 @@ export const getUniqueProjectName = (
|
||||
return `${desiredName} ${suffix}`
|
||||
}
|
||||
|
||||
const AUTO_PROJECT_NAME_PATTERN = /^new project(?: \d+)?$/
|
||||
|
||||
/**
|
||||
* True while the title is still one the app assigned itself — the seed project,
|
||||
* an untitled one, or a "New Project 3". Only those may be replaced silently.
|
||||
*/
|
||||
const isAutoProjectName = (name: string) => {
|
||||
const normalized = name.trim().toLocaleLowerCase('en-US')
|
||||
return normalized === ''
|
||||
|| normalized === DEFAULT_PROJECT_NAME.toLocaleLowerCase('en-US')
|
||||
|| AUTO_PROJECT_NAME_PATTERN.test(normalized)
|
||||
}
|
||||
|
||||
/**
|
||||
* The title an AI generation run should leave behind: the app name the user
|
||||
* entered, deduplicated against the other projects. Returns `null` when the
|
||||
* title must stay untouched, so a name the user typed is never overwritten.
|
||||
*/
|
||||
export const resolveGeneratedProjectName = (
|
||||
projects: ProjectSummary[],
|
||||
currentProjectId: string,
|
||||
currentName: string,
|
||||
appName: string,
|
||||
): string | null => {
|
||||
const desiredName = appName.trim()
|
||||
if (!desiredName || !isAutoProjectName(currentName)) return null
|
||||
const otherProjects = projects.filter((project) => project.id !== currentProjectId)
|
||||
return getUniqueProjectName(otherProjects, desiredName)
|
||||
}
|
||||
|
||||
export const formatProjectTime = (timestamp: number) => new Date(timestamp).toLocaleString('en-US', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
|
||||
286
src/app/share-link.test.ts
Normal file
286
src/app/share-link.test.ts
Normal file
@ -0,0 +1,286 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
consumeShareLinkHash,
|
||||
createShareLink,
|
||||
decodeSharePayload,
|
||||
SHARE_HASH_PREFIX,
|
||||
SHORT_SHARE_HASH_PREFIX,
|
||||
SHORT_SHARE_PATH_PREFIX,
|
||||
type SharedProjectPayload,
|
||||
} from './share-link'
|
||||
import type { Slide, TextElement } from '../types'
|
||||
|
||||
const makeSlide = (overrides: Partial<Slide> = {}): Slide => ({
|
||||
id: 'slide-1',
|
||||
name: 'Hero',
|
||||
background: { type: 'solid', color1: '#111111', color2: '#222222', angle: 45 },
|
||||
elements: [],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const makeTextElement = (overrides: Partial<TextElement> = {}): TextElement => ({
|
||||
id: 'element-1',
|
||||
type: 'text',
|
||||
x: 10,
|
||||
y: 12,
|
||||
width: 60,
|
||||
rotation: 0,
|
||||
opacity: 1,
|
||||
text: 'Hello',
|
||||
color: '#ffffff',
|
||||
fontFamily: 'Geist',
|
||||
fontSize: 32,
|
||||
fontWeight: 700,
|
||||
align: 'center',
|
||||
lineHeight: 1.2,
|
||||
letterSpacing: 0,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const makeProject = (overrides: Partial<SharedProjectPayload> = {}): SharedProjectPayload => ({
|
||||
projectName: 'Summer Launch',
|
||||
slides: [makeSlide({ elements: [makeTextElement()] })],
|
||||
uploads: [],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const hashOf = (link: string) => link.slice(link.indexOf('#'))
|
||||
|
||||
/** Builds an inline fallback link (the share API is stubbed offline). */
|
||||
const inlineShareHash = async (project: SharedProjectPayload) =>
|
||||
hashOf((await createShareLink(project)).url)
|
||||
|
||||
const compressJson = async (value: unknown): Promise<Uint8Array<ArrayBuffer>> => {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(value))
|
||||
const stream = new ReadableStream<BufferSource>({
|
||||
start(controller) {
|
||||
controller.enqueue(bytes)
|
||||
controller.close()
|
||||
},
|
||||
}).pipeThrough(new CompressionStream('deflate-raw'))
|
||||
return new Uint8Array(await new Response(stream).arrayBuffer())
|
||||
}
|
||||
|
||||
// Handcrafts a `#share=` fragment the way an attacker could, bypassing
|
||||
// createShareLink's well-formed input assumptions.
|
||||
const craftShareHash = async (value: unknown) => {
|
||||
const compressed = await compressJson(value)
|
||||
const base64 = btoa(String.fromCharCode(...compressed))
|
||||
return `${SHARE_HASH_PREFIX}${base64.replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')}`
|
||||
}
|
||||
|
||||
describe('share links', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new Error('share API offline'))))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('falls back to a self-contained link when the share API is unreachable', async () => {
|
||||
const project = makeProject({
|
||||
uploads: [{ id: 'upload-1', name: 'shot.png', src: 'data:image/png;base64,aGk=' }],
|
||||
})
|
||||
|
||||
const result = await createShareLink(project)
|
||||
expect(result.mode).toBe('inline')
|
||||
expect(result.url).toContain(SHARE_HASH_PREFIX)
|
||||
|
||||
const decoded = await decodeSharePayload(hashOf(result.url))
|
||||
expect(decoded).toEqual(project)
|
||||
})
|
||||
|
||||
it('creates a short /s/ link and uploads the unfurl preview', async () => {
|
||||
const upload = vi.fn((input: unknown) => Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(input === '/api/share' ? { id: 'abcDEF123456' } : { ok: true }),
|
||||
}))
|
||||
vi.stubGlobal('fetch', upload)
|
||||
|
||||
const result = await createShareLink(makeProject(), {
|
||||
createPreview: () => Promise.resolve(new Blob(['jpeg'], { type: 'image/jpeg' })),
|
||||
})
|
||||
expect(result.mode).toBe('short')
|
||||
expect(result.url).toBe(`${window.location.origin}${SHORT_SHARE_PATH_PREFIX}abcDEF123456`)
|
||||
expect(upload).toHaveBeenCalledWith('/api/share', expect.objectContaining({ method: 'POST' }))
|
||||
expect(upload).toHaveBeenCalledWith(
|
||||
'/api/share/abcDEF123456/preview?title=Summer%20Launch',
|
||||
expect.objectContaining({ method: 'POST' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('creates the short link even when rendering the preview fails', async () => {
|
||||
const upload = vi.fn((input: unknown) => Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(input === '/api/share' ? { id: 'abcDEF123456' } : { ok: true }),
|
||||
}))
|
||||
vi.stubGlobal('fetch', upload)
|
||||
|
||||
const result = await createShareLink(makeProject(), {
|
||||
createPreview: () => Promise.reject(new Error('no canvas')),
|
||||
})
|
||||
expect(result.mode).toBe('short')
|
||||
})
|
||||
|
||||
it('falls back to a self-contained link when the API answers with something else', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ unexpected: true }),
|
||||
})))
|
||||
|
||||
const result = await createShareLink(makeProject())
|
||||
expect(result.mode).toBe('inline')
|
||||
})
|
||||
|
||||
it('decodes a short link by downloading the stored payload', async () => {
|
||||
const project = makeProject()
|
||||
const payload = await compressJson({ v: 1, ...project })
|
||||
const download = vi.fn(() => Promise.resolve({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(payload.buffer),
|
||||
}))
|
||||
vi.stubGlobal('fetch', download)
|
||||
|
||||
const decoded = await decodeSharePayload(`${SHORT_SHARE_HASH_PREFIX}abcDEF123456`)
|
||||
expect(decoded).toEqual(project)
|
||||
expect(download).toHaveBeenCalledWith(
|
||||
'/api/share/abcDEF123456',
|
||||
expect.objectContaining({ signal: expect.any(AbortSignal) as unknown }),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects malformed short ids without calling the API', async () => {
|
||||
const download = vi.fn()
|
||||
vi.stubGlobal('fetch', download)
|
||||
|
||||
expect(await decodeSharePayload(`${SHORT_SHARE_HASH_PREFIX}../evil`)).toBeNull()
|
||||
expect(await decodeSharePayload(`${SHORT_SHARE_HASH_PREFIX}ab`)).toBeNull()
|
||||
expect(download).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns null when the stored payload is missing or expired', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({ ok: false, status: 404 })))
|
||||
|
||||
expect(await decodeSharePayload(`${SHORT_SHARE_HASH_PREFIX}abcDEF123456`)).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps inline data URL image sources intact for the recipient', async () => {
|
||||
const slide = makeSlide({
|
||||
background: {
|
||||
type: 'image',
|
||||
color1: '#111111',
|
||||
color2: '#222222',
|
||||
angle: 0,
|
||||
image: 'data:image/png;base64,aGk=',
|
||||
},
|
||||
})
|
||||
|
||||
const decoded = await decodeSharePayload(await inlineShareHash(makeProject({ slides: [slide] })))
|
||||
expect(decoded?.slides[0]?.background.image).toBe('data:image/png;base64,aGk=')
|
||||
})
|
||||
|
||||
it('sanitizes AI screen markup carried by a link', async () => {
|
||||
const slide = makeSlide({ html: '<div>Safe</div><script>alert(1)</script>' })
|
||||
|
||||
const decoded = await decodeSharePayload(await inlineShareHash(makeProject({ slides: [slide] })))
|
||||
expect(decoded?.slides[0]?.html).toContain('Safe')
|
||||
expect(decoded?.slides[0]?.html).not.toContain('script')
|
||||
})
|
||||
|
||||
it('sanitizes rich text markup on text elements', async () => {
|
||||
const element = makeTextElement({ html: 'Hi <img src="x" onerror="alert(1)"> there' })
|
||||
|
||||
const decoded = await decodeSharePayload(
|
||||
await inlineShareHash(makeProject({ slides: [makeSlide({ elements: [element] })] })),
|
||||
)
|
||||
const decodedElement = decoded?.slides[0]?.elements[0]
|
||||
expect(decodedElement?.type).toBe('text')
|
||||
expect((decodedElement as TextElement).html).not.toContain('onerror')
|
||||
expect((decodedElement as TextElement).html).not.toContain('img')
|
||||
})
|
||||
|
||||
it('drops unsafe image source schemes from a handcrafted payload', async () => {
|
||||
const slide = makeSlide({
|
||||
elements: [{
|
||||
id: 'element-2',
|
||||
type: 'image',
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 50,
|
||||
rotation: 0,
|
||||
opacity: 1,
|
||||
src: 'javascript:alert(1)',
|
||||
borderRadius: 0,
|
||||
}],
|
||||
})
|
||||
|
||||
const decoded = await decodeSharePayload(await inlineShareHash(makeProject({ slides: [slide] })))
|
||||
const decodedElement = decoded?.slides[0]?.elements[0]
|
||||
expect(decodedElement?.type).toBe('image')
|
||||
expect(decodedElement && 'src' in decodedElement ? decodedElement.src : null).toBe('')
|
||||
})
|
||||
|
||||
it('drops malformed slides, elements, and uploads instead of importing them', async () => {
|
||||
const hash = await craftShareHash({
|
||||
v: 1,
|
||||
projectName: 'Mixed bag',
|
||||
slides: [makeSlide(), { id: 42 }, 'nonsense'],
|
||||
uploads: [{ id: 'upload-1', name: 'ok.png', src: 'data:image/png;base64,aGk=' }, { id: 7 }],
|
||||
})
|
||||
|
||||
const decoded = await decodeSharePayload(hash)
|
||||
expect(decoded?.slides).toHaveLength(1)
|
||||
expect(decoded?.uploads).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('supports projects with zero slides', async () => {
|
||||
const decoded = await decodeSharePayload(await inlineShareHash(makeProject({ slides: [] })))
|
||||
expect(decoded?.slides).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects payloads that are not valid share links', async () => {
|
||||
expect(await decodeSharePayload('#other=abc')).toBeNull()
|
||||
expect(await decodeSharePayload(`${SHARE_HASH_PREFIX}not-real-base64!!!`)).toBeNull()
|
||||
expect(await decodeSharePayload(`${SHARE_HASH_PREFIX}${btoa('plain json')}`)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a payload with an unknown format version', async () => {
|
||||
expect(await decodeSharePayload(await craftShareHash({ v: 99, slides: [] }))).toBeNull()
|
||||
})
|
||||
|
||||
it('consumes short and inline share fragments exactly once', () => {
|
||||
window.location.hash = `${SHARE_HASH_PREFIX}payload`
|
||||
expect(consumeShareLinkHash()).toBe(`${SHARE_HASH_PREFIX}payload`)
|
||||
expect(window.location.hash).toBe('')
|
||||
expect(consumeShareLinkHash()).toBeNull()
|
||||
|
||||
window.location.hash = `${SHORT_SHARE_HASH_PREFIX}abcDEF123456`
|
||||
expect(consumeShareLinkHash()).toBe(`${SHORT_SHARE_HASH_PREFIX}abcDEF123456`)
|
||||
expect(window.location.hash).toBe('')
|
||||
})
|
||||
|
||||
it('consumes a /s/<id> share path and rewrites the URL back to the root', () => {
|
||||
history.replaceState(null, '', `${SHORT_SHARE_PATH_PREFIX}abcDEF123456`)
|
||||
|
||||
expect(consumeShareLinkHash()).toBe(`${SHORT_SHARE_HASH_PREFIX}abcDEF123456`)
|
||||
expect(window.location.pathname).toBe('/')
|
||||
expect(consumeShareLinkHash()).toBeNull()
|
||||
})
|
||||
|
||||
it('leaves /s/ paths that are not share ids alone', () => {
|
||||
history.replaceState(null, '', `${SHORT_SHARE_PATH_PREFIX}ab`)
|
||||
|
||||
expect(consumeShareLinkHash()).toBeNull()
|
||||
expect(window.location.pathname).toBe(`${SHORT_SHARE_PATH_PREFIX}ab`)
|
||||
history.replaceState(null, '', '/')
|
||||
})
|
||||
|
||||
it('ignores unrelated fragments', () => {
|
||||
window.location.hash = '#section'
|
||||
|
||||
expect(consumeShareLinkHash()).toBeNull()
|
||||
expect(window.location.hash).toBe('#section')
|
||||
window.location.hash = ''
|
||||
})
|
||||
})
|
||||
336
src/app/share-link.ts
Normal file
336
src/app/share-link.ts
Normal file
@ -0,0 +1,336 @@
|
||||
import { collectAssetSources, mapAssetSources } from '../asset-sources'
|
||||
import { hydrateProjectAssets } from '../asset-store'
|
||||
import { sanitizeScreenHtml } from '../html-slide/sanitize'
|
||||
import { fileToDataUrl, sanitizeRichText } from '../utils'
|
||||
import type { Background, CanvasElement, Slide, UploadAsset } from '../types'
|
||||
|
||||
/**
|
||||
* Project share links. The share payload is the project as deflate-raw
|
||||
* compressed JSON — screens, uploads, and every image inlined as a data URL —
|
||||
* so a link always transfers a complete, independent copy. Two link forms
|
||||
* exist:
|
||||
*
|
||||
* - `/s/<id>` (preferred): the payload is stored by the share API
|
||||
* (`scripts/share-api.ts`, Cloudflare KV, 90-day retention) and the link
|
||||
* stays short. The id lives in the path — not the fragment — so the Worker
|
||||
* can serve per-share Open Graph tags to link-preview crawlers; the app
|
||||
* itself consumes the id on boot and rewrites the URL back to `/`. A
|
||||
* rendered preview image and the project name are uploaded best-effort for
|
||||
* that unfurl. `#s=<id>` stays readable for compatibility.
|
||||
* - `#share=<base64url payload>` (fallback): when the share API is
|
||||
* unreachable, the link carries the payload itself and can get very long,
|
||||
* but sharing keeps working without any server.
|
||||
*
|
||||
* Opening either link imports an independent copy into the recipient's local
|
||||
* workspace; their edits and deletions stay on their device and never affect
|
||||
* the sender's project.
|
||||
*
|
||||
* A share payload is untrusted input: a link can be handcrafted, so decoding
|
||||
* re-sanitizes AI screen markup and rich text and drops unsafe image sources
|
||||
* before anything reaches the editor.
|
||||
*/
|
||||
|
||||
export type SharedProjectPayload = {
|
||||
projectName: string
|
||||
slides: Slide[]
|
||||
uploads: UploadAsset[]
|
||||
}
|
||||
|
||||
export const SHARE_HASH_PREFIX = '#share='
|
||||
export const SHORT_SHARE_HASH_PREFIX = '#s='
|
||||
export const SHORT_SHARE_PATH_PREFIX = '/s/'
|
||||
|
||||
const SHARE_API_PATH = '/api/share'
|
||||
const SHARE_ID_PATTERN = /^[A-Za-z0-9_-]{6,32}$/
|
||||
const SHARE_FORMAT_VERSION = 1
|
||||
|
||||
// A stalled share API request must degrade to the inline fallback (or a
|
||||
// failed import) instead of leaving the dialog on "Preparing link …" forever.
|
||||
const SHARE_API_TIMEOUT_MS = 15_000
|
||||
|
||||
// Ceiling for the decompressed payload so a handcrafted link cannot act as a
|
||||
// decompression bomb against the importing tab.
|
||||
const MAX_DECODED_BYTES = 64 * 1024 * 1024
|
||||
|
||||
/** Links longer than this are likely to be truncated by messengers. */
|
||||
export const SHARE_LINK_LENGTH_WARNING = 30_000
|
||||
|
||||
const bytesToBase64Url = (bytes: Uint8Array): string => {
|
||||
let binary = ''
|
||||
const chunkSize = 0x8000
|
||||
for (let index = 0; index < bytes.length; index += chunkSize) {
|
||||
binary += String.fromCharCode(...bytes.subarray(index, index + chunkSize))
|
||||
}
|
||||
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')
|
||||
}
|
||||
|
||||
const base64UrlToBytes = (encoded: string): Uint8Array<ArrayBuffer> => {
|
||||
const binary = atob(encoded.replaceAll('-', '+').replaceAll('_', '/'))
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
|
||||
return bytes
|
||||
}
|
||||
|
||||
// jsdom's Blob lacks stream(), so the pipelines start from a plain
|
||||
// ReadableStream over the raw bytes instead. BufferSource chunks match the
|
||||
// writable side of Compression/DecompressionStream.
|
||||
const bytesToStream = (bytes: Uint8Array<ArrayBuffer>): ReadableStream<BufferSource> =>
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(bytes)
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
|
||||
const compressText = async (text: string): Promise<Uint8Array<ArrayBuffer>> => {
|
||||
const stream = bytesToStream(new TextEncoder().encode(text)).pipeThrough(new CompressionStream('deflate-raw'))
|
||||
return new Uint8Array(await new Response(stream).arrayBuffer())
|
||||
}
|
||||
|
||||
const decompressBytes = async (bytes: Uint8Array<ArrayBuffer>): Promise<string> => {
|
||||
const stream = bytesToStream(bytes).pipeThrough(new DecompressionStream('deflate-raw'))
|
||||
const reader = stream.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let decodedBytes = 0
|
||||
let text = ''
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) return text + decoder.decode()
|
||||
decodedBytes += value.byteLength
|
||||
if (decodedBytes > MAX_DECODED_BYTES) {
|
||||
void reader.cancel()
|
||||
throw new Error('The share payload is too large.')
|
||||
}
|
||||
text += decoder.decode(value, { stream: true })
|
||||
}
|
||||
}
|
||||
|
||||
// Images dominate link length, so shared copies are capped at export
|
||||
// resolution and re-encoded as WebP. The smaller encoding wins; failures fall
|
||||
// back to the original bytes.
|
||||
const MAX_SHARED_IMAGE_DIMENSION = 2796
|
||||
const SHARED_IMAGE_WEBP_QUALITY = 0.85
|
||||
|
||||
const reencodeImageBlob = async (blob: Blob): Promise<Blob> => {
|
||||
if (blob.type === 'image/svg+xml') return blob
|
||||
try {
|
||||
const bitmap = await createImageBitmap(blob)
|
||||
const scale = Math.min(1, MAX_SHARED_IMAGE_DIMENSION / Math.max(bitmap.width, bitmap.height))
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = Math.max(1, Math.round(bitmap.width * scale))
|
||||
canvas.height = Math.max(1, Math.round(bitmap.height * scale))
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) return blob
|
||||
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
|
||||
bitmap.close()
|
||||
const encoded = await new Promise<Blob | null>((resolve) => {
|
||||
canvas.toBlob(resolve, 'image/webp', SHARED_IMAGE_WEBP_QUALITY)
|
||||
})
|
||||
return encoded && encoded.size < blob.size ? encoded : blob
|
||||
} catch {
|
||||
return blob
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces session-local object URLs with inlined data URLs so the link is
|
||||
* meaningful on another device. Sources that cannot be read keep their URL and
|
||||
* degrade to a missing image instead of failing the whole share.
|
||||
*/
|
||||
const inlineImageSources = async (project: SharedProjectPayload): Promise<SharedProjectPayload> => {
|
||||
const hydrated = await hydrateProjectAssets(project)
|
||||
const replacements = new Map<string, string>()
|
||||
for (const src of collectAssetSources(hydrated)) {
|
||||
if (!src.startsWith('blob:')) continue
|
||||
try {
|
||||
const blob = await (await fetch(src)).blob()
|
||||
replacements.set(src, await fileToDataUrl(await reencodeImageBlob(blob)))
|
||||
} catch {
|
||||
// Keep the source as-is; see above.
|
||||
}
|
||||
}
|
||||
return mapAssetSources(hydrated, (src) => replacements.get(src) ?? src)
|
||||
}
|
||||
|
||||
export type ShareLinkResult = {
|
||||
url: string
|
||||
/** 'short' when the payload is stored by the share API; 'inline' when the URL carries it. */
|
||||
mode: 'short' | 'inline'
|
||||
}
|
||||
|
||||
const requestShortShareId = async (payload: Uint8Array<ArrayBuffer>): Promise<string | null> => {
|
||||
try {
|
||||
const response = await fetch(SHARE_API_PATH, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/octet-stream' },
|
||||
body: payload,
|
||||
signal: AbortSignal.timeout(SHARE_API_TIMEOUT_MS),
|
||||
})
|
||||
if (!response.ok) return null
|
||||
const result = (await response.json()) as { id?: unknown }
|
||||
return typeof result.id === 'string' && SHARE_ID_PATTERN.test(result.id) ? result.id : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads the unfurl artwork and title for a stored share. Best-effort: the
|
||||
* link works without it, it just unfurls generically.
|
||||
*/
|
||||
const uploadSharePreview = async (id: string, title: string, preview: Blob | null): Promise<void> => {
|
||||
try {
|
||||
await fetch(`${SHARE_API_PATH}/${id}/preview?title=${encodeURIComponent(title)}`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'image/jpeg' },
|
||||
body: preview ?? new Blob([]),
|
||||
signal: AbortSignal.timeout(SHARE_API_TIMEOUT_MS),
|
||||
})
|
||||
} catch {
|
||||
// See above.
|
||||
}
|
||||
}
|
||||
|
||||
export type ShareLinkOptions = {
|
||||
/** Renders the Open Graph preview image; only invoked for short links. */
|
||||
createPreview?: () => Promise<Blob | null>
|
||||
}
|
||||
|
||||
export const createShareLink = async (
|
||||
project: SharedProjectPayload,
|
||||
options: ShareLinkOptions = {},
|
||||
): Promise<ShareLinkResult> => {
|
||||
const inlined = await inlineImageSources(project)
|
||||
const json = JSON.stringify({
|
||||
v: SHARE_FORMAT_VERSION,
|
||||
projectName: inlined.projectName,
|
||||
slides: inlined.slides,
|
||||
uploads: inlined.uploads,
|
||||
})
|
||||
const compressed = await compressText(json)
|
||||
const { origin, pathname } = window.location
|
||||
|
||||
const id = await requestShortShareId(compressed)
|
||||
if (id) {
|
||||
const preview = options.createPreview ? await options.createPreview().catch(() => null) : null
|
||||
await uploadSharePreview(id, project.projectName, preview)
|
||||
return { url: `${origin}${SHORT_SHARE_PATH_PREFIX}${id}`, mode: 'short' }
|
||||
}
|
||||
return { url: `${origin}${pathname}${SHARE_HASH_PREFIX}${bytesToBase64Url(compressed)}`, mode: 'inline' }
|
||||
}
|
||||
|
||||
// Sources render through <img> and CSS backgrounds only, but a handcrafted
|
||||
// payload gets no chance to smuggle in exotic schemes regardless.
|
||||
const isSafeImageSource = (src: string): boolean =>
|
||||
src.startsWith('data:image/')
|
||||
|| src.startsWith('https://')
|
||||
|| src.startsWith('http://')
|
||||
|| src.startsWith('blob-asset:')
|
||||
|| !src.includes(':')
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null
|
||||
|
||||
const normalizeSharedElement = (value: unknown): CanvasElement | null => {
|
||||
if (!isRecord(value) || typeof value['id'] !== 'string' || typeof value['type'] !== 'string') return null
|
||||
const element = value as unknown as CanvasElement
|
||||
if (element.type === 'text' && typeof element.html === 'string') {
|
||||
return { ...element, html: sanitizeRichText(element.html) }
|
||||
}
|
||||
return element
|
||||
}
|
||||
|
||||
const normalizeSharedSlide = (value: unknown): Slide | null => {
|
||||
if (!isRecord(value)) return null
|
||||
if (typeof value['id'] !== 'string' || typeof value['name'] !== 'string') return null
|
||||
if (!isRecord(value['background']) || !Array.isArray(value['elements'])) return null
|
||||
|
||||
const slide: Slide = {
|
||||
id: value['id'],
|
||||
name: value['name'],
|
||||
background: value['background'] as unknown as Background,
|
||||
elements: value['elements']
|
||||
.map(normalizeSharedElement)
|
||||
.filter((element): element is CanvasElement => element !== null),
|
||||
}
|
||||
if (typeof value['html'] === 'string') slide.html = sanitizeScreenHtml(value['html']).html
|
||||
return slide
|
||||
}
|
||||
|
||||
const normalizeSharedUpload = (value: unknown): UploadAsset | null => {
|
||||
if (!isRecord(value)) return null
|
||||
if (typeof value['id'] !== 'string' || typeof value['name'] !== 'string' || typeof value['src'] !== 'string') return null
|
||||
return { id: value['id'], name: value['name'], src: value['src'] }
|
||||
}
|
||||
|
||||
const normalizeSharedProject = (value: unknown): SharedProjectPayload | null => {
|
||||
if (!isRecord(value) || value['v'] !== SHARE_FORMAT_VERSION) return null
|
||||
if (!Array.isArray(value['slides'])) return null
|
||||
|
||||
const project: SharedProjectPayload = {
|
||||
projectName: typeof value['projectName'] === 'string' && value['projectName'].trim() !== ''
|
||||
? value['projectName']
|
||||
: 'Shared project',
|
||||
slides: value['slides']
|
||||
.map(normalizeSharedSlide)
|
||||
.filter((slide): slide is Slide => slide !== null),
|
||||
uploads: (Array.isArray(value['uploads']) ? value['uploads'] : [])
|
||||
.map(normalizeSharedUpload)
|
||||
.filter((upload): upload is UploadAsset => upload !== null),
|
||||
}
|
||||
return mapAssetSources(project, (src) => (isSafeImageSource(src) ? src : ''))
|
||||
}
|
||||
|
||||
const fetchStoredPayloadBytes = async (id: string): Promise<Uint8Array<ArrayBuffer> | null> => {
|
||||
if (!SHARE_ID_PATTERN.test(id)) return null
|
||||
const response = await fetch(`${SHARE_API_PATH}/${id}`, {
|
||||
signal: AbortSignal.timeout(SHARE_API_TIMEOUT_MS),
|
||||
})
|
||||
if (!response.ok) return null
|
||||
return new Uint8Array(await response.arrayBuffer())
|
||||
}
|
||||
|
||||
const sharePayloadBytes = async (hash: string): Promise<Uint8Array<ArrayBuffer> | null> => {
|
||||
if (hash.startsWith(SHORT_SHARE_HASH_PREFIX)) {
|
||||
return fetchStoredPayloadBytes(hash.slice(SHORT_SHARE_HASH_PREFIX.length))
|
||||
}
|
||||
if (hash.startsWith(SHARE_HASH_PREFIX)) {
|
||||
return base64UrlToBytes(hash.slice(SHARE_HASH_PREFIX.length))
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Decodes and validates a `#s=` or `#share=` fragment; null when it cannot be trusted. */
|
||||
export const decodeSharePayload = async (hash: string): Promise<SharedProjectPayload | null> => {
|
||||
try {
|
||||
const bytes = await sharePayloadBytes(hash)
|
||||
if (!bytes) return null
|
||||
const parsed: unknown = JSON.parse(await decompressBytes(bytes))
|
||||
return normalizeSharedProject(parsed)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const isShareHash = (hash: string) =>
|
||||
hash.startsWith(SHARE_HASH_PREFIX) || hash.startsWith(SHORT_SHARE_HASH_PREFIX)
|
||||
|
||||
/**
|
||||
* Reads and clears a pending share fragment or `/s/<id>` path so a reload
|
||||
* does not re-import the project. Returns a hash for {@link decodeSharePayload}.
|
||||
*/
|
||||
export const consumeShareLinkHash = (): string | null => {
|
||||
const { hash, pathname, search } = window.location
|
||||
if (isShareHash(hash)) {
|
||||
history.replaceState(null, '', `${pathname}${search}`)
|
||||
return hash
|
||||
}
|
||||
if (pathname.startsWith(SHORT_SHARE_PATH_PREFIX)) {
|
||||
const id = pathname.slice(SHORT_SHARE_PATH_PREFIX.length)
|
||||
if (SHARE_ID_PATTERN.test(id)) {
|
||||
history.replaceState(null, '', `/${search}`)
|
||||
return `${SHORT_SHARE_HASH_PREFIX}${id}`
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
61
src/app/share-preview-palette.test.ts
Normal file
61
src/app/share-preview-palette.test.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { deriveSharePreviewPalette } from './share-preview-palette'
|
||||
|
||||
type Rgb = readonly [number, number, number]
|
||||
|
||||
const makePixels = (width: number, height: number, color: Rgb, alpha = 255) => {
|
||||
const pixels = new Uint8ClampedArray(width * height * 4)
|
||||
for (let index = 0; index < width * height; index += 1) {
|
||||
const offset = index * 4
|
||||
pixels[offset] = color[0]
|
||||
pixels[offset + 1] = color[1]
|
||||
pixels[offset + 2] = color[2]
|
||||
pixels[offset + 3] = alpha
|
||||
}
|
||||
return pixels
|
||||
}
|
||||
|
||||
const setPixel = (pixels: Uint8ClampedArray, width: number, x: number, y: number, color: Rgb) => {
|
||||
const offset = (y * width + x) * 4
|
||||
pixels[offset] = color[0]
|
||||
pixels[offset + 1] = color[1]
|
||||
pixels[offset + 2] = color[2]
|
||||
pixels[offset + 3] = 255
|
||||
}
|
||||
|
||||
describe('deriveSharePreviewPalette', () => {
|
||||
it('uses the dominant and contrasting colors from the rendered screen edges', () => {
|
||||
const width = 10
|
||||
const height = 10
|
||||
const pixels = makePixels(width, height, [244, 236, 215])
|
||||
for (let y = 0; y < 2; y += 1) {
|
||||
for (let x = 0; x < width; x += 1) setPixel(pixels, width, x, y, [242, 165, 55])
|
||||
}
|
||||
|
||||
expect(deriveSharePreviewPalette(pixels, width, height)).toEqual({
|
||||
color1: '#f4ecd7',
|
||||
color2: '#f2a537',
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores focal content in the center and insignificant edge noise', () => {
|
||||
const width = 12
|
||||
const height = 12
|
||||
const pixels = makePixels(width, height, [223, 232, 218])
|
||||
for (let y = 4; y < 8; y += 1) {
|
||||
for (let x = 4; x < 8; x += 1) setPixel(pixels, width, x, y, [12, 13, 18])
|
||||
}
|
||||
setPixel(pixels, width, 0, 0, [255, 0, 255])
|
||||
|
||||
expect(deriveSharePreviewPalette(pixels, width, height)).toEqual({
|
||||
color1: '#dfe8da',
|
||||
color2: '#dfe8da',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns no palette when dimensions or visible pixels are unavailable', () => {
|
||||
expect(deriveSharePreviewPalette(new Uint8ClampedArray(), 0, 0)).toBeNull()
|
||||
expect(deriveSharePreviewPalette(new Uint8ClampedArray(3), 1, 1)).toBeNull()
|
||||
expect(deriveSharePreviewPalette(makePixels(2, 2, [255, 255, 255], 0), 2, 2)).toBeNull()
|
||||
})
|
||||
})
|
||||
97
src/app/share-preview-palette.ts
Normal file
97
src/app/share-preview-palette.ts
Normal file
@ -0,0 +1,97 @@
|
||||
export type SharePreviewPalette = {
|
||||
color1: string
|
||||
color2: string
|
||||
}
|
||||
|
||||
type ColorBucket = {
|
||||
count: number
|
||||
red: number
|
||||
green: number
|
||||
blue: number
|
||||
}
|
||||
|
||||
const EDGE_INSET_RATIO = 0.18
|
||||
const MIN_SECONDARY_SHARE = 0.03
|
||||
const MIN_SECONDARY_DISTANCE = 36
|
||||
const QUANTIZATION_SHIFT = 4
|
||||
|
||||
const isEdgePixel = (x: number, y: number, width: number, height: number) => {
|
||||
const horizontalInset = Math.max(1, Math.ceil(width * EDGE_INSET_RATIO))
|
||||
const verticalInset = Math.max(1, Math.ceil(height * EDGE_INSET_RATIO))
|
||||
return x < horizontalInset
|
||||
|| x >= width - horizontalInset
|
||||
|| y < verticalInset
|
||||
|| y >= height - verticalInset
|
||||
}
|
||||
|
||||
const colorDistance = (left: ColorBucket, right: ColorBucket) => Math.hypot(
|
||||
left.red / left.count - right.red / right.count,
|
||||
left.green / left.count - right.green / right.count,
|
||||
left.blue / left.count - right.blue / right.count,
|
||||
)
|
||||
|
||||
const toHex = (value: number) => Math.round(value).toString(16).padStart(2, '0')
|
||||
|
||||
const bucketToHex = ({ red, green, blue, count }: ColorBucket) =>
|
||||
`#${toHex(red / count)}${toHex(green / count)}${toHex(blue / count)}`
|
||||
|
||||
const chooseSecondary = (primary: ColorBucket, buckets: ColorBucket[]) => {
|
||||
const minimumCount = Math.max(2, Math.ceil(primary.count * MIN_SECONDARY_SHARE))
|
||||
let best = primary
|
||||
let bestScore = 0
|
||||
for (const bucket of buckets) {
|
||||
if (bucket === primary || bucket.count < minimumCount) continue
|
||||
const distance = colorDistance(primary, bucket)
|
||||
const score = bucket.count * distance
|
||||
if (distance >= MIN_SECONDARY_DISTANCE && score > bestScore) {
|
||||
best = bucket
|
||||
bestScore = score
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds representative colors along a rendered screen's perimeter. Sampling
|
||||
* the perimeter favors the design surface over text, devices, and other focal
|
||||
* content in the middle of the artboard.
|
||||
*/
|
||||
export const deriveSharePreviewPalette = (
|
||||
pixels: Uint8ClampedArray,
|
||||
width: number,
|
||||
height: number,
|
||||
): SharePreviewPalette | null => {
|
||||
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) return null
|
||||
if (pixels.length < width * height * 4) return null
|
||||
|
||||
const buckets = new Map<number, ColorBucket>()
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
if (!isEdgePixel(x, y, width, height)) continue
|
||||
const offset = (y * width + x) * 4
|
||||
const alpha = pixels[offset + 3] ?? 0
|
||||
if (alpha < 128) continue
|
||||
const red = pixels[offset] ?? 0
|
||||
const green = pixels[offset + 1] ?? 0
|
||||
const blue = pixels[offset + 2] ?? 0
|
||||
const key = ((red >> QUANTIZATION_SHIFT) << 8)
|
||||
| ((green >> QUANTIZATION_SHIFT) << 4)
|
||||
| (blue >> QUANTIZATION_SHIFT)
|
||||
const bucket = buckets.get(key)
|
||||
if (bucket) {
|
||||
bucket.count += 1
|
||||
bucket.red += red
|
||||
bucket.green += green
|
||||
bucket.blue += blue
|
||||
} else {
|
||||
buckets.set(key, { count: 1, red, green, blue })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sorted = [...buckets.values()].sort((left, right) => right.count - left.count)
|
||||
const primary = sorted[0]
|
||||
if (!primary) return null
|
||||
const secondary = chooseSecondary(primary, sorted)
|
||||
return { color1: bucketToHex(primary), color2: bucketToHex(secondary) }
|
||||
}
|
||||
243
src/app/share-preview.ts
Normal file
243
src/app/share-preview.ts
Normal file
@ -0,0 +1,243 @@
|
||||
import { toCanvas } from 'html-to-image'
|
||||
import { EXPORT_ARTBOARD_WIDTH, EXPORT_FORMATS } from './export-formats'
|
||||
import { deriveSharePreviewPalette, type SharePreviewPalette } from './share-preview-palette'
|
||||
import type { Slide } from '../types'
|
||||
|
||||
/**
|
||||
* Renders the Open Graph preview image for a share link: up to three screens
|
||||
* captured from the live artboard DOM, composed on a gradient sampled from the
|
||||
* rendered first screen, with the project name set in the UI face.
|
||||
* The share flow treats the preview as best-effort — any failure returns null
|
||||
* and the link still works, it just unfurls without an image.
|
||||
*/
|
||||
|
||||
export const SHARE_PREVIEW_WIDTH = 1200
|
||||
export const SHARE_PREVIEW_HEIGHT = 630
|
||||
|
||||
const MAX_PREVIEW_SCREENS = 3
|
||||
const PREVIEW_JPEG_QUALITY = 0.9
|
||||
|
||||
const ARTBOARD_ASPECT = EXPORT_FORMATS[0].width / EXPORT_FORMATS[0].height
|
||||
|
||||
const captureSlideCanvas = async (slide: Slide, screenHeight: number): Promise<HTMLCanvasElement | null> => {
|
||||
const node = document.getElementById(`artboard-${slide.id}`)
|
||||
if (!node) return null
|
||||
try {
|
||||
return await toCanvas(node, {
|
||||
pixelRatio: 1,
|
||||
width: EXPORT_ARTBOARD_WIDTH,
|
||||
height: EXPORT_ARTBOARD_WIDTH / ARTBOARD_ASPECT,
|
||||
canvasWidth: Math.round(screenHeight * ARTBOARD_ASPECT),
|
||||
canvasHeight: screenHeight,
|
||||
backgroundColor: slide.background.color1,
|
||||
filter: (candidate: HTMLElement) =>
|
||||
!(candidate instanceof HTMLElement && candidate.dataset['aiOverlay']),
|
||||
})
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const parseHexColor = (value: string): { r: number; g: number; b: number } | null => {
|
||||
const match = /^#([0-9a-f]{6})$/i.exec(value.trim())
|
||||
if (!match?.[1]) return null
|
||||
const hex = Number.parseInt(match[1], 16)
|
||||
return { r: (hex >> 16) & 255, g: (hex >> 8) & 255, b: hex & 255 }
|
||||
}
|
||||
|
||||
const isLightColor = (value: string): boolean => {
|
||||
const rgb = parseHexColor(value)
|
||||
if (!rgb) return false
|
||||
return (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255 > 0.62
|
||||
}
|
||||
|
||||
type ScreenPlacement = { x: number; y: number; rotation: number; height: number; z: number }
|
||||
|
||||
// Indexed by slide order: the first screen takes the hero spot in front.
|
||||
const screenPlacements = (count: number): ScreenPlacement[] => {
|
||||
if (count >= 3) {
|
||||
return [
|
||||
{ x: 860, y: 310, rotation: 0.02, height: 500, z: 2 },
|
||||
{ x: 690, y: 345, rotation: -0.1, height: 470, z: 0 },
|
||||
{ x: 1030, y: 360, rotation: 0.12, height: 470, z: 1 },
|
||||
]
|
||||
}
|
||||
if (count === 2) {
|
||||
return [
|
||||
{ x: 750, y: 340, rotation: -0.07, height: 490, z: 1 },
|
||||
{ x: 985, y: 320, rotation: 0.06, height: 490, z: 0 },
|
||||
]
|
||||
}
|
||||
return [{ x: 880, y: 330, rotation: 0.03, height: 540, z: 0 }]
|
||||
}
|
||||
|
||||
const drawScreen = (
|
||||
context: CanvasRenderingContext2D,
|
||||
screen: HTMLCanvasElement,
|
||||
placement: ScreenPlacement,
|
||||
) => {
|
||||
const height = placement.height
|
||||
const width = Math.round(height * ARTBOARD_ASPECT)
|
||||
context.save()
|
||||
context.translate(placement.x, placement.y)
|
||||
context.rotate(placement.rotation)
|
||||
const frame = new Path2D()
|
||||
frame.roundRect(-width / 2, -height / 2, width, height, 18)
|
||||
context.shadowColor = 'rgba(10, 12, 24, 0.45)'
|
||||
context.shadowBlur = 42
|
||||
context.shadowOffsetY = 22
|
||||
context.fillStyle = '#ffffff'
|
||||
context.fill(frame)
|
||||
context.shadowColor = 'transparent'
|
||||
context.shadowBlur = 0
|
||||
context.shadowOffsetY = 0
|
||||
context.clip(frame)
|
||||
context.drawImage(screen, -width / 2, -height / 2, width, height)
|
||||
context.restore()
|
||||
}
|
||||
|
||||
const ellipsize = (context: CanvasRenderingContext2D, text: string, maxWidth: number): string => {
|
||||
if (context.measureText(text).width <= maxWidth) return text
|
||||
let trimmed = text.replace(/…$/, '')
|
||||
while (trimmed.length > 1 && context.measureText(`${trimmed}…`).width > maxWidth) {
|
||||
trimmed = trimmed.slice(0, -1)
|
||||
}
|
||||
return `${trimmed}…`
|
||||
}
|
||||
|
||||
const wrapProjectName = (
|
||||
context: CanvasRenderingContext2D,
|
||||
name: string,
|
||||
maxWidth: number,
|
||||
): string[] => {
|
||||
const words = name.trim().split(/\s+/)
|
||||
const lines: string[] = []
|
||||
let current = ''
|
||||
for (const word of words) {
|
||||
const candidate = current === '' ? word : `${current} ${word}`
|
||||
if (current !== '' && context.measureText(candidate).width > maxWidth) {
|
||||
lines.push(current)
|
||||
current = word
|
||||
} else {
|
||||
current = candidate
|
||||
}
|
||||
}
|
||||
if (current !== '') lines.push(current)
|
||||
|
||||
// At most two lines fit the layout; a dropped remainder gets an ellipsis so
|
||||
// truncation is visible.
|
||||
const shown = lines.slice(0, 2)
|
||||
const overflowed = lines.length > shown.length
|
||||
return shown.map((line, index) => {
|
||||
const marked = overflowed && index === shown.length - 1 ? `${line}…` : line
|
||||
return ellipsize(context, marked, maxWidth)
|
||||
})
|
||||
}
|
||||
|
||||
const fallbackPalette = (slide: Slide | undefined): SharePreviewPalette => ({
|
||||
color1: slide?.background.color1 ?? '#101014',
|
||||
color2: slide?.background.color2 ?? '#1c1c26',
|
||||
})
|
||||
|
||||
const renderedPalette = (screen: HTMLCanvasElement | null | undefined): SharePreviewPalette | null => {
|
||||
if (!screen) return null
|
||||
const context = screen.getContext('2d', { willReadFrequently: true })
|
||||
if (!context) return null
|
||||
try {
|
||||
const pixels = context.getImageData(0, 0, screen.width, screen.height).data
|
||||
return deriveSharePreviewPalette(pixels, screen.width, screen.height)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const drawBackdrop = (context: CanvasRenderingContext2D, palette: SharePreviewPalette) => {
|
||||
const { color1, color2 } = palette
|
||||
const gradient = context.createLinearGradient(0, 0, SHARE_PREVIEW_WIDTH, SHARE_PREVIEW_HEIGHT)
|
||||
gradient.addColorStop(0, parseHexColor(color1) ? color1 : '#101014')
|
||||
gradient.addColorStop(1, parseHexColor(color2) ? color2 : '#1c1c26')
|
||||
context.fillStyle = gradient
|
||||
context.fillRect(0, 0, SHARE_PREVIEW_WIDTH, SHARE_PREVIEW_HEIGHT)
|
||||
|
||||
// A quiet vignette keeps white artboards from bleeding into the canvas edge
|
||||
// and gives the name block contrast on light gradients.
|
||||
const vignette = context.createLinearGradient(0, 0, SHARE_PREVIEW_WIDTH * 0.7, 0)
|
||||
vignette.addColorStop(0, 'rgba(8, 9, 18, 0.34)')
|
||||
vignette.addColorStop(1, 'rgba(8, 9, 18, 0)')
|
||||
context.fillStyle = vignette
|
||||
context.fillRect(0, 0, SHARE_PREVIEW_WIDTH, SHARE_PREVIEW_HEIGHT)
|
||||
return isLightColor(color1)
|
||||
}
|
||||
|
||||
const drawNameBlock = (context: CanvasRenderingContext2D, projectName: string, onLight: boolean) => {
|
||||
const ink = onLight ? '#15161c' : '#ffffff'
|
||||
const muted = onLight ? 'rgba(21, 22, 28, 0.66)' : 'rgba(255, 255, 255, 0.72)'
|
||||
const fontStack = '\'Instrument Sans Variable\', \'Instrument Sans\', system-ui, sans-serif'
|
||||
|
||||
context.textBaseline = 'alphabetic'
|
||||
context.fillStyle = muted
|
||||
context.font = `600 21px ${fontStack}`
|
||||
try {
|
||||
context.letterSpacing = '4px'
|
||||
} catch {
|
||||
// Older engines without canvas letter spacing simply render tighter.
|
||||
}
|
||||
context.fillText('SHOTLUMA', 84, 214)
|
||||
try {
|
||||
context.letterSpacing = '0px'
|
||||
} catch {
|
||||
// See above.
|
||||
}
|
||||
|
||||
context.fillStyle = ink
|
||||
context.font = `640 58px ${fontStack}`
|
||||
const lines = wrapProjectName(context, projectName, 430)
|
||||
lines.forEach((line, index) => {
|
||||
context.fillText(line, 84, 288 + index * 70)
|
||||
})
|
||||
|
||||
context.fillStyle = muted
|
||||
context.font = `500 22px ${fontStack}`
|
||||
context.fillText('Open the link to edit', 84, 320 + lines.length * 70)
|
||||
context.fillText('your own copy.', 84, 352 + lines.length * 70)
|
||||
}
|
||||
|
||||
const canvasToJpeg = (canvas: HTMLCanvasElement): Promise<Blob | null> =>
|
||||
new Promise((resolve) => {
|
||||
canvas.toBlob(resolve, 'image/jpeg', PREVIEW_JPEG_QUALITY)
|
||||
})
|
||||
|
||||
export const createSharePreviewImage = async (
|
||||
projectName: string,
|
||||
slides: Slide[],
|
||||
): Promise<Blob | null> => {
|
||||
try {
|
||||
await document.fonts.ready
|
||||
const shown = slides.slice(0, MAX_PREVIEW_SCREENS)
|
||||
const placements = screenPlacements(shown.length)
|
||||
const screens = await Promise.all(
|
||||
shown.map((slide, index) => captureSlideCanvas(slide, placements[index]?.height ?? 470)),
|
||||
)
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = SHARE_PREVIEW_WIDTH
|
||||
canvas.height = SHARE_PREVIEW_HEIGHT
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) return null
|
||||
|
||||
const palette = renderedPalette(screens[0]) ?? fallbackPalette(shown[0])
|
||||
const onLight = drawBackdrop(context, palette)
|
||||
screens
|
||||
.map((screen, index) => ({ screen, placement: placements[index] }))
|
||||
.filter((entry): entry is { screen: HTMLCanvasElement; placement: ScreenPlacement } =>
|
||||
entry.screen !== null && entry.placement !== undefined)
|
||||
.sort((a, b) => a.placement.z - b.placement.z)
|
||||
.forEach(({ screen, placement }) => {
|
||||
drawScreen(context, screen, placement)
|
||||
})
|
||||
drawNameBlock(context, projectName.trim() === '' ? 'Shared project' : projectName, onLight)
|
||||
return await canvasToJpeg(canvas)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState, type Dispatch, type RefObject, type SetStateAction } from 'react'
|
||||
import { hydrateProjectAssets } from '../asset-store'
|
||||
import { createInitialSlides } from '../data'
|
||||
import {
|
||||
deleteProject,
|
||||
@ -11,7 +12,14 @@ import {
|
||||
type ProjectSummary,
|
||||
} from '../persistence'
|
||||
import { uid } from '../utils'
|
||||
import { DEFAULT_PROJECT_NAME, getUniqueProjectName, upsertProjectSummary } from './project-utils'
|
||||
import {
|
||||
consumeInterruptedGeneration,
|
||||
DEFAULT_PROJECT_NAME,
|
||||
getUniqueProjectName,
|
||||
resolveGeneratedProjectName,
|
||||
upsertProjectSummary,
|
||||
} from './project-utils'
|
||||
import { consumeShareLinkHash, decodeSharePayload } from './share-link'
|
||||
import type { Slide, UploadAsset } from '../types'
|
||||
import type { SaveStatus } from './project-types'
|
||||
|
||||
@ -25,8 +33,17 @@ type ProjectWorkspaceOptions = {
|
||||
uploadsRef: RefObject<UploadAsset[]>
|
||||
onProjectReplaced: (project: PersistedProject) => void
|
||||
setToast: Dispatch<SetStateAction<string | null>>
|
||||
/**
|
||||
* True while an AI generation is running. Saves made during a run carry the
|
||||
* interrupted-generation marker, so a project closed mid-run can explain the
|
||||
* half-finished screens on its next load.
|
||||
*/
|
||||
isAiRunActive: () => boolean
|
||||
}
|
||||
|
||||
const INTERRUPTED_GENERATION_MESSAGE =
|
||||
'The last AI generation was interrupted — finished screens were kept'
|
||||
|
||||
const makeNewProject = (
|
||||
projectName: string,
|
||||
slides: Slide[],
|
||||
@ -43,6 +60,57 @@ const makeNewProject = (
|
||||
}
|
||||
}
|
||||
|
||||
type SharedImportResult =
|
||||
| { status: 'none' }
|
||||
| { status: 'invalid' }
|
||||
| { status: 'imported'; project: PersistedProject }
|
||||
|
||||
/**
|
||||
* Imports a project carried by a `#share=` link as a new, independent local
|
||||
* copy: inlined images become locally stored blobs on save, so later edits or
|
||||
* deletion only ever touch this browser's copy.
|
||||
*/
|
||||
const importSharedProject = async (existingProjects: ProjectSummary[]): Promise<SharedImportResult> => {
|
||||
const sharedHash = consumeShareLinkHash()
|
||||
if (!sharedHash) return { status: 'none' }
|
||||
sharedImportPending = true
|
||||
try {
|
||||
const shared = await decodeSharePayload(sharedHash)
|
||||
if (!shared) return { status: 'invalid' }
|
||||
const project = await hydrateProjectAssets(makeNewProject(
|
||||
getUniqueProjectName(existingProjects, shared.projectName),
|
||||
shared.slides,
|
||||
shared.uploads,
|
||||
))
|
||||
await saveProject(project)
|
||||
return { status: 'imported', project }
|
||||
} catch {
|
||||
return { status: 'invalid' }
|
||||
}
|
||||
}
|
||||
|
||||
// React StrictMode double-invokes the hydration effect in development. The
|
||||
// first run consumes the one-shot URL fragment and may be cancelled mid-way,
|
||||
// so both runs must share a single import request — otherwise the shared
|
||||
// project is either lost or saved twice.
|
||||
let sharedImportRequest: Promise<SharedImportResult> | null = null
|
||||
let sharedImportPending = false
|
||||
|
||||
const importSharedProjectOnce = (existingProjects: ProjectSummary[]): Promise<SharedImportResult> => {
|
||||
sharedImportRequest ??= importSharedProject(existingProjects)
|
||||
return sharedImportRequest
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the import as fully handled. Later effect runs (dependency identity
|
||||
* changes) then resolve to 'none' instead of re-applying the imported project
|
||||
* or re-showing its toast.
|
||||
*/
|
||||
const settleSharedImport = () => {
|
||||
sharedImportPending = false
|
||||
sharedImportRequest = Promise.resolve({ status: 'none' })
|
||||
}
|
||||
|
||||
export function useProjectWorkspace({
|
||||
initialProjectName,
|
||||
slides,
|
||||
@ -53,6 +121,7 @@ export function useProjectWorkspace({
|
||||
uploadsRef,
|
||||
onProjectReplaced,
|
||||
setToast,
|
||||
isAiRunActive,
|
||||
}: ProjectWorkspaceOptions) {
|
||||
const [projectName, setProjectNameState] = useState(initialProjectName)
|
||||
const projectNameRef = useRef(initialProjectName)
|
||||
@ -108,24 +177,47 @@ export function useProjectWorkspace({
|
||||
const workspace = await loadProjectWorkspace()
|
||||
if (isCancelled()) return
|
||||
|
||||
const project = workspace.activeProject ?? makeNewProject(
|
||||
const sharedImport = await importSharedProjectOnce(workspace.projects)
|
||||
const imported = sharedImport.status === 'imported' ? sharedImport.project : null
|
||||
let project = imported ?? workspace.activeProject ?? makeNewProject(
|
||||
projectNameRef.current,
|
||||
slidesRef.current,
|
||||
uploadsRef.current,
|
||||
)
|
||||
if (!workspace.activeProject) await saveProject(project)
|
||||
if (!imported && !workspace.activeProject) await saveProject(project)
|
||||
const interrupted = consumeInterruptedGeneration(project)
|
||||
if (interrupted) {
|
||||
project = interrupted
|
||||
await saveProject(project)
|
||||
}
|
||||
await setActiveProjectId(project.id)
|
||||
if (isCancelled()) return
|
||||
|
||||
replaceProject(project)
|
||||
setProjects(workspace.activeProject
|
||||
? workspace.projects
|
||||
setProjects(imported || workspace.activeProject
|
||||
? upsertProjectSummary(workspace.projects, project)
|
||||
: upsertProjectSummary([], project))
|
||||
if (sharedImport.status === 'imported') {
|
||||
setToast('Shared project imported as your own local copy')
|
||||
} else if (sharedImport.status === 'invalid') {
|
||||
setToast('Couldn’t open the shared project link')
|
||||
} else if (interrupted) {
|
||||
setToast(INTERRUPTED_GENERATION_MESSAGE)
|
||||
}
|
||||
if (sharedImport.status !== 'none') settleSharedImport()
|
||||
removeLegacyProject()
|
||||
skipNextAutoSaveRef.current = true
|
||||
setSaveStatus('saved')
|
||||
} catch {
|
||||
if (!isCancelled()) setSaveStatus('error')
|
||||
if (!isCancelled()) {
|
||||
// The share fragment is already consumed, so a hydration failure
|
||||
// must still tell the user their shared link went nowhere.
|
||||
if (sharedImportPending) {
|
||||
settleSharedImport()
|
||||
setToast('Couldn’t open the shared project link')
|
||||
}
|
||||
setSaveStatus('error')
|
||||
}
|
||||
} finally {
|
||||
if (!isCancelled()) {
|
||||
persistenceReadyRef.current = true
|
||||
@ -138,7 +230,7 @@ export function useProjectWorkspace({
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [replaceProject, slidesRef, uploadsRef])
|
||||
}, [replaceProject, setToast, slidesRef, uploadsRef])
|
||||
|
||||
const saveCurrentProject = useCallback(async (showConfirmation = false) => {
|
||||
if (!persistenceReadyRef.current || projectTransitionRef.current) return false
|
||||
@ -153,6 +245,7 @@ export function useProjectWorkspace({
|
||||
uploads: uploadsRef.current,
|
||||
createdAt: currentProjectCreatedAtRef.current,
|
||||
savedAt,
|
||||
...(isAiRunActive() ? { interruptedGeneration: true as const } : {}),
|
||||
}
|
||||
|
||||
setSaveStatus('saving')
|
||||
@ -178,7 +271,7 @@ export function useProjectWorkspace({
|
||||
if (showConfirmation) setToast('Couldn’t save locally')
|
||||
return false
|
||||
}
|
||||
}, [setToast, slidesRef, uploadsRef])
|
||||
}, [isAiRunActive, setToast, slidesRef, uploadsRef])
|
||||
|
||||
const runProjectTransition = useCallback(async (
|
||||
operation: () => Promise<PersistedProject>,
|
||||
@ -194,13 +287,18 @@ export function useProjectWorkspace({
|
||||
|
||||
projectTransitionRef.current = true
|
||||
try {
|
||||
const project = await operation()
|
||||
let project = await operation()
|
||||
const interrupted = consumeInterruptedGeneration(project)
|
||||
if (interrupted) {
|
||||
project = interrupted
|
||||
await saveProject(project)
|
||||
}
|
||||
await setActiveProjectId(project.id)
|
||||
skipNextAutoSaveRef.current = true
|
||||
replaceProject(project)
|
||||
setProjects((current) => upsertProjectSummary(current, project))
|
||||
setSaveStatus('saved')
|
||||
setToast(successMessage)
|
||||
setToast(interrupted ? INTERRUPTED_GENERATION_MESSAGE : successMessage)
|
||||
} catch {
|
||||
setSaveStatus('error')
|
||||
setToast(errorMessage)
|
||||
@ -230,6 +328,16 @@ export function useProjectWorkspace({
|
||||
}, 'New project created', 'Couldn’t create project')
|
||||
}, [projects, runProjectTransition])
|
||||
|
||||
const applyGeneratedProjectName = useCallback((appName: string) => {
|
||||
const nextName = resolveGeneratedProjectName(
|
||||
projects,
|
||||
currentProjectIdRef.current,
|
||||
projectNameRef.current,
|
||||
appName,
|
||||
)
|
||||
if (nextName) setProjectName(nextName)
|
||||
}, [projects, setProjectName])
|
||||
|
||||
const duplicateCurrentProject = useCallback(() => {
|
||||
const project = makeNewProject(
|
||||
getUniqueProjectName(
|
||||
@ -322,6 +430,7 @@ export function useProjectWorkspace({
|
||||
setDeleteDialogOpen,
|
||||
deletingProject,
|
||||
saveCurrentProject,
|
||||
applyGeneratedProjectName,
|
||||
openProject,
|
||||
createNewProject,
|
||||
duplicateCurrentProject,
|
||||
|
||||
@ -50,7 +50,8 @@ describe('AI API keys dialog', () => {
|
||||
expect(markup).toContain('Qwen')
|
||||
expect(markup).toContain('OpenAI')
|
||||
expect(markup).toContain('Anthropic')
|
||||
expect(markup).toContain('xAI')
|
||||
expect(markup).toContain('OpenRouter')
|
||||
expect(markup).toContain('OpenCode')
|
||||
expect(markup).toContain('type="password"')
|
||||
expect(markup).toContain('<form')
|
||||
expect(markup).toContain('type="submit"')
|
||||
|
||||
@ -5,7 +5,7 @@ import {
|
||||
type SyntheticEvent,
|
||||
} from 'react'
|
||||
import {
|
||||
AI_PROVIDERS,
|
||||
getAiProviderKeyFields,
|
||||
type AiProviderId,
|
||||
} from '../ai/provider-catalog'
|
||||
import {
|
||||
@ -51,9 +51,12 @@ export const AiApiKeysDialog = ({
|
||||
if (!open) return
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
const targetId = focusProviderId
|
||||
?? AI_PROVIDERS.find((provider) => provider.auth === 'apiKey')?.id
|
||||
?? getAiProviderKeyFields()[0]?.providerIds[0]
|
||||
if (!targetId) return
|
||||
const node = document.getElementById(`${formId}-${targetId}`)
|
||||
const field = getAiProviderKeyFields().find((entry) =>
|
||||
entry.providerIds.includes(targetId),
|
||||
)
|
||||
const node = document.getElementById(`${formId}-${field?.id ?? targetId}`)
|
||||
if (!(node instanceof HTMLInputElement)) return
|
||||
node.focus()
|
||||
node.select()
|
||||
@ -102,18 +105,24 @@ export const AiApiKeysDialog = ({
|
||||
</summary>
|
||||
<p>
|
||||
Keys are stored unencrypted in this browser. AI requests send a key only
|
||||
to the provider used for that request; Moonshot passes through the local proxy,
|
||||
and optional overlay assets use OpenAI. Use dedicated keys with strict limits.
|
||||
to the provider used for that request; Moonshot and OpenCode pass through
|
||||
a same-origin CORS proxy, and optional overlay assets use OpenAI. Use
|
||||
dedicated keys with strict limits.
|
||||
</p>
|
||||
</details>
|
||||
|
||||
<div className="ai-keys-dialog-fields">
|
||||
{AI_PROVIDERS.filter((provider) => provider.auth === 'apiKey').map((provider) => {
|
||||
const inputId = `${formId}-${provider.id}`
|
||||
const hasEnvFallback = envAvailability[provider.id] && !draft[provider.id]
|
||||
{getAiProviderKeyFields().map((field) => {
|
||||
const inputId = `${formId}-${field.id}`
|
||||
const value = field.providerIds
|
||||
.map((providerId) => draft[providerId])
|
||||
.find((entry) => entry.length > 0) ?? ''
|
||||
const hasEnvFallback = field.providerIds.some((providerId) =>
|
||||
envAvailability[providerId] && !draft[providerId],
|
||||
)
|
||||
return (
|
||||
<label className="ai-keys-dialog-field" htmlFor={inputId} key={provider.id}>
|
||||
<span>{provider.label}</span>
|
||||
<label className="ai-keys-dialog-field" htmlFor={inputId} key={field.id}>
|
||||
<span>{field.label}</span>
|
||||
<Input
|
||||
id={inputId}
|
||||
type="password"
|
||||
@ -121,16 +130,22 @@ export const AiApiKeysDialog = ({
|
||||
autoCapitalize="none"
|
||||
spellCheck={false}
|
||||
placeholder={hasEnvFallback ? 'Using .env.local' : 'Paste API key'}
|
||||
value={draft[provider.id]}
|
||||
value={value}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Enter' || event.nativeEvent.isComposing) return
|
||||
event.preventDefault()
|
||||
saveDraft()
|
||||
}}
|
||||
onChange={(event) => {
|
||||
const value = event.target.value
|
||||
const nextValue = event.target.value
|
||||
setSaveError(null)
|
||||
setDraft((current) => ({ ...current, [provider.id]: value }))
|
||||
setDraft((current) => {
|
||||
const next = { ...current }
|
||||
for (const providerId of field.providerIds) {
|
||||
next[providerId] = nextValue
|
||||
}
|
||||
return next
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
|
||||
@ -5,9 +5,16 @@ import {
|
||||
type DragEvent,
|
||||
type RefObject,
|
||||
} from 'react'
|
||||
import {
|
||||
isOpencodeProviderId,
|
||||
pickOpencodeVisionModel,
|
||||
} from '../ai/opencode-models'
|
||||
import {
|
||||
clampAiReasoningEffort,
|
||||
findAiModelById,
|
||||
getAiModel,
|
||||
getAiProvider,
|
||||
getDynamicProviderModels,
|
||||
modelSupportsVision,
|
||||
type AiModelSelection,
|
||||
type AiProviderId,
|
||||
} from '../ai/provider-catalog'
|
||||
@ -54,6 +61,28 @@ const toImageDrafts = async (files: File[], idPrefix: 'logo' | 'shot'): Promise<
|
||||
dataUrl: await fileToDataUrl(file),
|
||||
})))
|
||||
|
||||
const nextAiSelection = (
|
||||
provider: AiProviderId,
|
||||
modelId: string,
|
||||
current: AiModelSelection,
|
||||
): AiModelSelection => {
|
||||
const model = getAiModel({ provider, model: modelId })
|
||||
const reasoningEffort = clampAiReasoningEffort(model, current.reasoningEffort)
|
||||
const visionModel = isOpencodeProviderId(provider) && !modelSupportsVision(model)
|
||||
? pickOpencodeVisionModel(
|
||||
provider,
|
||||
[...getAiProvider(provider).models, ...getDynamicProviderModels(provider)],
|
||||
current.provider === provider ? current.visionModel : undefined,
|
||||
)?.id
|
||||
: undefined
|
||||
return {
|
||||
provider,
|
||||
model: modelId,
|
||||
...(reasoningEffort ? { reasoningEffort } : {}),
|
||||
...(visionModel ? { visionModel } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export type AiGenerateModalProps = {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
@ -61,8 +90,15 @@ export type AiGenerateModalProps = {
|
||||
/** `html` set means the target is an AI-authored HTML screen; edits then run the HTML toolset. */
|
||||
targetSlide?: { id: string; name: string; html?: string }
|
||||
onPrepareRun: (files: { name: string; dataUrl: string }[]) => Promise<{ assetId: string; name: string; dataUrl: string }[]>
|
||||
onFinished: (slidesCreated: number) => void
|
||||
/** `appName` is carried only by a generate run, so the project can adopt it as its title. */
|
||||
onFinished: (result: { slidesCreated: number; appName?: string }) => void
|
||||
onActivity?: (activity: AiToolActivity | null) => void
|
||||
/**
|
||||
* Reports the live run to the owner: a cancel handle while a run is active,
|
||||
* null once it ends. The owner uses it to guard project switches and page
|
||||
* unloads and to abort the run from outside the modal.
|
||||
*/
|
||||
onRunStateChange: (control: { cancel: () => void } | null) => void
|
||||
}
|
||||
|
||||
type ImageDropzoneProps = {
|
||||
@ -299,11 +335,11 @@ const IdleContent = ({
|
||||
onCheckedChange={onEnableHtmlScreensChange}
|
||||
/>
|
||||
<label htmlFor="ai-modal-html-screens" className="ai-modal-overlay-toggle__copy">
|
||||
<b>HTML screens <Badge variant="secondary">Experimental</Badge></b>
|
||||
<b>HTML screens <Badge variant="secondary" className="ai-modal-overlay-toggle__badge">Experimental</Badge></b>
|
||||
<span>
|
||||
The AI designs each screen as free-form HTML and CSS instead of canvas elements — often bolder layouts and typography.
|
||||
</span>
|
||||
<small>
|
||||
<small className="ai-modal-overlay-toggle__caution">
|
||||
HTML screens can only be edited with AI, not by hand.
|
||||
</small>
|
||||
</label>
|
||||
@ -320,6 +356,7 @@ const ModalFooter = ({
|
||||
transportAvailability,
|
||||
onModelSelect,
|
||||
onReasoningEffortChange,
|
||||
onVisionModelChange,
|
||||
onManageKeys,
|
||||
onConnectCodex,
|
||||
onGenerate,
|
||||
@ -331,6 +368,7 @@ const ModalFooter = ({
|
||||
transportAvailability: AiProviderAvailability
|
||||
onModelSelect: (provider: AiProviderId, modelId: string) => void
|
||||
onReasoningEffortChange: (reasoningEffort: NonNullable<AiModelSelection['reasoningEffort']>) => void
|
||||
onVisionModelChange: (visionModel: string) => void
|
||||
onManageKeys: (providerId: AiProviderId) => void
|
||||
onConnectCodex: () => void
|
||||
onGenerate: () => void
|
||||
@ -342,6 +380,7 @@ const ModalFooter = ({
|
||||
transportAvailability={transportAvailability}
|
||||
onModelSelect={onModelSelect}
|
||||
onReasoningEffortChange={onReasoningEffortChange}
|
||||
onVisionModelChange={onVisionModelChange}
|
||||
onManageKeys={onManageKeys}
|
||||
onConnectCodex={onConnectCodex}
|
||||
/>
|
||||
@ -357,7 +396,7 @@ const ModalFooter = ({
|
||||
</>
|
||||
)
|
||||
|
||||
export const AiGenerateModal = ({ open, onClose, controller, targetSlide, onPrepareRun, onFinished, onActivity }: AiGenerateModalProps) => {
|
||||
export const AiGenerateModal = ({ open, onClose, controller, targetSlide, onPrepareRun, onFinished, onActivity, onRunStateChange }: AiGenerateModalProps) => {
|
||||
const [appName, setAppName] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [logo, setLogo] = useState<ImageDraft | null>(null)
|
||||
@ -371,7 +410,7 @@ export const AiGenerateModal = ({ open, onClose, controller, targetSlide, onPrep
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
const [doneInfo, setDoneInfo] = useState<{ summary: string; slidesCreated: number } | null>(null)
|
||||
const [selection, setSelection] = useState<AiModelSelection>(INITIAL_AI_SELECTION)
|
||||
const [enableHtmlScreens, setEnableHtmlScreens] = useState(false)
|
||||
const [enableHtmlScreens, setEnableHtmlScreens] = useState(true)
|
||||
const [keysRevision, setKeysRevision] = useState(0)
|
||||
const [keysDialogOpen, setKeysDialogOpen] = useState(false)
|
||||
const [keysDialogInstance, setKeysDialogInstance] = useState(0)
|
||||
@ -452,19 +491,15 @@ export const AiGenerateModal = ({ open, onClose, controller, targetSlide, onPrep
|
||||
const removeScreenshot = (id: string) => setScreenshots((current) => current.filter((shot) => shot.id !== id))
|
||||
|
||||
const handleModelSelect = (provider: AiProviderId, modelId: string) => {
|
||||
const { model } = findAiModelById(modelId)
|
||||
const reasoningEffort = clampAiReasoningEffort(model, selection.reasoningEffort)
|
||||
setSelection({
|
||||
provider,
|
||||
model: modelId,
|
||||
...(reasoningEffort ? { reasoningEffort } : {}),
|
||||
})
|
||||
setSelection(nextAiSelection(provider, modelId, selection))
|
||||
}
|
||||
|
||||
const handleEvent = (event: AiRunEvent) => {
|
||||
if (cancelledRef.current) return
|
||||
if (event.type === 'tool') {
|
||||
setLatestActivity(event.detail)
|
||||
} else if (event.type === 'status') {
|
||||
setLatestActivity(event.message)
|
||||
} else if (event.type === 'plan') setPlan(event.screens)
|
||||
// `index` is the count of screens finished before this one, which is exactly the
|
||||
// rail's "built" count while this screen is in progress.
|
||||
@ -482,8 +517,11 @@ export const AiGenerateModal = ({ open, onClose, controller, targetSlide, onPrep
|
||||
setDoneInfo({ summary: event.summary, slidesCreated: event.slidesCreated })
|
||||
setPhase('done')
|
||||
onActivity?.(null)
|
||||
onFinished(event.slidesCreated)
|
||||
} else if (event.type === 'error') {
|
||||
onFinished({
|
||||
slidesCreated: event.slidesCreated,
|
||||
...(!isEditMode && appName.trim() ? { appName: appName.trim() } : {}),
|
||||
})
|
||||
} else {
|
||||
setNarration(flushNarration)
|
||||
setErrorMessage(event.message)
|
||||
setPhase('error')
|
||||
@ -505,6 +543,14 @@ export const AiGenerateModal = ({ open, onClose, controller, targetSlide, onPrep
|
||||
abortControllerRef.current = abortController
|
||||
cancelledRef.current = false
|
||||
const wasCancelled = () => cancelledRef.current
|
||||
// Registered before the first await so the run is cancellable (and its
|
||||
// controller writes are permitted) from the very first mutation.
|
||||
onRunStateChange({
|
||||
cancel: () => {
|
||||
cancelledRef.current = true
|
||||
abortController.abort()
|
||||
},
|
||||
})
|
||||
setAssistantText('')
|
||||
setNarration(createNarrationState())
|
||||
setPlan([])
|
||||
@ -540,12 +586,14 @@ export const AiGenerateModal = ({ open, onClose, controller, targetSlide, onPrep
|
||||
}
|
||||
} finally {
|
||||
runActiveRef.current = false
|
||||
onRunStateChange(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
cancelledRef.current = true
|
||||
abortControllerRef.current?.abort()
|
||||
onRunStateChange(null)
|
||||
setPhase('idle')
|
||||
onActivity?.(null)
|
||||
}
|
||||
@ -627,6 +675,9 @@ export const AiGenerateModal = ({ open, onClose, controller, targetSlide, onPrep
|
||||
onReasoningEffortChange={(reasoningEffort) => {
|
||||
setSelection((current) => ({ ...current, reasoningEffort }))
|
||||
}}
|
||||
onVisionModelChange={(visionModel) => {
|
||||
setSelection((current) => ({ ...current, visionModel }))
|
||||
}}
|
||||
onManageKeys={handleManageKeys}
|
||||
onConnectCodex={handleConnectCodex}
|
||||
onGenerate={() => void handleGenerate()}
|
||||
|
||||
@ -42,6 +42,8 @@ const availableTransports = {
|
||||
anthropic: true,
|
||||
xai: true,
|
||||
openrouter: true,
|
||||
'opencode-zen': true,
|
||||
'opencode-go': true,
|
||||
}
|
||||
|
||||
vi.mock('./ui/button', () => ({
|
||||
@ -72,10 +74,13 @@ describe('AI provider controls', () => {
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: false,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
}}
|
||||
transportAvailability={availableTransports}
|
||||
onModelSelect={() => undefined}
|
||||
onReasoningEffortChange={() => undefined}
|
||||
onVisionModelChange={() => undefined}
|
||||
onManageKeys={() => undefined}
|
||||
onConnectCodex={() => undefined}
|
||||
/>,
|
||||
@ -100,10 +105,13 @@ describe('AI provider controls', () => {
|
||||
anthropic: true,
|
||||
xai: true,
|
||||
openrouter: true,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
}}
|
||||
transportAvailability={availableTransports}
|
||||
onModelSelect={() => undefined}
|
||||
onReasoningEffortChange={() => undefined}
|
||||
onVisionModelChange={() => undefined}
|
||||
onManageKeys={() => undefined}
|
||||
onConnectCodex={() => undefined}
|
||||
/>,
|
||||
@ -135,10 +143,13 @@ describe('AI provider controls', () => {
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: false,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
}}
|
||||
transportAvailability={availableTransports}
|
||||
onModelSelect={() => undefined}
|
||||
onReasoningEffortChange={() => undefined}
|
||||
onVisionModelChange={() => undefined}
|
||||
onManageKeys={() => undefined}
|
||||
onConnectCodex={() => undefined}
|
||||
/>,
|
||||
@ -168,10 +179,13 @@ describe('AI provider controls', () => {
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: false,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
}}
|
||||
transportAvailability={availableTransports}
|
||||
onModelSelect={() => undefined}
|
||||
onReasoningEffortChange={() => undefined}
|
||||
onVisionModelChange={() => undefined}
|
||||
onManageKeys={() => undefined}
|
||||
onConnectCodex={() => undefined}
|
||||
/>,
|
||||
@ -202,10 +216,13 @@ describe('AI provider controls', () => {
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: false,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
}}
|
||||
transportAvailability={availableTransports}
|
||||
onModelSelect={() => undefined}
|
||||
onReasoningEffortChange={() => undefined}
|
||||
onVisionModelChange={() => undefined}
|
||||
onManageKeys={() => undefined}
|
||||
onConnectCodex={() => undefined}
|
||||
/>,
|
||||
@ -238,10 +255,13 @@ describe('AI provider controls', () => {
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: true,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
}}
|
||||
transportAvailability={availableTransports}
|
||||
onModelSelect={() => undefined}
|
||||
onReasoningEffortChange={() => undefined}
|
||||
onVisionModelChange={() => undefined}
|
||||
onManageKeys={() => undefined}
|
||||
onConnectCodex={() => undefined}
|
||||
/>,
|
||||
@ -265,10 +285,13 @@ describe('AI provider controls', () => {
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: false,
|
||||
'opencode-zen': false,
|
||||
'opencode-go': false,
|
||||
}}
|
||||
transportAvailability={{ ...availableTransports, moonshot: false }}
|
||||
onModelSelect={() => undefined}
|
||||
onReasoningEffortChange={() => undefined}
|
||||
onVisionModelChange={() => undefined}
|
||||
onManageKeys={() => undefined}
|
||||
onConnectCodex={() => undefined}
|
||||
/>,
|
||||
@ -278,4 +301,37 @@ describe('AI provider controls', () => {
|
||||
expect(markup).toContain('Moonshot · local proxy unavailable')
|
||||
expect(markup).not.toContain('Enter API key')
|
||||
})
|
||||
|
||||
it('offers a vision fallback picker for OpenCode models without native vision', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<AiProviderControls
|
||||
selection={{
|
||||
provider: 'opencode-go',
|
||||
model: 'opencode-go/glm-5.3',
|
||||
reasoningEffort: 'high',
|
||||
}}
|
||||
availability={{
|
||||
...availableTransports,
|
||||
moonshot: false,
|
||||
google: false,
|
||||
qwen: false,
|
||||
openai: false,
|
||||
anthropic: false,
|
||||
xai: false,
|
||||
openrouter: false,
|
||||
}}
|
||||
transportAvailability={availableTransports}
|
||||
onModelSelect={() => undefined}
|
||||
onReasoningEffortChange={() => undefined}
|
||||
onVisionModelChange={() => undefined}
|
||||
onManageKeys={() => undefined}
|
||||
onConnectCodex={() => undefined}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(markup).toContain('OpenCode Go · GLM 5.3')
|
||||
expect(markup).toContain('Vision fallback')
|
||||
expect(markup).toContain('cannot see images')
|
||||
expect(markup).toContain('Other models…')
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,4 +1,13 @@
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
isOpencodeProviderId,
|
||||
listOpencodeVisionModels,
|
||||
loadAllOpencodeModels,
|
||||
loadOpencodeModels,
|
||||
pickOpencodeVisionModel,
|
||||
type OpencodeProviderId,
|
||||
} from '../ai/opencode-models'
|
||||
import { loadOpenRouterModels } from '../ai/openrouter-models'
|
||||
import {
|
||||
AI_PROVIDERS,
|
||||
AI_REASONING_EFFORT_LABELS,
|
||||
@ -6,11 +15,16 @@ import {
|
||||
findAiModelById,
|
||||
getAiModel,
|
||||
getAiProvider,
|
||||
getDynamicProviderModels,
|
||||
modelSupportsVision,
|
||||
type AiModelOption,
|
||||
type AiModelSelection,
|
||||
type AiProviderId,
|
||||
type AiProviderOption,
|
||||
type AiReasoningEffort,
|
||||
} from '../ai/provider-catalog'
|
||||
import {
|
||||
AiGenerative,
|
||||
AiNetwork,
|
||||
AlertCircle,
|
||||
ChatGpt,
|
||||
@ -21,7 +35,7 @@ import {
|
||||
KimiAi,
|
||||
Qwen,
|
||||
} from './icons'
|
||||
import { OpenRouterModelBrowser } from './OpenRouterModelBrowser'
|
||||
import { AiCatalogModelBrowser } from './OpenRouterModelBrowser'
|
||||
import { Button } from './ui/button'
|
||||
import {
|
||||
Popover,
|
||||
@ -45,7 +59,24 @@ import type { ComponentType } from 'react'
|
||||
* browser instead of selecting a model. Real OpenRouter ids use `vendor/model`,
|
||||
* so the `:` namespace cannot collide.
|
||||
*/
|
||||
const OPENROUTER_BROWSE_VALUE = 'openrouter:browse-all'
|
||||
const CATALOG_BROWSE_SUFFIX = ':browse-all'
|
||||
|
||||
const catalogBrowseValue = (providerId: AiProviderId): string =>
|
||||
`${providerId}${CATALOG_BROWSE_SUFFIX}`
|
||||
|
||||
const catalogProviderFromBrowseValue = (value: string): AiProviderId | null => {
|
||||
if (!value.endsWith(CATALOG_BROWSE_SUFFIX)) return null
|
||||
const providerId = value.slice(0, -CATALOG_BROWSE_SUFFIX.length)
|
||||
return AI_PROVIDERS.some((provider) => provider.id === providerId)
|
||||
? providerId as AiProviderId
|
||||
: null
|
||||
}
|
||||
|
||||
const CATALOG_BROWSE_PROVIDERS = new Set<AiProviderId>([
|
||||
'openrouter',
|
||||
'opencode-zen',
|
||||
'opencode-go',
|
||||
])
|
||||
|
||||
const AI_PROVIDER_ICONS: Record<AiProviderId, ComponentType<{ className?: string; size?: number }>> = {
|
||||
codex: ChatGpt,
|
||||
@ -56,6 +87,8 @@ const AI_PROVIDER_ICONS: Record<AiProviderId, ComponentType<{ className?: string
|
||||
anthropic: Claude,
|
||||
xai: Grok,
|
||||
openrouter: AiNetwork,
|
||||
'opencode-zen': AiGenerative,
|
||||
'opencode-go': AiGenerative,
|
||||
}
|
||||
|
||||
export type AiProviderControlsProps = {
|
||||
@ -64,6 +97,7 @@ export type AiProviderControlsProps = {
|
||||
transportAvailability: AiProviderAvailability
|
||||
onModelSelect: (providerId: AiProviderId, modelId: string) => void
|
||||
onReasoningEffortChange: (reasoningEffort: AiReasoningEffort) => void
|
||||
onVisionModelChange: (visionModel: string) => void
|
||||
onManageKeys: (providerId: AiProviderId) => void
|
||||
onConnectCodex: () => void
|
||||
}
|
||||
@ -76,22 +110,192 @@ const triggerLabel = (
|
||||
return `${modelLabel} · ${AI_REASONING_EFFORT_LABELS[reasoningEffort]}`
|
||||
}
|
||||
|
||||
const uniqueVisionModels = (providerId: OpencodeProviderId): AiModelOption[] => {
|
||||
const models = [
|
||||
...getAiProvider(providerId).models,
|
||||
...getDynamicProviderModels(providerId),
|
||||
]
|
||||
const seen = new Set<string>()
|
||||
return listOpencodeVisionModels(models).filter((model) => {
|
||||
if (seen.has(model.id)) return false
|
||||
seen.add(model.id)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
const providerGroupCaption = (
|
||||
option: AiProviderOption,
|
||||
availability: AiProviderAvailability,
|
||||
transportAvailability: AiProviderAvailability,
|
||||
): string => {
|
||||
if (availability[option.id]) return option.label
|
||||
if (option.id === 'codex') return `${option.label} · connect`
|
||||
if (transportAvailability[option.id]) return `${option.label} · key missing`
|
||||
return `${option.label} · local proxy unavailable`
|
||||
}
|
||||
|
||||
const CatalogModelBrowsers = ({
|
||||
browsingProvider,
|
||||
selectedModelId,
|
||||
onModelSelect,
|
||||
}: {
|
||||
browsingProvider: AiProviderId | null
|
||||
selectedModelId: string
|
||||
onModelSelect: (providerId: AiProviderId, modelId: string) => void
|
||||
}) => {
|
||||
// The key remounts the browser per provider — its load-once effect would
|
||||
// otherwise keep the previous provider's catalog when React reuses the instance.
|
||||
if (browsingProvider === 'openrouter') {
|
||||
return (
|
||||
<AiCatalogModelBrowser
|
||||
key="openrouter"
|
||||
heading="All OpenRouter models"
|
||||
selectedModelId={selectedModelId}
|
||||
loadModels={loadOpenRouterModels}
|
||||
onModelSelect={(modelId) => onModelSelect('openrouter', modelId)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (!isOpencodeProviderId(browsingProvider)) return null
|
||||
return (
|
||||
<AiCatalogModelBrowser
|
||||
key={browsingProvider}
|
||||
heading={`All ${getAiProvider(browsingProvider).label} models`}
|
||||
selectedModelId={selectedModelId}
|
||||
loadModels={() => loadOpencodeModels(browsingProvider)}
|
||||
onModelSelect={(modelId) => onModelSelect(browsingProvider, modelId)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const VisionFallbackPicker = ({
|
||||
codingModelLabel,
|
||||
visionModel,
|
||||
visionModels,
|
||||
onVisionModelChange,
|
||||
}: {
|
||||
codingModelLabel: string
|
||||
visionModel: AiModelOption
|
||||
visionModels: readonly AiModelOption[]
|
||||
onVisionModelChange: (visionModel: string) => void
|
||||
}) => (
|
||||
<div className="ai-model-picker-section">
|
||||
<span className="ai-model-picker-section__label" id="ai-vision-label">
|
||||
Vision fallback
|
||||
</span>
|
||||
<Select
|
||||
value={visionModel.id}
|
||||
onValueChange={(value) => {
|
||||
if (typeof value === 'string') onVisionModelChange(value)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="ai-vision-trigger"
|
||||
className="ai-provider-trigger"
|
||||
aria-labelledby="ai-vision-label"
|
||||
aria-label="Vision fallback model"
|
||||
>
|
||||
<SelectValue>
|
||||
<span>{visionModel.label}</span>
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent align="start" className="ai-modal-select-content">
|
||||
{visionModels.map((option) => (
|
||||
<SelectItem key={option.id} value={option.id}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<small className="ai-provider-description">
|
||||
{codingModelLabel} cannot see images. {visionModel.label} will describe
|
||||
screenshots and previews first.
|
||||
</small>
|
||||
</div>
|
||||
)
|
||||
|
||||
const ProviderSetupWarning = ({
|
||||
providerId,
|
||||
keyLabel,
|
||||
isTransportAvailable,
|
||||
onManageKeys,
|
||||
onConnectCodex,
|
||||
}: {
|
||||
providerId: AiProviderId
|
||||
keyLabel: string
|
||||
isTransportAvailable: boolean
|
||||
onManageKeys: (providerId: AiProviderId) => void
|
||||
onConnectCodex: () => void
|
||||
}) => {
|
||||
const isCodex = providerId === 'codex'
|
||||
return (
|
||||
<div className="ai-provider-warning" role="alert">
|
||||
<AlertCircle size={15} />
|
||||
<div className="ai-provider-warning-body">
|
||||
<span>
|
||||
{isCodex
|
||||
? <><b>Codex isn’t connected.</b> Use your ChatGPT plan without an API key.</>
|
||||
: isTransportAvailable
|
||||
? <><b>API key missing.</b> Add your {keyLabel} key to generate with this model.</>
|
||||
: <><b>Local proxy unavailable.</b> Moonshot can be used only from localhost.</>}
|
||||
</span>
|
||||
{(isCodex || isTransportAvailable) && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="ai-provider-warning-action"
|
||||
onClick={() => {
|
||||
if (isCodex) onConnectCodex()
|
||||
else onManageKeys(providerId)
|
||||
}}
|
||||
>
|
||||
{isCodex ? 'Connect Codex' : 'Enter API key'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const AiProviderControls = ({
|
||||
selection,
|
||||
availability,
|
||||
transportAvailability,
|
||||
onModelSelect,
|
||||
onReasoningEffortChange,
|
||||
onVisionModelChange,
|
||||
onManageKeys,
|
||||
onConnectCodex,
|
||||
}: AiProviderControlsProps) => {
|
||||
const [isBrowsingOpenRouter, setBrowsingOpenRouter] = useState(false)
|
||||
const [browsingProvider, setBrowsingProvider] = useState<AiProviderId | null>(null)
|
||||
const [catalogRevision, setCatalogRevision] = useState(0)
|
||||
const provider = getAiProvider(selection.provider)
|
||||
const model = getAiModel(selection)
|
||||
const isConfigured = availability[selection.provider]
|
||||
const isTransportAvailable = transportAvailability[selection.provider]
|
||||
const reasoningEffort = clampAiReasoningEffort(model, selection.reasoningEffort)
|
||||
const SelectedIcon = AI_PROVIDER_ICONS[selection.provider]
|
||||
const keyLabel = provider.keyGroup?.label ?? provider.label
|
||||
const needsVisionFallback = isOpencodeProviderId(selection.provider)
|
||||
&& !modelSupportsVision(model)
|
||||
void catalogRevision
|
||||
const visionModels = isOpencodeProviderId(selection.provider)
|
||||
? uniqueVisionModels(selection.provider)
|
||||
: []
|
||||
const visionModel = needsVisionFallback && isOpencodeProviderId(selection.provider)
|
||||
? pickOpencodeVisionModel(selection.provider, visionModels, selection.visionModel)
|
||||
: undefined
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void loadAllOpencodeModels().then(() => {
|
||||
if (!cancelled) setCatalogRevision((current) => current + 1)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
@ -129,11 +333,12 @@ export const AiProviderControls = ({
|
||||
value={selection.model}
|
||||
onValueChange={(value) => {
|
||||
if (typeof value !== 'string') return
|
||||
if (value === OPENROUTER_BROWSE_VALUE) {
|
||||
setBrowsingOpenRouter(true)
|
||||
const browseProvider = catalogProviderFromBrowseValue(value)
|
||||
if (browseProvider) {
|
||||
setBrowsingProvider(browseProvider)
|
||||
return
|
||||
}
|
||||
setBrowsingOpenRouter(false)
|
||||
setBrowsingProvider(null)
|
||||
const match = findAiModelById(value)
|
||||
onModelSelect(match.provider.id, match.model.id)
|
||||
}}
|
||||
@ -156,13 +361,7 @@ export const AiProviderControls = ({
|
||||
<SelectLabel>
|
||||
<ProviderIcon className="ai-provider-icon" size={14} />
|
||||
<span>
|
||||
{availability[option.id]
|
||||
? option.label
|
||||
: option.id === 'codex'
|
||||
? `${option.label} · connect`
|
||||
: transportAvailability[option.id]
|
||||
? `${option.label} · key missing`
|
||||
: `${option.label} · local proxy unavailable`}
|
||||
{providerGroupCaption(option, availability, transportAvailability)}
|
||||
</span>
|
||||
</SelectLabel>
|
||||
{option.models.map((modelOption) => (
|
||||
@ -170,8 +369,8 @@ export const AiProviderControls = ({
|
||||
{modelOption.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
{option.id === 'openrouter' && (
|
||||
<SelectItem value={OPENROUTER_BROWSE_VALUE}>
|
||||
{CATALOG_BROWSE_PROVIDERS.has(option.id) && (
|
||||
<SelectItem value={catalogBrowseValue(option.id)}>
|
||||
Other models…
|
||||
</SelectItem>
|
||||
)}
|
||||
@ -182,10 +381,18 @@ export const AiProviderControls = ({
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{isBrowsingOpenRouter && (
|
||||
<OpenRouterModelBrowser
|
||||
selectedModelId={selection.model}
|
||||
onModelSelect={(modelId) => onModelSelect('openrouter', modelId)}
|
||||
<CatalogModelBrowsers
|
||||
browsingProvider={browsingProvider}
|
||||
selectedModelId={selection.model}
|
||||
onModelSelect={onModelSelect}
|
||||
/>
|
||||
|
||||
{needsVisionFallback && visionModel && (
|
||||
<VisionFallbackPicker
|
||||
codingModelLabel={model.label}
|
||||
visionModel={visionModel}
|
||||
visionModels={visionModels}
|
||||
onVisionModelChange={onVisionModelChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
@ -230,32 +437,13 @@ export const AiProviderControls = ({
|
||||
</div>
|
||||
|
||||
{!isConfigured && (
|
||||
<div className="ai-provider-warning" role="alert">
|
||||
<AlertCircle size={15} />
|
||||
<div className="ai-provider-warning-body">
|
||||
<span>
|
||||
{selection.provider === 'codex'
|
||||
? <><b>Codex isn’t connected.</b> Use your ChatGPT plan without an API key.</>
|
||||
: isTransportAvailable
|
||||
? <><b>API key missing.</b> Add your {provider.label} key to generate with this model.</>
|
||||
: <><b>Local proxy unavailable.</b> Moonshot can be used only from localhost.</>}
|
||||
</span>
|
||||
{(selection.provider === 'codex' || isTransportAvailable) && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="ai-provider-warning-action"
|
||||
onClick={() => {
|
||||
if (selection.provider === 'codex') onConnectCodex()
|
||||
else onManageKeys(selection.provider)
|
||||
}}
|
||||
>
|
||||
{selection.provider === 'codex' ? 'Connect Codex' : 'Enter API key'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ProviderSetupWarning
|
||||
providerId={selection.provider}
|
||||
keyLabel={keyLabel}
|
||||
isTransportAvailable={isTransportAvailable}
|
||||
onManageKeys={onManageKeys}
|
||||
onConnectCodex={onConnectCodex}
|
||||
/>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
@ -8,10 +8,12 @@ import {
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
} from 'react'
|
||||
import { photoMockups, type PhotoMockupDefinition } from '../mockups/catalog'
|
||||
import { createPerspectiveMapping } from '../mockups/perspective'
|
||||
import { hexToRgba, richTextHasFormatting, richTextToPlain, sanitizeRichText } from '../utils'
|
||||
import { IconGraphic } from './IconGraphic'
|
||||
import { Bold, Home01, Italic, LockKeyhole, MoreHorizontal, Search01, Signal, Underline, UserCircle, Wifi01, BatteryFull, Add01 } from './icons'
|
||||
import { ShapeGraphic } from './ShapeGraphic'
|
||||
import type { ResizeHandle } from '../editor/resize-element'
|
||||
import type { CanvasElement } from '../types'
|
||||
|
||||
const FakeScreen = ({ theme }: { theme: Extract<CanvasElement, { type: 'device' }>['screenTheme'] }) => (
|
||||
@ -35,82 +37,6 @@ const FakeScreen = ({ theme }: { theme: Extract<CanvasElement, { type: 'device'
|
||||
</div>
|
||||
)
|
||||
|
||||
const solveLinearSystem = (matrix: number[][], vector: number[]) => {
|
||||
const size = vector.length
|
||||
const augmented = matrix.map((row, index) => [...row, vector[index]])
|
||||
|
||||
for (let column = 0; column < size; column += 1) {
|
||||
let pivot = column
|
||||
for (let row = column + 1; row < size; row += 1) {
|
||||
const candidate = augmented[row]?.[column] ?? 0
|
||||
const currentPivot = augmented[pivot]?.[column] ?? 0
|
||||
if (Math.abs(candidate) > Math.abs(currentPivot)) pivot = row
|
||||
}
|
||||
const columnRow = augmented[column]
|
||||
const pivotRow = augmented[pivot]
|
||||
if (!columnRow || !pivotRow) return null
|
||||
augmented[column] = pivotRow
|
||||
augmented[pivot] = columnRow
|
||||
const activeRow = pivotRow
|
||||
const divisor = activeRow[column]
|
||||
if (divisor === undefined) return null
|
||||
if (Math.abs(divisor) < 1e-10) return null
|
||||
for (let item = column; item <= size; item += 1) {
|
||||
activeRow[item] = (activeRow[item] ?? 0) / divisor
|
||||
}
|
||||
for (let row = 0; row < size; row += 1) {
|
||||
if (row === column) continue
|
||||
const targetRow = augmented[row]
|
||||
if (!targetRow) return null
|
||||
const factor = targetRow[column] ?? 0
|
||||
for (let item = column; item <= size; item += 1) {
|
||||
targetRow[item] = (targetRow[item] ?? 0) - factor * (activeRow[item] ?? 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return augmented.map((row) => row[size] ?? 0)
|
||||
}
|
||||
|
||||
const perspectiveMatrix = (width: number, height: number, definition: PhotoMockupDefinition) => {
|
||||
const sourceWidth = 139.2
|
||||
const sourceHeight = sourceWidth / definition.sourceAspectRatio
|
||||
const source: [number, number][] = [
|
||||
[0, 0],
|
||||
[sourceWidth, 0],
|
||||
[sourceWidth, sourceHeight],
|
||||
[0, sourceHeight],
|
||||
]
|
||||
const target: [number, number][] = definition.screenQuad.map(
|
||||
(point) => [point.x * width, point.y * height],
|
||||
)
|
||||
const equations: number[][] = []
|
||||
const values: number[] = []
|
||||
|
||||
for (let index = 0; index < 4; index += 1) {
|
||||
const sourcePoint = source[index]
|
||||
const targetPoint = target[index]
|
||||
if (!sourcePoint || !targetPoint) {
|
||||
return { transform: 'none', sourceWidth, sourceHeight }
|
||||
}
|
||||
const [x, y] = sourcePoint
|
||||
const [targetX, targetY] = targetPoint
|
||||
equations.push([x, y, 1, 0, 0, 0, -targetX * x, -targetX * y])
|
||||
values.push(targetX)
|
||||
equations.push([0, 0, 0, x, y, 1, -targetY * x, -targetY * y])
|
||||
values.push(targetY)
|
||||
}
|
||||
|
||||
const solved = solveLinearSystem(equations, values)
|
||||
if (!solved) return { transform: 'none', sourceWidth, sourceHeight }
|
||||
const [a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0] = solved
|
||||
return {
|
||||
transform: `matrix3d(${a},${d},0,${g},${b},${e},0,${h},0,0,1,0,${c},${f},0,1)`,
|
||||
sourceWidth,
|
||||
sourceHeight,
|
||||
}
|
||||
}
|
||||
|
||||
const runRichTextCommand = (command: string, value?: string) => {
|
||||
// execCommand is the only browser API that preserves an arbitrary
|
||||
// contenteditable selection while applying inline formatting.
|
||||
@ -132,7 +58,12 @@ const PhotoMockup = ({ element, definition }: { element: Extract<CanvasElement,
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
const mapping = perspectiveMatrix(size.width, size.height, definition)
|
||||
const mapping = createPerspectiveMapping({
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
definition,
|
||||
hasScreenshot: Boolean(element.screenshot),
|
||||
})
|
||||
const screenClip = definition.screenMask
|
||||
? `inset(${definition.screenMask.top * mapping.sourceHeight}px ${definition.screenMask.right * mapping.sourceWidth}px ${definition.screenMask.bottom * mapping.sourceHeight}px ${definition.screenMask.left * mapping.sourceWidth}px round ${definition.screenMask.cornerRadius * mapping.sourceWidth}px)`
|
||||
: undefined
|
||||
@ -248,7 +179,7 @@ type CanvasItemProps = {
|
||||
exporting: boolean
|
||||
onSelect: (additive: boolean) => void
|
||||
onBeginDrag: (event: ReactPointerEvent, element: CanvasElement) => void
|
||||
onBeginResize: (event: ReactPointerEvent, element: CanvasElement) => void
|
||||
onBeginResize: (event: ReactPointerEvent, element: CanvasElement, handle: ResizeHandle) => void
|
||||
onBeginRotate: (event: ReactPointerEvent, element: CanvasElement) => void
|
||||
onCommitText: (patch: { text: string; html?: string }) => void
|
||||
}
|
||||
@ -423,10 +354,10 @@ export const CanvasItem = ({ element, selected, showTransformHandles, exporting,
|
||||
: showTransformHandles
|
||||
? (
|
||||
<>
|
||||
<button className="resize-handle resize-handle--nw" onPointerDown={(e) => onBeginResize(e, element)} tabIndex={-1} />
|
||||
<button className="resize-handle resize-handle--ne" onPointerDown={(e) => onBeginResize(e, element)} tabIndex={-1} />
|
||||
<button className="resize-handle resize-handle--sw" onPointerDown={(e) => onBeginResize(e, element)} tabIndex={-1} />
|
||||
<button className="resize-handle resize-handle--se" onPointerDown={(e) => onBeginResize(e, element)} tabIndex={-1} />
|
||||
<button className="resize-handle resize-handle--nw" onPointerDown={(e) => onBeginResize(e, element, 'nw')} tabIndex={-1} />
|
||||
<button className="resize-handle resize-handle--ne" onPointerDown={(e) => onBeginResize(e, element, 'ne')} tabIndex={-1} />
|
||||
<button className="resize-handle resize-handle--sw" onPointerDown={(e) => onBeginResize(e, element, 'sw')} tabIndex={-1} />
|
||||
<button className="resize-handle resize-handle--se" onPointerDown={(e) => onBeginResize(e, element, 'se')} tabIndex={-1} />
|
||||
<button className="rotate-handle" onPointerDown={(e) => onBeginRotate(e, element)} tabIndex={-1}><span /></button>
|
||||
</>
|
||||
)
|
||||
|
||||
@ -13,8 +13,16 @@ describe('coding assistant prompt', () => {
|
||||
expect(CODING_ASSISTANT_PROMPT).toContain('the theme the screenshots should match')
|
||||
})
|
||||
|
||||
it('asks for the hero benefit and the differentiator the story arc builds on', () => {
|
||||
expect(CODING_ASSISTANT_PROMPT).toContain('single strongest benefit')
|
||||
expect(CODING_ASSISTANT_PROMPT).toContain('headline the first screenshot')
|
||||
expect(CODING_ASSISTANT_PROMPT).toContain('sets it apart from similar apps')
|
||||
expect(CODING_ASSISTANT_PROMPT).toContain('in order of importance')
|
||||
expect(CODING_ASSISTANT_PROMPT).toContain('pains they remove')
|
||||
})
|
||||
|
||||
it('forbids inventing features and code-level detail', () => {
|
||||
expect(CODING_ASSISTANT_PROMPT).toContain('do not invent features')
|
||||
expect(CODING_ASSISTANT_PROMPT).toContain('do not invent features, claims, or ratings')
|
||||
expect(CODING_ASSISTANT_PROMPT).toContain('not the code, tech stack, or file layout')
|
||||
})
|
||||
})
|
||||
|
||||
@ -3,12 +3,14 @@ import { Check, Copy } from './icons'
|
||||
|
||||
export const CODING_ASSISTANT_PROMPT = `I use Shotluma to generate App Store screenshots from a short written description of my app. Read this codebase and write that description for me.
|
||||
|
||||
Return a single plain-prose paragraph (about 60-120 words, no markdown, no bullet lists, no headings) that I can paste straight into the generator. Cover:
|
||||
Return a single plain-prose paragraph (about 80-150 words, no markdown, no bullet lists, no headings) that I can paste straight into the generator. Cover:
|
||||
- What the app does and who it is for.
|
||||
- Its three to five most important features or selling points, phrased the way a user would understand them rather than in technical terms.
|
||||
- The single strongest benefit — the one thing that should headline the first screenshot.
|
||||
- What sets it apart from similar apps, if the codebase makes that clear.
|
||||
- Its three to five most important features or selling points in order of importance, phrased as user benefits or pains they remove rather than in technical terms.
|
||||
- The overall tone and mood, and if the codebase has a clear visual identity (brand colors, dark or light, playful or serious), the theme the screenshots should match.
|
||||
|
||||
Describe the product like a marketer would, not the code, tech stack, or file layout, and do not invent features that are not in the codebase.`
|
||||
Describe the product like a marketer would, not the code, tech stack, or file layout, and do not invent features, claims, or ratings that are not grounded in the codebase.`
|
||||
|
||||
export const CopyCodingPromptButton = () => {
|
||||
const [copied, setCopied] = useState(false)
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { useRef, useState, type PointerEvent as ReactPointerEvent } from 'react'
|
||||
import { DRAG_MAX, getDragMaxX, getDragMinX, getDragMinY } from '../editor/drag-bounds'
|
||||
import { getNorthResizeY, getResizePatch, type ResizeHandle } from '../editor/resize-element'
|
||||
import { getSpanGhosts } from '../editor/screen-span'
|
||||
import { clamp, getBackgroundPatternStyle, getBackgroundStyle } from '../utils'
|
||||
import { AiCursorOverlay } from './AiCursorOverlay'
|
||||
@ -24,6 +25,20 @@ type Interaction = {
|
||||
centerX?: number
|
||||
centerY?: number
|
||||
startAngle?: number
|
||||
resizeHandle?: ResizeHandle
|
||||
resizeNode?: HTMLElement
|
||||
resizeStartHeightPercent?: number
|
||||
artboardHeightPx?: number
|
||||
}
|
||||
|
||||
// Text can rewrap and mockups keep an aspect ratio, so the next height is only
|
||||
// known after layout. Probe the live node, then let React apply the real width.
|
||||
const measureHeightPercent = (node: HTMLElement, widthPercent: number, artboardHeightPx: number) => {
|
||||
const previousWidth = node.style.width
|
||||
node.style.width = `${widthPercent}%`
|
||||
const heightPercent = (node.offsetHeight / artboardHeightPx) * 100
|
||||
node.style.width = previousWidth
|
||||
return heightPercent
|
||||
}
|
||||
|
||||
type Props = {
|
||||
@ -73,7 +88,7 @@ export const EditorCanvas = ({
|
||||
const [isInteracting, setIsInteracting] = useState(false)
|
||||
const [snapGuides, setSnapGuides] = useState<{ slideId: string; vertical: boolean; horizontal: boolean } | null>(null)
|
||||
|
||||
const begin = (type: Interaction['type'], event: ReactPointerEvent, slideId: string, element: CanvasElement) => {
|
||||
const begin = (type: Interaction['type'], event: ReactPointerEvent, slideId: string, element: CanvasElement, resizeHandle?: ResizeHandle) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const artboardNode = event.currentTarget.closest('.artboard-export')
|
||||
@ -123,6 +138,20 @@ export const EditorCanvas = ({
|
||||
centerX,
|
||||
centerY,
|
||||
startAngle: Math.atan2(event.clientY - centerY, event.clientX - centerX) * (180 / Math.PI),
|
||||
...(resizeHandle
|
||||
? {
|
||||
resizeHandle,
|
||||
artboardHeightPx: artboardNode.clientHeight,
|
||||
...(itemNode instanceof HTMLElement
|
||||
? {
|
||||
resizeNode: itemNode,
|
||||
resizeStartHeightPercent: artboardNode.clientHeight > 0
|
||||
? (itemNode.offsetHeight / artboardNode.clientHeight) * 100
|
||||
: 0,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
onCheckpoint()
|
||||
setIsInteracting(true)
|
||||
@ -163,9 +192,22 @@ export const EditorCanvas = ({
|
||||
}
|
||||
|
||||
if (current.type === 'resize') {
|
||||
const handle = current.resizeHandle
|
||||
if (!handle) return
|
||||
const patch = getResizePatch(current.element, dx, handle)
|
||||
const { resizeNode, resizeStartHeightPercent, artboardHeightPx } = current
|
||||
const nextHeightPercent = handle.startsWith('n')
|
||||
&& resizeNode
|
||||
&& resizeStartHeightPercent !== undefined
|
||||
&& artboardHeightPx !== undefined
|
||||
&& artboardHeightPx > 0
|
||||
? measureHeightPercent(resizeNode, patch.width, artboardHeightPx)
|
||||
: undefined
|
||||
onUpdateElements(current.slideId, [{
|
||||
id: current.element.id,
|
||||
patch: { width: clamp(current.element.width + dx, 8, 140) },
|
||||
patch: nextHeightPercent === undefined || resizeStartHeightPercent === undefined
|
||||
? patch
|
||||
: { ...patch, y: getNorthResizeY(current.element.y, resizeStartHeightPercent, nextHeightPercent) },
|
||||
}])
|
||||
return
|
||||
}
|
||||
@ -282,7 +324,7 @@ export const EditorCanvas = ({
|
||||
exporting={exporting}
|
||||
onSelect={(additive) => onSelectElement(element.id, slide.id, additive)}
|
||||
onBeginDrag={(event, item) => begin('drag', event, slide.id, item)}
|
||||
onBeginResize={(event, item) => begin('resize', event, slide.id, item)}
|
||||
onBeginResize={(event, item, handle) => begin('resize', event, slide.id, item, handle)}
|
||||
onBeginRotate={(event, item) => begin('rotate', event, slide.id, item)}
|
||||
onCommitText={(patch) => onCommitText(slide.id, element.id, patch)}
|
||||
/>
|
||||
|
||||
@ -1,17 +1,21 @@
|
||||
import { useEffect, useId, useMemo, useState } from 'react'
|
||||
import {
|
||||
loadOpenRouterModels,
|
||||
type OpenRouterModelsResult,
|
||||
} from '../ai/openrouter-models'
|
||||
import { Search01 } from './icons'
|
||||
import { Input } from './ui/input'
|
||||
import type { AiModelOption } from '../ai/provider-catalog'
|
||||
|
||||
const VISIBLE_MODEL_LIMIT = 60
|
||||
|
||||
export type OpenRouterModelBrowserProps = {
|
||||
export type CatalogModelsResult = {
|
||||
models: readonly AiModelOption[]
|
||||
source: 'remote' | 'cache' | 'fallback'
|
||||
}
|
||||
|
||||
export type AiCatalogModelBrowserProps = {
|
||||
heading: string
|
||||
selectedModelId: string
|
||||
onModelSelect: (modelId: string) => void
|
||||
loadModels: () => Promise<CatalogModelsResult>
|
||||
fallbackNote?: string
|
||||
}
|
||||
|
||||
const filterModels = (
|
||||
@ -26,26 +30,30 @@ const filterModels = (
|
||||
}
|
||||
|
||||
/**
|
||||
* Searchable list over the full OpenRouter catalog (vision + tools capable
|
||||
* models only). Shown in the model picker once the OpenRouter provider is
|
||||
* selected; the curated shortlist stays in the grouped select above.
|
||||
* Searchable list over a runtime provider catalog. Shown in the model picker
|
||||
* once the user chooses "Other models…".
|
||||
*/
|
||||
export const OpenRouterModelBrowser = ({
|
||||
export const AiCatalogModelBrowser = ({
|
||||
heading,
|
||||
selectedModelId,
|
||||
onModelSelect,
|
||||
}: OpenRouterModelBrowserProps) => {
|
||||
loadModels,
|
||||
fallbackNote = 'Model list could not be loaded — showing the built-in shortlist.',
|
||||
}: AiCatalogModelBrowserProps) => {
|
||||
const labelId = useId()
|
||||
const [query, setQuery] = useState('')
|
||||
const [result, setResult] = useState<OpenRouterModelsResult | null>(null)
|
||||
const [result, setResult] = useState<CatalogModelsResult | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void loadOpenRouterModels().then((loaded) => {
|
||||
void loadModels().then((loaded) => {
|
||||
if (!cancelled) setResult(loaded)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
// Load once when this catalog panel mounts; the parent remounts it per provider.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
const models = useMemo(
|
||||
@ -58,7 +66,7 @@ export const OpenRouterModelBrowser = ({
|
||||
return (
|
||||
<div className="ai-model-picker-section">
|
||||
<span className="ai-model-picker-section__label" id={labelId}>
|
||||
{result ? `All OpenRouter models (${models.length})` : 'All OpenRouter models'}
|
||||
{result ? `${heading} (${models.length})` : heading}
|
||||
</span>
|
||||
<div className="ai-openrouter-search">
|
||||
<Search01 size={13} aria-hidden="true" />
|
||||
@ -72,7 +80,7 @@ export const OpenRouterModelBrowser = ({
|
||||
</div>
|
||||
{result?.source === 'fallback' && (
|
||||
<small className="ai-openrouter-note" role="status">
|
||||
Model list could not be loaded — showing the built-in shortlist.
|
||||
{fallbackNote}
|
||||
</small>
|
||||
)}
|
||||
<div className="ai-openrouter-list" role="listbox" aria-labelledby={labelId}>
|
||||
|
||||
@ -29,6 +29,7 @@ import {
|
||||
KimiAiIcon,
|
||||
Layers as Layers3Icon,
|
||||
LayoutTwoColumnIcon,
|
||||
Link01Icon,
|
||||
Lock as LockIcon,
|
||||
LockKeyhole as LockKeyholeIcon,
|
||||
LockOpen as LockOpenIcon,
|
||||
@ -95,6 +96,7 @@ export const Italic = createIcon(ItalicIcon)
|
||||
export const KimiAi = createIcon(KimiAiIcon)
|
||||
export const Layers3 = createIcon(Layers3Icon)
|
||||
export const LayoutTwoColumn = createIcon(LayoutTwoColumnIcon)
|
||||
export const Link01 = createIcon(Link01Icon)
|
||||
export const Lock = createIcon(LockIcon)
|
||||
export const LockKeyhole = createIcon(LockKeyholeIcon)
|
||||
export const LockOpen = createIcon(LockOpenIcon)
|
||||
|
||||
45
src/editor/resize-element.test.ts
Normal file
45
src/editor/resize-element.test.ts
Normal file
@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getNorthResizeY, getResizePatch, type ResizeHandle } from './resize-element'
|
||||
|
||||
describe('getResizePatch', () => {
|
||||
it.each<ResizeHandle>(['nw', 'ne', 'sw', 'se'])(
|
||||
'resizes outward and inward from the %s handle while fixing the opposite edge',
|
||||
(handle) => {
|
||||
const element = { x: 20, width: 40 }
|
||||
const isLeftHandle = handle.endsWith('w')
|
||||
const outwardDeltaX = isLeftHandle ? -10 : 10
|
||||
const inwardDeltaX = -outwardDeltaX
|
||||
const fixedEdge = isLeftHandle ? element.x + element.width : element.x
|
||||
const outward = getResizePatch(element, outwardDeltaX, handle)
|
||||
const inward = getResizePatch(element, inwardDeltaX, handle)
|
||||
|
||||
expect(outward.width).toBe(50)
|
||||
expect(inward.width).toBe(30)
|
||||
expect(isLeftHandle ? outward.x + outward.width : outward.x).toBe(fixedEdge)
|
||||
expect(isLeftHandle ? inward.x + inward.width : inward.x).toBe(fixedEdge)
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps the opposite edge fixed when the width reaches either limit', () => {
|
||||
const element = { x: 20, width: 40 }
|
||||
|
||||
expect(getResizePatch(element, 100, 'nw')).toEqual({ x: 52, width: 8 })
|
||||
expect(getResizePatch(element, -200, 'nw')).toEqual({ x: -80, width: 140 })
|
||||
expect(getResizePatch(element, -100, 'se')).toEqual({ x: 20, width: 8 })
|
||||
expect(getResizePatch(element, 200, 'se')).toEqual({ x: 20, width: 140 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('getNorthResizeY', () => {
|
||||
it('moves the top edge up when the element grows so the bottom stays fixed', () => {
|
||||
expect(getNorthResizeY(20, 30, 40)).toBe(10)
|
||||
})
|
||||
|
||||
it('moves the top edge down when the element shrinks so the bottom stays fixed', () => {
|
||||
expect(getNorthResizeY(20, 30, 20)).toBe(30)
|
||||
})
|
||||
|
||||
it('keeps y unchanged when the height does not change', () => {
|
||||
expect(getNorthResizeY(20, 30, 30)).toBe(20)
|
||||
})
|
||||
})
|
||||
25
src/editor/resize-element.ts
Normal file
25
src/editor/resize-element.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import type { BaseElement } from '../types'
|
||||
|
||||
export type ResizeHandle = 'nw' | 'ne' | 'sw' | 'se'
|
||||
|
||||
export const getResizePatch = (
|
||||
element: Pick<BaseElement, 'x' | 'width'>,
|
||||
deltaX: number,
|
||||
handle: ResizeHandle,
|
||||
): Pick<BaseElement, 'x' | 'width'> => {
|
||||
const isLeftHandle = handle.endsWith('w')
|
||||
const requestedWidth = element.width + (isLeftHandle ? -deltaX : deltaX)
|
||||
const width = Math.min(140, Math.max(8, requestedWidth))
|
||||
|
||||
return {
|
||||
x: isLeftHandle ? element.x + element.width - width : element.x,
|
||||
width,
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps the bottom edge fixed when a top handle changes the element's height. */
|
||||
export const getNorthResizeY = (
|
||||
startY: number,
|
||||
startHeightPercent: number,
|
||||
nextHeightPercent: number,
|
||||
): number => startY + startHeightPercent - nextHeightPercent
|
||||
@ -39,6 +39,11 @@ describe('deviceElementFromAttributes', () => {
|
||||
expect(deviceElementFromAttributes({ screenshot: 'https://evil.example/shot.png' }, 0).screenshot).toBeUndefined()
|
||||
})
|
||||
|
||||
it('accepts an object URL resolved from the Blob asset store', () => {
|
||||
const screenshot = 'blob:http://127.0.0.1:4173/0b1c2d3e'
|
||||
expect(deviceElementFromAttributes({ screenshot }, 0).screenshot).toBe(screenshot)
|
||||
})
|
||||
|
||||
it('clamps shadow into the editor range', () => {
|
||||
expect(deviceElementFromAttributes({ shadow: '400' }, 0).shadow).toBe(100)
|
||||
expect(deviceElementFromAttributes({ shadow: '-4' }, 0).shadow).toBe(0)
|
||||
|
||||
@ -27,9 +27,13 @@ export const deviceElementFromAttributes = (
|
||||
const mockup = attributes.mockup ?? ''
|
||||
const theme = attributes.theme ?? ''
|
||||
const shadow = Number(attributes.shadow ?? '')
|
||||
// Only an already-resolved upload (data URL) may reach the screen; an
|
||||
// Only an already-resolved upload may reach the screen: an object URL from
|
||||
// the Blob asset store, or a data URL from its storage fallback. An
|
||||
// unresolved asset: reference or anything else falls back to the fake screen.
|
||||
const screenshot = attributes.screenshot?.startsWith('data:image/') ? attributes.screenshot : undefined
|
||||
const rawScreenshot = attributes.screenshot
|
||||
const screenshot = rawScreenshot && (rawScreenshot.startsWith('blob:') || rawScreenshot.startsWith('data:image/'))
|
||||
? rawScreenshot
|
||||
: undefined
|
||||
|
||||
return {
|
||||
id: `html-device-${index}`,
|
||||
|
||||
@ -39,6 +39,8 @@ Example:
|
||||
|
||||
Shotluma calculates a projective `matrix3d` from these points. Uploaded screenshots are therefore distorted into the original Photoshop perspective instead of merely being rotated.
|
||||
|
||||
At runtime, real screenshots use a perspective source plane at least as wide as the rendered mockup. This matters for native-size HTML screens that are scaled down in the editor: it prevents the browser from enlarging a small intermediate texture before the outer scale is applied. Placeholder screens retain their fixed reference plane because their generated UI uses absolute CSS pixel sizes.
|
||||
|
||||
## What does not work
|
||||
|
||||
A single flattened JPG is not enough: the original screen cannot be removed cleanly and there are no reliable perspective coordinates. A flattened transparent PNG can be used only when the display area is already empty and its four corners are supplied manually.
|
||||
|
||||
55
src/mockups/perspective.test.ts
Normal file
55
src/mockups/perspective.test.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createPerspectiveMapping } from './perspective'
|
||||
import type { PhotoMockupDefinition } from './catalog'
|
||||
|
||||
const definition: PhotoMockupDefinition = {
|
||||
overlay: 'mockup.webp',
|
||||
canvasAspectRatio: 0.5,
|
||||
sourceAspectRatio: 0.5,
|
||||
defaultPlacement: { x: 0, y: 0, width: 100, rotation: 0 },
|
||||
screenQuad: [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 0 },
|
||||
{ x: 1, y: 1 },
|
||||
{ x: 0, y: 1 },
|
||||
],
|
||||
}
|
||||
|
||||
describe('createPerspectiveMapping', () => {
|
||||
it('uses the rendered mockup width for real screenshots', () => {
|
||||
const mapping = createPerspectiveMapping({
|
||||
width: 900,
|
||||
height: 1800,
|
||||
definition,
|
||||
hasScreenshot: true,
|
||||
})
|
||||
|
||||
expect(mapping.sourceWidth).toBe(900)
|
||||
expect(mapping.sourceHeight).toBe(1800)
|
||||
expect(mapping.transform).toBe('matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)')
|
||||
})
|
||||
|
||||
it('keeps small screens oversampled', () => {
|
||||
const mapping = createPerspectiveMapping({
|
||||
width: 80,
|
||||
height: 160,
|
||||
definition,
|
||||
hasScreenshot: true,
|
||||
})
|
||||
|
||||
expect(mapping.sourceWidth).toBe(139.2)
|
||||
expect(mapping.sourceHeight).toBe(278.4)
|
||||
})
|
||||
|
||||
it('keeps the fixed coordinate plane for generated placeholders', () => {
|
||||
const mapping = createPerspectiveMapping({
|
||||
width: 900,
|
||||
height: 1800,
|
||||
definition,
|
||||
hasScreenshot: false,
|
||||
})
|
||||
|
||||
expect(mapping.sourceWidth).toBe(139.2)
|
||||
expect(mapping.sourceHeight).toBe(278.4)
|
||||
})
|
||||
})
|
||||
95
src/mockups/perspective.ts
Normal file
95
src/mockups/perspective.ts
Normal file
@ -0,0 +1,95 @@
|
||||
import type { PhotoMockupDefinition } from './catalog'
|
||||
|
||||
const PLACEHOLDER_SCREEN_WIDTH = 139.2
|
||||
|
||||
type PerspectiveMappingOptions = {
|
||||
width: number
|
||||
height: number
|
||||
definition: PhotoMockupDefinition
|
||||
hasScreenshot: boolean
|
||||
}
|
||||
|
||||
const solveLinearSystem = (matrix: number[][], vector: number[]) => {
|
||||
const size = vector.length
|
||||
const augmented = matrix.map((row, index) => [...row, vector[index]])
|
||||
|
||||
for (let column = 0; column < size; column += 1) {
|
||||
let pivot = column
|
||||
for (let row = column + 1; row < size; row += 1) {
|
||||
const candidate = augmented[row]?.[column] ?? 0
|
||||
const currentPivot = augmented[pivot]?.[column] ?? 0
|
||||
if (Math.abs(candidate) > Math.abs(currentPivot)) pivot = row
|
||||
}
|
||||
const columnRow = augmented[column]
|
||||
const pivotRow = augmented[pivot]
|
||||
if (!columnRow || !pivotRow) return null
|
||||
augmented[column] = pivotRow
|
||||
augmented[pivot] = columnRow
|
||||
const activeRow = pivotRow
|
||||
const divisor = activeRow[column]
|
||||
if (divisor === undefined || Math.abs(divisor) < 1e-10) return null
|
||||
for (let item = column; item <= size; item += 1) {
|
||||
activeRow[item] = (activeRow[item] ?? 0) / divisor
|
||||
}
|
||||
for (let row = 0; row < size; row += 1) {
|
||||
if (row === column) continue
|
||||
const targetRow = augmented[row]
|
||||
if (!targetRow) return null
|
||||
const factor = targetRow[column] ?? 0
|
||||
for (let item = column; item <= size; item += 1) {
|
||||
targetRow[item] = (targetRow[item] ?? 0) - factor * (activeRow[item] ?? 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return augmented.map((row) => row[size] ?? 0)
|
||||
}
|
||||
|
||||
export const createPerspectiveMapping = ({
|
||||
width,
|
||||
height,
|
||||
definition,
|
||||
hasScreenshot,
|
||||
}: PerspectiveMappingOptions) => {
|
||||
// HTML slides are laid out at export size and scaled down as one surface.
|
||||
// Giving real screenshots a source plane as wide as the unscaled mockup
|
||||
// prevents Chromium from enlarging a small intermediate texture first.
|
||||
const sourceWidth = hasScreenshot
|
||||
? Math.max(PLACEHOLDER_SCREEN_WIDTH, width)
|
||||
: PLACEHOLDER_SCREEN_WIDTH
|
||||
const sourceHeight = sourceWidth / definition.sourceAspectRatio
|
||||
const source: [number, number][] = [
|
||||
[0, 0],
|
||||
[sourceWidth, 0],
|
||||
[sourceWidth, sourceHeight],
|
||||
[0, sourceHeight],
|
||||
]
|
||||
const target: [number, number][] = definition.screenQuad.map(
|
||||
(point) => [point.x * width, point.y * height],
|
||||
)
|
||||
const equations: number[][] = []
|
||||
const values: number[] = []
|
||||
|
||||
for (let index = 0; index < 4; index += 1) {
|
||||
const sourcePoint = source[index]
|
||||
const targetPoint = target[index]
|
||||
if (!sourcePoint || !targetPoint) {
|
||||
return { transform: 'none', sourceWidth, sourceHeight }
|
||||
}
|
||||
const [x, y] = sourcePoint
|
||||
const [targetX, targetY] = targetPoint
|
||||
equations.push([x, y, 1, 0, 0, 0, -targetX * x, -targetX * y])
|
||||
values.push(targetX)
|
||||
equations.push([0, 0, 0, x, y, 1, -targetY * x, -targetY * y])
|
||||
values.push(targetY)
|
||||
}
|
||||
|
||||
const solved = solveLinearSystem(equations, values)
|
||||
if (!solved) return { transform: 'none', sourceWidth, sourceHeight }
|
||||
const [a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0] = solved
|
||||
return {
|
||||
transform: `matrix3d(${a},${d},0,${g},${b},${e},0,${h},0,0,1,0,${c},${f},0,1)`,
|
||||
sourceWidth,
|
||||
sourceHeight,
|
||||
}
|
||||
}
|
||||
@ -28,4 +28,21 @@ describe('persisted project normalization', () => {
|
||||
savedAt: 20,
|
||||
})).toBeNull()
|
||||
})
|
||||
|
||||
it('carries the interrupted-generation marker only when it is exactly true', () => {
|
||||
const record = {
|
||||
id: 'project-run',
|
||||
projectName: 'Mid-run project',
|
||||
slides: [],
|
||||
uploads: [],
|
||||
createdAt: 10,
|
||||
savedAt: 20,
|
||||
}
|
||||
|
||||
expect(normalizePersistedProject({ ...record, interruptedGeneration: true }))
|
||||
.toMatchObject({ interruptedGeneration: true })
|
||||
expect(normalizePersistedProject(record)).not.toHaveProperty('interruptedGeneration')
|
||||
expect(normalizePersistedProject({ ...record, interruptedGeneration: 'yes' }))
|
||||
.not.toHaveProperty('interruptedGeneration')
|
||||
})
|
||||
})
|
||||
|
||||
@ -17,6 +17,12 @@ export type PersistedProject = {
|
||||
uploads: UploadAsset[]
|
||||
createdAt: number
|
||||
savedAt: number
|
||||
/**
|
||||
* Set on saves that happen while an AI generation is running. A project that
|
||||
* still carries it on load was closed mid-run, and the editor tells the user
|
||||
* about the interrupted generation once before clearing it.
|
||||
*/
|
||||
interruptedGeneration?: true
|
||||
}
|
||||
|
||||
export type ProjectSummary = Pick<PersistedProject, 'id' | 'projectName' | 'createdAt' | 'savedAt'>
|
||||
@ -41,6 +47,7 @@ export const normalizePersistedProject = (value: unknown): PersistedProject | nu
|
||||
uploads: project.uploads,
|
||||
createdAt: typeof project.createdAt === 'number' ? project.createdAt : project.savedAt,
|
||||
savedAt: project.savedAt,
|
||||
...(project.interruptedGeneration === true ? { interruptedGeneration: true as const } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -712,6 +712,14 @@ button:disabled { cursor: not-allowed; opacity: .35; }
|
||||
line-height: 1.35;
|
||||
color: var(--muted);
|
||||
}
|
||||
.ai-modal-overlay-toggle__copy .ai-modal-overlay-toggle__caution {
|
||||
font-weight: 600;
|
||||
color: #0369a1;
|
||||
}
|
||||
.ai-modal-overlay-toggle .ai-modal-overlay-toggle__badge {
|
||||
background: #e0f2fe;
|
||||
color: #0369a1;
|
||||
}
|
||||
.ai-modal-copy-prompt {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
@ -202,6 +202,20 @@ select:focus-visible {
|
||||
.project-delete-dialog .project-delete-confirm:hover { color: white; background: color-mix(in oklch, var(--destructive) 88%, black); }
|
||||
.project-delete-dialog button:focus-visible { outline: none; box-shadow: 0 0 0 2px color-mix(in oklch, var(--ring) 45%, transparent); }
|
||||
|
||||
.ai-run-cancel-dialog { width: min(calc(100vw - 32px), 360px); max-width: 360px; gap: 0; padding: 0; overflow: hidden; border-radius: var(--radius-lg); box-shadow: 0 18px 48px oklch(0 0 0 / 18%), 0 2px 8px oklch(0 0 0 / 8%); }
|
||||
.ai-run-cancel-dialog [data-slot='alert-dialog-header'] { display: grid; grid-template-columns: 34px minmax(0, 1fr); grid-template-rows: auto auto; place-items: start; gap: 3px 12px; padding: 18px 18px 15px; text-align: left; }
|
||||
.ai-run-cancel-dialog [data-slot='alert-dialog-media'] { grid-row: 1 / span 2; width: 34px; height: 34px; margin: 0; color: var(--primary); background: color-mix(in oklch, var(--primary) 11%, var(--background)); border-radius: var(--radius-md); }
|
||||
.ai-run-cancel-dialog [data-slot='alert-dialog-title'] { grid-column: 2; color: var(--foreground); font-size: 13px; font-weight: 580; line-height: 18px; letter-spacing: 0; }
|
||||
.ai-run-cancel-dialog [data-slot='alert-dialog-description'] { grid-column: 2; color: var(--muted-foreground); font-size: 13px; font-weight: 400; line-height: 18px; text-wrap: pretty; }
|
||||
.ai-run-cancel-dialog [data-slot='alert-dialog-footer'] { margin: 0; padding: 11px 14px 13px; flex-direction: row; justify-content: flex-end; gap: 7px; background: var(--background); border-top: 1px solid var(--border); border-radius: 0; }
|
||||
.ai-run-cancel-dialog [data-slot='alert-dialog-action'],
|
||||
.ai-run-cancel-dialog [data-slot='alert-dialog-cancel'] { min-width: 78px; height: 29px; padding: 0 10px; border-radius: var(--radius-md); font-size: 11px; font-weight: 520; line-height: 1; }
|
||||
.ai-run-cancel-dialog .ai-run-cancel-keep { color: var(--foreground); background: var(--background); border-color: var(--input); }
|
||||
.ai-run-cancel-dialog .ai-run-cancel-keep:hover { background: var(--muted); }
|
||||
.ai-run-cancel-dialog .ai-run-cancel-confirm { color: white; background: var(--destructive); border-color: var(--destructive); box-shadow: 0 1px 2px color-mix(in oklch, var(--destructive) 28%, transparent); }
|
||||
.ai-run-cancel-dialog .ai-run-cancel-confirm:hover { color: white; background: color-mix(in oklch, var(--destructive) 88%, black); }
|
||||
.ai-run-cancel-dialog button:focus-visible { outline: none; box-shadow: 0 0 0 2px color-mix(in oklch, var(--ring) 45%, transparent); }
|
||||
|
||||
.ai-keys-dialog {
|
||||
width: min(calc(100vw - 32px), 380px);
|
||||
max-width: 380px;
|
||||
@ -362,6 +376,133 @@ select:focus-visible {
|
||||
box-shadow: 0 0 0 2px color-mix(in oklch, var(--ring) 45%, transparent);
|
||||
}
|
||||
|
||||
.share-link-dialog {
|
||||
width: min(calc(100vw - 32px), 380px);
|
||||
max-width: 380px;
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: 0 18px 48px oklch(0 0 0 / 18%), 0 2px 8px oklch(0 0 0 / 8%);
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-header'] {
|
||||
display: grid;
|
||||
grid-template-columns: 34px minmax(0, 1fr);
|
||||
grid-template-rows: auto auto;
|
||||
place-items: start;
|
||||
gap: 3px 12px;
|
||||
padding: 18px 18px 14px;
|
||||
text-align: left;
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-media'] {
|
||||
grid-row: 1 / span 2;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
margin: 0;
|
||||
color: var(--foreground);
|
||||
background: var(--muted);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-title'] {
|
||||
grid-column: 2;
|
||||
color: var(--foreground);
|
||||
font-size: 13px;
|
||||
font-weight: 580;
|
||||
line-height: 18px;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-description'] {
|
||||
grid-column: 2;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
line-height: 16px;
|
||||
text-wrap: pretty;
|
||||
}
|
||||
.share-link-dialog-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 0 18px 16px;
|
||||
}
|
||||
.share-link-dialog-preview {
|
||||
max-height: 44px;
|
||||
padding: 8px 10px;
|
||||
overflow: hidden;
|
||||
color: var(--muted-foreground);
|
||||
background: color-mix(in oklch, var(--muted) 70%, transparent);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
font-family: ui-monospace, 'SFMono-Regular', Menlo, monospace;
|
||||
font-size: 10px;
|
||||
line-height: 1.4;
|
||||
word-break: break-all;
|
||||
user-select: none;
|
||||
}
|
||||
.share-link-dialog-status,
|
||||
.share-link-dialog-meta {
|
||||
margin: 0;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 10px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.share-link-dialog-error {
|
||||
margin: 0;
|
||||
color: var(--destructive);
|
||||
font-size: 10px;
|
||||
font-weight: 540;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.share-link-dialog-fallback {
|
||||
height: 28px;
|
||||
padding: 0 10px;
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
border: 1px solid var(--input);
|
||||
border-radius: var(--radius-md);
|
||||
font-family: ui-monospace, 'SFMono-Regular', Menlo, monospace;
|
||||
font-size: 10px;
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-footer'] {
|
||||
margin: 0;
|
||||
padding: 11px 14px 13px;
|
||||
flex-direction: row;
|
||||
justify-content: flex-end;
|
||||
gap: 7px;
|
||||
background: var(--muted);
|
||||
border-top: 1px solid var(--border);
|
||||
border-radius: 0 0 var(--radius-lg) var(--radius-lg);
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-cancel'],
|
||||
.share-link-dialog .share-link-dialog-copy {
|
||||
min-width: 78px;
|
||||
height: 29px;
|
||||
padding: 0 10px;
|
||||
border-radius: var(--radius-md);
|
||||
font-size: 11px;
|
||||
font-weight: 520;
|
||||
line-height: 1;
|
||||
}
|
||||
.share-link-dialog .share-link-dialog-close {
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
border-color: var(--input);
|
||||
}
|
||||
.share-link-dialog .share-link-dialog-close:hover { background: var(--accent); }
|
||||
.share-link-dialog .share-link-dialog-copy {
|
||||
color: white;
|
||||
background: var(--foreground);
|
||||
border-color: var(--foreground);
|
||||
}
|
||||
.share-link-dialog .share-link-dialog-copy:hover:not(:disabled) {
|
||||
color: white;
|
||||
background: color-mix(in oklch, var(--foreground) 88%, black);
|
||||
}
|
||||
.share-link-dialog button:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px color-mix(in oklch, var(--ring) 45%, transparent);
|
||||
}
|
||||
|
||||
.history-actions button:hover {
|
||||
background: var(--accent);
|
||||
color: var(--accent-foreground);
|
||||
@ -770,6 +911,16 @@ select:focus-visible {
|
||||
.ai-modal-overlay-toggle__copy small,
|
||||
.ai-modal-copy-prompt { color: var(--muted-foreground); }
|
||||
|
||||
/* Light-blue "Experimental" badge and the matching caution line; the sky hue
|
||||
is mixed with the theme tokens so both light and dark mode stay legible. */
|
||||
.ai-modal-overlay-toggle .ai-modal-overlay-toggle__badge {
|
||||
background: color-mix(in oklch, oklch(0.68 0.13 240) 22%, var(--background));
|
||||
color: color-mix(in oklch, oklch(0.68 0.13 240) 65%, var(--foreground));
|
||||
}
|
||||
.ai-modal-overlay-toggle__copy .ai-modal-overlay-toggle__caution {
|
||||
color: color-mix(in oklch, oklch(0.68 0.13 240) 55%, var(--foreground));
|
||||
}
|
||||
|
||||
.ai-provider-description { color: var(--muted-foreground); }
|
||||
|
||||
.ai-provider-warning {
|
||||
|
||||
1
src/vite-env.d.ts
vendored
1
src/vite-env.d.ts
vendored
@ -10,6 +10,7 @@ interface ImportMetaEnv {
|
||||
readonly VITE_ANTHROPIC_API_KEY?: string
|
||||
readonly VITE_XAI_API_KEY?: string
|
||||
readonly VITE_OPENROUTER_API_KEY?: string
|
||||
readonly VITE_OPENCODE_API_KEY?: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
|
||||
@ -10,12 +10,33 @@ export default defineConfig(({ command, mode }) => {
|
||||
const env = loadEnv(mode, process.cwd(), '')
|
||||
const aiLoggingValue = env['SHOTLUMA_AI_LOGGING'] ?? env['FRAMEFLOW_AI_LOGGING']
|
||||
const isAiLoggingEnabled = aiLoggingValue?.trim().toLowerCase() === 'true'
|
||||
const moonshotProxy = {
|
||||
const moonshotAndOpencodeProxy = {
|
||||
'/api/moonshot': {
|
||||
target: 'https://api.moonshot.ai',
|
||||
changeOrigin: true,
|
||||
rewrite: (requestPath: string) => requestPath.replace(/^\/api\/moonshot/, ''),
|
||||
},
|
||||
'/api/opencode/go': {
|
||||
target: 'https://opencode.ai',
|
||||
changeOrigin: true,
|
||||
rewrite: (requestPath: string) =>
|
||||
requestPath.replace(/^\/api\/opencode\/go/, '/zen/go') || '/zen/go',
|
||||
},
|
||||
'/api/opencode/zen': {
|
||||
target: 'https://opencode.ai',
|
||||
changeOrigin: true,
|
||||
rewrite: (requestPath: string) =>
|
||||
requestPath.replace(/^\/api\/opencode\/zen/, '/zen') || '/zen',
|
||||
},
|
||||
}
|
||||
// Local dev has no share Worker, so short share links go through the
|
||||
// deployed one; the client falls back to self-contained links on failure.
|
||||
const devProxy = {
|
||||
...moonshotAndOpencodeProxy,
|
||||
'/api/share': {
|
||||
target: 'https://app.shotluma.com',
|
||||
changeOrigin: true,
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
@ -40,10 +61,10 @@ export default defineConfig(({ command, mode }) => {
|
||||
server: {
|
||||
host: '127.0.0.1',
|
||||
port: Number(process.env['PORT']) || 4173,
|
||||
proxy: moonshotProxy,
|
||||
proxy: devProxy,
|
||||
},
|
||||
preview: {
|
||||
proxy: moonshotProxy,
|
||||
proxy: devProxy,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
@ -10,7 +10,9 @@ export default defineConfig({
|
||||
reporter: ['text', 'lcov'],
|
||||
include: [
|
||||
'src/ai/chroma-key.ts',
|
||||
'src/ai/describe-images.ts',
|
||||
'src/ai/normalize-copy.ts',
|
||||
'src/ai/opencode-models.ts',
|
||||
'src/ai/overlay-asset-prompt.ts',
|
||||
'src/ai/provider-config.ts',
|
||||
'src/ai/provider-catalog.ts',
|
||||
@ -19,11 +21,15 @@ export default defineConfig({
|
||||
'src/app/export-image-sizing.ts',
|
||||
'src/asset-sources.ts',
|
||||
'src/app/project-utils.ts',
|
||||
'src/app/share-link.ts',
|
||||
'src/app/share-preview-palette.ts',
|
||||
'src/editor/drag-bounds.ts',
|
||||
'src/editor/element-utils.ts',
|
||||
'src/editor/nudge.ts',
|
||||
'src/editor/resize-element.ts',
|
||||
'src/editor/screen-span.ts',
|
||||
'src/editor/slide-operations.ts',
|
||||
'src/mockups/perspective.ts',
|
||||
],
|
||||
thresholds: {
|
||||
lines: 80,
|
||||
|
||||
@ -2,9 +2,31 @@
|
||||
"$schema": "./node_modules/wrangler/config-schema.json",
|
||||
"name": "shotluma-app",
|
||||
"compatibility_date": "2026-08-03",
|
||||
"main": "scripts/shotluma-worker.ts",
|
||||
"assets": {
|
||||
"directory": "./dist",
|
||||
"not_found_handling": "single-page-application"
|
||||
"binding": "ASSETS",
|
||||
"not_found_handling": "single-page-application",
|
||||
"run_worker_first": ["/api/opencode/*", "/api/share", "/api/share/*", "/s/*"]
|
||||
},
|
||||
"kv_namespaces": [
|
||||
{
|
||||
"binding": "SHARE_KV",
|
||||
"id": "a5c85baed396460b8f79536f88692afc"
|
||||
}
|
||||
],
|
||||
"unsafe": {
|
||||
"bindings": [
|
||||
{
|
||||
"type": "ratelimit",
|
||||
"name": "SHARE_RATE",
|
||||
"namespace_id": "2101",
|
||||
"simple": {
|
||||
"limit": 10,
|
||||
"period": 60
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"routes": [
|
||||
{
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user