mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7eab377b7f | ||
|
|
6da4b63a85 | ||
|
|
565ae93aed | ||
|
|
429dafce92 | ||
|
|
49889be240 | ||
|
|
c285dbcd05 | ||
|
|
b80205a942 |
No files matched your search
@@ -1,5 +1,19 @@
|
||||
# Changelog
|
||||
|
||||
## [9.11.4] - 2026-04-17
|
||||
|
||||
### Fixed
|
||||
- Preview pane no longer gets stuck on stale builds during rapid edits
|
||||
|
||||
### Changed
|
||||
- Reduce AI costs for Anthropic models via OpenRouter by caching tool definitions across turns
|
||||
|
||||
## [9.11.3] - 2026-04-12
|
||||
|
||||
### Fixed
|
||||
- App publish dialog now appears on mobile devices
|
||||
- Changelog available offline via ServiceWorker precache
|
||||
|
||||
## [9.11.2] - 2026-04-06
|
||||
|
||||
### Fixed
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "shakespeare.diy",
|
||||
"version": "9.11.0",
|
||||
"version": "9.11.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "shakespeare.diy",
|
||||
"version": "9.11.0",
|
||||
"version": "9.11.2",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@capacitor/app": "^8.1.0",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
||||
"homepage": "https://shakespeare.diy",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "9.11.2",
|
||||
"version": "9.11.4",
|
||||
"type": "module",
|
||||
"author": {
|
||||
"name": "shakespeare.diy",
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
# Changelog
|
||||
|
||||
## [9.11.4] - 2026-04-17
|
||||
|
||||
### Fixed
|
||||
- Preview pane no longer gets stuck on stale builds during rapid edits
|
||||
|
||||
### Changed
|
||||
- Reduce AI costs for Anthropic models via OpenRouter by caching tool definitions across turns
|
||||
|
||||
## [9.11.3] - 2026-04-12
|
||||
|
||||
### Fixed
|
||||
- App publish dialog now appears on mobile devices
|
||||
- Changelog available offline via ServiceWorker precache
|
||||
|
||||
## [9.11.2] - 2026-04-06
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -91,6 +91,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
|
||||
const [isLogsOpen, setIsLogsOpen] = useState(false);
|
||||
// Incremented to force a full remount of the preview iframe. Using a
|
||||
// remount (via React key) is more reliable than sending a `refresh`
|
||||
// JSON-RPC to the nested iframe.diy frames: messages can be silently
|
||||
// dropped if the inner iframe is mid-reload, not yet mounted, or if
|
||||
// the outer frame's handshake is still pending. A remount always works.
|
||||
const [iframeReloadKey, setIframeReloadKey] = useState(0);
|
||||
const previewContainerRef = useRef<HTMLDivElement>(null);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const iframePanelRef = useRef<ImperativePanelHandle>(null);
|
||||
@@ -284,8 +290,14 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
}, [sendNavigationCommand]);
|
||||
|
||||
const refreshIframe = useCallback(() => {
|
||||
sendNavigationCommand('refresh');
|
||||
}, [sendNavigationCommand]);
|
||||
// Force a full remount of the iframe rather than sending a `refresh`
|
||||
// JSON-RPC command. The RPC path is unreliable during rapid build
|
||||
// cycles because the command has to traverse two iframes (outer
|
||||
// iframe.diy frame → inner app iframe) and can be silently dropped
|
||||
// if the inner iframe is mid-reload, not yet mounted, or the outer
|
||||
// frame's handshake is still pending.
|
||||
setIframeReloadKey((n) => n + 1);
|
||||
}, []);
|
||||
|
||||
const toggleFullscreen = useCallback(() => {
|
||||
setIsFullscreen(prev => !prev);
|
||||
@@ -709,7 +721,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
)}
|
||||
>
|
||||
<iframe
|
||||
key={projectId}
|
||||
key={`${projectId}:${iframeReloadKey}`}
|
||||
ref={iframeRef}
|
||||
src={`${previewOrigin}/`}
|
||||
className="w-full h-full border-0"
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type OpenAI from 'openai';
|
||||
import { applyOpenRouterTransforms } from './ai-client';
|
||||
|
||||
/**
|
||||
* Helper: minimal valid ChatCompletionCreateParams for transform tests.
|
||||
*/
|
||||
function makeBody(overrides: Partial<OpenAI.Chat.Completions.ChatCompletionCreateParams> = {})
|
||||
: OpenAI.Chat.Completions.ChatCompletionCreateParams {
|
||||
return {
|
||||
model: 'anthropic/claude-opus-4.6',
|
||||
messages: [
|
||||
{ role: 'system', content: 'you are helpful' },
|
||||
{ role: 'user', content: 'hello' },
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('applyOpenRouterTransforms', () => {
|
||||
it('adds usage accounting to the body regardless of model', () => {
|
||||
const body = makeBody({ model: 'openai/gpt-4' });
|
||||
applyOpenRouterTransforms(body);
|
||||
expect((body as { usage?: { include?: boolean } }).usage).toEqual({ include: true });
|
||||
});
|
||||
|
||||
it('does not apply cache_control for non-Anthropic models', () => {
|
||||
const body = makeBody({
|
||||
model: 'openai/gpt-4',
|
||||
tools: [
|
||||
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
|
||||
],
|
||||
});
|
||||
applyOpenRouterTransforms(body);
|
||||
// messages remain as plain strings (no normalization)
|
||||
expect(body.messages[0].content).toBe('you are helpful');
|
||||
// tools untouched
|
||||
expect((body.tools![0] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||
});
|
||||
|
||||
it('places cache_control on the last tool for Anthropic models', () => {
|
||||
const body = makeBody({
|
||||
tools: [
|
||||
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
|
||||
{ type: 'function', function: { name: 't2', description: '', parameters: { type: 'object' } } },
|
||||
{ type: 'function', function: { name: 't3', description: '', parameters: { type: 'object' } } },
|
||||
],
|
||||
});
|
||||
applyOpenRouterTransforms(body);
|
||||
|
||||
// Only the LAST tool gets cache_control — Anthropic caches everything
|
||||
// up to and including the marked block, so marking the last tool is
|
||||
// sufficient and we spend only one of the 4 breakpoints.
|
||||
expect((body.tools![0] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||
expect((body.tools![1] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||
expect((body.tools![2] as { cache_control?: { type: string } }).cache_control)
|
||||
.toEqual({ type: 'ephemeral' });
|
||||
});
|
||||
|
||||
it('places cache_control on the system message and last two non-system messages', () => {
|
||||
const body = makeBody({
|
||||
messages: [
|
||||
{ role: 'system', content: 'you are helpful' },
|
||||
{ role: 'user', content: 'first' },
|
||||
{ role: 'assistant', content: 'reply 1' },
|
||||
{ role: 'user', content: 'second' },
|
||||
{ role: 'assistant', content: 'reply 2' },
|
||||
],
|
||||
});
|
||||
applyOpenRouterTransforms(body);
|
||||
|
||||
const hasCache = (m: OpenAI.Chat.Completions.ChatCompletionMessageParam): boolean => {
|
||||
if (!Array.isArray(m.content)) return false;
|
||||
return m.content.some((b) => {
|
||||
const block = b as { cache_control?: unknown };
|
||||
return block.cache_control !== undefined;
|
||||
});
|
||||
};
|
||||
|
||||
// System: cached
|
||||
expect(hasCache(body.messages[0])).toBe(true);
|
||||
// Old turns: not cached
|
||||
expect(hasCache(body.messages[1])).toBe(false);
|
||||
expect(hasCache(body.messages[2])).toBe(false);
|
||||
// Last two non-system: cached
|
||||
expect(hasCache(body.messages[3])).toBe(true);
|
||||
expect(hasCache(body.messages[4])).toBe(true);
|
||||
});
|
||||
|
||||
it('normalizes string content to text block arrays for Anthropic', () => {
|
||||
const body = makeBody();
|
||||
applyOpenRouterTransforms(body);
|
||||
// System and user both turned into arrays of text blocks
|
||||
expect(Array.isArray(body.messages[0].content)).toBe(true);
|
||||
expect(Array.isArray(body.messages[1].content)).toBe(true);
|
||||
const sysBlocks = body.messages[0].content as Array<{ type: string; text: string }>;
|
||||
expect(sysBlocks[0]).toEqual(
|
||||
expect.objectContaining({ type: 'text', text: 'you are helpful' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not crash when tools is undefined or empty', () => {
|
||||
const a = makeBody();
|
||||
expect(() => applyOpenRouterTransforms(a)).not.toThrow();
|
||||
expect(a.tools).toBeUndefined();
|
||||
|
||||
const b = makeBody({ tools: [] });
|
||||
expect(() => applyOpenRouterTransforms(b)).not.toThrow();
|
||||
expect(b.tools).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not mutate the original tools array reference (uses structuredClone)', () => {
|
||||
const originalTools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
|
||||
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
|
||||
];
|
||||
const originalRef = originalTools;
|
||||
const body = makeBody({ tools: originalTools });
|
||||
applyOpenRouterTransforms(body);
|
||||
|
||||
// body.tools is now a clone, original array untouched
|
||||
expect(body.tools).not.toBe(originalRef);
|
||||
expect((originalTools[0] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||
// But body.tools has cache_control
|
||||
expect((body.tools![0] as { cache_control?: { type: string } }).cache_control)
|
||||
.toEqual({ type: 'ephemeral' });
|
||||
});
|
||||
|
||||
it('produces byte-identical output across two calls with the same input (cache stability)', () => {
|
||||
// This is the property the Anthropic cache relies on: the tools block
|
||||
// hashes to the same value on every turn. If this test ever fails, tool
|
||||
// caching will silently stop working.
|
||||
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
|
||||
{ type: 'function', function: { name: 'a', description: 'x', parameters: { type: 'object', properties: { foo: { type: 'string' } } } } },
|
||||
{ type: 'function', function: { name: 'b', description: 'y', parameters: { type: 'object' } } },
|
||||
];
|
||||
|
||||
const body1 = makeBody({ tools: structuredClone(tools) });
|
||||
const body2 = makeBody({ tools: structuredClone(tools) });
|
||||
applyOpenRouterTransforms(body1);
|
||||
applyOpenRouterTransforms(body2);
|
||||
|
||||
expect(JSON.stringify(body1.tools)).toEqual(JSON.stringify(body2.tools));
|
||||
});
|
||||
});
|
||||
+70
-28
@@ -74,34 +74,7 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
||||
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||
// OpenRouter-specific hacks
|
||||
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
||||
// Usage accounting field to get token usage and cost per request
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||
|
||||
// Prompt caching for Claude models
|
||||
// https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
|
||||
if (body.model.startsWith("anthropic/")) {
|
||||
// First normalize the message history to use content blocks
|
||||
body.messages = structuredClone(body.messages);
|
||||
body.messages = body.messages.map((m) => {
|
||||
if (m.role !== "function" && typeof m.content === "string") {
|
||||
return { ...m, content: [{ type: "text", text: m.content }] };
|
||||
} else {
|
||||
return m;
|
||||
}
|
||||
});
|
||||
|
||||
const systemMessage = body.messages.find((m) => m.role === "system");
|
||||
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
|
||||
const lastTwoMessages = nonSystemMessages.slice(-2);
|
||||
|
||||
if (systemMessage) {
|
||||
addCacheControl(systemMessage);
|
||||
}
|
||||
for (const msg of lastTwoMessages) {
|
||||
addCacheControl(msg);
|
||||
}
|
||||
}
|
||||
applyOpenRouterTransforms(body);
|
||||
}
|
||||
|
||||
return createCompletion(body, options);
|
||||
@@ -110,6 +83,75 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
||||
return openai;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply OpenRouter-specific request body mutations: opt into usage accounting,
|
||||
* and (for Anthropic models) place `cache_control` breakpoints so the tools
|
||||
* array, system prompt, and last two messages get cached. Exported for tests.
|
||||
*
|
||||
* References:
|
||||
* - OpenRouter prompt caching guide:
|
||||
* https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
|
||||
* - OpenRouter tool caching announcement: "gif-prompts-omni-search-tool-caching-and-byok-flags"
|
||||
* - Anthropic prompt caching docs:
|
||||
* https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
|
||||
*
|
||||
* Anthropic's cache hierarchy is `tools` → `system` → `messages`. We use all
|
||||
* four breakpoints Anthropic allows per request:
|
||||
* 1. last tool definition (caches the entire tools array)
|
||||
* 2. system message (caches system prompt + AGENTS.md)
|
||||
* 3. second-to-last non-system (caches most of conversation)
|
||||
* 4. last non-system (caches everything including latest msg)
|
||||
*/
|
||||
export function applyOpenRouterTransforms(
|
||||
body: OpenAI.Chat.Completions.ChatCompletionCreateParams,
|
||||
): void {
|
||||
// Usage accounting field to get token usage and cost per request.
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||
|
||||
if (!body.model.startsWith("anthropic/")) return;
|
||||
|
||||
// Normalize the message history to use content blocks so we can attach
|
||||
// cache_control to individual text parts.
|
||||
body.messages = structuredClone(body.messages);
|
||||
body.messages = body.messages.map((m) => {
|
||||
if (m.role !== "function" && typeof m.content === "string") {
|
||||
return { ...m, content: [{ type: "text", text: m.content }] };
|
||||
} else {
|
||||
return m;
|
||||
}
|
||||
});
|
||||
|
||||
const systemMessage = body.messages.find((m) => m.role === "system");
|
||||
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
|
||||
const lastTwoMessages = nonSystemMessages.slice(-2);
|
||||
|
||||
if (systemMessage) {
|
||||
addCacheControl(systemMessage);
|
||||
}
|
||||
for (const msg of lastTwoMessages) {
|
||||
addCacheControl(msg);
|
||||
}
|
||||
|
||||
// Cache the tools array by marking the last tool with cache_control.
|
||||
// Anthropic caches everything up to and including the marked block, so
|
||||
// marking just the last tool caches the whole array. The tools array
|
||||
// must be byte-stable across turns for cache hits — Shakespeare builds
|
||||
// it once per session in `ChatPane`, so this holds as long as we don't
|
||||
// mutate session.tools mid-session.
|
||||
//
|
||||
// Note: the OpenAI SDK serializes the body via plain `JSON.stringify`
|
||||
// (see node_modules/openai/internal/request-options) and does not strip
|
||||
// unknown fields, so the `cache_control` property survives the trip to
|
||||
// OpenRouter.
|
||||
if (body.tools && body.tools.length > 0) {
|
||||
body.tools = structuredClone(body.tools);
|
||||
const lastTool = body.tools[body.tools.length - 1];
|
||||
(lastTool as { cache_control?: { type: "ephemeral" } })
|
||||
.cache_control = { type: "ephemeral" };
|
||||
}
|
||||
}
|
||||
|
||||
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
|
||||
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
|
||||
if (Array.isArray(msg.content)) {
|
||||
|
||||
@@ -142,7 +142,7 @@ export function getPreviewInjectedScript(): string {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: '2.0',
|
||||
id: ++rpcId,
|
||||
id: rpcId(),
|
||||
method: 'updateNavigationState',
|
||||
params: {
|
||||
currentUrl: semanticPath,
|
||||
@@ -259,7 +259,7 @@ export function getPreviewInjectedScript(): string {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: '2.0',
|
||||
id: ++rpcId,
|
||||
id: rpcId(),
|
||||
method: 'console',
|
||||
params: {
|
||||
level: 'error',
|
||||
@@ -279,7 +279,7 @@ export function getPreviewInjectedScript(): string {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: '2.0',
|
||||
id: ++rpcId,
|
||||
id: rpcId(),
|
||||
method: 'console',
|
||||
params: {
|
||||
level: 'error',
|
||||
|
||||
@@ -389,6 +389,11 @@ export function ProjectView() {
|
||||
open={deleteDialogOpen}
|
||||
onOpenChange={setDeleteDialogOpen}
|
||||
/>
|
||||
<AppDialog
|
||||
projectId={project.id}
|
||||
open={appDialogOpen}
|
||||
onOpenChange={setAppDialogOpen}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ export default defineConfig(() => ({
|
||||
plugins: [
|
||||
react(),
|
||||
VitePWA({
|
||||
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3'],
|
||||
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3', 'CHANGELOG.md'],
|
||||
manifest: false, // Use existing manifest.webmanifest from public folder
|
||||
workbox: {
|
||||
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
|
||||
|
||||
Reference in new issue
Block a user