webchat: bundle assets with rolldown

This commit is contained in:
Peter Steinberger
2025-12-07 17:44:37 +01:00
parent 74e5e5e182
commit 98651c2a14
10 changed files with 195780 additions and 142 deletions

View File

@@ -0,0 +1,122 @@
// Bundled entry point for the macOS WKWebView web chat.
// This replaces the inline module script in index.html so we can ship a single JS bundle.
/* global window, document, crypto */
if (!globalThis.process) {
// Some vendor modules peek at process.env; provide a minimal stub for browser.
globalThis.process = { env: {} };
}
const logStatus = (msg) => {
try {
console.log(msg);
if (typeof window.__clawdisLog === "function") {
window.__clawdisLog(msg);
}
const el = document.getElementById("app");
if (el && !el.dataset.booted) el.textContent = msg;
} catch {
// Ignore logging failures—never block bootstrap.
}
};
const getBootstrap = () => {
const bootstrap = window.__clawdisBootstrap || {};
return {
initialMessages: Array.isArray(bootstrap.initialMessages) ? bootstrap.initialMessages : [],
sessionKey: typeof bootstrap.sessionKey === "string" ? bootstrap.sessionKey : "main",
};
};
class NativeTransport {
constructor(sessionKey) {
this.sessionKey = sessionKey;
}
async *run(messages, userMessage, cfg, signal) {
const result = await window.__clawdisSend({
type: "chat",
payload: { text: userMessage.content?.[0]?.text ?? "", sessionKey: this.sessionKey },
});
const usage = {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
};
const assistant = {
role: "assistant",
content: [{ type: "text", text: result.text ?? "" }],
api: cfg.model.api,
provider: cfg.model.provider,
model: cfg.model.id,
usage,
stopReason: "stop",
timestamp: Date.now(),
};
yield { type: "turn_start" };
yield { type: "message_start", message: assistant };
yield { type: "message_end", message: assistant };
yield { type: "turn_end" };
yield { type: "agent_end" };
}
}
const startChat = async () => {
const { initialMessages, sessionKey } = getBootstrap();
logStatus("boot: starting imports");
const { Agent } = await import("./agent/agent.js");
const { ChatPanel } = await import("./ChatPanel.js");
const { AppStorage, setAppStorage } = await import("./storage/app-storage.js");
const { getModel } = await import("@mariozechner/pi-ai");
logStatus("boot: modules loaded");
const storage = new AppStorage();
setAppStorage(storage);
const agent = new Agent({
initialState: {
systemPrompt: "You are Clawd (primary session).",
model: getModel("anthropic", "claude-opus-4-5"),
thinkingLevel: "off",
messages: initialMessages,
},
transport: new NativeTransport(sessionKey),
});
const origPrompt = agent.prompt.bind(agent);
agent.prompt = async (input, attachments) => {
const userMessage = {
role: "user",
content: [{ type: "text", text: input }],
attachments: attachments?.length ? attachments : undefined,
timestamp: Date.now(),
};
agent.appendMessage(userMessage);
return origPrompt(input, attachments);
};
const panel = new ChatPanel();
panel.style.height = "100%";
panel.style.display = "block";
await panel.setAgent(agent);
const mount = document.getElementById("app");
if (!mount) throw new Error("#app container missing");
mount.dataset.booted = "1";
mount.textContent = "";
mount.appendChild(panel);
logStatus("boot: ready");
};
startChat().catch((err) => {
const msg = err?.stack || err?.message || String(err);
logStatus(`boot failed: ${msg}`);
document.body.style.color = "#e06666";
document.body.style.fontFamily = "monospace";
document.body.style.padding = "16px";
document.body.innerText = "Web chat failed to load:\\n" + msg;
});

View File

