mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7eab377b7f | ||
|
|
6da4b63a85 | ||
|
|
565ae93aed | ||
|
|
429dafce92 | ||
|
|
49889be240 |
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
-25
@@ -5001,7 +5001,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5015,7 +5014,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5029,7 +5027,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5043,7 +5040,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5057,7 +5053,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5071,7 +5066,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5085,7 +5079,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5099,7 +5092,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5113,7 +5105,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5127,7 +5118,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5141,7 +5131,6 @@
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5155,7 +5144,6 @@
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5169,7 +5157,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5183,7 +5170,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5197,7 +5183,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5211,7 +5196,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5225,7 +5209,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5239,7 +5222,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5253,7 +5235,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5267,7 +5248,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5281,7 +5261,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5295,7 +5274,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5309,7 +5287,6 @@
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5323,7 +5300,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5337,7 +5313,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
+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
|
||||
|
||||
@@ -895,231 +895,6 @@ export function AIProviderConfigDialog({
|
||||
}
|
||||
};
|
||||
|
||||
const escapeHtml = (str: string): string =>
|
||||
str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
||||
|
||||
const handlePrintReceipt = (payment: Payment) => {
|
||||
const receiptDate = new Date((payment.completed_at ?? payment.created_at) * 1000);
|
||||
const formattedDate = new Intl.DateTimeFormat('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
}).format(receiptDate);
|
||||
const formattedTime = new Intl.DateTimeFormat('en-US', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(receiptDate);
|
||||
|
||||
const paymentMethodDisplay = payment.method === 'stripe' ? t('creditCard') : t('lightning');
|
||||
const statusDisplay = payment.status.charAt(0).toUpperCase() + payment.status.slice(1);
|
||||
|
||||
const printWindow = window.open('', '_blank');
|
||||
if (!printWindow) {
|
||||
toast({
|
||||
title: t('printFailed'),
|
||||
description: t('failedToOpenPrintWindow'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const printHTML = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>${t('receipt')} - ${escapeHtml(payment.id)}</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
padding: 40px 20px;
|
||||
background: white;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.receipt {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
border: 1px solid #e0e0e0;
|
||||
padding: 48px 40px;
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
padding-bottom: 28px;
|
||||
border-bottom: 2px solid #000;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.company-name {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.5px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.company-detail {
|
||||
font-size: 13px;
|
||||
color: #555;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.company-detail a {
|
||||
color: #555;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.receipt-title {
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 2px;
|
||||
text-transform: uppercase;
|
||||
color: #333;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.details-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 140px 1fr;
|
||||
gap: 8px 16px;
|
||||
margin-bottom: 28px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.details-grid dt {
|
||||
color: #666;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.details-grid dd {
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.divider {
|
||||
border: none;
|
||||
border-top: 1px solid #e0e0e0;
|
||||
margin: 0 0 28px 0;
|
||||
}
|
||||
|
||||
.line-items {
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.line-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 6px 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.line-item-label {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.line-item-value {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.line-item-total {
|
||||
border-top: 1px solid #000;
|
||||
margin-top: 8px;
|
||||
padding-top: 10px;
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.footer {
|
||||
text-align: center;
|
||||
padding-top: 28px;
|
||||
border-top: 1px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.footer p {
|
||||
font-size: 13px;
|
||||
color: #666;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
@media print {
|
||||
body {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.receipt {
|
||||
border: none;
|
||||
padding: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="receipt">
|
||||
<div class="header">
|
||||
<div class="company-name">Soapbox Technology, LLC</div>
|
||||
<div class="company-detail">
|
||||
<a href="https://soapbox.pub">soapbox.pub</a><br />
|
||||
[email protected]
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="receipt-title">${t('receipt')}</div>
|
||||
|
||||
<dl class="details-grid">
|
||||
<dt>${t('receiptNumber')}</dt>
|
||||
<dd>${escapeHtml(payment.id)}</dd>
|
||||
<dt>${t('date')}</dt>
|
||||
<dd>${formattedDate} ${formattedTime}</dd>
|
||||
<dt>${t('status')}</dt>
|
||||
<dd>${escapeHtml(statusDisplay)}</dd>
|
||||
<dt>${t('paymentMethodLabel')}</dt>
|
||||
<dd>${paymentMethodDisplay}</dd>
|
||||
${payment.description ? `<dt>${t('description')}</dt><dd>${escapeHtml(payment.description)}</dd>` : ''}
|
||||
</dl>
|
||||
|
||||
<hr class="divider" />
|
||||
|
||||
<div class="line-items">
|
||||
<div class="line-item">
|
||||
<span class="line-item-label">${t('credits')}</span>
|
||||
<span class="line-item-value">${formatCurrency(payment.amount)}</span>
|
||||
</div>
|
||||
${payment.fee > 0 ? `
|
||||
<div class="line-item">
|
||||
<span class="line-item-label">${t('processingFee')}</span>
|
||||
<span class="line-item-value">${formatCurrency(payment.fee)}</span>
|
||||
</div>
|
||||
` : ''}
|
||||
<div class="line-item line-item-total">
|
||||
<span class="line-item-label">${t('totalCharged')}</span>
|
||||
<span class="line-item-value">${formatCurrency(payment.total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p>${t('thankYouForPurchase')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
printWindow.document.write(printHTML);
|
||||
printWindow.document.close();
|
||||
|
||||
printWindow.onload = () => {
|
||||
setTimeout(() => {
|
||||
printWindow.print();
|
||||
}, 250);
|
||||
};
|
||||
};
|
||||
|
||||
const handleDownloadCSV = () => {
|
||||
if (!giftcards || giftcards.length === 0) return;
|
||||
|
||||
@@ -1532,17 +1307,6 @@ export function AIProviderConfigDialog({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{payment.status === 'completed' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handlePrintReceipt(payment)}
|
||||
className="h-6 px-2 text-xs"
|
||||
>
|
||||
<Printer className="h-3 w-3 mr-1" />
|
||||
{t('printReceipt')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -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',
|
||||
|
||||
+1
-9
@@ -573,13 +573,5 @@
|
||||
"failedToDuplicateProject": "Failed to duplicate project",
|
||||
"newProjectName": "New Project Name",
|
||||
"duplicateProjectDescription": "Create a copy of this project with a new name",
|
||||
"resume": "Resume",
|
||||
"printReceipt": "Print Receipt",
|
||||
"receipt": "Receipt",
|
||||
"receiptNumber": "Receipt #",
|
||||
"date": "Date",
|
||||
"status": "Status",
|
||||
"paymentMethodLabel": "Payment Method",
|
||||
"totalCharged": "Total Charged",
|
||||
"thankYouForPurchase": "Thank you for your purchase!"
|
||||
"resume": "Resume"
|
||||
}
|
||||
+1
-9
@@ -487,13 +487,5 @@
|
||||
"failedToDuplicateProject": "An kasa kwafin aikin",
|
||||
"newProjectName": "Sunan Sabon Aikin",
|
||||
"duplicateProjectDescription": "Ƙirƙiri kwafin wannan aikin da sabon suna",
|
||||
"resume": "Ci gaba",
|
||||
"printReceipt": "Buga Rasidi",
|
||||
"receipt": "Rasidi",
|
||||
"receiptNumber": "Rasidi #",
|
||||
"date": "Kwanan wata",
|
||||
"status": "Matsayi",
|
||||
"paymentMethodLabel": "Hanyar Biyan Kuɗi",
|
||||
"totalCharged": "Jimlar da aka Caji",
|
||||
"thankYouForPurchase": "Mun gode da sayan ku!"
|
||||
"resume": "Ci gaba"
|
||||
}
|
||||
+1
-9
@@ -484,13 +484,5 @@
|
||||
"failedToDuplicateProject": "Ọ dara ada imepụta ọrụ",
|
||||
"newProjectName": "Aha Ọrụ Ọhụrụ",
|
||||
"duplicateProjectDescription": "Mepụta oyiri nke ọrụ a na aha ọhụrụ",
|
||||
"resume": "Gaa n'ihu",
|
||||
"printReceipt": "Bipụta Risịịtị",
|
||||
"receipt": "Risịịtị",
|
||||
"receiptNumber": "Risịịtị #",
|
||||
"date": "Ụbọchị",
|
||||
"status": "Ọnọdụ",
|
||||
"paymentMethodLabel": "Ụzọ Ịkwụ Ụgwọ",
|
||||
"totalCharged": "Nchịkọta Ego a Gbara",
|
||||
"thankYouForPurchase": "Daalụ maka ịzụta gị!"
|
||||
"resume": "Gaa n'ihu"
|
||||
}
|
||||
+1
-9
@@ -496,13 +496,5 @@
|
||||
"failedToDuplicateProject": "Falha ao duplicar projeto",
|
||||
"newProjectName": "Nome do Novo Projeto",
|
||||
"duplicateProjectDescription": "Criar uma cópia deste projeto com um novo nome",
|
||||
"resume": "Retomar",
|
||||
"printReceipt": "Imprimir Recibo",
|
||||
"receipt": "Recibo",
|
||||
"receiptNumber": "Recibo Nº",
|
||||
"date": "Data",
|
||||
"status": "Status",
|
||||
"paymentMethodLabel": "Método de Pagamento",
|
||||
"totalCharged": "Total Cobrado",
|
||||
"thankYouForPurchase": "Obrigado pela sua compra!"
|
||||
"resume": "Retomar"
|
||||
}
|
||||
+1
-9
@@ -484,13 +484,5 @@
|
||||
"failedToDuplicateProject": "O kuna lati ṣe ẹda iṣẹ akanṣe",
|
||||
"newProjectName": "Orukọ Iṣẹ Akanṣe Tuntun",
|
||||
"duplicateProjectDescription": "Ṣẹda ẹda ti iṣẹ akanṣe yii pẹlu orukọ tuntun",
|
||||
"resume": "Tẹsiwaju",
|
||||
"printReceipt": "Tẹ Ìwé Ẹ̀rí",
|
||||
"receipt": "Ìwé Ẹ̀rí",
|
||||
"receiptNumber": "Ìwé Ẹ̀rí #",
|
||||
"date": "Ọjọ́",
|
||||
"status": "Ipò",
|
||||
"paymentMethodLabel": "Ọ̀nà Ìsanwó",
|
||||
"totalCharged": "Àpapọ̀ tí a gba",
|
||||
"thankYouForPurchase": "A dúpẹ́ fún rírà rẹ!"
|
||||
"resume": "Tẹsiwaju"
|
||||
}
|
||||
+1
-9
@@ -496,13 +496,5 @@
|
||||
"failedToDuplicateProject": "复制项目失败",
|
||||
"newProjectName": "新项目名称",
|
||||
"duplicateProjectDescription": "使用新名称创建此项目的副本",
|
||||
"resume": "继续",
|
||||
"printReceipt": "打印收据",
|
||||
"receipt": "收据",
|
||||
"receiptNumber": "收据编号",
|
||||
"date": "日期",
|
||||
"status": "状态",
|
||||
"paymentMethodLabel": "支付方式",
|
||||
"totalCharged": "总收费",
|
||||
"thankYouForPurchase": "感谢您的购买!"
|
||||
"resume": "继续"
|
||||
}
|
||||
+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