Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"dependencies": {
"@open-codesign/artifacts": "workspace:*",
"@open-codesign/core": "workspace:*",
"@open-codesign/exporters": "workspace:*",
"@open-codesign/providers": "workspace:*",
"@open-codesign/runtime": "workspace:*",
"@open-codesign/shared": "workspace:*",
Expand Down
64 changes: 64 additions & 0 deletions apps/desktop/src/main/exporter-ipc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { type ExporterFormat, exportArtifact } from '@open-codesign/exporters';
import { CodesignError } from '@open-codesign/shared';
import { type BrowserWindow, dialog, ipcMain } from 'electron';

const FORMAT_FILTERS: Record<ExporterFormat, Electron.FileFilter[]> = {
html: [{ name: 'HTML', extensions: ['html'] }],
pdf: [{ name: 'PDF', extensions: ['pdf'] }],
pptx: [{ name: 'PowerPoint', extensions: ['pptx'] }],
zip: [{ name: 'ZIP archive', extensions: ['zip'] }],
};

export interface ExportRequest {
format: ExporterFormat;
htmlContent: string;
defaultFilename?: string;
}

export interface ExportResponse {
status: 'saved' | 'cancelled';
path?: string;
bytes?: number;
}

function parseRequest(raw: unknown): ExportRequest {
if (raw === null || typeof raw !== 'object') {
throw new CodesignError('export expects an object payload', 'IPC_BAD_INPUT');
}
const r = raw as Record<string, unknown>;
const format = r['format'];
const html = r['htmlContent'];
const defaultFilename = r['defaultFilename'];
if (format !== 'html' && format !== 'pdf' && format !== 'pptx' && format !== 'zip') {
throw new CodesignError(`Unknown export format: ${String(format)}`, 'EXPORTER_UNKNOWN');
}
if (typeof html !== 'string' || html.length === 0) {
throw new CodesignError('export requires non-empty htmlContent', 'IPC_BAD_INPUT');
}
const out: ExportRequest = { format, htmlContent: html };
if (typeof defaultFilename === 'string' && defaultFilename.length > 0) {
out.defaultFilename = defaultFilename;
}
return out;
}

export function registerExporterIpc(getWindow: () => BrowserWindow | null): void {
ipcMain.handle('codesign:export', async (_evt, raw: unknown): Promise<ExportResponse> => {
const req = parseRequest(raw);
const win = getWindow();
const opts: Electron.SaveDialogOptions = {
title: `Export design as ${req.format.toUpperCase()}`,
defaultPath: req.defaultFilename ?? `design.${req.format}`,
filters: FORMAT_FILTERS[req.format],
};
const picked = win ? await dialog.showSaveDialog(win, opts) : await dialog.showSaveDialog(opts);
if (picked.canceled || !picked.filePath) {
return { status: 'cancelled' };
}

// All four formats ship in tier 1; the heavy deps load lazily inside
// exportArtifact. Errors propagate to the renderer as toasts (PRINCIPLES §10).
const result = await exportArtifact(req.format, req.htmlContent, picked.filePath);
return { status: 'saved', path: result.path, bytes: result.bytes };
});
}
2 changes: 2 additions & 0 deletions apps/desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { detectProviderFromKey } from '@open-codesign/providers';
import { BRAND, CodesignError, GeneratePayload } from '@open-codesign/shared';
import { BrowserWindow, app, ipcMain, shell } from 'electron';
import { autoUpdater } from 'electron-updater';
import { registerExporterIpc } from './exporter-ipc';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
Expand Down Expand Up @@ -78,6 +79,7 @@ function setupAutoUpdater(): void {

void app.whenReady().then(() => {
registerIpcHandlers();
registerExporterIpc(() => mainWindow);
setupAutoUpdater();
createWindow();

Expand Down
9 changes: 9 additions & 0 deletions apps/desktop/src/preload/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import type { ChatMessage, ModelRef } from '@open-codesign/shared';
import { contextBridge, ipcRenderer } from 'electron';

export type ExportFormat = 'html' | 'pdf' | 'pptx' | 'zip';
export interface ExportInvokeResponse {
status: 'saved' | 'cancelled';
path?: string;
bytes?: number;
}

const api = {
detectProvider: (key: string) =>
ipcRenderer.invoke('codesign:detect-provider', key) as Promise<string | null>,
Expand All @@ -11,6 +18,8 @@ const api = {
apiKey: string;
baseUrl?: string;
}) => ipcRenderer.invoke('codesign:generate', payload),
export: (payload: { format: ExportFormat; htmlContent: string; defaultFilename?: string }) =>
ipcRenderer.invoke('codesign:export', payload) as Promise<ExportInvokeResponse>,
checkForUpdates: () => ipcRenderer.invoke('codesign:check-for-updates'),
downloadUpdate: () => ipcRenderer.invoke('codesign:download-update'),
installUpdate: () => ipcRenderer.invoke('codesign:install-update'),
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { BUILTIN_DEMOS } from '@open-codesign/templates';
import { Button } from '@open-codesign/ui';
import { Send, Sparkles } from 'lucide-react';
import { useState } from 'react';
import { PreviewToolbar } from './components/PreviewToolbar';
import { useCodesignStore } from './store';

export function App() {
Expand Down Expand Up @@ -58,7 +59,6 @@ export function App() {
) : (
messages.map((m, i) => (
<div
// biome-ignore lint/suspicious/noArrayIndexKey: tier-1 chat list with no reordering
key={`${m.role}-${i}`}
className={`px-3 py-2 rounded-[var(--radius-md)] text-sm ${
m.role === 'user'
Expand Down Expand Up @@ -99,6 +99,7 @@ export function App() {
BYOK · local-first · multi-model
</span>
</header>
<PreviewToolbar />
<div className="flex-1 p-6 overflow-auto">
{previewHtml ? (
<iframe
Expand Down
97 changes: 97 additions & 0 deletions apps/desktop/src/renderer/src/components/PreviewToolbar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { Download } from 'lucide-react';
import { type ReactElement, useEffect, useRef, useState } from 'react';
import type { ExportFormat } from '../../../preload/index';
import { useCodesignStore } from '../store';

interface ExportItem {
format: ExportFormat;
label: string;
hint?: string;
ready: boolean;
}

const EXPORT_ITEMS: ExportItem[] = [
{ format: 'html', label: 'HTML', ready: true, hint: 'Single self-contained .html file' },
{ format: 'pdf', label: 'PDF', ready: true, hint: 'Rendered via your installed Chrome' },
{ format: 'pptx', label: 'PPTX', ready: true, hint: 'Editable slides; one per <section>' },
{ format: 'zip', label: 'ZIP bundle', ready: true, hint: 'index.html + assets + README.md' },
];

export function PreviewToolbar(): ReactElement {
const previewHtml = useCodesignStore((s) => s.previewHtml);
const exportActive = useCodesignStore((s) => s.exportActive);
const toastMessage = useCodesignStore((s) => s.toastMessage);
const dismissToast = useCodesignStore((s) => s.dismissToast);
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement | null>(null);

useEffect(() => {
if (!open) return;
function onClick(e: MouseEvent): void {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
}
document.addEventListener('mousedown', onClick);
return () => document.removeEventListener('mousedown', onClick);
}, [open]);

useEffect(() => {
if (!toastMessage) return;
const t = setTimeout(() => dismissToast(), 4000);
return () => clearTimeout(t);
}, [toastMessage, dismissToast]);

const disabled = !previewHtml;

return (
<div className="flex items-center justify-end gap-2 px-5 py-2 border-b border-[var(--color-border)] bg-[var(--color-background-secondary)]">
{toastMessage && (
<output className="mr-auto text-xs text-[var(--color-text-secondary)] truncate max-w-[60%]">
{toastMessage}
</output>
)}

<div className="relative" ref={ref}>
<button
type="button"
disabled={disabled}
onClick={() => setOpen((v) => !v)}
className="inline-flex items-center gap-1.5 h-8 px-3 rounded-[var(--radius-md)] text-sm font-medium border border-[var(--color-border)] bg-[var(--color-surface)] text-[var(--color-text-primary)] hover:bg-[var(--color-surface-hover)] disabled:opacity-50 disabled:pointer-events-none transition-colors"
aria-haspopup="menu"
aria-expanded={open}
>
<Download className="w-4 h-4" aria-hidden="true" />
Export
</button>

{open && (
<div
role="menu"
className="absolute right-0 top-full mt-1 min-w-[180px] rounded-[var(--radius-md)] border border-[var(--color-border)] bg-[var(--color-surface)] shadow-[var(--shadow-card)] py-1 z-10"
>
{EXPORT_ITEMS.map((item) => (
<button
key={item.format}
type="button"
role="menuitem"
disabled={!item.ready}
title={item.hint}
onClick={() => {
setOpen(false);
void exportActive(item.format);
}}
className="w-full flex items-center justify-between gap-3 px-3 py-2 text-sm text-left text-[var(--color-text-primary)] hover:bg-[var(--color-surface-hover)] disabled:opacity-50 disabled:hover:bg-transparent disabled:cursor-not-allowed transition-colors"
>
<span>{item.label}</span>
{item.hint && (
<span className="text-xs text-[var(--color-text-muted)] truncate max-w-[60%]">
{item.hint}
</span>
)}
</button>
))}
</div>
)}
</div>
</div>
);
}
50 changes: 45 additions & 5 deletions apps/desktop/src/renderer/src/store.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,38 @@
import type { ChatMessage } from '@open-codesign/shared';
import { create } from 'zustand';
import type { CodesignApi } from '../../preload/index';
import type { CodesignApi, ExportFormat } from '../../preload/index';

declare global {
interface Window {
codesign?: CodesignApi;
}
}

// TIER 1 / DEV ONLY. The renderer reads `VITE_OPEN_CODESIGN_DEV_KEY` so the
// "first demo" path works before `wt/onboarding` lands real keychain plumbing.
// Once onboarding ships, this constant + the !apiKey branch in sendPrompt go
// away in the integration commit. Vite inlines `import.meta.env.*` at build
// time, so a missing var resolves to `undefined`.
const DEV_API_KEY: string =
(import.meta.env['VITE_OPEN_CODESIGN_DEV_KEY'] as string | undefined) ?? '';

interface CodesignState {
messages: ChatMessage[];
previewHtml: string | null;
isGenerating: boolean;
errorMessage: string | null;
toastMessage: string | null;
sendPrompt: (prompt: string) => Promise<void>;
exportActive: (format: ExportFormat) => Promise<void>;
dismissToast: () => void;
}

export const useCodesignStore = create<CodesignState>((set, get) => ({
messages: [],
previewHtml: null,
isGenerating: false,
errorMessage: null,
toastMessage: null,

async sendPrompt(prompt: string) {
if (get().isGenerating) return;
Expand All @@ -36,17 +48,15 @@ export const useCodesignStore = create<CodesignState>((set, get) => ({
errorMessage: null,
}));

// Tier 1 wiring: hardcoded provider/model and key-from-env until the
// onboarding flow lands. The real flow will read from the keychain.
const apiKey = '';
const apiKey = DEV_API_KEY;
if (!apiKey) {
set((s) => ({
messages: [
...s.messages,
{
role: 'assistant',
content:
'No API key configured yet. Onboarding flow coming in v0.1 — see docs/research/06-api-onboarding-ux.md.',
'No API key configured yet. Set VITE_OPEN_CODESIGN_DEV_KEY for dev, or wait for the onboarding flow (wt/onboarding) to land.',
},
],
isGenerating: false,
Expand Down Expand Up @@ -77,4 +87,34 @@ export const useCodesignStore = create<CodesignState>((set, get) => ({
}));
}
},

async exportActive(format: ExportFormat) {
const html = get().previewHtml;
if (!html) {
set({ toastMessage: 'No design to export yet.' });
return;
}
if (!window.codesign) {
set({ errorMessage: 'Renderer is not connected to the main process.' });
return;
}
try {
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const res = await window.codesign.export({
format,
htmlContent: html,
defaultFilename: `codesign-${stamp}.${format}`,
});
if (res.status === 'saved' && res.path) {
set({ toastMessage: `Exported to ${res.path}` });
}
} catch (err) {
const msg = err instanceof Error ? err.message : 'Unknown error';
set({ toastMessage: msg, errorMessage: msg });
}
},

dismissToast() {
set({ toastMessage: null });
},
}));
51 changes: 51 additions & 0 deletions examples/calm-spaces/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Demo · Calm Spaces meditation app

The "Calm Spaces" mobile prototype is the headline first demo for open-codesign,
mirroring the marquee Claude Design example (see `docs/research/01-claude-design-teardown.md`).

## What it generates

A single self-contained HTML artifact rendering a phone-frame mockup of a
meditation app home screen — meditation list, play button, soft greens/blues
palette, and tunable design tokens via CSS custom properties on `:root`.

## Run it

```bash
# 1. Provide a dev API key (Anthropic key works out of the box).
export VITE_OPEN_CODESIGN_DEV_KEY=sk-ant-...

# 2. Boot the desktop app from the repo root.
pnpm install
pnpm --filter @open-codesign/desktop dev
```

Then in the app:

1. Click the **Calm Spaces meditation app** starter in the left sidebar.
2. Press **Send** (or `Enter`).
3. Within ~30 s the iframe on the right renders the design.
4. Open the **Export** menu in the preview toolbar → choose **HTML** → pick a
destination → **Save**.
5. `open <chosen-path>` in the browser shows the same design without the app.

## Expected behaviour

- The model emits exactly one `<artifact identifier="design-1" type="html" …>`
block. The orchestrator extracts it via `@open-codesign/artifacts` and feeds
the HTML into the sandbox iframe.
- Tailwind is loaded via the official CDN (`https://cdn.tailwindcss.com`). The
HTML exporter inlines the CDN tag if the model forgot to.
- All colors, spacing, and font sizes are CSS variables — that's what the slider
tier (Phase 2) will hook into.

## Failure modes (loud, by design)

- **No key** → assistant message tells you to set `VITE_OPEN_CODESIGN_DEV_KEY`.
- **PDF / PPTX / ZIP export** → throws `CodesignError` with code
`EXPORTER_NOT_READY` and the toast reads "PDF export ships in Phase 2".
- **Network / provider error** → propagates as a `CodesignError` with code
`PROVIDER_ERROR`; surfaced as the assistant's reply prefixed with `Error:`.

There are deliberately no silent fallbacks anywhere in this path
(see PRINCIPLES §10).
3 changes: 2 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"dependencies": {
"@open-codesign/artifacts": "workspace:*",
"@open-codesign/providers": "workspace:*",
"@open-codesign/shared": "workspace:*"
"@open-codesign/shared": "workspace:*",
"@open-codesign/templates": "workspace:*"
},
"devDependencies": {
"typescript": "^5.7.2",
Expand Down
Loading