Webchat: sync thinking level with session

main
Peter Steinberger 2025-12-08 16:09:04 +00:00
parent 0f0a2dddfe
commit dc3c82ad40
8 changed files with 169 additions and 137 deletions

View File

@ -52,6 +52,7 @@ let ChatPanel = class ChatPanel extends LitElement {
// Create AgentInterface // Create AgentInterface
this.agentInterface = document.createElement("agent-interface"); this.agentInterface = document.createElement("agent-interface");
this.agentInterface.session = agent; this.agentInterface.session = agent;
this.agentInterface.sessionThinkingLevel = config?.sessionThinkingLevel ?? agent?.state?.thinkingLevel ?? "off";
this.agentInterface.enableAttachments = true; this.agentInterface.enableAttachments = true;
// Hide model selector in the embedded chat; use fixed model configured at bootstrap. // Hide model selector in the embedded chat; use fixed model configured at bootstrap.
this.agentInterface.enableModelSelector = false; this.agentInterface.enableModelSelector = false;

View File

@ -80,7 +80,7 @@ export class Agent {
const { systemPrompt, model, messages } = this._state; const { systemPrompt, model, messages } = this._state;
console.log(message, { systemPrompt, model, messages }); console.log(message, { systemPrompt, model, messages });
} }
async prompt(input, attachments) { async prompt(input, attachments, opts) {
const model = this._state.model; const model = this._state.model;
if (!model) { if (!model) {
this.emit({ type: "error-no-model" }); this.emit({ type: "error-no-model" });
@ -111,16 +111,20 @@ export class Agent {
this.abortController = new AbortController(); this.abortController = new AbortController();
this.patch({ isStreaming: true, streamMessage: null, error: undefined }); this.patch({ isStreaming: true, streamMessage: null, error: undefined });
this.emit({ type: "started" }); this.emit({ type: "started" });
const reasoning = this._state.thinkingLevel === "off" const thinkingLevel = (opts?.thinkingOverride ?? this._state.thinkingLevel) ?? "off";
const reasoning = thinkingLevel === "off"
? undefined ? undefined
: this._state.thinkingLevel === "minimal" : thinkingLevel === "minimal"
? "low" ? "low"
: this._state.thinkingLevel; : thinkingLevel;
const shouldSendOverride = opts?.transient === true;
const cfg = { const cfg = {
systemPrompt: this._state.systemPrompt, systemPrompt: this._state.systemPrompt,
tools: this._state.tools, tools: this._state.tools,
model, model,
reasoning, reasoning,
thinkingOverride: shouldSendOverride ? thinkingLevel : undefined,
thinkingOnce: shouldSendOverride ? thinkingLevel : undefined,
getQueuedMessages: async () => { getQueuedMessages: async () => {
// Return queued messages (they'll be added to state via message_end event) // Return queued messages (they'll be added to state via message_end event)
const queued = this.messageQueue.slice(); const queued = this.messageQueue.slice();

View File

@ -31,6 +31,7 @@ async function fetchBootstrap() {
sessionKey, sessionKey,
basePath: info.basePath || "/webchat/", basePath: info.basePath || "/webchat/",
initialMessages: Array.isArray(info.initialMessages) ? info.initialMessages : [], initialMessages: Array.isArray(info.initialMessages) ? info.initialMessages : [],
thinkingLevel: typeof info.thinkingLevel === "string" ? info.thinkingLevel : "off",
}; };
} }
@ -50,14 +51,20 @@ class NativeTransport {
: btoa(String.fromCharCode(...new Uint8Array(a.content))), : btoa(String.fromCharCode(...new Uint8Array(a.content))),
})); }));
const rpcUrl = new URL("./rpc", window.location.href); const rpcUrl = new URL("./rpc", window.location.href);
const rpcBody = {
text: userMessage.content?.[0]?.text ?? "",
session: this.sessionKey,
attachments,
};
if (cfg?.thinkingOnce) {
rpcBody.thinkingOnce = cfg.thinkingOnce;
} else if (cfg?.thinkingOverride) {
rpcBody.thinking = cfg.thinkingOverride;
}
const resultResp = await fetch(rpcUrl, { const resultResp = await fetch(rpcUrl, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify(rpcBody),
text: userMessage.content?.[0]?.text ?? "",
session: this.sessionKey,
attachments,
}),
signal, signal,
}); });
@ -98,7 +105,7 @@ class NativeTransport {
const startChat = async () => { const startChat = async () => {
logStatus("boot: fetching session info"); logStatus("boot: fetching session info");
const { initialMessages, sessionKey } = await fetchBootstrap(); const { initialMessages, sessionKey, thinkingLevel } = await fetchBootstrap();
logStatus("boot: starting imports"); logStatus("boot: starting imports");
const { Agent } = await import("./agent/agent.js"); const { Agent } = await import("./agent/agent.js");
@ -154,7 +161,7 @@ const startChat = async () => {
initialState: { initialState: {
systemPrompt: "You are Clawd (primary session).", systemPrompt: "You are Clawd (primary session).",
model: getModel("anthropic", "claude-opus-4-5"), model: getModel("anthropic", "claude-opus-4-5"),
thinkingLevel: "off", thinkingLevel,
messages: initialMessages, messages: initialMessages,
}, },
transport: new NativeTransport(sessionKey), transport: new NativeTransport(sessionKey),
@ -175,7 +182,7 @@ const startChat = async () => {
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, { sessionThinkingLevel: thinkingLevel });
const mount = document.getElementById("app"); const mount = document.getElementById("app");
if (!mount) throw new Error("#app container missing"); if (!mount) throw new Error("#app container missing");

View File

@ -5,7 +5,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
return c > 3 && r && Object.defineProperty(target, key, r), r; return c > 3 && r && Object.defineProperty(target, key, r), r;
}; };
import { html, LitElement } from "lit"; import { html, LitElement } from "lit";
import { customElement, property, query } from "lit/decorators.js"; import { customElement, property, query, state } from "lit/decorators.js";
import { ModelSelector } from "../dialogs/ModelSelector.js"; import { ModelSelector } from "../dialogs/ModelSelector.js";
import "./MessageEditor.js"; import "./MessageEditor.js";
import "./MessageList.js"; import "./MessageList.js";
@ -21,6 +21,8 @@ let AgentInterface = class AgentInterface extends LitElement {
this.enableModelSelector = true; this.enableModelSelector = true;
this.enableThinkingSelector = true; this.enableThinkingSelector = true;
this.showThemeToggle = false; this.showThemeToggle = false;
this.sessionThinkingLevel = "off";
this.pendingThinkingLevel = null;
this._autoScroll = true; this._autoScroll = true;
this._lastScrollTop = 0; this._lastScrollTop = 0;
this._lastClientHeight = 0; this._lastClientHeight = 0;
@ -121,13 +123,16 @@ let AgentInterface = class AgentInterface extends LitElement {
} }
if (!this.session) if (!this.session)
return; return;
this._unsubscribeSession = this.session.subscribe(async (ev) => { this._unsubscribeSession = this.session.subscribe(async (ev) => {
if (ev.type === "state-update") { if (ev.type === "state-update") {
if (this._streamingContainer) { if (this.pendingThinkingLevel === null && ev.state.thinkingLevel) {
this._streamingContainer.isStreaming = ev.state.isStreaming; this.sessionThinkingLevel = ev.state.thinkingLevel;
this._streamingContainer.setMessage(ev.state.streamMessage, !ev.state.isStreaming); }
} if (this._streamingContainer) {
this.requestUpdate(); this._streamingContainer.isStreaming = ev.state.isStreaming;
this._streamingContainer.setMessage(ev.state.streamMessage, !ev.state.isStreaming);
}
this.requestUpdate();
} }
else if (ev.type === "error-no-model") { else if (ev.type === "error-no-model") {
// TODO show some UI feedback // TODO show some UI feedback
@ -164,11 +169,25 @@ let AgentInterface = class AgentInterface extends LitElement {
if (this.onBeforeSend) { if (this.onBeforeSend) {
await this.onBeforeSend(); await this.onBeforeSend();
} }
const baseThinking =
this.sessionThinkingLevel || session.state.thinkingLevel || "off";
const thinkingOverride = this.pendingThinkingLevel ?? baseThinking;
const transient =
this.pendingThinkingLevel !== null &&
this.pendingThinkingLevel !== baseThinking;
// Only clear editor after we know we can send // Only clear editor after we know we can send
this._messageEditor.value = ""; this._messageEditor.value = "";
this._messageEditor.attachments = []; this._messageEditor.attachments = [];
this._autoScroll = true; // Enable auto-scroll when sending a message this._autoScroll = true; // Enable auto-scroll when sending a message
await this.session?.prompt(input, attachments); await this.session?.prompt(input, attachments, {
thinkingOverride,
transient,
});
this.pendingThinkingLevel = null;
// Reset editor thinking selector to session baseline
if (this._messageEditor) {
this._messageEditor.thinkingLevel = this.sessionThinkingLevel || "off";
}
} }
renderMessages() { renderMessages() {
if (!this.session) if (!this.session)
@ -261,12 +280,12 @@ let AgentInterface = class AgentInterface extends LitElement {
<div class="max-w-3xl mx-auto px-2"> <div class="max-w-3xl mx-auto px-2">
<message-editor <message-editor
.isStreaming=${state.isStreaming} .isStreaming=${state.isStreaming}
.currentModel=${state.model} .currentModel=${state.model}
.thinkingLevel=${state.thinkingLevel} .thinkingLevel=${this.pendingThinkingLevel ?? this.sessionThinkingLevel ?? state.thinkingLevel}
.showAttachmentButton=${this.enableAttachments} .showAttachmentButton=${this.enableAttachments}
.showModelSelector=${this.enableModelSelector} .showModelSelector=${this.enableModelSelector}
.showThinkingSelector=${this.enableThinkingSelector} .showThinkingSelector=${this.enableThinkingSelector}
.onSend=${(input, attachments) => { .onSend=${(input, attachments) => {
this.sendMessage(input, attachments); this.sendMessage(input, attachments);
}} }}
.onAbort=${() => session.abort()} .onAbort=${() => session.abort()}
@ -275,7 +294,11 @@ let AgentInterface = class AgentInterface extends LitElement {
}} }}
.onThinkingChange=${this.enableThinkingSelector .onThinkingChange=${this.enableThinkingSelector
? (level) => { ? (level) => {
session.setThinkingLevel(level); this.pendingThinkingLevel = level;
if (this._messageEditor) {
this._messageEditor.thinkingLevel = level;
}
this.requestUpdate();
} }
: undefined} : undefined}
></message-editor> ></message-editor>
@ -298,6 +321,9 @@ __decorate([
__decorate([ __decorate([
property({ type: Boolean }) property({ type: Boolean })
], AgentInterface.prototype, "enableThinkingSelector", void 0); ], AgentInterface.prototype, "enableThinkingSelector", void 0);
__decorate([
property({ type: String })
], AgentInterface.prototype, "sessionThinkingLevel", void 0);
__decorate([ __decorate([
property({ type: Boolean }) property({ type: Boolean })
], AgentInterface.prototype, "showThemeToggle", void 0); ], AgentInterface.prototype, "showThemeToggle", void 0);
@ -319,6 +345,9 @@ __decorate([
__decorate([ __decorate([
query("streaming-message-container") query("streaming-message-container")
], AgentInterface.prototype, "_streamingContainer", void 0); ], AgentInterface.prototype, "_streamingContainer", void 0);
__decorate([
state()
], AgentInterface.prototype, "pendingThinkingLevel", void 0);
AgentInterface = __decorate([ AgentInterface = __decorate([
customElement("agent-interface") customElement("agent-interface")
], AgentInterface); ], AgentInterface);

View File

@ -196,7 +196,7 @@ var init_agent = __esmMin((() => {
messages messages
}); });
} }
async prompt(input, attachments) { async prompt(input, attachments, opts) {
const model = this._state.model; const model = this._state.model;
if (!model) { if (!model) {
this.emit({ type: "error-no-model" }); this.emit({ type: "error-no-model" });
@ -236,12 +236,16 @@ var init_agent = __esmMin((() => {
error: undefined error: undefined
}); });
this.emit({ type: "started" }); this.emit({ type: "started" });
const reasoning = this._state.thinkingLevel === "off" ? undefined : this._state.thinkingLevel === "minimal" ? "low" : this._state.thinkingLevel; const thinkingLevel = opts?.thinkingOverride ?? this._state.thinkingLevel ?? "off";
const reasoning = thinkingLevel === "off" ? undefined : thinkingLevel === "minimal" ? "low" : thinkingLevel;
const shouldSendOverride = opts?.transient === true;
const cfg = { const cfg = {
systemPrompt: this._state.systemPrompt, systemPrompt: this._state.systemPrompt,
tools: this._state.tools, tools: this._state.tools,
model, model,
reasoning, reasoning,
thinkingOverride: shouldSendOverride ? thinkingLevel : undefined,
thinkingOnce: shouldSendOverride ? thinkingLevel : undefined,
getQueuedMessages: async () => { getQueuedMessages: async () => {
const queued = this.messageQueue.slice(); const queued = this.messageQueue.slice();
this.messageQueue = []; this.messageQueue = [];
@ -107901,6 +107905,8 @@ var init_AgentInterface = __esmMin((() => {
this.enableModelSelector = true; this.enableModelSelector = true;
this.enableThinkingSelector = true; this.enableThinkingSelector = true;
this.showThemeToggle = false; this.showThemeToggle = false;
this.sessionThinkingLevel = "off";
this.pendingThinkingLevel = null;
this._autoScroll = true; this._autoScroll = true;
this._lastScrollTop = 0; this._lastScrollTop = 0;
this._lastClientHeight = 0; this._lastClientHeight = 0;
@ -107989,6 +107995,9 @@ var init_AgentInterface = __esmMin((() => {
if (!this.session) return; if (!this.session) return;
this._unsubscribeSession = this.session.subscribe(async (ev) => { this._unsubscribeSession = this.session.subscribe(async (ev) => {
if (ev.type === "state-update") { if (ev.type === "state-update") {
if (this.pendingThinkingLevel === null && ev.state.thinkingLevel) {
this.sessionThinkingLevel = ev.state.thinkingLevel;
}
if (this._streamingContainer) { if (this._streamingContainer) {
this._streamingContainer.isStreaming = ev.state.isStreaming; this._streamingContainer.isStreaming = ev.state.isStreaming;
this._streamingContainer.setMessage(ev.state.streamMessage, !ev.state.isStreaming); this._streamingContainer.setMessage(ev.state.streamMessage, !ev.state.isStreaming);
@ -108017,10 +108026,20 @@ var init_AgentInterface = __esmMin((() => {
if (this.onBeforeSend) { if (this.onBeforeSend) {
await this.onBeforeSend(); await this.onBeforeSend();
} }
const baseThinking = this.sessionThinkingLevel || session.state.thinkingLevel || "off";
const thinkingOverride = this.pendingThinkingLevel ?? baseThinking;
const transient = this.pendingThinkingLevel !== null && this.pendingThinkingLevel !== baseThinking;
this._messageEditor.value = ""; this._messageEditor.value = "";
this._messageEditor.attachments = []; this._messageEditor.attachments = [];
this._autoScroll = true; this._autoScroll = true;
await this.session?.prompt(input, attachments); await this.session?.prompt(input, attachments, {
thinkingOverride,
transient
});
this.pendingThinkingLevel = null;
if (this._messageEditor) {
this._messageEditor.thinkingLevel = this.sessionThinkingLevel || "off";
}
} }
renderMessages() { renderMessages() {
if (!this.session) return x`<div class="p-4 text-center text-muted-foreground">${i18n("No session available")}</div>`; if (!this.session) return x`<div class="p-4 text-center text-muted-foreground">${i18n("No session available")}</div>`;
@ -108109,12 +108128,12 @@ var init_AgentInterface = __esmMin((() => {
<div class="max-w-3xl mx-auto px-2"> <div class="max-w-3xl mx-auto px-2">
<message-editor <message-editor
.isStreaming=${state$1.isStreaming} .isStreaming=${state$1.isStreaming}
.currentModel=${state$1.model} .currentModel=${state$1.model}
.thinkingLevel=${state$1.thinkingLevel} .thinkingLevel=${this.pendingThinkingLevel ?? this.sessionThinkingLevel ?? state$1.thinkingLevel}
.showAttachmentButton=${this.enableAttachments} .showAttachmentButton=${this.enableAttachments}
.showModelSelector=${this.enableModelSelector} .showModelSelector=${this.enableModelSelector}
.showThinkingSelector=${this.enableThinkingSelector} .showThinkingSelector=${this.enableThinkingSelector}
.onSend=${(input, attachments) => { .onSend=${(input, attachments) => {
this.sendMessage(input, attachments); this.sendMessage(input, attachments);
}} }}
.onAbort=${() => session.abort()} .onAbort=${() => session.abort()}
@ -108122,7 +108141,11 @@ var init_AgentInterface = __esmMin((() => {
ModelSelector.open(state$1.model, (model) => session.setModel(model)); ModelSelector.open(state$1.model, (model) => session.setModel(model));
}} }}
.onThinkingChange=${this.enableThinkingSelector ? (level) => { .onThinkingChange=${this.enableThinkingSelector ? (level) => {
session.setThinkingLevel(level); this.pendingThinkingLevel = level;
if (this._messageEditor) {
this._messageEditor.thinkingLevel = level;
}
this.requestUpdate();
} : undefined} } : undefined}
></message-editor> ></message-editor>
${this.renderStats()} ${this.renderStats()}
@ -108136,6 +108159,7 @@ var init_AgentInterface = __esmMin((() => {
__decorate$17([n$1({ type: Boolean })], AgentInterface.prototype, "enableAttachments", void 0); __decorate$17([n$1({ type: Boolean })], AgentInterface.prototype, "enableAttachments", void 0);
__decorate$17([n$1({ type: Boolean })], AgentInterface.prototype, "enableModelSelector", void 0); __decorate$17([n$1({ type: Boolean })], AgentInterface.prototype, "enableModelSelector", void 0);
__decorate$17([n$1({ type: Boolean })], AgentInterface.prototype, "enableThinkingSelector", void 0); __decorate$17([n$1({ type: Boolean })], AgentInterface.prototype, "enableThinkingSelector", void 0);
__decorate$17([n$1({ type: String })], AgentInterface.prototype, "sessionThinkingLevel", void 0);
__decorate$17([n$1({ type: Boolean })], AgentInterface.prototype, "showThemeToggle", void 0); __decorate$17([n$1({ type: Boolean })], AgentInterface.prototype, "showThemeToggle", void 0);
__decorate$17([n$1({ attribute: false })], AgentInterface.prototype, "onApiKeyRequired", void 0); __decorate$17([n$1({ attribute: false })], AgentInterface.prototype, "onApiKeyRequired", void 0);
__decorate$17([n$1({ attribute: false })], AgentInterface.prototype, "onBeforeSend", void 0); __decorate$17([n$1({ attribute: false })], AgentInterface.prototype, "onBeforeSend", void 0);
@ -108143,6 +108167,7 @@ var init_AgentInterface = __esmMin((() => {
__decorate$17([n$1({ attribute: false })], AgentInterface.prototype, "onCostClick", void 0); __decorate$17([n$1({ attribute: false })], AgentInterface.prototype, "onCostClick", void 0);
__decorate$17([e$1("message-editor")], AgentInterface.prototype, "_messageEditor", void 0); __decorate$17([e$1("message-editor")], AgentInterface.prototype, "_messageEditor", void 0);
__decorate$17([e$1("streaming-message-container")], AgentInterface.prototype, "_streamingContainer", void 0); __decorate$17([e$1("streaming-message-container")], AgentInterface.prototype, "_streamingContainer", void 0);
__decorate$17([r()], AgentInterface.prototype, "pendingThinkingLevel", void 0);
AgentInterface = __decorate$17([t("agent-interface")], AgentInterface); AgentInterface = __decorate$17([t("agent-interface")], AgentInterface);
if (!customElements.get("agent-interface")) { if (!customElements.get("agent-interface")) {
customElements.define("agent-interface", AgentInterface); customElements.define("agent-interface", AgentInterface);
@ -195731,6 +195756,7 @@ var init_ChatPanel = __esmMin((() => {
this.agent = agent; this.agent = agent;
this.agentInterface = document.createElement("agent-interface"); this.agentInterface = document.createElement("agent-interface");
this.agentInterface.session = agent; this.agentInterface.session = agent;
this.agentInterface.sessionThinkingLevel = config?.sessionThinkingLevel ?? agent?.state?.thinkingLevel ?? "off";
this.agentInterface.enableAttachments = true; this.agentInterface.enableAttachments = true;
this.agentInterface.enableModelSelector = false; this.agentInterface.enableModelSelector = false;
this.agentInterface.enableThinkingSelector = true; this.agentInterface.enableThinkingSelector = true;
@ -196264,7 +196290,8 @@ async function fetchBootstrap() {
return { return {
sessionKey, sessionKey,
basePath: info$1.basePath || "/webchat/", basePath: info$1.basePath || "/webchat/",
initialMessages: Array.isArray(info$1.initialMessages) ? info$1.initialMessages : [] initialMessages: Array.isArray(info$1.initialMessages) ? info$1.initialMessages : [],
thinkingLevel: typeof info$1.thinkingLevel === "string" ? info$1.thinkingLevel : "off"
}; };
} }
var NativeTransport = class { var NativeTransport = class {
@ -196279,14 +196306,20 @@ var NativeTransport = class {
content: typeof a$2.content === "string" ? a$2.content : btoa(String.fromCharCode(...new Uint8Array(a$2.content))) content: typeof a$2.content === "string" ? a$2.content : btoa(String.fromCharCode(...new Uint8Array(a$2.content)))
})); }));
const rpcUrl = new URL("./rpc", window.location.href); const rpcUrl = new URL("./rpc", window.location.href);
const rpcBody = {
text: userMessage.content?.[0]?.text ?? "",
session: this.sessionKey,
attachments
};
if (cfg?.thinkingOnce) {
rpcBody.thinkingOnce = cfg.thinkingOnce;
} else if (cfg?.thinkingOverride) {
rpcBody.thinking = cfg.thinkingOverride;
}
const resultResp = await fetch(rpcUrl, { const resultResp = await fetch(rpcUrl, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify(rpcBody),
text: userMessage.content?.[0]?.text ?? "",
session: this.sessionKey,
attachments
}),
signal signal
}); });
if (!resultResp.ok) { if (!resultResp.ok) {
@ -196339,7 +196372,7 @@ var NativeTransport = class {
}; };
const startChat = async () => { const startChat = async () => {
logStatus("boot: fetching session info"); logStatus("boot: fetching session info");
const { initialMessages, sessionKey } = await fetchBootstrap(); const { initialMessages, sessionKey, thinkingLevel } = await fetchBootstrap();
logStatus("boot: starting imports"); logStatus("boot: starting imports");
const { Agent: Agent$1 } = await Promise.resolve().then(() => (init_agent(), agent_exports)); const { Agent: Agent$1 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
const { ChatPanel: ChatPanel$1 } = await Promise.resolve().then(() => (init_ChatPanel(), ChatPanel_exports)); const { ChatPanel: ChatPanel$1 } = await Promise.resolve().then(() => (init_ChatPanel(), ChatPanel_exports));
@ -196386,7 +196419,7 @@ const startChat = async () => {
initialState: { initialState: {
systemPrompt: "You are Clawd (primary session).", systemPrompt: "You are Clawd (primary session).",
model: getModel$1("anthropic", "claude-opus-4-5"), model: getModel$1("anthropic", "claude-opus-4-5"),
thinkingLevel: "off", thinkingLevel,
messages: initialMessages messages: initialMessages
}, },
transport: new NativeTransport(sessionKey) transport: new NativeTransport(sessionKey)
@ -196408,7 +196441,7 @@ const startChat = async () => {
const panel = new ChatPanel$1(); const panel = new ChatPanel$1();
panel.style.height = "100%"; panel.style.height = "100%";
panel.style.display = "block"; panel.style.display = "block";
await panel.setAgent(agent); await panel.setAgent(agent, { sessionThinkingLevel: thinkingLevel });
const mount = document.getElementById("app"); const mount = document.getElementById("app");
if (!mount) throw new Error("#app container missing"); if (!mount) throw new Error("#app container missing");
mount.dataset.booted = "1"; mount.dataset.booted = "1";

View File

@ -31,3 +31,8 @@
## Heartbeats ## Heartbeats
- Heartbeat probe body is `HEARTBEAT /think:high`, so it always asks for max thinking on the probe. Inline directive wins; session/global defaults are used only when no directive is present. - Heartbeat probe body is `HEARTBEAT /think:high`, so it always asks for max thinking on the probe. Inline directive wins; session/global defaults are used only when no directive is present.
## Web chat UI
- The web chat thinking selector mirrors the session's stored level from the inbound session store/config when the page loads.
- Picking another level applies only to the next message (`thinkingOnce`); after sending, the selector snaps back to the stored session level.
- To change the session default, send a `/think:<level>` directive (as before); the selector will reflect it after the next reload.

View File

@ -172,11 +172,17 @@ export async function agentCommand(
.filter((val) => val.length > 1); .filter((val) => val.length > 1);
const thinkOverride = normalizeThinkLevel(opts.thinking); const thinkOverride = normalizeThinkLevel(opts.thinking);
const thinkOnce = normalizeThinkLevel(opts.thinkingOnce);
if (opts.thinking && !thinkOverride) { if (opts.thinking && !thinkOverride) {
throw new Error( throw new Error(
"Invalid thinking level. Use one of: off, minimal, low, medium, high.", "Invalid thinking level. Use one of: off, minimal, low, medium, high.",
); );
} }
if (opts.thinkingOnce && !thinkOnce) {
throw new Error(
"Invalid one-shot thinking level. Use one of: off, minimal, low, medium, high.",
);
}
const verboseOverride = normalizeVerboseLevel(opts.verbose); const verboseOverride = normalizeVerboseLevel(opts.verbose);
if (opts.verbose && !verboseOverride) { if (opts.verbose && !verboseOverride) {
throw new Error('Invalid verbose level. Use "on" or "off".'); throw new Error('Invalid verbose level. Use "on" or "off".');
@ -213,8 +219,9 @@ export async function agentCommand(
const sendSystemOnce = sessionCfg?.sendSystemOnce === true; const sendSystemOnce = sessionCfg?.sendSystemOnce === true;
const isFirstTurnInSession = isNewSession || !systemSent; const isFirstTurnInSession = isNewSession || !systemSent;
// Merge thinking/verbose levels: flag override > persisted > defaults. // Merge thinking/verbose levels: one-shot override > flag override > persisted > defaults.
const resolvedThinkLevel: ThinkLevel | undefined = const resolvedThinkLevel: ThinkLevel | undefined =
thinkOnce ??
thinkOverride ?? thinkOverride ??
persistedThinking ?? persistedThinking ??
(replyCfg.thinkingDefault as ThinkLevel | undefined); (replyCfg.thinkingDefault as ThinkLevel | undefined);

View File

@ -1,19 +1,20 @@
import http from "node:http";
import path from "node:path";
import os from "node:os";
import { fileURLToPath } from "node:url";
import crypto from "node:crypto"; import crypto from "node:crypto";
import fs from "node:fs"; import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import sharp from "sharp"; import sharp from "sharp";
import { agentCommand } from "../commands/agent.js";
import { loadConfig } from "../config/config.js"; import { loadConfig } from "../config/config.js";
import { import {
loadSessionStore, loadSessionStore,
resolveStorePath, resolveStorePath,
type SessionEntry, type SessionEntry,
} from "../config/sessions.js"; } from "../config/sessions.js";
import { danger, info } from "../globals.js";
import { logDebug } from "../logger.js"; import { logDebug } from "../logger.js";
import { agentCommand } from "../commands/agent.js";
import type { RuntimeEnv } from "../runtime.js"; import type { RuntimeEnv } from "../runtime.js";
const WEBCHAT_DEFAULT_PORT = 18788; const WEBCHAT_DEFAULT_PORT = 18788;
@ -23,14 +24,6 @@ type WebChatServerState = {
port: number; port: number;
}; };
type ChatMessage = { role: string; content: string };
type AttachmentInput = {
content?: string;
mimeType?: string;
fileName?: string;
type?: string;
};
let state: WebChatServerState | null = null; let state: WebChatServerState | null = null;
function resolveWebRoot() { function resolveWebRoot() {
@ -39,17 +32,11 @@ function resolveWebRoot() {
// 1) Packaged app: resources live next to the relay bundle at // 1) Packaged app: resources live next to the relay bundle at
// Contents/Resources/WebChat. The relay binary runs from // Contents/Resources/WebChat. The relay binary runs from
// Contents/Resources/Relay/bun, so walk up one and check. // Contents/Resources/Relay/bun, so walk up one and check.
const packagedRoot = path.resolve( const packagedRoot = path.resolve(path.dirname(process.execPath), "../WebChat");
path.dirname(process.execPath),
"../WebChat",
);
if (fs.existsSync(packagedRoot)) return packagedRoot; if (fs.existsSync(packagedRoot)) return packagedRoot;
// 2) Dev / source checkout: repo-relative path. // 2) Dev / source checkout: repo-relative path.
return path.resolve( return path.resolve(here, "../../apps/macos/Sources/Clawdis/Resources/WebChat");
here,
"../../apps/macos/Sources/Clawdis/Resources/WebChat",
);
} }
function readBody(req: http.IncomingMessage): Promise<Buffer> { function readBody(req: http.IncomingMessage): Promise<Buffer> {
@ -62,28 +49,15 @@ function readBody(req: http.IncomingMessage): Promise<Buffer> {
}); });
} }
function pickSessionId( function pickSessionId(sessionKey: string, store: Record<string, SessionEntry>): string | null {
sessionKey: string,
store: Record<string, SessionEntry>,
): string | null {
if (store[sessionKey]?.sessionId) return store[sessionKey].sessionId; if (store[sessionKey]?.sessionId) return store[sessionKey].sessionId;
const first = Object.values(store)[0]?.sessionId; const first = Object.values(store)[0]?.sessionId;
return first ?? null; return first ?? null;
} }
function readSessionMessages( function readSessionMessages(sessionId: string, storePath: string): any[] {
sessionId: string,
storePath: string,
): ChatMessage[] {
const dir = path.dirname(storePath); const dir = path.dirname(storePath);
const candidates = [ const candidates = [path.join(dir, `${sessionId}.jsonl`), path.join(os.homedir(), ".tau/agent/sessions/clawdis", `${sessionId}.jsonl`)];
path.join(dir, `${sessionId}.jsonl`),
path.join(
os.homedir(),
".tau/agent/sessions/clawdis",
`${sessionId}.jsonl`,
),
];
let content: string | null = null; let content: string | null = null;
for (const p of candidates) { for (const p of candidates) {
if (fs.existsSync(p)) { if (fs.existsSync(p)) {
@ -97,7 +71,7 @@ function readSessionMessages(
} }
if (!content) return []; if (!content) return [];
const messages: ChatMessage[] = []; const messages: any[] = [];
for (const line of content.split(/\r?\n/)) { for (const line of content.split(/\r?\n/)) {
if (!line.trim()) continue; if (!line.trim()) continue;
try { try {
@ -113,32 +87,22 @@ function readSessionMessages(
} }
async function persistAttachments( async function persistAttachments(
attachments: AttachmentInput[], attachments: any[],
sessionId: string, sessionId: string,
): Promise<{ placeholder: string; path: string }[]> { ): Promise<{ placeholder: string; path: string }[]> {
const out: { placeholder: string; path: string }[] = []; const out: { placeholder: string; path: string }[] = [];
if (!attachments?.length) return out; if (!attachments?.length) return out;
const root = path.join( const root = path.join(os.homedir(), ".clawdis", "webchat-uploads", sessionId);
os.homedir(),
".clawdis",
"webchat-uploads",
sessionId,
);
await fs.promises.mkdir(root, { recursive: true }); await fs.promises.mkdir(root, { recursive: true });
let idx = 1; let idx = 1;
for (const att of attachments) { for (const att of attachments) {
try { try {
if (!att?.content || typeof att.content !== "string") continue; if (!att?.content || typeof att.content !== "string") continue;
const mime = const mime = typeof att.mimeType === "string" ? att.mimeType : "application/octet-stream";
typeof att.mimeType === "string"
? att.mimeType
: "application/octet-stream";
const baseName = att.fileName || `${att.type || "attachment"}-${idx}`; const baseName = att.fileName || `${att.type || "attachment"}-${idx}`;
const ext = mime.startsWith("image/") const ext = mime.startsWith("image/") ? mime.split("/")[1] || "bin" : "bin";
? mime.split("/")[1] || "bin"
: "bin";
const fileName = `${baseName}.${ext}`.replace(/[^a-zA-Z0-9._-]/g, "_"); const fileName = `${baseName}.${ext}`.replace(/[^a-zA-Z0-9._-]/g, "_");
const buf = Buffer.from(att.content, "base64"); const buf = Buffer.from(att.content, "base64");
@ -149,8 +113,7 @@ async function persistAttachments(
const image = sharp(buf, { failOn: "none" }); const image = sharp(buf, { failOn: "none" });
meta = await image.metadata(); meta = await image.metadata();
const needsResize = const needsResize =
(meta.width && meta.width > 2000) || (meta.width && meta.width > 2000) || (meta.height && meta.height > 2000);
(meta.height && meta.height > 2000);
if (needsResize) { if (needsResize) {
const resized = await image const resized = await image
.resize({ width: 2000, height: 2000, fit: "inside" }) .resize({ width: 2000, height: 2000, fit: "inside" })
@ -174,8 +137,7 @@ async function persistAttachments(
await fs.promises.writeFile(dest, finalBuf); await fs.promises.writeFile(dest, finalBuf);
const sizeLabel = `${(finalBuf.length / 1024).toFixed(0)} KB`; const sizeLabel = `${(finalBuf.length / 1024).toFixed(0)} KB`;
const dimLabel = const dimLabel = meta?.width && meta?.height ? `, ${meta.width}x${meta.height}` : "";
meta?.width && meta?.height ? `, ${meta.width}x${meta.height}` : "";
const placeholder = `[Attachment saved: ${dest} (${mime}${dimLabel}, ${sizeLabel})]`; const placeholder = `[Attachment saved: ${dest} (${mime}${dimLabel}, ${sizeLabel})]`;
out.push({ placeholder, path: dest }); out.push({ placeholder, path: dest });
} catch (err) { } catch (err) {
@ -187,34 +149,16 @@ async function persistAttachments(
return out; return out;
} }
function formatMessageWithAttachments( function formatMessageWithAttachments(text: string, saved: { placeholder: string }[]): string {
text: string,
saved: { placeholder: string }[],
): string {
if (!saved || saved.length === 0) return text; if (!saved || saved.length === 0) return text;
const parts = [text, ...saved.map((s) => `\n\n${s.placeholder}`)]; const parts = [text, ...saved.map((s) => `\n\n${s.placeholder}`)];
return parts.join(""); return parts.join("");
} }
type RpcPayload = { role: string; content: string }; async function handleRpc(body: any, sessionKey: string): Promise<{ ok: boolean; payloads?: any[]; error?: string }> {
const text: string = (body?.text ?? "").toString();
async function handleRpc(
body: unknown,
sessionKey: string,
): Promise<{ ok: boolean; payloads?: RpcPayload[]; error?: string }> {
const payload = body as {
text?: unknown;
attachments?: unknown;
thinking?: unknown;
deliver?: unknown;
to?: unknown;
};
const text: string = (payload.text ?? "").toString();
if (!text.trim()) return { ok: false, error: "empty text" }; if (!text.trim()) return { ok: false, error: "empty text" };
const attachments = Array.isArray(payload.attachments) const attachments = Array.isArray(body?.attachments) ? body.attachments : [];
? (payload.attachments as AttachmentInput[])
: [];
const cfg = loadConfig(); const cfg = loadConfig();
const replyCfg = cfg.inbound?.reply; const replyCfg = cfg.inbound?.reply;
@ -246,6 +190,7 @@ async function handleRpc(
message: formatMessageWithAttachments(text, savedAttachments), message: formatMessageWithAttachments(text, savedAttachments),
sessionId, sessionId,
thinking: body?.thinking, thinking: body?.thinking,
thinkingOnce: body?.thinkingOnce,
deliver: Boolean(body?.deliver), deliver: Boolean(body?.deliver),
to: body?.to, to: body?.to,
json: true, json: true,
@ -278,10 +223,7 @@ export async function startWebChatServer(port = WEBCHAT_DEFAULT_PORT) {
const server = http.createServer(async (req, res) => { const server = http.createServer(async (req, res) => {
if (!req.url) return notFound(res); if (!req.url) return notFound(res);
// enforce loopback only // enforce loopback only
if ( if (req.socket.remoteAddress && !req.socket.remoteAddress.startsWith("127.")) {
req.socket.remoteAddress &&
!req.socket.remoteAddress.startsWith("127.")
) {
res.statusCode = 403; res.statusCode = 403;
res.end("loopback only"); res.end("loopback only");
return; return;
@ -300,9 +242,9 @@ export async function startWebChatServer(port = WEBCHAT_DEFAULT_PORT) {
: resolveStorePath(undefined); : resolveStorePath(undefined);
const store = loadSessionStore(storePath); const store = loadSessionStore(storePath);
const sessionId = pickSessionId(sessionKey, store); const sessionId = pickSessionId(sessionKey, store);
const messages = sessionId const sessionEntry = sessionKey ? store[sessionKey] : undefined;
? readSessionMessages(sessionId, storePath) const persistedThinking = sessionEntry?.thinkingLevel;
: []; const messages = sessionId ? readSessionMessages(sessionId, storePath) : [];
res.setHeader("Content-Type", "application/json"); res.setHeader("Content-Type", "application/json");
res.end( res.end(
JSON.stringify({ JSON.stringify({
@ -312,6 +254,10 @@ export async function startWebChatServer(port = WEBCHAT_DEFAULT_PORT) {
sessionId, sessionId,
initialMessages: messages, initialMessages: messages,
basePath: "/", basePath: "/",
thinkingLevel:
typeof persistedThinking === "string"
? persistedThinking
: cfg.inbound?.reply?.thinkingDefault ?? "off",
}), }),
); );
return; return;
@ -319,7 +265,7 @@ export async function startWebChatServer(port = WEBCHAT_DEFAULT_PORT) {
if (isRpc && req.method === "POST") { if (isRpc && req.method === "POST") {
const bodyBuf = await readBody(req); const bodyBuf = await readBody(req);
let body: Record<string, unknown> = {}; let body: any = {};
try { try {
body = JSON.parse(bodyBuf.toString("utf-8")); body = JSON.parse(bodyBuf.toString("utf-8"));
} catch { } catch {
@ -334,7 +280,7 @@ export async function startWebChatServer(port = WEBCHAT_DEFAULT_PORT) {
if (url.pathname.startsWith("/webchat")) { if (url.pathname.startsWith("/webchat")) {
let rel = url.pathname.replace(/^\/webchat\/?/, ""); let rel = url.pathname.replace(/^\/webchat\/?/, "");
if (!rel || rel.endsWith("/")) rel = `${rel}index.html`; if (!rel || rel.endsWith("/")) rel = rel + "index.html";
const filePath = path.join(root, rel); const filePath = path.join(root, rel);
if (!filePath.startsWith(root)) return notFound(res); if (!filePath.startsWith(root)) return notFound(res);
if (!fs.existsSync(filePath)) return notFound(res); if (!fs.existsSync(filePath)) return notFound(res);