@@ -5,31 +5,6 @@
<meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline' data: blob:;">
<title>Clawd Web Chat</title>
<link rel="stylesheet" href="app.css">
<script type="importmap">
{
"imports": {
"@mariozechner/pi-web-ui": "./index.js",
"@mariozechner/pi-web-ui/": "./",
"@mariozechner/pi-ai": "./pi-ai-stub.js",
"@mariozechner/pi-ai/": "./pi-ai-stub.js",
"@mariozechner/mini-lit": "./vendor/@mariozechner/mini-lit/dist/index.js",
"@mariozechner/mini-lit/": "./vendor/@mariozechner/mini-lit/dist/",
"lit": "./vendor/lit/index.js",
"lit/": "./vendor/lit/",
"lucide": "./vendor/lucide/dist/esm/lucide.js",
"pdfjs-dist": "./vendor/pdfjs-dist/build/pdf.js",
"pdfjs-dist/": "./vendor/pdfjs-dist/",
"pdfjs-dist/build/pdf.worker.min.mjs": "./vendor/pdfjs-dist/build/pdf.worker.min.mjs",
"docx-preview": "./vendor/docx-preview/dist/docx-preview.mjs",
"jszip": "./vendor/jszip/dist/jszip.min.js",
"highlight.js": "./vendor/highlight.js/es/index.js",
"@lmstudio/sdk": "./vendor/@lmstudio/sdk/dist/index.mjs",
"ollama/browser": "./vendor/ollama/dist/browser.mjs",
"@sinclair/typebox": "./vendor/@sinclair/typebox/build/esm/index.mjs",
"xlsx": "./vendor/xlsx/xlsx.mjs"
}
}
</script>
<style>
html, body { height: 100%; margin: 0; padding: 0; }
#app { height: 100%; }
@@ -37,107 +12,6 @@
</head>
<body>
<div id="app" style="padding:16px;font:14px -apple-system, BlinkMacSystemFont, sans-serif;color:#222">Booting web chat…</div>
<script type="module">
if (!window.process) window.process = { env: {} };
const bootstrap = window.__clawdisBootstrap || {};
const initialMessages = Array.isArray(bootstrap.initialMessages) ? bootstrap.initialMessages : [];
const sessionKey = typeof bootstrap.sessionKey === "string" ? bootstrap.sessionKey : "main";
const status = (msg) => {
console.log(msg);
if (typeof window.__clawdisLog === "function") window.__clawdisLog(msg);
const el = document.getElementById("app");
if (el && !el.dataset.booted) el.textContent = msg;
};
status("boot: starting imports");
(async () => {
try {
const { Agent } = await import("./agent/agent.js");
status("boot: agent loaded");
const { ChatPanel } = await import("./ChatPanel.js");
status("boot: ChatPanel loaded");
const { AppStorage, setAppStorage } = await import("./storage/app-storage.js");
status("boot: pi-web-ui imported");
const { getModel } = await import("@mariozechner/pi-ai");
status("boot: pi-ai stub imported");
class NativeTransport {
async *run(messages, userMessage, cfg, signal) {
const result = await window.__clawdisSend({
type: "chat",
payload: { text: userMessage.content?.[0]?.text ?? "", sessionKey }
});
const usage = {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
};
const assistant = {
role: "assistant",
content: [{ type: "text", text: result.text ?? "" }],
api: cfg.model.api,
provider: cfg.model.provider,
model: cfg.model.id,
usage,
stopReason: "stop",
timestamp: Date.now()
};
yield { type: "turn_start" };
yield { type: "message_start", message: assistant };
yield { type: "message_end", message: assistant };
yield { type: "turn_end" };
yield { type: "agent_end" };
}
}
const storage = new AppStorage();
setAppStorage(storage);
const agent = new Agent({
initialState: {
systemPrompt: "You are Clawd (primary session).",
model: getModel("anthropic", "claude-opus-4-5"),
thinkingLevel: "off",
messages: initialMessages
},
transport: new NativeTransport()
});
const origPrompt = agent.prompt.bind(agent);
agent.prompt = async (input, attachments) => {
const userMessage = {
role: "user",
content: [{ type: "text", text: input }],
attachments: attachments?.length ? attachments : undefined,
timestamp: Date.now()
};
agent.appendMessage(userMessage);
return origPrompt(input, attachments);
};
const panel = new ChatPanel();
panel.style.height = "100%";
panel.style.display = "block";
await panel.setAgent(agent);
const mount = document.getElementById("app");
mount.dataset.booted = "1";
mount.textContent = "";
mount.appendChild(panel);
status("boot: ready");
} catch (err) {
const msg = err?.stack || err?.message || String(err);
if (typeof window.__clawdisLog === "function") window.__clawdisLog(msg);
document.body.style.color = "#e06666";
document.body.style.fontFamily = "monospace";
document.body.style.padding = "16px";
document.body.innerText = "Web chat failed to load:\\n" + msg;
}
})();
</script>
<script type="module" src="webchat.bundle.js"></script>
</body>
</html>

