mac: fix web chat boot in WKWebView

main
Peter Steinberger 2025-12-06 21:33:35 +01:00
parent e528b439bc
commit 6182b205c8
2 changed files with 96 additions and 65 deletions

View File

@ -80,11 +80,16 @@ final class WebChatWindowController: NSWindowController, WKScriptMessageHandler
let importMap = [ let importMap = [
"imports": [ "imports": [
"@mariozechner/pi-web-ui": "file://\(distPath)/index.js", "@mariozechner/pi-web-ui": "file://\(distPath)/index.js",
"@mariozechner/pi-web-ui/": "file://\(distPath)/",
"@mariozechner/pi-ai": "file://\(piAi)", "@mariozechner/pi-ai": "file://\(piAi)",
"@mariozechner/pi-ai/": "file://\(vendor.appendingPathComponent("pi-ai/").path(percentEncoded: false))",
"@mariozechner/mini-lit": "file://\(miniLit)", "@mariozechner/mini-lit": "file://\(miniLit)",
"@mariozechner/mini-lit/": "file://\(vendor.appendingPathComponent("mini-lit/").path(percentEncoded: false))",
"lit": "file://\(lit)", "lit": "file://\(lit)",
"lit/": "file://\(vendor.appendingPathComponent("lit/").path(percentEncoded: false))",
"lucide": "file://\(lucide)", "lucide": "file://\(lucide)",
"pdfjs-dist": "file://\(pdfjs)", "pdfjs-dist": "file://\(pdfjs)",
"pdfjs-dist/": "file://\(vendor.appendingPathComponent("pdfjs-dist/").path(percentEncoded: false))",
"pdfjs-dist/build/pdf.worker.min.mjs": "file://\(pdfWorker)", "pdfjs-dist/build/pdf.worker.min.mjs": "file://\(pdfWorker)",
], ],
] ]
@ -114,73 +119,92 @@ final class WebChatWindowController: NSWindowController, WKScriptMessageHandler
<body> <body>
<div id="app"></div> <div id="app"></div>
<script type="module"> <script type="module">
try { const status = (msg) => {
const { Agent, ChatPanel, AppStorage, setAppStorage } = await import('@mariozechner/pi-web-ui'); console.log(msg);
const { getModel } = await import('@mariozechner/pi-ai'); window.__clawdisLog(msg);
const el = document.getElementById('app');
if (el && !el.dataset.booted) {
el.textContent = msg;
}
};
class NativeTransport { status('boot: starting imports');
async *run(messages, userMessage, cfg, signal) {
const result = await window.__clawdisSend({ type: 'chat', payload: { text: userMessage.content?.[0]?.text ?? '', sessionKey: '\( (async () => {
sessionKey)' } }); try {
const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }; const { Agent, ChatPanel, AppStorage, setAppStorage } = await import('@mariozechner/pi-web-ui');
const assistant = { status('boot: pi-web-ui imported');
role: 'assistant', const { getModel } = await import('@mariozechner/pi-ai');
content: [{ type: 'text', text: result.text ?? '' }], status('boot: pi-ai imported');
api: cfg.model.api,
provider: cfg.model.provider, class NativeTransport {
model: cfg.model.id, async *run(messages, userMessage, cfg, signal) {
usage, const result = await window.__clawdisSend({ type: 'chat', payload: { text: userMessage.content?.[0]?.text ?? '', sessionKey: '\(
stopReason: 'stop', 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' };
}
}
// Minimal storage
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: []
},
transport: new NativeTransport()
});
// Patch prompt to append user message into history first
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() timestamp: Date.now()
}; };
yield { type: 'turn_start' }; agent.appendMessage(userMessage);
yield { type: 'message_start', message: assistant }; return origPrompt(input, attachments);
yield { type: 'message_end', message: assistant };
yield { type: 'turn_end' };
yield { type: 'agent_end' };
}
}
// Minimal storage
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: []
},
transport: new NativeTransport()
});
// Patch prompt to append user message into history first
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(); const panel = new ChatPanel();
panel.style.height = '100%'; panel.style.height = '100%';
panel.style.display = 'block'; panel.style.display = 'block';
await panel.setAgent(agent); await panel.setAgent(agent);
document.getElementById('app').appendChild(panel); const mount = document.getElementById('app');
} catch (err) { mount.dataset.booted = '1';
const msg = err?.stack || err?.message || String(err); mount.textContent = '';
window.__clawdisLog(msg); mount.appendChild(panel);
document.body.style.color = '#e06666'; status('boot: ready');
document.body.style.fontFamily = 'monospace'; } catch (err) {
document.body.style.padding = '16px'; const msg = err?.stack || err?.message || String(err);
document.body.innerText = 'Web chat failed to load:\\n' + msg; 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>
</body> </body>
</html> </html>
@ -191,8 +215,15 @@ final class WebChatWindowController: NSWindowController, WKScriptMessageHandler
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let body = message.body as? [String: Any], guard let body = message.body as? [String: Any],
let id = body["id"] as? String, let id = body["id"] as? String,
let type = body["type"] as? String, let type = body["type"] as? String
type == "chat", else { return }
if id == "log", let log = body["log"] as? String {
NSLog("WebChat JS: %@", log)
return
}
guard type == "chat",
let payload = body["payload"] as? [String: Any], let payload = body["payload"] as? [String: Any],
let text = payload["text"] as? String let text = payload["text"] as? String
else { return } else { return }

View File

@ -23,5 +23,5 @@ The macOS Clawdis app ships a built-in web chat window that reuses your primary
## Usage ## Usage
- Launch the macOS Clawdis menu bar app, click the lobster icon → “Open Web Chat”. - Launch the macOS Clawdis menu bar app, click the lobster icon → “Open Chat”.
- Type and send; replies continue the primary Clawd session. - Type and send; replies continue the primary Clawd session.