Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(desktop): Optimus notch capsule, live voice in Chat, thought process, rich markdown

Salman Qureshi6f0704e73709
diff --git a/apps/desktop/package-lock.json b/apps/desktop/package-lock.json
index 8ea1dbfa..882d773b 100644
--- a/apps/desktop/package-lock.json
+++ b/apps/desktop/package-lock.json
@@ -32,6 +32,7 @@
"react-dom": "^18.3.1",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
+ "shiki": "^4.5.0",
"zustand": "^5.0.5"
},
"devDependencies": {
@@ -1911,6 +1912,106 @@
"win32"
]
},
+ "node_modules/@shikijs/core": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.5.0.tgz",
+ "integrity": "sha512-6CIgwq+bt2JZ3OSjb/nBkkwEf/CfpHcbam+Mg5Pllco7HAGRQ2/EFhZrrJtbyNTgKwknfVS+llsXGygiDGwJWw==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/primitive": "4.5.0",
+ "@shikijs/types": "4.5.0",
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "@types/hast": "^3.0.5",
+ "hast-util-to-html": "^9.0.5"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@shikijs/engine-javascript": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.5.0.tgz",
+ "integrity": "sha512-Ed6UdEj84LyYkwnxM5CvSMWAD+id9ExTYri0/+x41U9zrgNifPSS9lZm0JqBP0VfYI8yr8tY5nbNq9+p9R0kFA==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "4.5.0",
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "oniguruma-to-es": "^4.3.6"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@shikijs/engine-oniguruma": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.5.0.tgz",
+ "integrity": "sha512-dKVmbJecVdB9recl8a/CU4jdpNXyjJQrIcesIkpS70s5HS02ohpnCSpMUbotPnEUzbAcLQ+S4hwZYbkBBiTcJw==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "4.5.0",
+ "@shikijs/vscode-textmate": "^10.0.2"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@shikijs/langs": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.5.0.tgz",
+ "integrity": "sha512-wwBTqwduXSz0X4v9Qa2EWeFaYJEw1clCncWjoRNQRbVDu3SPRTRWucnouYapKj3b8Q+sk/41Vbc4B5c8nuYzLA==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "4.5.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@shikijs/primitive": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.5.0.tgz",
+ "integrity": "sha512-UM7ShlA8oz0OWxLLO8BmO9Ip6fVqdkt8yF0EH7nOCqHfrx1eEAzF0ZUVK7L+I8NEgeu1PEWSRlxaiPPeCb4iDg==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "4.5.0",
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "@types/hast": "^3.0.5"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@shikijs/themes": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.5.0.tgz",
+ "integrity": "sha512-zGb87H3UBbpuI4yoh5UguB1XbU+2BDU3kflM7UfZ+Cy2hWo9lBtqjSVK20gmLY6ukYl040hAypGXMgud9vul8Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "4.5.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@shikijs/types": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.5.0.tgz",
+ "integrity": "sha512-drtPrtD8N0DENyD2cyt6Ajy+IWsiCLgMxODwLTpvH1UsN6a9jf90tNTPjqwHvA+0Lzu9e0txk8DjfqH1p9UJRw==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "@types/hast": "^3.0.5"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@shikijs/vscode-textmate": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.1.0.tgz",
+ "integrity": "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ==",
+ "license": "MIT"
+ },
"node_modules/@tauri-apps/api": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.4.tgz",
@@ -3243,6 +3344,29 @@
"node": ">= 0.4"
}
},
+ "node_modules/hast-util-to-html": {
+ "version": "9.0.5",
+ "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",
+ "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "ccount": "^2.0.0",
+ "comma-separated-tokens": "^2.0.0",
+ "hast-util-whitespace": "^3.0.0",
+ "html-void-elements": "^3.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "property-information": "^7.0.0",
+ "space-separated-tokens": "^2.0.0",
+ "stringify-entities": "^4.0.0",
+ "zwitch": "^2.0.4"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/hast-util-to-jsx-runtime": {
"version": "2.3.6",
"resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",
@@ -3293,6 +3417,16 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/html-void-elements": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz",
+ "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/inline-style-parser": {
"version": "0.2.7",
"resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",
@@ -4504,6 +4638,23 @@
"node": ">= 6"
}
},
+ "node_modules/oniguruma-parser": {
+ "version": "0.12.2",
+ "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz",
+ "integrity": "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==",
+ "license": "MIT"
+ },
+ "node_modules/oniguruma-to-es": {
+ "version": "4.3.6",
+ "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.6.tgz",
+ "integrity": "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==",
+ "license": "MIT",
+ "dependencies": {
+ "oniguruma-parser": "^0.12.2",
+ "regex": "^6.1.0",
+ "regex-recursion": "^6.0.2"
+ }
+ },
"node_modules/parse-entities": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",
@@ -4928,6 +5079,30 @@
"node": ">=8.10.0"
}
},
+ "node_modules/regex": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz",
+ "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==",
+ "license": "MIT",
+ "dependencies": {
+ "regex-utilities": "^2.3.0"
+ }
+ },
+ "node_modules/regex-recursion": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz",
+ "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==",
+ "license": "MIT",
+ "dependencies": {
+ "regex-utilities": "^2.3.0"
+ }
+ },
+ "node_modules/regex-utilities": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz",
+ "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==",
+ "license": "MIT"
+ },
"node_modules/remark-gfm": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",
@@ -5116,6 +5291,25 @@
"semver": "bin/semver.js"
}
},
+ "node_modules/shiki": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.5.0.tgz",
+ "integrity": "sha512-OcRW72ngQvc+MSVWBRIovC/BTW589iUE/Vxav7VeM4RcY9MUjqB+IR6ILG1k9nuW6LiG/nct9uma4/MBtnZbmQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/core": "4.5.0",
+ "@shikijs/engine-javascript": "4.5.0",
+ "@shikijs/engine-oniguruma": "4.5.0",
+ "@shikijs/langs": "4.5.0",
+ "@shikijs/themes": "4.5.0",
+ "@shikijs/types": "4.5.0",
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "@types/hast": "^3.0.5"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 6f1dcb75..9f6f07a9 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -39,6 +39,7 @@
"react-dom": "^18.3.1",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
+ "shiki": "^4.5.0",
"zustand": "^5.0.5"
},
"devDependencies": {
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock
index fb0b48c2..3b9bf99d 100644
--- a/apps/desktop/src-tauri/Cargo.lock
+++ b/apps/desktop/src-tauri/Cargo.lock
@@ -2415,6 +2415,7 @@ dependencies = [
"flate2",
"keyring",
"log",
+ "objc2-app-kit",
"reqwest 0.12.28",
"serde",
"serde_json",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index f68bb228..f560d469 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -16,7 +16,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]
tauri-build = { version = "2.7", features = [] }
[dependencies]
-tauri = { version = "2.12", features = ["tray-icon", "image-png"] }
+tauri = { version = "2.12", features = ["tray-icon", "image-png", "macos-private-api"] }
tauri-plugin-single-instance = { version = "2.5", features = ["deep-link"] }
tauri-plugin-window-state = "2.5"
tauri-plugin-store = "2.5"
@@ -41,6 +41,10 @@ serde_json = "1"
dirs = "6"
log = "0.4"
+[target.'cfg(target_os = "macos")'.dependencies]
+# The voice capsule sits above the menu bar (see src/notch.rs).
+objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWindow", "NSResponder"] }
+
[profile.release]
codegen-units = 1
lto = true
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json
index 976467e7..05f3c6ff 100644
--- a/apps/desktop/src-tauri/capabilities/default.json
+++ b/apps/desktop/src-tauri/capabilities/default.json
@@ -2,7 +2,9 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "What the main window may ask the native side for.",
- "windows": ["main"],
+ "windows": [
+ "main"
+ ],
"permissions": [
"core:default",
"core:window:allow-show",
diff --git a/apps/desktop/src-tauri/capabilities/notch.json b/apps/desktop/src-tauri/capabilities/notch.json
new file mode 100644
index 00000000..0fb21a89
--- /dev/null
+++ b/apps/desktop/src-tauri/capabilities/notch.json
@@ -0,0 +1,12 @@
+{
+ "$schema": "../gen/schemas/desktop-schema.json",
+ "identifier": "notch",
+ "description": "The voice capsule: it only listens for state and sends controls back to the main window.",
+ "windows": [
+ "notch"
+ ],
+ "permissions": [
+ "core:event:default",
+ "core:window:allow-set-size"
+ ]
+}
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index d96ccbb3..b5939141 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -6,6 +6,7 @@
//! (../../../ui), talking to a runtime over its HTTP API.
mod commands;
+mod notch;
mod tray;
use tauri::{AppHandle, Manager, WindowEvent};
@@ -44,6 +45,8 @@ pub fn run() {
commands::secrets::secret_get,
commands::secrets::secret_set,
commands::secrets::secret_delete,
+ notch::notch_show,
+ notch::notch_hide,
])
.setup(|app| {
tray::install(app.handle())?;
diff --git a/apps/desktop/src-tauri/src/notch.rs b/apps/desktop/src-tauri/src/notch.rs
new file mode 100644
index 00000000..acdd101e
--- /dev/null
+++ b/apps/desktop/src-tauri/src/notch.rs
@@ -0,0 +1,77 @@
+//! The voice capsule: a small borderless window that drops from the top
+//! centre of the main display while Optimus is listening or speaking.
+//!
+//! On macOS it sits ABOVE the menu bar (status-window level) so it reads as
+//! coming out of the notch — on Macs with a notch it hangs from it, on Macs
+//! without one it takes the same place — and it follows the user across
+//! Spaces and over full-screen apps without stealing focus. Elsewhere it is
+//! an always-on-top pill at the top centre.
+
+use tauri::{AppHandle, LogicalPosition, LogicalSize, Manager, WebviewUrl, WebviewWindowBuilder};
+
+pub const LABEL: &str = "notch";
+
+#[tauri::command]
+pub fn notch_show(app: AppHandle, width: f64, height: f64) -> Result<(), String> {
+ let width = width.clamp(240.0, 640.0);
+ let height = height.clamp(32.0, 320.0);
+ let window = match app.get_webview_window(LABEL) {
+ Some(w) => w,
+ None => WebviewWindowBuilder::new(&app, LABEL, WebviewUrl::App("index.html?surface=notch".into()))
+ .title("Mercury voice")
+ .inner_size(width, height)
+ .decorations(false)
+ .transparent(true)
+ .shadow(false)
+ .resizable(false)
+ .always_on_top(true)
+ .skip_taskbar(true)
+ .visible_on_all_workspaces(true)
+ .focused(false)
+ .visible(false)
+ .build()
+ .map_err(|e| e.to_string())?,
+ };
+ window.set_size(LogicalSize::new(width, height)).map_err(|e| e.to_string())?;
+ if let Some(monitor) = window.primary_monitor().map_err(|e| e.to_string())? {
+ let scale = monitor.scale_factor();
+ let screen = monitor.size().to_logical::<f64>(scale);
+ let origin = monitor.position().to_logical::<f64>(scale);
+ window
+ .set_position(LogicalPosition::new(origin.x + (screen.width - width) / 2.0, origin.y))
+ .map_err(|e| e.to_string())?;
+ }
+ #[cfg(target_os = "macos")]
+ raise_above_menu_bar(&window);
+ window.show().map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+#[tauri::command]
+pub fn notch_hide(app: AppHandle) -> Result<(), String> {
+ if let Some(w) = app.get_webview_window(LABEL) {
+ w.hide().map_err(|e| e.to_string())?;
+ }
+ Ok(())
+}
+
+#[cfg(target_os = "macos")]
+fn raise_above_menu_bar(window: &tauri::WebviewWindow) {
+ use objc2_app_kit::{NSWindow, NSWindowCollectionBehavior};
+ let Ok(ptr) = window.ns_window() else { return };
+ if ptr.is_null() {
+ return;
+ }
+ // SAFETY: Tauri hands back the live NSWindow of this webview window; it is
+ // used on the main thread (commands run there for window work) and not retained.
+ let ns: &NSWindow = unsafe { &*(ptr as *const NSWindow) };
+ // NSStatusWindowLevel (25) + 1: above the menu bar and its status items.
+ ns.setLevel(26);
+ ns.setCollectionBehavior(
+ NSWindowCollectionBehavior::CanJoinAllSpaces
+ | NSWindowCollectionBehavior::Stationary
+ | NSWindowCollectionBehavior::FullScreenAuxiliary
+ | NSWindowCollectionBehavior::IgnoresCycle,
+ );
+ ns.setHasShadow(false);
+}
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index d8257559..bc88aca5 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -39,7 +39,8 @@
"frame-src": "'none'",
"object-src": "'none'"
}
- }
+ },
+ "macOSPrivateApi": true
},
"bundle": {
"active": true,
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index f0a9e12b..6c9f2cac 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -51,6 +51,25 @@ export interface ChatMessage {
steps?: ToolStep[];
/** Files sent with this message. `url` is an API path (auth required); `src` is a local preview. */
attachments?: MessageAttachment[];
+ /** How the answer was reached (live turns only): reasoning and steps. */
+ trace?: ThoughtTrace;
+}
+
+export interface ThoughtStep {
+ id: number;
+ tool: string;
+ label: string;
+ status: "running" | "done" | "error";
+ summary?: string;
+ startedAt: number;
+ endedAt?: number;
+}
+
+export interface ThoughtTrace {
+ reasoning: string;
+ steps: ThoughtStep[];
+ startedAt: number;
+ endedAt?: number;
}
export interface MessageAttachment {
diff --git a/apps/desktop/src/app/conversation.ts b/apps/desktop/src/app/conversation.ts
index a6ad4a69..2fb52af1 100644
--- a/apps/desktop/src/app/conversation.ts
+++ b/apps/desktop/src/app/conversation.ts
@@ -7,7 +7,7 @@
import { createContext, useContext } from "react";
import { create, type StoreApi, type UseBoundStore } from "zustand";
-import type { ChatMessage, PendingPrompt } from "~/api/types";
+import type { ChatMessage, PendingPrompt, ThoughtTrace } from "~/api/types";
import type { AgentState } from "./store";
export type Surface = "chat" | "code";
@@ -21,6 +21,10 @@ export interface ConversationState {
agent: AgentState;
step: { total: number; current: number; tool: string } | null;
prompts: PendingPrompt[];
+ /** The current turn's thought process, streaming. */
+ live: ThoughtTrace | null;
+ setLive(update: (live: ThoughtTrace) => ThoughtTrace): void;
+ clearLive(): void;
setActive(id: string | null): void;
setMessages(messages: ChatMessage[]): void;
addMessage(message: ChatMessage): void;
@@ -45,7 +49,10 @@ function makeConversation(surface: Surface): ConversationStore {
agent: "idle",
step: null,
prompts: [],
- setActive: (activeId) => set({ activeId, prompts: [], step: null, agent: "idle" }),
+ live: null,
+ setLive: (update) => set((s) => ({ live: update(s.live ?? { reasoning: "", steps: [], startedAt: Date.now() }) })),
+ clearLive: () => set({ live: null }),
+ setActive: (activeId) => set({ activeId, prompts: [], step: null, agent: "idle", live: null }),
setMessages: (messages) => set({ messages }),
addMessage: (message) => set((s) => ({ messages: [...s.messages, message] })),
appendStreaming: (text) => set((s) => ({ streaming: s.streaming + text })),
diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.ts
index cabb2708..9bf4d91e 100644
--- a/apps/desktop/src/app/events.ts
+++ b/apps/desktop/src/app/events.ts
@@ -90,20 +90,44 @@ function handleEvent(store: ConversationStore, event: string, raw: string): void
break;
case "thinking":
conv.setAgent("thinking");
+ conv.setLive((l) => l);
break;
- case "step_start":
- case "step_done":
- conv.setStep({ total: Number(data.totalSteps ?? 0), current: Number(data.stepNumber ?? 0), tool: String(data.tool ?? "") });
+ case "reasoning":
+ if (data.done === true) break;
+ if (typeof data.text === "string" && data.text) conv.setLive((l) => ({ ...l, reasoning: (l.reasoning + data.text).slice(-20_000) }));
+ break;
+ case "step_start": {
+ const tool = String(data.tool ?? "");
+ conv.setStep({ total: Number(data.totalSteps ?? 0), current: Number(data.step ?? data.stepNumber ?? 0), tool });
conv.setAgent("working");
+ conv.setLive((l) => ({ ...l, steps: [...l.steps, { id: Number(data.step ?? l.steps.length + 1), tool, label: String(data.label ?? tool), status: "running" as const, startedAt: Date.now() }].slice(-100) }));
+ break;
+ }
+ case "step_done": {
+ const tool = String(data.tool ?? "");
+ const summary = typeof data.summary === "string" ? data.summary : undefined;
+ const failed = !!summary && /^(error|failed|denied|blocked)\b/i.test(summary.trim());
+ conv.setStep({ total: Number(data.totalSteps ?? 0), current: Number(data.stepNumber ?? 0), tool });
+ conv.setLive((l) => {
+ const steps = [...l.steps];
+ for (let i = steps.length - 1; i >= 0; i--) {
+ if (steps[i].status === "running" && steps[i].tool === tool) { steps[i] = { ...steps[i], status: failed ? "error" : "done", summary, endedAt: Date.now() }; break; }
+ }
+ return { ...l, steps };
+ });
break;
+ }
case "text_delta":
conv.setAgent("streaming");
conv.appendStreaming(String(data.text ?? ""));
break;
case "text_done": {
const text = String(data.fullText ?? data.text ?? raw);
+ const live = store.getState().live;
+ const trace = live && (live.reasoning || live.steps.length) ? { ...live, endedAt: Date.now(), steps: live.steps.map((st) => st.status === "running" ? { ...st, status: "done" as const, endedAt: Date.now() } : st) } : undefined;
conv.clearStreaming();
- conv.addMessage({ id: crypto.randomUUID(), role: "assistant", content: text, timestamp: new Date().toISOString() });
+ conv.clearLive();
+ conv.addMessage({ id: crypto.randomUUID(), role: "assistant", content: text, timestamp: new Date().toISOString(), ...(trace ? { trace } : {}) });
conv.setStep(null);
store.getState().setAgent(store.getState().prompts.length ? "needs-you" : "idle");
void refreshThreads();
@@ -125,6 +149,7 @@ function handleEvent(store: ConversationStore, event: string, raw: string): void
case "error": {
const message = typeof data.message === "string" ? data.message : raw || "Something went wrong";
conv.clearStreaming();
+ conv.clearLive();
conv.setStep(null);
conv.setAgent("idle");
conv.addMessage({ id: crypto.randomUUID(), role: "system", content: message, timestamp: new Date().toISOString() });
@@ -214,6 +239,7 @@ export async function sendMessage(surface: Surface, content: string, attachments
};
store.getState().addMessage(optimistic);
store.getState().setAgent("thinking");
+ store.getState().setLive(() => ({ reasoning: "", steps: [], startedAt: Date.now() }));
await api.chat.send(content, id, attachments.map(({ name, data }) => ({ name, data })), code ? { programming: code.mode, cwd: code.folder ?? undefined } : undefined);
void refreshThreads();
}
diff --git a/apps/desktop/src/app/store.ts b/apps/desktop/src/app/store.ts
index 62cceb90..1a64fe06 100644
--- a/apps/desktop/src/app/store.ts
+++ b/apps/desktop/src/app/store.ts
@@ -15,6 +15,9 @@ export type AgentState = "idle" | "thinking" | "streaming" | "working" | "needs-
interface UiState {
view: View;
setView(view: View): void;
+ /** Chat is showing the live Optimus voice session instead of a thread. */
+ voiceOpen: boolean;
+ setVoiceOpen(open: boolean): void;
sidebar: boolean;
toggleSidebar(): void;
}
@@ -22,6 +25,8 @@ interface UiState {
export const useUi = create<UiState>((set) => ({
view: "chat",
setView: (view) => set({ view }),
+ voiceOpen: false,
+ setVoiceOpen: (voiceOpen) => set({ voiceOpen }),
sidebar: true,
toggleSidebar: () => set((s) => ({ sidebar: !s.sidebar })),
}));
diff --git a/apps/desktop/src/app/voice.ts b/apps/desktop/src/app/voice.ts
new file mode 100644
index 00000000..d0df7e5b
--- /dev/null
+++ b/apps/desktop/src/app/voice.ts
@@ -0,0 +1,114 @@
+/* ═══════════════════════════════════════════════════════════════
+ Optimus voice, from the runtime's /api/voice feed. The main window
+ streams it, mirrors it to the notch capsule, and turns the capsule's
+ buttons into /api/voice/control calls.
+ ═══════════════════════════════════════════════════════════════ */
+
+import { useEffect } from "react";
+import { create } from "zustand";
+import { http } from "~/api/client";
+import { openStream } from "~/api/stream";
+import { isTauri } from "~/shell/tauri";
+
+export type VoiceAction = "mute" | "unmute" | "interrupt" | "stop";
+
+export interface VoiceTurn {
+ id: number;
+ role: "owner" | "mercury" | "activity" | "approval" | "system";
+ text: string;
+ at: number;
+}
+
+export interface VoiceState {
+ available: boolean;
+ plugin: string | null;
+ active: boolean;
+ callId: string | null;
+ startedAt: number | null;
+ endedAt: number | null;
+ listening: boolean;
+ speaking: boolean;
+ working: boolean;
+ muted: boolean;
+ thinking: boolean;
+ activity: string | null;
+ outcome: string | null;
+ turns: VoiceTurn[];
+}
+
+export type VoicePhase = "off" | "listening" | "speaking" | "thinking" | "working" | "muted";
+
+export function phaseOf(s: Pick<VoiceState, "active" | "listening" | "speaking" | "thinking" | "working" | "muted">): VoicePhase {
+ if (!s.active) return "off";
+ if (s.muted) return "muted";
+ if (s.speaking) return "speaking";
+ if (s.working) return "working";
+ if (s.thinking) return "thinking";
+ return "listening";
+}
+
+export const PHASE_LABEL: Record<VoicePhase, string> = {
+ off: "Optimus",
+ listening: "Listening",
+ speaking: "Speaking",
+ thinking: "Thinking",
+ working: "Working",
+ muted: "Muted",
+};
+
+const EMPTY: VoiceState = {
+ available: false, plugin: null, active: false, callId: null, startedAt: null, endedAt: null,
+ listening: false, speaking: false, working: false, muted: false, thinking: false, activity: null, outcome: null, turns: [],
+};
+
+export const useVoice = create<VoiceState & { supported: boolean }>(() => ({ ...EMPTY, supported: true }));
+
+export async function voiceControl(action: VoiceAction): Promise<void> {
+ await http.post("/api/voice/control", { action });
+}
+
+/** Main window: stream the feed, mirror it to the capsule, show/hide the capsule. */
+export function useVoiceFeed(connectionId: string): void {
+ useEffect(() => {
+ let closed = false;
+ void http.get<VoiceState>("/api/voice")
+ .then((s) => { if (!closed) useVoice.setState({ ...s, supported: true }); })
+ .catch(() => { if (!closed) useVoice.setState({ ...EMPTY, supported: false }); });
+ const stream = openStream("/api/voice/events", {
+ onEvent: (event, raw) => {
+ try {
+ const data = JSON.parse(raw);
+ if (event === "state") {
+ const { turns, ...rest } = data as VoiceState;
+ useVoice.setState((s) => ({ ...s, ...rest, turns: Array.isArray(turns) ? turns : rest.active && !s.active ? [] : s.turns, supported: true }));
+ } else if (event === "turn") {
+ useVoice.setState((s) => ({ turns: [...s.turns.filter((t) => t.id !== (data as VoiceTurn).id), data as VoiceTurn].slice(-200) }));
+ }
+ } catch { /* ignore a bad frame */ }
+ },
+ });
+ return () => { closed = true; stream.close(); };
+ }, [connectionId]);
+
+ // The capsule: shown while a session runs, given every change.
+ useEffect(() => {
+ if (!isTauri) return;
+ let unlisten: (() => void) | null = null;
+ let shown = false;
+ void (async () => {
+ const { invoke } = await import("@tauri-apps/api/core");
+ const { emitTo, listen } = await import("@tauri-apps/api/event");
+ unlisten = await listen<{ action: VoiceAction }>("voice-control", (e) => { void voiceControl(e.payload.action).catch(() => {}); });
+ const push = async (s: VoiceState) => {
+ if (s.active && !shown) { shown = true; await invoke("notch_show", { width: 440, height: 52 }).catch(() => {}); }
+ if (!s.active && shown) { shown = false; await invoke("notch_hide").catch(() => {}); }
+ if (s.active) await emitTo("notch", "voice-state", { ...s, turns: s.turns.slice(-3) }).catch(() => {});
+ };
+ const off = useVoice.subscribe((s) => { void push(s); });
+ const prev = unlisten;
+ unlisten = () => { off(); prev?.(); };
+ void push(useVoice.getState());
+ })();
+ return () => { unlisten?.(); };
+ }, []);
+}
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsx
index 39d68c53..ad46e96e 100644
--- a/apps/desktop/src/components/Markdown.tsx
+++ b/apps/desktop/src/components/Markdown.tsx
@@ -1,55 +1,123 @@
-import { memo, useState } from "react";
-import ReactMarkdown from "react-markdown";
+import { Children, isValidElement, memo, useEffect, useState, type ReactElement, type ReactNode } from "react";
+import ReactMarkdown, { type Components } from "react-markdown";
import remarkGfm from "remark-gfm";
-import { Check, Copy } from "lucide-react";
+import { AlertTriangle, Check, CircleAlert, Copy, Info, Lightbulb, OctagonAlert, WrapText } from "lucide-react";
+import { cx } from "~/lib/cx";
+import { highlight, languageOf } from "./highlight";
-/** The agent's answers. Code blocks get a copy button; links open outside. */
-export const Markdown = memo(function Markdown({ text }: { text: string }) {
+/**
+ * The agent's answers, rendered for reading:
+ * - code blocks: syntax highlighted (lazy Shiki, light + dark), language
+ * label, copy, soft-wrap toggle; not highlighted while still streaming;
+ * - task lists as real checkboxes, done items struck through;
+ * - GitHub alerts (> [!NOTE] / TIP / IMPORTANT / WARNING / CAUTION) as callouts;
+ * - tables in a scroll box; links open outside; images rounded.
+ */
+export const Markdown = memo(function Markdown({ text, streaming = false }: { text: string; streaming?: boolean }) {
+ const components: Components = {
+ a: ({ href, children }) => <a href={href} target="_blank" rel="noopener noreferrer">{children}</a>,
+ pre: ({ children }) => <CodeBlock streaming={streaming}>{children}</CodeBlock>,
+ code: ({ className, children, ...rest }) => <code className={className} {...rest}>{children}</code>,
+ table: ({ children }) => <div className="md-table"><table>{children}</table></div>,
+ blockquote: ({ children }) => <Blockquote>{children}</Blockquote>,
+ li: ({ className, children }) => {
+ const task = typeof className === "string" && className.includes("task-list-item");
+ if (!task) return <li>{children}</li>;
+ const items = Children.toArray(children);
+ const box = items.find((c) => isValidElement(c) && (c as ReactElement<{ type?: string }>).props.type === "checkbox") as ReactElement<{ checked?: boolean }> | undefined;
+ const checked = Boolean(box?.props.checked);
+ const rest = items.filter((c) => c !== box);
+ return (
+ <li className={cx("md-task", checked && "md-task-done")}>
+ <span className={cx("md-check", checked && "md-check-on")} aria-hidden="true">{checked && <Check size={11} strokeWidth={3} />}</span>
+ <span className="sr-only">{checked ? "Done: " : "To do: "}</span>
+ <span className="md-task-text">{rest}</span>
+ </li>
+ );
+ },
+ ul: ({ className, children }) => <ul className={cx(typeof className === "string" && className.includes("contains-task-list") && "md-task-list")}>{children}</ul>,
+ input: () => null,
+ };
return (
<div className="prose" data-selectable>
- <ReactMarkdown
- remarkPlugins={[remarkGfm]}
- components={{
- a: ({ href, children }) => (
- <a href={href} target="_blank" rel="noopener noreferrer">{children}</a>
- ),
- pre: ({ children }) => <CodeBlock>{children}</CodeBlock>,
- }}
- >
- {text}
- </ReactMarkdown>
+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>{text}</ReactMarkdown>
</div>
);
});
-function CodeBlock({ children }: { children: React.ReactNode }) {
+function CodeBlock({ children, streaming }: { children: ReactNode; streaming: boolean }) {
+ const child = Children.only(children) as ReactElement<{ className?: string; children?: ReactNode }>;
+ const raw = extractText(child?.props?.children).replace(/\n$/, "");
+ const langRaw = /language-([\w+#-]+)/.exec(child?.props?.className ?? "")?.[1];
+ const lang = languageOf(langRaw);
+ const [html, setHtml] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
+ const [wrap, setWrap] = useState(false);
+
+ useEffect(() => {
+ if (streaming || !lang) { setHtml(null); return; }
+ let live = true;
+ void highlight(raw, lang).then((h) => { if (live) setHtml(h); }).catch(() => {});
+ return () => { live = false; };
+ }, [raw, lang, streaming]);
+
async function copy() {
- const node = document.activeElement?.closest?.("pre") ?? null;
- const text = extractText(children) || node?.textContent || "";
try {
- await navigator.clipboard.writeText(text);
+ await navigator.clipboard.writeText(raw);
setCopied(true);
setTimeout(() => setCopied(false), 1200);
- } catch { /* clipboard blocked */ }
+ } catch { /* blocked */ }
}
+
return (
- <div className="group relative">
- <pre>{children}</pre>
- <button
- onClick={() => void copy()}
- className="absolute right-2 top-2 rounded-md border border-line bg-surface p-1 text-ink3 opacity-0 transition-opacity hover:text-ink group-hover:opacity-100"
- aria-label="Copy code"
- >
- {copied ? <Check size={13} className="text-accent" /> : <Copy size={13} />}
- </button>
+ <div className="md-code group">
+ <div className="md-code-bar">
+ <span className="md-code-lang">{langRaw ?? "text"}</span>
+ <span className="flex-1" />
+ <button onClick={() => setWrap((w) => !w)} className={cx("md-code-btn", wrap && "md-code-btn-on")} aria-label="Wrap lines" title="Wrap lines"><WrapText size={13} /></button>
+ <button onClick={() => void copy()} className="md-code-btn" aria-label="Copy code">{copied ? <><Check size={13} /> Copied</> : <><Copy size={13} /> Copy</>}</button>
+ </div>
+ {html
+ ? <div className={cx("md-code-body", wrap && "md-wrap")} dangerouslySetInnerHTML={{ __html: html }} />
+ : <pre className={cx("md-code-body", wrap && "md-wrap")}><code>{raw}</code></pre>}
</div>
);
}
-function extractText(node: React.ReactNode): string {
- if (typeof node === "string") return node;
+const ALERTS = {
+ NOTE: { icon: Info, label: "Note", tone: "md-alert-note" },
+ TIP: { icon: Lightbulb, label: "Tip", tone: "md-alert-tip" },
+ IMPORTANT: { icon: CircleAlert, label: "Important", tone: "md-alert-important" },
+ WARNING: { icon: AlertTriangle, label: "Warning", tone: "md-alert-warning" },
+ CAUTION: { icon: OctagonAlert, label: "Caution", tone: "md-alert-caution" },
+} as const;
+
+/** `> [!NOTE]` … becomes a callout; any other quote stays a quote. */
+function Blockquote({ children }: { children: ReactNode }) {
+ const items = Children.toArray(children).filter((c) => !(typeof c === "string" && !c.trim()));
+ const first = items[0];
+ if (isValidElement(first)) {
+ const parts = Children.toArray((first as ReactElement<{ children?: ReactNode }>).props.children);
+ const head = parts[0];
+ const match = typeof head === "string" ? /^\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*/i.exec(head) : null;
+ if (match) {
+ const kind = match[1].toUpperCase() as keyof typeof ALERTS;
+ const a = ALERTS[kind];
+ const rest = [(head as string).slice(match[0].length), ...parts.slice(1)];
+ return (
+ <div className={cx("md-alert", a.tone)} role="note">
+ <div className="md-alert-title"><a.icon size={15} aria-hidden="true" />{a.label}</div>
+ <div className="md-alert-body">{rest.some((r) => typeof r !== "string" || r.trim()) && <p>{rest}</p>}{items.slice(1)}</div>
+ </div>
+ );
+ }
+ }
+ return <blockquote>{children}</blockquote>;
+}
+
+function extractText(node: ReactNode): string {
+ if (typeof node === "string" || typeof node === "number") return String(node);
if (Array.isArray(node)) return node.map(extractText).join("");
- if (node && typeof node === "object" && "props" in node) return extractText((node as { props: { children?: React.ReactNode } }).props.children);
+ if (isValidElement(node)) return extractText((node as ReactElement<{ children?: ReactNode }>).props.children);
return "";
}
diff --git a/apps/desktop/src/components/OptimusFace.tsx b/apps/desktop/src/components/OptimusFace.tsx
new file mode 100644
index 00000000..1349c920
--- /dev/null
+++ b/apps/desktop/src/components/OptimusFace.tsx
@@ -0,0 +1,38 @@
+import { cx } from "~/lib/cx";
+import type { VoicePhase } from "~/app/voice";
+
+/**
+ * Optimus's face — fixed, its own, never generated: a rounded hexagon in a
+ * blue-to-violet gradient with a dark visor and two lit eyes, so it reads as
+ * "the one that uses the computer" next to the round, friendly bot faces.
+ * The face shows the phase: eyes pulse while listening, a mouth wave while
+ * speaking, eyes sweep while thinking or working, eyes dim when muted.
+ */
+export function OptimusFace({ size = 28, phase = "off", className }: { size?: number; phase?: VoicePhase; className?: string }) {
+ const eyes = phase === "muted" ? "#5b6b8c" : "#E6FCFF";
+ return (
+ <svg viewBox="0 0 100 100" width={size} height={size} role="img" aria-label="Optimus" className={cx("shrink-0", className)}>
+ <defs>
+ <linearGradient id="optimus-shell" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0" stopColor="#38BDF8" />
+ <stop offset="1" stopColor="#7C3AED" />
+ </linearGradient>
+ </defs>
+ <path d="M50 4 89 26.5v47L50 96 11 73.5v-47z" fill="url(#optimus-shell)" stroke="#fff" strokeOpacity="0.25" strokeWidth="2" strokeLinejoin="round" />
+ <rect x="22" y="36" width="56" height="24" rx="12" fill="#0B1020" opacity="0.9" />
+ <g className={cx(phase === "listening" && "optimus-eyes-pulse", (phase === "thinking" || phase === "working") && "optimus-eyes-scan")}>
+ <circle cx="38" cy="48" r="5.5" fill={eyes} />
+ <circle cx="62" cy="48" r="5.5" fill={eyes} />
+ </g>
+ {phase === "speaking" ? (
+ <g fill="#E6FCFF">
+ {[0, 1, 2, 3, 4].map((i) => (
+ <rect key={i} x={36 + i * 6} y={68} width="3.5" height="12" rx="1.75" className="optimus-mouth" style={{ animationDelay: `${i * 0.11}s`, transformOrigin: `${37.75 + i * 6}px 74px` }} />
+ ))}
+ </g>
+ ) : (
+ <path d="M40 72 q10 6 20 0" stroke="#E6FCFF" strokeOpacity="0.85" strokeWidth="4" strokeLinecap="round" fill="none" />
+ )}
+ </svg>
+ );
+}
diff --git a/apps/desktop/src/components/ThoughtProcess.tsx b/apps/desktop/src/components/ThoughtProcess.tsx
new file mode 100644
index 00000000..5d25b90d
--- /dev/null
+++ b/apps/desktop/src/components/ThoughtProcess.tsx
@@ -0,0 +1,64 @@
+import { Brain, Check, ChevronRight, CircleAlert } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import type { ThoughtTrace } from "~/api/types";
+import { Spinner } from "~/components/ui/bits";
+import { cx } from "~/lib/cx";
+
+/**
+ * How an answer was reached. Live: open, with the reasoning streaming in a
+ * short scrolling window and each step appearing as it runs. Done: folded
+ * into one line ("Thought for 12s · 4 steps") above the answer, open on click.
+ */
+export function ThoughtProcess({ trace, live = false }: { trace: ThoughtTrace; live?: boolean }) {
+ const [open, setOpen] = useState(live);
+ const box = useRef<HTMLDivElement>(null);
+ useEffect(() => { if (live) setOpen(true); }, [live]);
+ useEffect(() => {
+ const el = box.current;
+ if (el && live) el.scrollTop = el.scrollHeight;
+ }, [trace.reasoning, live]);
+
+ const seconds = Math.max(1, Math.round(((trace.endedAt ?? Date.now()) - trace.startedAt) / 1000));
+ const running = trace.steps.find((s) => s.status === "running");
+ const failed = trace.steps.filter((s) => s.status === "error").length;
+ const summary = live
+ ? running ? `Running ${running.tool}` : trace.reasoning ? "Thinking" : "Starting"
+ : `Thought for ${seconds}s${trace.steps.length ? ` · ${trace.steps.length} step${trace.steps.length === 1 ? "" : "s"}` : ""}${failed ? ` · ${failed} failed` : ""}`;
+
+ if (!live && !trace.reasoning && trace.steps.length === 0) return null;
+
+ return (
+ <div className="mb-3">
+ <button onClick={() => setOpen((o) => !o)} className="flex items-center gap-2 rounded-md py-1 text-sm text-ink3 hover:text-ink" aria-expanded={open}>
+ {live ? <Spinner size={13} className="text-cyan" /> : <Brain size={14} aria-hidden="true" />}
+ <span className={cx(live && "text-cyan")}>{summary}{live && "…"}</span>
+ <ChevronRight size={14} className={cx("transition-transform", open && "rotate-90")} aria-hidden="true" />
+ </button>
+ {open && (
+ <div className="ml-[7px] mt-1 border-l border-line pl-4">
+ {trace.reasoning && (
+ <div ref={box} className={cx("whitespace-pre-wrap text-[13.5px] leading-relaxed text-ink3", live ? "thought-stream max-h-[7.5em] overflow-hidden" : "max-h-[18em] overflow-y-auto")} data-selectable>
+ {trace.reasoning.trim()}
+ </div>
+ )}
+ {trace.steps.length > 0 && (
+ <ol className={cx("flex flex-col gap-1.5", trace.reasoning && "mt-3")}>
+ {trace.steps.map((s) => (
+ <li key={`${s.id}-${s.startedAt}`} className="flex items-start gap-2 text-[13px]">
+ <span className="mt-[3px] flex h-4 w-4 shrink-0 items-center justify-center">
+ {s.status === "running" ? <Spinner size={11} className="text-accent" /> : s.status === "error" ? <CircleAlert size={13} className="text-red" /> : <Check size={13} className="text-accent" strokeWidth={2.5} />}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="break-all font-mono text-ink2">{s.label}</span>
+ {s.summary && s.status !== "running" && <span className="mt-0.5 line-clamp-2 block text-xs text-ink4">{s.summary}</span>}
+ </span>
+ {s.endedAt && <span className="shrink-0 font-mono text-2xs text-ink4">{((s.endedAt - s.startedAt) / 1000).toFixed(1)}s</span>}
+ </li>
+ ))}
+ </ol>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/components/highlight.ts b/apps/desktop/src/components/highlight.ts
new file mode 100644
index 00000000..21e303f9
--- /dev/null
+++ b/apps/desktop/src/components/highlight.ts
@@ -0,0 +1,83 @@
+/* ═══════════════════════════════════════════════════════════════
+ Syntax highlighting with Shiki, loaded lazily: the highlighter, its
+ JavaScript regex engine (no WASM) and each language arrive only when a
+ code block needs them. Colours come from two themes at once (light and
+ dark) as CSS variables, so a theme switch needs no re-highlight.
+ ═══════════════════════════════════════════════════════════════ */
+
+import type { HighlighterCore } from "shiki/core";
+
+const ALIASES: Record<string, string> = {
+ js: "javascript", mjs: "javascript", cjs: "javascript", jsx: "jsx",
+ ts: "typescript", mts: "typescript", cts: "typescript", tsx: "tsx",
+ py: "python", python3: "python", rb: "ruby", rs: "rust", go: "go", golang: "go",
+ sh: "bash", shell: "bash", zsh: "bash", console: "bash", shellscript: "bash", ps1: "powershell", pwsh: "powershell",
+ yml: "yaml", md: "markdown", html: "html", xml: "xml", svg: "xml", css: "css", scss: "scss",
+ json: "json", jsonc: "jsonc", json5: "json5", toml: "toml", ini: "ini", env: "dotenv", dotenv: "dotenv",
+ c: "c", h: "c", cpp: "cpp", "c++": "cpp", hpp: "cpp", cs: "csharp", csharp: "csharp", java: "java", kt: "kotlin", kotlin: "kotlin",
+ swift: "swift", php: "php", sql: "sql", graphql: "graphql", gql: "graphql", dockerfile: "docker", docker: "docker",
+ lua: "lua", r: "r", dart: "dart", scala: "scala", elixir: "elixir", ex: "elixir", hs: "haskell", haskell: "haskell",
+ diff: "diff", patch: "diff", make: "makefile", makefile: "makefile", vue: "vue", svelte: "svelte", astro: "astro",
+ zig: "zig", nix: "nix", proto: "proto", protobuf: "proto", hcl: "hcl", tf: "terraform", terraform: "terraform",
+};
+
+export function languageOf(raw: string | undefined): string | null {
+ if (!raw) return null;
+ const key = raw.trim().toLowerCase();
+ return ALIASES[key] ?? (/^[a-z0-9+#-]{1,20}$/.test(key) ? key : null);
+}
+
+let highlighter: Promise<HighlighterCore> | null = null;
+const loaded = new Set<string>();
+const failed = new Set<string>();
+
+async function getHighlighter(): Promise<HighlighterCore> {
+ if (!highlighter) {
+ highlighter = (async () => {
+ const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, light, dark] = await Promise.all([
+ import("shiki/core"),
+ import("shiki/engine/javascript"),
+ import("shiki/themes/github-light-default.mjs"),
+ import("shiki/themes/github-dark-default.mjs"),
+ ]);
+ return createHighlighterCore({ themes: [light.default, dark.default], langs: [], engine: createJavaScriptRegexEngine() });
+ })();
+ }
+ return highlighter;
+}
+
+async function ensureLanguage(h: HighlighterCore, lang: string): Promise<boolean> {
+ if (loaded.has(lang)) return true;
+ if (failed.has(lang)) return false;
+ try {
+ const { bundledLanguages } = await import("shiki/langs");
+ const loader = (bundledLanguages as Record<string, () => Promise<{ default: unknown }>>)[lang];
+ if (!loader) { failed.add(lang); return false; }
+ await h.loadLanguage((await loader()).default as Parameters<HighlighterCore["loadLanguage"]>[0]);
+ loaded.add(lang);
+ return true;
+ } catch {
+ failed.add(lang);
+ return false;
+ }
+}
+
+const cache = new Map<string, string>();
+
+/** HTML for a code block, or null when the language is unknown (render plain). */
+export async function highlight(code: string, lang: string | null): Promise<string | null> {
+ if (!lang) return null;
+ const key = `${lang}\u0000${code}`;
+ const hit = cache.get(key);
+ if (hit) return hit;
+ const h = await getHighlighter();
+ if (!(await ensureLanguage(h, lang))) return null;
+ const html = h.codeToHtml(code, {
+ lang,
+ themes: { light: "github-light-default", dark: "github-dark-default" },
+ defaultColor: false,
+ });
+ if (cache.size > 300) cache.clear();
+ cache.set(key, html);
+ return html;
+}
diff --git a/apps/desktop/src/extensions/builtin-status.tsx b/apps/desktop/src/extensions/builtin-status.tsx
index 45ec9209..52aa88e4 100644
--- a/apps/desktop/src/extensions/builtin-status.tsx
+++ b/apps/desktop/src/extensions/builtin-status.tsx
@@ -10,6 +10,8 @@ import { StateOrb, LABELS } from "~/components/indicators/StateOrb";
import { StatusButton, StatusPopover } from "~/layout/StatusBar";
import { compact } from "~/views/bots/Usage";
import { mercuryUi } from "./registry";
+import { useVoice, phaseOf, PHASE_LABEL } from "~/app/voice";
+import { OptimusFace } from "~/components/OptimusFace";
/* The built-in status bar items. Each is a contribution like any plugin's. */
@@ -93,6 +95,21 @@ function BotsRunning() {
);
}
+/** Optimus voice: its face and phase while a session runs; click to open it. */
+function OptimusVoice() {
+ const v = useVoice();
+ const setView = useUi((s) => s.setView);
+ const setVoiceOpen = useUi((s) => s.setVoiceOpen);
+ if (!v.active) return null;
+ const phase = phaseOf(v);
+ return (
+ <StatusButton title="Optimus voice session" tone="accent" onClick={() => { setVoiceOpen(true); setView("chat"); }}>
+ <OptimusFace size={15} phase={phase} />
+ <span>{PHASE_LABEL[phase]}</span>
+ </StatusButton>
+ );
+}
+
function Schedules() {
const schedules = usePulse((s) => s.schedules);
return (
@@ -240,6 +257,7 @@ export function registerBuiltinStatusItems(): void {
registered = true;
mercuryUi.registerStatusItem({ id: "mercury.connection", title: "Connection", area: "status.left", priority: 100, render: Connection });
mercuryUi.registerStatusItem({ id: "mercury.agent", title: "Agent state", area: "status.left", priority: 90, render: AgentState });
+ mercuryUi.registerStatusItem({ id: "mercury.optimus", title: "Optimus voice", area: "status.left", priority: 88, render: OptimusVoice });
mercuryUi.registerStatusItem({ id: "mercury.bots", title: "Bots running", area: "status.left", priority: 85, render: BotsRunning });
mercuryUi.registerStatusItem({ id: "mercury.background", title: "Background work", area: "status.left", priority: 80, render: Background });
mercuryUi.registerStatusItem({ id: "mercury.schedules", title: "Schedules", area: "status.left", priority: 70, render: Schedules });
diff --git a/apps/desktop/src/layout/Workspace.tsx b/apps/desktop/src/layout/Workspace.tsx
index 6de4c367..7114915e 100644
--- a/apps/desktop/src/layout/Workspace.tsx
+++ b/apps/desktop/src/layout/Workspace.tsx
@@ -2,6 +2,7 @@ import { useEffect } from "react";
import { useUi, type View } from "~/app/store";
import { useRuntimeEvents, refreshBots, refreshThreads } from "~/app/events";
import { usePulsePolling } from "~/app/pulse";
+import { useVoiceFeed } from "~/app/voice";
import { registerBuiltinStatusItems } from "~/extensions/builtin-status";
import type { Connection } from "~/shell/connections";
import type { HealthInfo } from "~/api/types";
@@ -27,6 +28,7 @@ export function Workspace({ connection, health, onSwitchConnection }: { connecti
const view = useUi((s) => s.view);
useRuntimeEvents(true);
usePulsePolling(connection.id);
+ useVoiceFeed(connection.id);
useEffect(() => {
void refreshThreads();
diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsx
index 3b28c218..0d4aa690 100644
--- a/apps/desktop/src/main.tsx
+++ b/apps/desktop/src/main.tsx
@@ -1,11 +1,15 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { App } from "./app/App";
+import { NotchApp } from "./notch/NotchApp";
import "./styles/base.css";
import "./app/theme";
+// The same bundle serves the main window and the voice capsule (?surface=notch).
+const surface = new URLSearchParams(window.location.search).get("surface");
+
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
- <App />
+ {surface === "notch" ? <NotchApp /> : <App />}
</React.StrictMode>
);
diff --git a/apps/desktop/src/notch/NotchApp.tsx b/apps/desktop/src/notch/NotchApp.tsx
new file mode 100644
index 00000000..f75b5150
--- /dev/null
+++ b/apps/desktop/src/notch/NotchApp.tsx
@@ -0,0 +1,82 @@
+import { Mic, MicOff, Pause, Square } from "lucide-react";
+import { useEffect, useState } from "react";
+import { OptimusFace } from "~/components/OptimusFace";
+import { VoiceBars } from "~/components/indicators/Thinking";
+import { PHASE_LABEL, phaseOf, type VoiceAction, type VoiceState } from "~/app/voice";
+import { cx } from "~/lib/cx";
+
+/**
+ * The capsule that drops from the notch while Optimus is in a voice session:
+ * its face, what it's doing, and Mute / Pause / Stop. It holds no
+ * credentials — state arrives from the main window and controls go back to
+ * it as events.
+ */
+export function NotchApp() {
+ const [state, setState] = useState<VoiceState | null>(null);
+ const [shown, setShown] = useState(false);
+ const [hover, setHover] = useState(false);
+
+ useEffect(() => {
+ document.documentElement.classList.add("dark");
+ document.body.style.background = "transparent";
+ let off: (() => void) | null = null;
+ void import("@tauri-apps/api/event").then(async ({ listen }) => {
+ off = await listen<VoiceState>("voice-state", (e) => setState(e.payload));
+ });
+ const t = setTimeout(() => setShown(true), 30);
+ return () => { off?.(); clearTimeout(t); };
+ }, []);
+
+ async function send(action: VoiceAction) {
+ const { emitTo } = await import("@tauri-apps/api/event");
+ await emitTo("main", "voice-control", { action });
+ }
+
+ const phase = state ? phaseOf(state) : "listening";
+ const lastOwner = [...(state?.turns ?? [])].reverse().find((t) => t.role === "owner");
+ const detail = state?.activity ?? (phase === "thinking" && lastOwner ? `“${lastOwner.text}”` : null);
+
+ return (
+ <div className="flex h-screen w-screen justify-center overflow-hidden bg-transparent">
+ <div
+ onMouseEnter={() => setHover(true)}
+ onMouseLeave={() => setHover(false)}
+ className={cx(
+ "flex h-[52px] w-full items-center gap-3 rounded-b-[22px] bg-black pl-3 pr-2 text-white shadow-[0_10px_30px_rgba(0,0,0,0.45)] transition-transform duration-300 ease-out",
+ shown ? "translate-y-0" : "-translate-y-full",
+ )}
+ style={{ fontFamily: '"Geist Variable", system-ui, sans-serif' }}
+ >
+ <OptimusFace size={30} phase={phase} />
+ <div className="min-w-0 flex-1 leading-tight">
+ <div className="flex items-center gap-2 text-[13px] font-semibold">
+ <span className={cx(phase === "muted" ? "text-white/50" : "text-white")}>{PHASE_LABEL[phase]}</span>
+ {(phase === "listening" || phase === "speaking") && <VoiceBars tone={phase === "speaking" ? "cyan" : "accent"} />}
+ </div>
+ {detail && <div className="truncate text-[11.5px] text-white/60">{detail}</div>}
+ </div>
+ <div className={cx("flex items-center gap-1 transition-opacity", hover || phase !== "listening" ? "opacity-100" : "opacity-70")}>
+ <CapsuleButton label={state?.muted ? "Unmute" : "Mute"} onClick={() => void send(state?.muted ? "unmute" : "mute")} active={state?.muted}>
+ {state?.muted ? <MicOff size={15} /> : <Mic size={15} />}
+ </CapsuleButton>
+ <CapsuleButton label="Pause: stop what it's saying or doing" onClick={() => void send("interrupt")}>
+ <Pause size={15} />
+ </CapsuleButton>
+ <CapsuleButton label="End the session" onClick={() => void send("stop")} danger>
+ <Square size={13} fill="currentColor" />
+ </CapsuleButton>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function CapsuleButton({ children, label, onClick, active, danger }: { children: React.ReactNode; label: string; onClick: () => void; active?: boolean; danger?: boolean }) {
+ return (
+ <button onClick={onClick} title={label} aria-label={label}
+ className={cx("flex h-8 w-8 items-center justify-center rounded-full transition-colors",
+ danger ? "bg-[#FF6B6B]/20 text-[#FF8A8A] hover:bg-[#FF6B6B]/35" : active ? "bg-white text-black" : "bg-white/10 text-white hover:bg-white/20")}>
+ {children}
+ </button>
+ );
+}
diff --git a/apps/desktop/src/styles/base.css b/apps/desktop/src/styles/base.css
index e764d348..0398df8f 100644
--- a/apps/desktop/src/styles/base.css
+++ b/apps/desktop/src/styles/base.css
@@ -58,15 +58,65 @@ button, input, textarea, a, [role="button"], [data-no-drag] { -webkit-app-region
.prose h1 { font-size: 1.35em; } .prose h2 { font-size: 1.2em; } .prose h3 { font-size: 1.08em; } .prose h4 { font-size: 1em; }
.prose ul, .prose ol { padding-left: 1.4em; }
.prose ul { list-style: disc; } .prose ol { list-style: decimal; }
-.prose li + li { margin-top: 0.25em; }
+.prose ul ul { list-style: circle; } .prose ul ul ul { list-style: square; }
+.prose li + li { margin-top: 0.3em; }
+.prose li::marker { color: rgb(var(--ink-3)); }
+.prose ol > li::marker { font-variant-numeric: tabular-nums; font-weight: 500; }
+.prose li > p { margin: 0; }
.prose a { color: rgb(var(--accent)); text-decoration: underline; text-decoration-color: rgb(var(--accent) / 0.4); text-underline-offset: 2px; }
.prose strong { font-weight: 600; }
.prose code { font-family: "Geist Mono Variable", ui-monospace, monospace; font-size: 0.9em; background: rgb(var(--ink) / 0.07); padding: 1px 5px; border-radius: 5px; }
-.prose pre { background: rgb(var(--surface-2)); border: 1px solid rgb(var(--ink) / 0.08); border-radius: 10px; padding: 14px 16px; overflow-x: auto; font-size: 13.5px; line-height: 1.6; }
.prose pre code { background: none; padding: 0; font-size: inherit; }
.prose blockquote { border-left: 2px solid rgb(var(--ink) / 0.18); padding-left: 12px; color: rgb(var(--ink-2)); }
.prose table { border-collapse: collapse; width: 100%; font-size: 14px; }
+.md-table { overflow-x: auto; border: 1px solid rgb(var(--ink) / 0.12); border-radius: 10px; }
+.md-table table { border: 0; }
+.md-table th, .md-table td { border: 0; border-bottom: 1px solid rgb(var(--ink) / 0.08); }
+.md-table tr:last-child td { border-bottom: 0; }
+.md-table tbody tr:nth-child(even) { background: rgb(var(--ink) / 0.025); }
.prose th, .prose td { border: 1px solid rgb(var(--ink) / 0.12); padding: 6px 10px; text-align: left; }
.prose th { background: rgb(var(--ink) / 0.04); font-weight: 600; }
.prose hr { border: 0; border-top: 1px solid rgb(var(--ink) / 0.12); }
.prose img { max-width: 100%; border-radius: 8px; }
+
+/* ── Optimus face ── */
+@keyframes optimus-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.45; } }
+@keyframes optimus-scan { 0%, 100% { transform: translateX(-3px); } 50% { transform: translateX(3px); } }
+@keyframes optimus-mouth { 0%, 100% { transform: scaleY(0.35); } 50% { transform: scaleY(1); } }
+.optimus-eyes-pulse { animation: optimus-pulse 1.6s ease-in-out infinite; }
+.optimus-eyes-scan { animation: optimus-scan 1.1s ease-in-out infinite; }
+.optimus-mouth { animation: optimus-mouth 0.8s ease-in-out infinite; }
+@media (prefers-reduced-motion: reduce) { .optimus-eyes-pulse, .optimus-eyes-scan, .optimus-mouth { animation: none; } }
+
+/* ── Code blocks (Shiki emits both themes as CSS variables) ── */
+.md-code { border: 1px solid rgb(var(--ink) / 0.1); border-radius: 12px; overflow: hidden; background: rgb(var(--surface-2)); }
+.md-code-bar { display: flex; align-items: center; gap: 4px; height: 34px; padding: 0 6px 0 12px; border-bottom: 1px solid rgb(var(--ink) / 0.08); font-size: 12px; color: rgb(var(--ink-3)); }
+.md-code-lang { font-family: "Geist Mono Variable", ui-monospace, monospace; text-transform: lowercase; }
+.md-code-btn { display: inline-flex; align-items: center; gap: 4px; height: 24px; padding: 0 7px; border-radius: 6px; color: rgb(var(--ink-3)); }
+.md-code-btn:hover { background: rgb(var(--ink) / 0.07); color: rgb(var(--ink)); }
+.md-code-btn-on { color: rgb(var(--accent)); }
+.md-code-body, .md-code-body pre { margin: 0; padding: 14px 16px; overflow-x: auto; font-family: "Geist Mono Variable", ui-monospace, monospace; font-size: 13.5px; line-height: 1.6; background: transparent !important; }
+.md-code-body > pre { padding: 0; }
+.md-wrap, .md-wrap pre { white-space: pre-wrap; word-break: break-word; }
+.shiki, .shiki span { color: var(--shiki-light); background-color: transparent !important; }
+.dark .shiki, .dark .shiki span { color: var(--shiki-dark); }
+
+/* ── Task lists ── */
+.prose ul.md-task-list { list-style: none; padding-left: 0.2em; }
+.md-task { display: flex; align-items: flex-start; gap: 9px; }
+.md-check { flex: none; display: inline-flex; align-items: center; justify-content: center; width: 17px; height: 17px; margin-top: 0.27em; border-radius: 5px; border: 1.5px solid rgb(var(--ink) / 0.3); color: rgb(var(--on-accent)); }
+.md-check-on { background: rgb(var(--accent)); border-color: rgb(var(--accent)); }
+.md-task-done .md-task-text { color: rgb(var(--ink-3)); text-decoration: line-through; text-decoration-color: rgb(var(--ink) / 0.3); }
+
+/* ── Alerts ── */
+.md-alert { border-left: 3px solid var(--alert); background: color-mix(in srgb, var(--alert) 8%, transparent); border-radius: 0 10px 10px 0; padding: 10px 14px; }
+.md-alert-title { display: flex; align-items: center; gap: 6px; font-weight: 600; font-size: 14px; color: var(--alert); margin-bottom: 4px; }
+.md-alert-body > * + * { margin-top: 0.5em; }
+.md-alert-note { --alert: rgb(var(--cyan)); }
+.md-alert-tip { --alert: rgb(var(--accent)); }
+.md-alert-important { --alert: #8B5CF6; }
+.md-alert-warning { --alert: rgb(var(--amber)); }
+.md-alert-caution { --alert: rgb(var(--red)); }
+
+/* ── Live thought process ── */
+.thought-stream { mask-image: linear-gradient(to bottom, transparent 0, #000 18px); -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 18px); }
diff --git a/apps/desktop/src/views/chat/ChatView.tsx b/apps/desktop/src/views/chat/ChatView.tsx
index f03aa7b9..e1413f3f 100644
--- a/apps/desktop/src/views/chat/ChatView.tsx
+++ b/apps/desktop/src/views/chat/ChatView.tsx
@@ -8,6 +8,10 @@ import { Tooltip } from "~/components/ui/Tooltip";
import { Mark } from "~/components/Logo";
import { ThreadList } from "./ThreadList";
import { Conversation } from "./Conversation";
+import { VoiceConversation } from "./VoiceConversation";
+import { OptimusFace } from "~/components/OptimusFace";
+import { useVoice, phaseOf, PHASE_LABEL } from "~/app/voice";
+import { cx } from "~/lib/cx";
/**
* Chat: sessions on the left (with New chat), one conversation. Its own
@@ -20,10 +24,20 @@ export function ChatView() {
const threads = useChat((s) => s.threads);
const codeIds = useCodeSessions((s) => s.sessions);
const activeId = conversations.chat((s) => s.activeId);
+ const voiceOpen = useUi((s) => s.voiceOpen);
+ const setVoiceOpen = useUi((s) => s.setVoiceOpen);
+ const voice = useVoice();
+ const voicePhase = phaseOf(voice);
const title = threads.find((t) => t.id === activeId)?.title || (activeId ? "Untitled" : "New chat");
const codeSet = new Set(codeIds.map((c) => c.id));
+ // A voice session starting takes over: Chat opens on the live session.
+ const setView = useUi((s) => s.setView);
+ useEffect(() => {
+ if (voice.active) { setVoiceOpen(true); setView("chat"); }
+ }, [voice.active, voice.callId, setVoiceOpen, setView]);
+
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (view !== "chat") return;
@@ -41,12 +55,24 @@ export function ChatView() {
<ThreadList
threads={threads.filter((t) => !codeSet.has(t.id) && !(t.title ?? "").startsWith("Code · "))}
activeId={activeId}
- onOpen={(id) => void openThread("chat", id)}
- onNew={() => void openThread("chat", null)}
+ onOpen={(id) => { setVoiceOpen(false); void openThread("chat", id); }}
+ onNew={() => { setVoiceOpen(false); void openThread("chat", null); }}
newLabel="New chat"
searchLabel="Search chats"
+ pinned={(voice.active || voice.turns.length > 0) && (
+ <button onClick={() => setVoiceOpen(true)}
+ className={cx("mb-3 flex w-full items-center gap-3 rounded-lg border px-3 py-2.5 text-left", voiceOpen ? "border-line-strong bg-ink/[0.07]" : "border-line bg-surface hover:border-line-strong")}>
+ <OptimusFace size={30} phase={voicePhase} />
+ <span className="min-w-0 flex-1">
+ <span className="block text-base font-medium text-ink">Optimus</span>
+ <span className={cx("block truncate text-xs", voice.active ? "text-accent" : "text-ink4")}>{voice.active ? (voice.activity ?? PHASE_LABEL[voicePhase]) : "Last voice session"}</span>
+ </span>
+ {voice.active && <span className="h-2 w-2 shrink-0 animate-dot-pulse rounded-full bg-accent" aria-label="live" />}
+ </button>
+ )}
/>
)}
+ {voiceOpen ? <VoiceConversation /> : (
<Conversation
header={
<>
@@ -68,6 +94,7 @@ export function ChatView() {
}
composer={{ surface: "chat", placeholder: "Ask anything…" }}
/>
+ )}
</div>
</ConversationContext.Provider>
);
diff --git a/apps/desktop/src/views/chat/Conversation.tsx b/apps/desktop/src/views/chat/Conversation.tsx
index cbf1114d..e5591742 100644
--- a/apps/desktop/src/views/chat/Conversation.tsx
+++ b/apps/desktop/src/views/chat/Conversation.tsx
@@ -25,6 +25,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
const agent = useConversation((s) => s.agent);
const step = useConversation((s) => s.step);
const prompts = useConversation((s) => s.prompts);
+ const live = useConversation((s) => s.live);
const scroller = useRef<HTMLDivElement>(null);
const stickToBottom = useRef(true);
const [visible, setVisible] = useState(PAGE);
@@ -50,7 +51,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
const el = scroller.current;
if (!el || !stickToBottom.current) return;
el.scrollTop = el.scrollHeight;
- }, [messages, streaming, prompts.length, loading]);
+ }, [messages, streaming, prompts.length, loading, live]);
const isEmpty = !activeId && messages.length === 0 && !streaming;
@@ -79,8 +80,10 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
</button>
)}
{shown.map((m) => <Message key={m.id} message={m} />)}
- {streaming && <StreamingMessage text={streaming} />}
- {!streaming && (agent === "thinking" || agent === "working") && (
+ {(streaming || (live && (agent === "thinking" || agent === "working" || agent === "streaming" || agent === "needs-you"))) && (
+ <StreamingMessage text={streaming} live={live} />
+ )}
+ {!streaming && !live && (agent === "thinking" || agent === "working") && (
<ThinkingDots label={agent === "working" && step?.tool ? `Running ${step.tool}` : "Thinking"} className="pl-10" />
)}
{prompts.map((p) => (
diff --git a/apps/desktop/src/views/chat/Message.tsx b/apps/desktop/src/views/chat/Message.tsx
index 6f338ca2..807d0102 100644
--- a/apps/desktop/src/views/chat/Message.tsx
+++ b/apps/desktop/src/views/chat/Message.tsx
@@ -1,11 +1,12 @@
import { Check, ChevronRight, Copy, Wrench } from "lucide-react";
import { memo, useState } from "react";
-import type { ChatMessage } from "~/api/types";
+import type { ChatMessage, ThoughtTrace } from "~/api/types";
import { Mark } from "~/components/Logo";
import { Markdown } from "~/components/Markdown";
import { StreamCaret } from "~/components/indicators/Thinking";
import { ActionResult } from "~/components/indicators/Activity";
import { Attachments } from "~/components/Attachments";
+import { ThoughtProcess } from "~/components/ThoughtProcess";
import { cx } from "~/lib/cx";
/**
@@ -43,6 +44,7 @@ export const Message = memo(function Message({ message }: { message: ChatMessage
<div className="group flex gap-4">
<span className="mt-1 flex h-6 w-6 shrink-0 items-center justify-center" aria-hidden="true"><Mark size={22} /></span>
<div className="min-w-0 flex-1">
+ {message.trace && <ThoughtProcess trace={message.trace} />}
{message.steps && message.steps.length > 0 && (
<div className="mb-3 flex flex-col gap-1">
{message.steps.map((s, i) => <ActionResult key={i} tool={s.tool} status={s.status} detail={s.result} />)}
@@ -134,13 +136,14 @@ function ToolActivity({ content }: { content: string }) {
);
}
-export function StreamingMessage({ text }: { text: string }) {
+/** The answer being written, with its thought process above it (open while it runs). */
+export function StreamingMessage({ text, live }: { text: string; live: ThoughtTrace | null }) {
return (
<div className="flex gap-4">
<span className="mt-1 flex h-6 w-6 shrink-0 items-center justify-center" aria-hidden="true"><Mark size={22} /></span>
<div className="min-w-0 flex-1">
- <Markdown text={text} />
- <StreamCaret />
+ {live && <ThoughtProcess trace={live} live={!text} />}
+ {text && <><Markdown text={text} streaming /><StreamCaret /></>}
</div>
</div>
);
diff --git a/apps/desktop/src/views/chat/ThreadList.tsx b/apps/desktop/src/views/chat/ThreadList.tsx
index 47c76f5a..bb8362bf 100644
--- a/apps/desktop/src/views/chat/ThreadList.tsx
+++ b/apps/desktop/src/views/chat/ThreadList.tsx
@@ -12,7 +12,7 @@ const PAGE = 40;
* New and search on top. Renders a page at a time and adds the next page as
* the list scrolls.
*/
-export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchLabel, renderMeta }: {
+export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchLabel, renderMeta, pinned }: {
threads: ChatThread[];
activeId: string | null;
onOpen: (id: string) => void;
@@ -20,6 +20,8 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL
newLabel: string;
searchLabel: string;
renderMeta?: (t: ChatThread) => React.ReactNode;
+ /** Shown above the sessions (e.g. the live Optimus voice session). */
+ pinned?: React.ReactNode;
}) {
const [limit, setLimit] = useState(PAGE);
const [query, setQuery] = useState("");
@@ -66,6 +68,7 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL
</label>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-2 pb-3">
+ {pinned}
{filtered.length === 0 && <p className="px-3 pt-2 text-base text-ink4">{query ? "Nothing matches." : "No sessions yet."}</p>}
{groups.map(([day, list]) => (
<div key={day} className="mb-5">
diff --git a/apps/desktop/src/views/chat/VoiceConversation.tsx b/apps/desktop/src/views/chat/VoiceConversation.tsx
new file mode 100644
index 00000000..c7dec178
--- /dev/null
+++ b/apps/desktop/src/views/chat/VoiceConversation.tsx
@@ -0,0 +1,82 @@
+import { Mic, MicOff, Pause, Square, Wrench, ShieldAlert } from "lucide-react";
+import { useEffect, useRef } from "react";
+import { useVoice, phaseOf, PHASE_LABEL, voiceControl } from "~/app/voice";
+import { OptimusFace } from "~/components/OptimusFace";
+import { Markdown } from "~/components/Markdown";
+import { Button } from "~/components/ui/Button";
+import { ThinkingDots, VoiceBars } from "~/components/indicators/Thinking";
+import { cx } from "~/lib/cx";
+
+/**
+ * The live Optimus session, as a conversation: what you said, what it is
+ * doing on the screen, approvals it asked for, what it answered — streaming
+ * in as it happens. Controls in the header mirror the notch capsule.
+ */
+export function VoiceConversation() {
+ const v = useVoice();
+ const phase = phaseOf(v);
+ const scroller = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const el = scroller.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ }, [v.turns.length, v.thinking, v.activity]);
+
+ const duration = v.startedAt ? Math.max(0, Math.round(((v.endedAt ?? Date.now()) - v.startedAt) / 1000)) : 0;
+
+ return (
+ <section className="flex min-w-0 flex-1 flex-col">
+ <header className="flex h-[52px] shrink-0 items-center gap-3 border-b border-line px-4" data-tauri-drag-region>
+ <OptimusFace size={28} phase={phase} />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2 text-base font-medium text-ink">
+ Optimus
+ <span className={cx("text-sm font-normal", v.active ? "text-accent" : "text-ink3")}>{v.active ? PHASE_LABEL[phase] : "Session ended"}</span>
+ {(phase === "listening" || phase === "speaking") && <VoiceBars tone={phase === "speaking" ? "cyan" : "accent"} />}
+ </div>
+ <div className="text-xs text-ink4">{v.active ? "Voice session on this computer" : v.outcome ? `Ended · ${v.outcome}` : "Ended"} · {fmt(duration)}</div>
+ </div>
+ {v.active && (
+ <div className="flex items-center gap-1.5">
+ <Button size="sm" variant={v.muted ? "primary" : "outline"} onClick={() => void voiceControl(v.muted ? "unmute" : "mute")}>{v.muted ? <MicOff size={14} /> : <Mic size={14} />}{v.muted ? "Unmute" : "Mute"}</Button>
+ <Button size="sm" variant="outline" onClick={() => void voiceControl("interrupt")} title="Stop what it's saying or doing; keep listening"><Pause size={14} />Pause</Button>
+ <Button size="sm" variant="danger" onClick={() => void voiceControl("stop")}><Square size={12} fill="currentColor" />End</Button>
+ </div>
+ )}
+ </header>
+
+ <div ref={scroller} className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto flex w-full max-w-[780px] flex-col gap-6 px-8 py-8">
+ {v.turns.length === 0 && (
+ <div className="flex flex-col items-center gap-3 py-16 text-center">
+ <OptimusFace size={72} phase={phase} />
+ <p className="text-lg font-medium text-ink">{v.active ? "Listening. Just talk." : "No voice session yet."}</p>
+ <p className="max-w-[420px] text-sm text-ink3">What you say and everything Optimus does on your screen appears here as it happens.</p>
+ </div>
+ )}
+ {v.turns.map((t) => {
+ if (t.role === "owner") return <div key={t.id} className="pl-10 pt-1"><p className="text-lg font-medium leading-[1.55] text-ink" data-selectable>{t.text}</p><span className="text-xs text-ink4">You, out loud · {time(t.at)}</span></div>;
+ if (t.role === "activity") return <div key={t.id} className="flex items-center gap-2 pl-10 text-sm text-ink3"><Wrench size={13} aria-hidden="true" />{t.text}</div>;
+ if (t.role === "approval") return <div key={t.id} className="ml-10 flex items-start gap-2 rounded-lg border border-amber/40 bg-amber/[0.06] px-3 py-2 text-sm text-ink"><ShieldAlert size={15} className="mt-0.5 shrink-0 text-amber" />Asked you: {t.text}</div>;
+ if (t.role === "system") return <p key={t.id} className="pl-10 text-sm text-ink3">{t.text}</p>;
+ return (
+ <div key={t.id} className="flex gap-4">
+ <OptimusFace size={24} className="mt-1" />
+ <div className="min-w-0 flex-1"><Markdown text={t.text} /><span className="text-xs text-ink4">Said out loud · {time(t.at)}</span></div>
+ </div>
+ );
+ })}
+ {v.active && v.thinking && <ThinkingDots className="pl-10" label={v.activity ?? "Working on it"} />}
+ </div>
+ </div>
+ </section>
+ );
+}
+
+function fmt(s: number): string {
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
+}
+
+function time(at: number): string {
+ return new Date(at).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
+}