View File

@@ -0,0 +1,19 @@
// Minimal stub to satisfy @lmstudio/sdk imports in the bundled web chat.
export class LMStudioClient {
constructor() {
this.system = {
async listDownloadedModels() {
return [];
},
};
}
}
export function connect() {
throw new Error("LM Studio is not available in the embedded web chat bundle.");
}
export default {
LMStudioClient,
connect,
};

View File

@@ -1,24 +1,53 @@
// Minimal browser-friendly stub for @mariozechner/pi-ai
const DEFAULT_MODEL = {
provider: "anthropic",
id: "claude-opus-4-5",
name: "Claude 3.5 Sonnet",
api: "anthropic-messages",
input: ["text"],
output: ["text"],
maxTokens: 200000,
reasoning: true,
headers: undefined,
baseUrl: undefined,
};
export function getModel(provider, id) {
return {
provider,
id,
name: id,
api: `${provider}-messages`,
input: ["text"],
output: ["text"],
maxTokens: 200000,
reasoning: true,
headers: undefined,
baseUrl: undefined,
};
return { ...DEFAULT_MODEL, provider, id, name: id };
}
export function getModels() {
return [DEFAULT_MODEL];
}
export function getProviders() {
return [
{
id: DEFAULT_MODEL.provider,
name: "Anthropic",
models: getModels(),
},
];
}
export async function complete() {
return { text: "" };
}
// Dummy stream helpers used in some debug flows; no-ops in web chat.
export function agentLoop() {
throw new Error("agentLoop is not available in embedded web chat");
}
export class AssistantMessageEventStream {
push() {}
end() {}
}
export const StringEnum = (values, options = {}) => ({
enum: [...values],
description: options.description,
});
export function parseStreamingJson() {
return null;
}

View File

@@ -0,0 +1,42 @@
import path from "node:path";
import { defineConfig } from "rolldown";
const here = path.dirname(new URL(import.meta.url).pathname);
const repoRoot = path.resolve(here, "../../../../../..");
const fromRoot = (p) => path.resolve(here, p);
export default defineConfig({
input: fromRoot("bootstrap.js"),
treeshake: false,
resolve: {
alias: {
"@mariozechner/pi-web-ui": fromRoot("index.js"),
"@mariozechner/pi-ai": fromRoot("pi-ai-stub.js"),
"@mariozechner/pi-ai/dist/utils/event-stream.js": fromRoot("pi-ai-stub.js"),
"@mariozechner/pi-ai/dist/utils/json-parse.js": fromRoot("pi-ai-stub.js"),
"@mariozechner/mini-lit": path.resolve(repoRoot, "node_modules/@mariozechner/mini-lit/dist/index.js"),
"@mariozechner/mini-lit/": path.resolve(repoRoot, "node_modules/@mariozechner/mini-lit/"),
"@mariozechner/mini-lit/dist/": path.resolve(repoRoot, "node_modules/@mariozechner/mini-lit/dist/"),
lit: path.resolve(repoRoot, "node_modules/lit/index.js"),
"lit/": path.resolve(repoRoot, "node_modules/lit/"),
lucide: fromRoot("vendor/lucide/dist/esm/lucide.js"),
"pdfjs-dist": fromRoot("vendor/pdfjs-dist/build/pdf.mjs"),
"pdfjs-dist/": fromRoot("vendor/pdfjs-dist/"),
"pdfjs-dist/build/pdf.worker.min.mjs": fromRoot("vendor/pdfjs-dist/build/pdf.worker.min.mjs"),
"docx-preview": fromRoot("vendor/docx-preview/dist/docx-preview.mjs"),
jszip: fromRoot("vendor/jszip/dist/jszip.min.js"),
"highlight.js": fromRoot("vendor/highlight.js/es/index.js"),
"@lmstudio/sdk": fromRoot("lmstudio-sdk-stub.js"),
"ollama/browser": fromRoot("vendor/ollama/dist/browser.mjs"),
"@sinclair/typebox": fromRoot("vendor/@sinclair/typebox/build/esm/index.mjs"),
xlsx: fromRoot("vendor/xlsx/xlsx.mjs"),
"whatwg-fetch": fromRoot("whatwg-fetch-stub.js"),
},
},
output: {
file: fromRoot("webchat.bundle.js"),
format: "esm",
inlineDynamicImports: true,
sourcemap: false,
},
});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
// Fetch is available in WKWebView already; this stub satisfies bundler imports.
export {};

View File

@@ -22,6 +22,7 @@ final class WebChatServer: @unchecked Sendable {
self.root = root
let params = NWParameters.tcp
params.allowLocalEndpointReuse = true
params.requiredInterfaceType = .loopback
do {
let listener = try NWListener(using: params, on: .any)
listener.stateUpdateHandler = { [weak self] state in

View File

@@ -18,7 +18,8 @@
"format": "biome format src",
"format:fix": "biome format src --write",
"test": "vitest",
"test:coverage": "vitest run --coverage"
"test:coverage": "vitest run --coverage",
"webchat:bundle": "rolldown -c apps/macos/Sources/Clawdis/Resources/WebChat/rolldown.config.mjs"
},
"keywords": [],
"author": "",
@@ -28,9 +29,9 @@
},
"packageManager": "pnpm@10.23.0",
"dependencies": {
"@whiskeysockets/baileys": "7.0.0-rc.9",
"@mariozechner/pi-ai": "^0.12.11",
"@mariozechner/pi-coding-agent": "^0.12.11",
"@whiskeysockets/baileys": "7.0.0-rc.9",
"body-parser": "^2.2.1",
"chalk": "^5.6.2",
"commander": "^14.0.2",
@@ -44,11 +45,14 @@
},
"devDependencies": {
"@biomejs/biome": "^2.3.7",
"@mariozechner/mini-lit": "0.2.1",
"@types/body-parser": "^1.19.6",
"@types/express": "^5.0.5",
"@types/node": "^24.10.1",
"@types/qrcode-terminal": "^0.12.2",
"@vitest/coverage-v8": "^4.0.13",
"lit": "^3.3.1",
"rolldown": "1.0.0-beta.53",
"tsx": "^4.20.6",
"typescript": "^5.9.3",
"vitest": "^4.0.13"

View File

@@ -49,6 +49,9 @@ log "==> Killing existing Clawdis instances"
kill_all_clawdis
stop_launch_agent
# 1.5) Bundle web chat assets (single-file JS to avoid import-map issues).
run_step "bundle webchat" bash -lc "cd '${ROOT_DIR}' && pnpm webchat:bundle"
# 2) Rebuild into the same path the packager consumes (.build).
run_step "clean build cache" bash -lc "cd '${ROOT_DIR}/apps/macos' && rm -rf .build .build-swift .swiftpm 2>/dev/null || true"
run_step "swift build" bash -lc "cd '${ROOT_DIR}/apps/macos' && swift build -q --product Clawdis"