Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(code): separate Code sessions with per-session programming mode
Salman Qureshi3dce679099ac
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.tsindex eb25e758..e5193532 100644--- a/apps/desktop/src/api/mercury.ts+++ b/apps/desktop/src/api/mercury.ts@@ -49,8 +49,8 @@ export const chat = {thread: (id: string) => http.get<ChatThread>(`/api/chat/threads/${encodeURIComponent(id)}`),createThread: (title?: string) => http.post<ChatThread>("/api/chat/threads", { title }),deleteThread: (id: string) => http.post<{ deleted: boolean }>(`/api/chat/threads/${encodeURIComponent(id)}/delete`, { confirmSessionId: id }),- send: (content: string, sessionId?: string, attachments?: Array<{ name: string; data: string }>) =>- http.post<{ sent: boolean; sessionId: string }>("/api/chat/send", { content, sessionId, ...(attachments?.length ? { attachments } : {}) }),+ send: (content: string, sessionId?: string, attachments?: Array<{ name: string; data: string }>, code?: { programming: string; cwd?: string }) =>+ http.post<{ sent: boolean; sessionId: string }>("/api/chat/send", { content, sessionId, ...(attachments?.length ? { attachments } : {}), ...(code ?? {}) }),answer: (promptId: string, action: string, targetId?: string) => http.post<{ resolved: boolean }>(`/api/chat/permission/${encodeURIComponent(promptId)}`, { action, targetId }),settings: () => http.get<ChatSettings>("/api/chat/settings"),updateSettings: (patch: Partial<ChatSettings>) => http.put<ChatSettings>("/api/chat/settings", patch),@@ -59,6 +59,18 @@ export const chat = {setReasoning: (provider: string, model: string, reasoning: ReasoningChoice | null) => http.post<{ ok: boolean }>("/api/chat/models/prefs", { provider, model, reasoning }),};+export const workspace = {+ info: () => http.get<{ cwd: string; projectName: string; projectType: string; isGit: boolean; branch: string; remoteUrl: string }>("/api/workspace/info"),+ setRoot: (path: string) => http.put<{ success: boolean; workspace: string }>("/api/workspace/root", { path }),+ tree: (path?: string) => http.get<{ root: string; currentPath: string; items: Array<{ name: string; path: string; isDirectory: boolean; type: string; size?: number; ext?: string }> }>(`/api/workspace/tree${path ? `?path=${encodeURIComponent(path)}` : ""}`),+ file: (path: string) => http.get<{ path: string; name: string; size: number; truncated: boolean; content: string; ext: string }>(`/api/workspace/file?path=${encodeURIComponent(path)}`),+};++export const git = {+ status: () => http.get<{ branch: string; upstream: string; ahead: number; behind: number; files: Array<{ path: string; status: string; staged: boolean }>; cwd: string }>("/api/git/status"),+ diff: (file: string) => http.get<{ diff: string }>(`/api/git/diff?file=${encodeURIComponent(file)}`),+};+export const code = {status: () => http.get<CodeStatus>("/api/code/status"),set: (state: CodeMode) => http.post<{ state: string; active: boolean }>("/api/code/set", { state }),diff --git a/apps/desktop/src/app/conversation.ts b/apps/desktop/src/app/conversation.tsnew file mode 100644index 00000000..a6ad4a69--- /dev/null+++ b/apps/desktop/src/app/conversation.ts@@ -0,0 +1,116 @@+/* ═══════════════════════════════════════════════════════════════+ A conversation surface: Chat and Code each have their own. Their+ sessions, messages, live stream, agent state and pending approvals are+ separate stores, fed by separate event streams, so nothing one does+ shows up in the other.+ ═══════════════════════════════════════════════════════════════ */++import { createContext, useContext } from "react";+import { create, type StoreApi, type UseBoundStore } from "zustand";+import type { ChatMessage, PendingPrompt } from "~/api/types";+import type { AgentState } from "./store";++export type Surface = "chat" | "code";++export interface ConversationState {+ surface: Surface;+ activeId: string | null;+ messages: ChatMessage[];+ streaming: string;+ loading: boolean;+ agent: AgentState;+ step: { total: number; current: number; tool: string } | null;+ prompts: PendingPrompt[];+ setActive(id: string | null): void;+ setMessages(messages: ChatMessage[]): void;+ addMessage(message: ChatMessage): void;+ appendStreaming(text: string): void;+ clearStreaming(): void;+ setLoading(loading: boolean): void;+ setAgent(agent: AgentState): void;+ setStep(step: ConversationState["step"]): void;+ addPrompt(prompt: PendingPrompt): void;+ removePrompt(id: string): void;+}++export type ConversationStore = UseBoundStore<StoreApi<ConversationState>>;++function makeConversation(surface: Surface): ConversationStore {+ return create<ConversationState>((set) => ({+ surface,+ activeId: null,+ messages: [],+ streaming: "",+ loading: false,+ agent: "idle",+ step: null,+ prompts: [],+ setActive: (activeId) => set({ activeId, prompts: [], step: null, agent: "idle" }),+ setMessages: (messages) => set({ messages }),+ addMessage: (message) => set((s) => ({ messages: [...s.messages, message] })),+ appendStreaming: (text) => set((s) => ({ streaming: s.streaming + text })),+ clearStreaming: () => set({ streaming: "" }),+ setLoading: (loading) => set({ loading }),+ setAgent: (agent) => set({ agent }),+ setStep: (step) => set({ step }),+ addPrompt: (prompt) => set((s) => ({ prompts: [...s.prompts.filter((p) => p.id !== prompt.id), prompt], agent: "needs-you" })),+ removePrompt: (id) => set((s) => {+ const prompts = s.prompts.filter((p) => p.id !== id);+ return { prompts, agent: prompts.length === 0 && s.agent === "needs-you" ? "working" : s.agent };+ }),+ }));+}++export const conversations: Record<Surface, ConversationStore> = {+ chat: makeConversation("chat"),+ code: makeConversation("code"),+};++export const ConversationContext = createContext<ConversationStore>(conversations.chat);++/** The conversation of the surface this component is rendered in. */+export function useConversation<T>(selector: (s: ConversationState) => T): T {+ return useContext(ConversationContext)(selector);+}++export function useConversationStore(): ConversationStore {+ return useContext(ConversationContext);+}++/* ── Code sessions: which runtime sessions belong to Code, and their folder ── */++export interface CodeSession {+ id: string;+ folder: string | null;+ createdAt: string;+}++interface CodeSessionsState {+ scope: string;+ sessions: CodeSession[];+ load(scope: string): void;+ upsert(session: CodeSession): void;+ remove(id: string): void;+}++const keyFor = (scope: string) => `mercury.code.sessions.v1:${scope}`;++export const useCodeSessions = create<CodeSessionsState>((set, get) => ({+ scope: "",+ sessions: [],+ load(scope) {+ let sessions: CodeSession[] = [];+ try { sessions = JSON.parse(localStorage.getItem(keyFor(scope)) ?? "[]") as CodeSession[]; } catch { sessions = []; }+ set({ scope, sessions: Array.isArray(sessions) ? sessions : [] });+ },+ upsert(session) {+ const sessions = [session, ...get().sessions.filter((s) => s.id !== session.id)];+ try { localStorage.setItem(keyFor(get().scope), JSON.stringify(sessions)); } catch { /* ignore */ }+ set({ sessions });+ },+ remove(id) {+ const sessions = get().sessions.filter((s) => s.id !== id);+ try { localStorage.setItem(keyFor(get().scope), JSON.stringify(sessions)); } catch { /* ignore */ }+ set({ sessions });+ },+}));diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.tsindex 0e2d6e6d..cabb2708 100644--- a/apps/desktop/src/app/events.ts+++ b/apps/desktop/src/app/events.ts@@ -1,30 +1,23 @@/* ═══════════════════════════════════════════════════════════════- Live events from the runtime → app state. One chat stream (scoped to- the active thread) and one bots stream, for as long as a connection is- up. Every view reads the stores; nothing polls for what streams.+ Live events from the runtime → app state. Each conversation surface+ (Chat, Code) has its own event stream scoped to its own session, so+ their activity never mixes; plus one bots stream. Nothing polls for+ what streams.═══════════════════════════════════════════════════════════════ */import { useEffect } from "react";import { openStream } from "~/api/stream";import * as api from "~/api/mercury";-import type { BotActivityEvent, ChatMessage, PendingPrompt } from "~/api/types";-import { useBots, useChat, useRuntimeState } from "./store";+import type { BotActivityEvent, ChatMessage, CodeMode, PendingPrompt } from "~/api/types";+import { useBots, useChat, useRuntimeState, type AgentState } from "./store";+import { conversations, useCodeSessions, type ConversationStore, type Surface } from "./conversation";export function useRuntimeEvents(enabled: boolean): void {- const activeId = useChat((s) => s.activeId);+ const chatId = conversations.chat((s) => s.activeId);+ const codeId = conversations.code((s) => s.activeId);- useEffect(() => {- if (!enabled) return;- const runtime = useRuntimeState.getState();- const query = activeId ? `?sessionId=${encodeURIComponent(activeId)}` : "";- const stream = openStream(`/api/chat/events${query}`, {- onOpen: () => useRuntimeState.getState().setConnected(true),- onClose: (reason) => { if (reason !== "closed") useRuntimeState.getState().setConnected(false); },- onEvent: (event, raw) => handleChatEvent(event, raw),- });- runtime.setAgent(runtime.connected ? runtime.agent : "idle");- return () => stream.close();- }, [enabled, activeId]);+ useSurfaceStream(enabled, "chat", chatId, true);+ useSurfaceStream(enabled, "code", codeId, false);useEffect(() => {if (!enabled) return;@@ -39,6 +32,41 @@ export function useRuntimeEvents(enabled: boolean): void {});return () => stream.close();}, [enabled]);++ // The chrome (rail, status bar) shows one agent state: the busiest surface.+ useEffect(() => {+ const rank: Record<AgentState, number> = { "needs-you": 5, working: 4, streaming: 3, thinking: 2, idle: 1, offline: 0 };+ const sync = () => {+ if (!useRuntimeState.getState().connected) return;+ const a = conversations.chat.getState();+ const b = conversations.code.getState();+ const top = rank[a.agent] >= rank[b.agent] ? a : b;+ useRuntimeState.setState({ agent: top.agent, step: top.step, prompts: [...a.prompts, ...b.prompts] });+ };+ const offA = conversations.chat.subscribe(sync);+ const offB = conversations.code.subscribe(sync);+ return () => { offA(); offB(); };+ }, []);+}++/**+ * One stream per surface. Unscoped (no session yet) the runtime would send+ * every web event; only the chat surface listens unscoped, so a brand-new+ * Code view never shows Chat's traffic.+ */+function useSurfaceStream(enabled: boolean, surface: Surface, sessionId: string | null, tracksConnection: boolean): void {+ useEffect(() => {+ if (!enabled) return;+ if (!sessionId && surface !== "chat") return;+ const store = conversations[surface];+ const query = sessionId ? `?sessionId=${encodeURIComponent(sessionId)}` : "";+ const stream = openStream(`/api/chat/events${query}`, {+ onOpen: () => { if (tracksConnection) useRuntimeState.getState().setConnected(true); },+ onClose: (reason) => { if (tracksConnection && reason !== "closed") useRuntimeState.getState().setConnected(false); },+ onEvent: (event, raw) => handleEvent(store, event, raw),+ });+ return () => stream.close();+ }, [enabled, surface, sessionId, tracksConnection]);}function safeJson<T>(raw: string): T | null {@@ -49,55 +77,57 @@ function safeJson<T>(raw: string): T | null {}}-function handleChatEvent(event: string, raw: string): void {- const rt = useRuntimeState.getState();- const chat = useChat.getState();+function handleEvent(store: ConversationStore, event: string, raw: string): void {+ const conv = store.getState();const data = safeJson<Record<string, unknown>>(raw) ?? {};+ // A scoped stream may still carry another session's events on old runtimes.+ const eventSession = typeof data.sessionId === "string" ? data.sessionId : null;+ if (eventSession && conv.activeId && eventSession !== conv.activeId) return;switch (event) {case "connected":case "provider":- rt.setProvider(String(data.provider ?? ""), String(data.model ?? ""));+ useRuntimeState.getState().setProvider(String(data.provider ?? ""), String(data.model ?? ""));break;case "thinking":- rt.setAgent("thinking");+ conv.setAgent("thinking");break;case "step_start":case "step_done":- rt.setStep({ total: Number(data.totalSteps ?? 0), current: Number(data.stepNumber ?? 0), tool: String(data.tool ?? "") });- rt.setAgent("working");+ conv.setStep({ total: Number(data.totalSteps ?? 0), current: Number(data.stepNumber ?? 0), tool: String(data.tool ?? "") });+ conv.setAgent("working");break;case "text_delta":- rt.setAgent("streaming");- chat.appendStreaming(String(data.text ?? ""));+ conv.setAgent("streaming");+ conv.appendStreaming(String(data.text ?? ""));break;case "text_done": {const text = String(data.fullText ?? data.text ?? raw);- chat.clearStreaming();- chat.addMessage({ id: crypto.randomUUID(), role: "assistant", content: text, timestamp: new Date().toISOString() });- rt.setStep(null);- rt.setAgent(rt.prompts.length ? "needs-you" : "idle");+ conv.clearStreaming();+ conv.addMessage({ id: crypto.randomUUID(), role: "assistant", content: text, timestamp: new Date().toISOString() });+ conv.setStep(null);+ store.getState().setAgent(store.getState().prompts.length ? "needs-you" : "idle");void refreshThreads();break;}case "permission_request":- rt.addPrompt(toPrompt("permission", data, String(data.prompt ?? "")));+ conv.addPrompt(toPrompt("permission", data, String(data.prompt ?? "")));break;case "permission_continue":- rt.addPrompt(toPrompt("continue", data, String(data.question ?? "")));+ conv.addPrompt(toPrompt("continue", data, String(data.question ?? "")));break;case "choice_prompt":- rt.addPrompt(toPrompt("choice", data, String(data.question ?? "")));+ conv.addPrompt(toPrompt("choice", data, String(data.question ?? "")));break;case "permission_resolved":case "choice_resolved":- if (typeof data.id === "string") rt.removePrompt(data.id);+ if (typeof data.id === "string") conv.removePrompt(data.id);break;case "error": {const message = typeof data.message === "string" ? data.message : raw || "Something went wrong";- chat.clearStreaming();- rt.setStep(null);- rt.setAgent("idle");- chat.addMessage({ id: crypto.randomUUID(), role: "system", content: message, timestamp: new Date().toISOString() });+ conv.clearStreaming();+ conv.setStep(null);+ conv.setAgent("idle");+ conv.addMessage({ id: crypto.randomUUID(), role: "system", content: message, timestamp: new Date().toISOString() });break;}default:@@ -138,34 +168,39 @@ export async function refreshBots(): Promise<void> {} catch { /* bots unavailable on this runtime */ }}-export async function openThread(id: string | null): Promise<void> {- const chat = useChat.getState();- chat.setActive(id);- chat.clearStreaming();+export async function openThread(surface: Surface, id: string | null): Promise<void> {+ const store = conversations[surface];+ store.getState().setActive(id);+ store.getState().clearStreaming();if (!id) {- chat.setMessages([]);+ store.getState().setMessages([]);return;}- chat.setLoading(true);+ store.getState().setLoading(true);try {const thread = await api.chat.thread(id);- useChat.getState().setMessages(thread.messages ?? []);+ store.getState().setMessages(thread.messages ?? []);} catch {- useChat.getState().setMessages([]);+ store.getState().setMessages([]);} finally {- useChat.getState().setLoading(false);+ store.getState().setLoading(false);}}-export async function sendMessage(content: string, attachments: Array<{ name: string; data: string; mime?: string }> = []): Promise<void> {- const chat = useChat.getState();- const rt = useRuntimeState.getState();- let id = chat.activeId;+export interface CodeTurn {+ mode: Exclude<CodeMode, "off">;+ folder: string | null;+}++export async function sendMessage(surface: Surface, content: string, attachments: Array<{ name: string; data: string; mime?: string }> = [], code?: CodeTurn): Promise<void> {+ const store = conversations[surface];+ let id = store.getState().activeId;if (!id) {- const thread = await api.chat.createThread();+ const thread = await api.chat.createThread(surface === "code" ? `Code · ${content.slice(0, 40)}` : undefined);id = thread.id;- chat.setActive(id);- chat.setMessages([]);+ store.getState().setActive(id);+ store.getState().setMessages([]);+ if (surface === "code") useCodeSessions.getState().upsert({ id, folder: code?.folder ?? null, createdAt: new Date().toISOString() });}const shown = content || `(Attached: ${attachments.map((a) => a.name).join(", ")})`;const optimistic: ChatMessage = {@@ -177,13 +212,13 @@ export async function sendMessage(content: string, attachments: Array<{ name: st? { attachments: attachments.map((a) => ({ name: a.name, kind: a.mime?.startsWith("image/") ? "image" : "document", mime: a.mime, src: a.mime?.startsWith("image/") ? `data:${a.mime};base64,${a.data}` : undefined })) }: {}),};- useChat.getState().addMessage(optimistic);- rt.setAgent("thinking");- await api.chat.send(content, id, attachments.map(({ name, data }) => ({ name, data })));+ store.getState().addMessage(optimistic);+ store.getState().setAgent("thinking");+ await api.chat.send(content, id, attachments.map(({ name, data }) => ({ name, data })), code ? { programming: code.mode, cwd: code.folder ?? undefined } : undefined);void refreshThreads();}-export async function answerPrompt(prompt: PendingPrompt, value: string | null): Promise<void> {+export async function answerPrompt(store: ConversationStore, prompt: PendingPrompt, value: string | null): Promise<void> {await api.chat.answer(prompt.id, value ?? "", prompt.targetId);- useRuntimeState.getState().removePrompt(prompt.id);+ store.getState().removePrompt(prompt.id);}diff --git a/apps/desktop/src/app/store.ts b/apps/desktop/src/app/store.tsindex 9ce62ed4..62cceb90 100644--- a/apps/desktop/src/app/store.ts+++ b/apps/desktop/src/app/store.ts@@ -5,7 +5,7 @@═══════════════════════════════════════════════════════════════ */import { create } from "zustand";-import type { BotStatus, ChatMessage, ChatThread, PendingPrompt } from "~/api/types";+import type { BotStatus, ChatThread, PendingPrompt } from "~/api/types";export type View = "chat" | "code" | "bots" | "plugins" | "skills" | "settings";@@ -59,34 +59,15 @@ export const useRuntimeState = create<RuntimeState>((set, get) => ({}),}));-interface ChatState {+interface ThreadsState {+ /** Every session the runtime has; each surface filters its own. */threads: ChatThread[];- activeId: string | null;- messages: ChatMessage[];- streaming: string;- loading: boolean;setThreads(threads: ChatThread[]): void;- setActive(id: string | null): void;- setMessages(messages: ChatMessage[]): void;- addMessage(message: ChatMessage): void;- appendStreaming(text: string): void;- clearStreaming(): void;- setLoading(loading: boolean): void;}-export const useChat = create<ChatState>((set) => ({+export const useChat = create<ThreadsState>((set) => ({threads: [],- activeId: null,- messages: [],- streaming: "",- loading: false,setThreads: (threads) => set({ threads }),- setActive: (activeId) => set({ activeId }),- setMessages: (messages) => set({ messages }),- addMessage: (message) => set((s) => ({ messages: [...s.messages, message] })),- appendStreaming: (text) => set((s) => ({ streaming: s.streaming + text })),- clearStreaming: () => set({ streaming: "" }),- setLoading: (loading) => set({ loading }),}));interface BotsState {diff --git a/apps/desktop/src/components/PixelWordmark.tsx b/apps/desktop/src/components/PixelWordmark.tsxnew file mode 100644index 00000000..cea3d182--- /dev/null+++ b/apps/desktop/src/components/PixelWordmark.tsx@@ -0,0 +1,49 @@+/**+ * The Mercury Code wordmark in the same 5-row pixel font as the terminal+ * splash (src/ui/pixel-logo.ts in the runtime): one brand, two screens.+ * Drawn as SVG squares; rows shade top→bottom like the terminal's+ * `████▓`, and the fill runs the accent → cyan so it reads as one mark.+ */++const GLYPHS: Record<string, string[]> = {+ M: ["10001", "11011", "10101", "10001", "10001"],+ E: ["1111", "1000", "1110", "1000", "1111"],+ R: ["1110", "1001", "1110", "1010", "1001"],+ C: ["0111", "1000", "1000", "1000", "0111"],+ U: ["1001", "1001", "1001", "1001", "0110"],+ Y: ["1001", "1001", "0110", "0110", "0110"],+ O: ["0110", "1001", "1001", "1001", "0110"],+ D: ["1110", "1001", "1001", "1001", "1110"],+ " ": ["00", "00", "00", "00", "00"],+};++const ROW_SHADE = [1, 1, 1, 0.82, 0.62];++export function PixelWordmark({ text = "MERCURY CODE", cell = 9, gap = 1.5, className }: { text?: string; cell?: number; gap?: number; className?: string }) {+ const cells: Array<{ x: number; y: number; row: number }> = [];+ let cursor = 0;+ for (const ch of text.toUpperCase()) {+ const glyph = GLYPHS[ch] ?? GLYPHS[" "];+ glyph.forEach((row, y) => {+ [...row].forEach((bit, x) => { if (bit === "1") cells.push({ x: cursor + x, y, row: y }); });+ });+ cursor += glyph[0].length + 1;+ }+ const cols = cursor - 1;+ const pitch = cell + gap;+ const width = cols * pitch - gap;+ const height = 5 * pitch - gap;+ return (+ <svg viewBox={`0 0 ${width} ${height}`} width={width} height={height} role="img" aria-label={text} className={className}>+ <defs>+ <linearGradient id="pixel-wordmark" x1="0" y1="0" x2="1" y2="0">+ <stop offset="0" stopColor="rgb(var(--accent))" />+ <stop offset="1" stopColor="rgb(var(--cyan))" />+ </linearGradient>+ </defs>+ {cells.map((c, i) => (+ <rect key={i} x={c.x * pitch} y={c.y * pitch} width={cell} height={cell} rx={1.5} fill="url(#pixel-wordmark)" opacity={ROW_SHADE[c.row]} />+ ))}+ </svg>+ );+}diff --git a/apps/desktop/src/layout/Workspace.tsx b/apps/desktop/src/layout/Workspace.tsxindex e4dee721..6de4c367 100644--- a/apps/desktop/src/layout/Workspace.tsx+++ b/apps/desktop/src/layout/Workspace.tsx@@ -39,7 +39,7 @@ export function Workspace({ connection, health, onSwitchConnection }: { connecti<div className="flex min-h-0 flex-1"><Rail connectionName={connection.name} /><main className="relative flex min-w-0 flex-1 flex-col">- <Pane active={view === "chat"}><ChatView mode="chat" /></Pane>+ <Pane active={view === "chat"}><ChatView /></Pane><Pane active={view === "code"}><CodeView /></Pane><Pane active={view === "bots"}><BotsView /></Pane><Pane active={view === "plugins"}><PluginsView /></Pane>diff --git a/apps/desktop/src/views/chat/ChatView.tsx b/apps/desktop/src/views/chat/ChatView.tsxindex 2c8c70b8..f03aa7b9 100644--- a/apps/desktop/src/views/chat/ChatView.tsx+++ b/apps/desktop/src/views/chat/ChatView.tsx@@ -1,149 +1,74 @@-import { PanelLeft, Plus } from "lucide-react";-import { useEffect, useLayoutEffect, useRef, useState } from "react";-import { cx } from "~/lib/cx";-import { useChat, useRuntimeState, useUi } from "~/app/store";-import { answerPrompt, openThread } from "~/app/events";+import { PanelLeft } from "lucide-react";+import { useEffect } from "react";+import { useChat, useUi } from "~/app/store";+import { conversations, ConversationContext, useCodeSessions } from "~/app/conversation";+import { openThread } from "~/app/events";import { Button } from "~/components/ui/Button";import { Tooltip } from "~/components/ui/Tooltip";-import { StateLabel } from "~/components/indicators/StateOrb";-import { Approval } from "~/components/indicators/Approval";-import { ThinkingDots } from "~/components/indicators/Thinking";-import { ThreadList } from "./ThreadList";import { Mark } from "~/components/Logo";-import { Message, StreamingMessage } from "./Message";-import { Composer } from "./Composer";+import { ThreadList } from "./ThreadList";+import { Conversation } from "./Conversation";/**- * Chat: threads on the left (collapsible), one conversation in a 760px- * column, the composer at the bottom. The same component serves Code- * mode with a different header.+ * Chat: sessions on the left (with New chat), one conversation. Its own+ * conversation store; Code sessions are not listed here.*/-const PAGE = 30;--export function ChatView({ mode, header }: { mode: "chat" | "code"; header?: React.ReactNode }) {+export function ChatView() {const sidebar = useUi((s) => s.sidebar);const toggleSidebar = useUi((s) => s.toggleSidebar);- const messages = useChat((s) => s.messages);- const streaming = useChat((s) => s.streaming);- const loading = useChat((s) => s.loading);- const activeId = useChat((s) => s.activeId);+ const view = useUi((s) => s.view);const threads = useChat((s) => s.threads);- const agent = useRuntimeState((s) => s.agent);- const step = useRuntimeState((s) => s.step);- const prompts = useRuntimeState((s) => s.prompts);- const scroller = useRef<HTMLDivElement>(null);- const stickToBottom = useRef(true);- // Render only the newest PAGE messages; older ones come in a page at a- // time when the reader scrolls near the top, keeping their place.- const [visible, setVisible] = useState(PAGE);- const prepend = useRef<{ height: number; top: number } | null>(null);- useEffect(() => { setVisible(PAGE); stickToBottom.current = true; }, [activeId]);- const shown = messages.length > visible ? messages.slice(messages.length - visible) : messages;- const hiddenCount = messages.length - shown.length;- useLayoutEffect(() => {- const el = scroller.current;- const p = prepend.current;- if (!el || !p) return;- el.scrollTop = p.top + (el.scrollHeight - p.height);- prepend.current = null;- }, [visible]);- function loadEarlier() {- const el = scroller.current;- if (!el || hiddenCount <= 0) return;- prepend.current = { height: el.scrollHeight, top: el.scrollTop };- setVisible((v) => v + PAGE);- }+ const codeIds = useCodeSessions((s) => s.sessions);+ const activeId = conversations.chat((s) => s.activeId);- const title = threads.find((t) => t.id === activeId)?.title || (activeId ? "Untitled" : "New thread");- const empty = !activeId && messages.length === 0 && !streaming;-- useEffect(() => {- const el = scroller.current;- if (!el || !stickToBottom.current) return;- el.scrollTop = el.scrollHeight;- }, [messages, streaming, prompts.length, loading]);+ const title = threads.find((t) => t.id === activeId)?.title || (activeId ? "Untitled" : "New chat");+ const codeSet = new Set(codeIds.map((c) => c.id));useEffect(() => {const onKey = (e: KeyboardEvent) => {- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "n" && !e.shiftKey) { e.preventDefault(); void openThread(null); }+ if (view !== "chat") return;+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "n" && !e.shiftKey) { e.preventDefault(); void openThread("chat", null); }if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "b") { e.preventDefault(); toggleSidebar(); }};window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);- }, [toggleSidebar]);+ }, [toggleSidebar, view]);return (- <div className="flex h-full min-h-0">- {mode === "chat" && sidebar && <ThreadList />}-- <section className="flex min-w-0 flex-1 flex-col">- <header className="flex h-[52px] shrink-0 items-center gap-2 border-b border-line px-3" data-tauri-drag-region>- {mode === "chat" && (- <Tooltip label={sidebar ? "Hide threads" : "Show threads"} shortcut="⌘B" side="bottom">- <Button variant="ghost" size="sm" icon onClick={toggleSidebar} aria-label="Toggle threads"><PanelLeft size={16} /></Button>- </Tooltip>- )}- <div className="min-w-0 flex-1 truncate text-base font-medium text-ink">{header ?? title}</div>- <StateLabel state={agent} detail={step?.tool ? `${step.tool}${step.total ? ` ${step.current}/${step.total}` : ""}` : undefined} />- {mode === "chat" && (- <Tooltip label="New thread" shortcut="⌘N" side="bottom">- <Button variant="ghost" size="sm" icon onClick={() => void openThread(null)} aria-label="New thread"><Plus size={16} /></Button>- </Tooltip>- )}- </header>-- <div- ref={scroller}- onScroll={(e) => {- const el = e.currentTarget;- stickToBottom.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;- if (el.scrollTop < 160 && hiddenCount > 0 && !prepend.current) loadEarlier();- }}- className={cx("min-h-0 flex-1 overflow-y-auto", empty && "flex items-center justify-center")}- >- {empty ? (- <EmptyPrompt mode={mode} />- ) : (- <div className="mx-auto flex w-full max-w-[780px] flex-col gap-7 px-8 py-8">- {loading && messages.length === 0 && <ThinkingDots label="Loading" />}- {hiddenCount > 0 && (- <button onClick={loadEarlier} className="self-center rounded-full border border-line px-3 py-1 text-xs text-ink3 hover:text-ink">- {hiddenCount} earlier message{hiddenCount === 1 ? "" : "s"}- </button>- )}- {shown.map((m) => <Message key={m.id} message={m} />)}- {streaming && <StreamingMessage text={streaming} />}- {!streaming && (agent === "thinking" || agent === "working") && (- <ThinkingDots label={agent === "working" && step?.tool ? `Running ${step.tool}` : "Thinking"} className="pl-10" />- )}- {prompts.map((p) => (- <div key={p.id} className="pl-10">- <Approval prompt={p} onAnswer={(v) => answerPrompt(p, v)} />- </div>- ))}+ <ConversationContext.Provider value={conversations.chat}>+ <div className="flex h-full min-h-0">+ {sidebar && (+ <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)}+ newLabel="New chat"+ searchLabel="Search chats"+ />+ )}+ <Conversation+ header={+ <>+ <Tooltip label={sidebar ? "Hide sessions" : "Show sessions"} shortcut="⌘B" side="bottom">+ <Button variant="ghost" size="sm" icon onClick={toggleSidebar} aria-label="Toggle sessions"><PanelLeft size={16} /></Button>+ </Tooltip>+ <span className="truncate text-base font-medium text-ink">{title}</span>+ </>+ }+ empty={+ <div className="flex flex-col items-center gap-4 px-6 pb-24 text-center">+ <div className="relative flex items-center justify-center">+ <span aria-hidden="true" className="absolute h-28 w-28 rounded-full animate-breathe" style={{ background: "radial-gradient(closest-side, rgb(var(--glow) / 0.22), rgb(var(--glow) / 0))" }} />+ <Mark size={64} className="relative" />+ </div>+ <h2 className="text-2xl font-bold tracking-tight text-ink">Mercury Agent</h2>+ <p className="max-w-[460px] text-base text-ink3">This chat is empty. Ask, delegate, or think out loud. Mercury remembers what matters.</p></div>- )}- </div>-- <Composer mode={mode} />- </section>- </div>- );-}--function EmptyPrompt({ mode }: { mode: "chat" | "code" }) {- return (- <div className="flex flex-col items-center gap-4 px-6 pb-24 text-center">- <div className="relative flex items-center justify-center">- <span aria-hidden="true" className="absolute h-28 w-28 rounded-full animate-breathe" style={{ background: "radial-gradient(closest-side, rgb(var(--glow) / 0.22), rgb(var(--glow) / 0))" }} />- <Mark size={64} className="relative" />+ }+ composer={{ surface: "chat", placeholder: "Ask anything…" }}+ /></div>- <h2 className="text-2xl font-bold tracking-tight text-ink">Mercury Agent</h2>- <p className="max-w-[460px] text-base text-ink3">- {mode === "code"- ? "What should we build? Mercury works in your workspace: reads, edits, runs, and asks before anything that can't be undone."- : "This chat is empty. Ask, delegate, or think out loud. Mercury remembers what matters."}- </p>- </div>+ </ConversationContext.Provider>);}diff --git a/apps/desktop/src/views/chat/Composer.tsx b/apps/desktop/src/views/chat/Composer.tsxindex 9d5e9006..d54179e7 100644--- a/apps/desktop/src/views/chat/Composer.tsx+++ b/apps/desktop/src/views/chat/Composer.tsx@@ -4,7 +4,8 @@ import { cx } from "~/lib/cx";import * as api from "~/api/mercury";import type { ChatSettings, ModelsResponse } from "~/api/types";import { useRuntimeState } from "~/app/store";-import { sendMessage } from "~/app/events";+import { sendMessage, type CodeTurn } from "~/app/events";+import { useConversation, type Surface } from "~/app/conversation";import { Button } from "~/components/ui/Button";import { Menu, MenuItem, MenuLabel, MenuSeparator } from "~/components/ui/Menu";import { Tooltip } from "~/components/ui/Tooltip";@@ -28,7 +29,18 @@ const MAX_FILES = 4;const MAX_IMAGE_BYTES = 8 * 1024 * 1024;const MAX_PDF_BYTES = 15 * 1024 * 1024;-export function Composer({ mode }: { mode: "chat" | "code" }) {+export interface ComposerProps {+ surface: Surface;+ placeholder: string;+ /** Code turns carry their mode and folder; Chat turns carry nothing extra. */+ code?: CodeTurn;+ /** Shown left of send (e.g. the Code mode picker); replaces the model/approval pickers' slot order. */+ extra?: React.ReactNode;+ /** Block sending with this reason (e.g. no folder chosen). */+ blockedReason?: string;+}++export function Composer({ surface, placeholder, code, extra, blockedReason }: ComposerProps) {const [text, setText] = useState("");const [files, setFiles] = useState<Pending[]>([]);const [dragging, setDragging] = useState(false);@@ -36,7 +48,7 @@ export function Composer({ mode }: { mode: "chat" | "code" }) {const [error, setError] = useState<string | null>(null);const ref = useRef<HTMLTextAreaElement>(null);const picker = useRef<HTMLInputElement>(null);- const agent = useRuntimeState((s) => s.agent);+ const agent = useConversation((s) => s.agent);const connected = useRuntimeState((s) => s.connected);useEffect(() => {@@ -88,7 +100,7 @@ export function Composer({ mode }: { mode: "chat" | "code" }) {setSending(true);setError(null);try {- await sendMessage(content, files.map((f) => ({ name: f.name, data: f.data, mime: f.mime })));+ await sendMessage(surface, content, files.map((f) => ({ name: f.name, data: f.data, mime: f.mime })), code);setText("");for (const f of files) if (f.preview) URL.revokeObjectURL(f.preview);setFiles([]);@@ -101,7 +113,7 @@ export function Composer({ mode }: { mode: "chat" | "code" }) {}const busy = agent === "thinking" || agent === "streaming" || agent === "working";- const canSend = connected && (text.trim().length > 0 || files.length > 0);+ const canSend = connected && !blockedReason && (text.trim().length > 0 || files.length > 0);return (<div className="shrink-0 px-8 pb-6 pt-2">@@ -142,7 +154,7 @@ export function Composer({ mode }: { mode: "chat" | "code" }) {if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); void submit(); }if (e.key === "Escape" && text) { e.preventDefault(); setText(""); }}}- placeholder={!connected ? "Waiting for Mercury…" : mode === "code" ? "Describe the change…" : "Ask anything…"}+ placeholder={!connected ? "Waiting for Mercury…" : blockedReason ?? placeholder}rows={1}disabled={!connected}className="block w-full resize-none bg-transparent px-5 pt-4 text-md leading-[26px] text-ink caret-accent placeholder:text-ink4"@@ -155,8 +167,9 @@ export function Composer({ mode }: { mode: "chat" | "code" }) {</Button></Tooltip><input ref={picker} type="file" accept="image/*,application/pdf" multiple hidden onChange={(e) => { if (e.target.files) void addFiles(e.target.files); e.target.value = ""; }} />+ {extra}<ModelPicker />- <ModePicker />+ {surface === "chat" && <ModePicker />}<div className="flex-1" />{busy ? (<span className="mr-2 text-xs text-ink4">{agent === "streaming" ? "Answering" : agent === "working" ? "Working" : "Thinking"}…</span>diff --git a/apps/desktop/src/views/chat/Conversation.tsx b/apps/desktop/src/views/chat/Conversation.tsxnew file mode 100644index 00000000..cbf1114d--- /dev/null+++ b/apps/desktop/src/views/chat/Conversation.tsx@@ -0,0 +1,98 @@+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";+import { cx } from "~/lib/cx";+import { useConversation, useConversationStore } from "~/app/conversation";+import { answerPrompt } from "~/app/events";+import { StateLabel } from "~/components/indicators/StateOrb";+import { Approval } from "~/components/indicators/Approval";+import { ThinkingDots } from "~/components/indicators/Thinking";+import { Message, StreamingMessage } from "./Message";+import { Composer, type ComposerProps } from "./Composer";++const PAGE = 30;++/**+ * One conversation column: header, messages (newest PAGE, older on+ * scroll-up with the place kept), approvals, composer. It reads the+ * surface it is rendered in (ConversationContext), so Chat and Code use+ * the same component without sharing any state.+ */+export function Conversation({ header, empty, composer }: { header: ReactNode; empty: ReactNode; composer: ComposerProps }) {+ const store = useConversationStore();+ const messages = useConversation((s) => s.messages);+ const streaming = useConversation((s) => s.streaming);+ const loading = useConversation((s) => s.loading);+ const activeId = useConversation((s) => s.activeId);+ const agent = useConversation((s) => s.agent);+ const step = useConversation((s) => s.step);+ const prompts = useConversation((s) => s.prompts);+ const scroller = useRef<HTMLDivElement>(null);+ const stickToBottom = useRef(true);+ const [visible, setVisible] = useState(PAGE);+ const prepend = useRef<{ height: number; top: number } | null>(null);++ useEffect(() => { setVisible(PAGE); stickToBottom.current = true; }, [activeId]);+ const shown = messages.length > visible ? messages.slice(messages.length - visible) : messages;+ const hiddenCount = messages.length - shown.length;+ useLayoutEffect(() => {+ const el = scroller.current;+ const p = prepend.current;+ if (!el || !p) return;+ el.scrollTop = p.top + (el.scrollHeight - p.height);+ prepend.current = null;+ }, [visible]);+ function loadEarlier() {+ const el = scroller.current;+ if (!el || hiddenCount <= 0) return;+ prepend.current = { height: el.scrollHeight, top: el.scrollTop };+ setVisible((v) => v + PAGE);+ }+ useEffect(() => {+ const el = scroller.current;+ if (!el || !stickToBottom.current) return;+ el.scrollTop = el.scrollHeight;+ }, [messages, streaming, prompts.length, loading]);++ const isEmpty = !activeId && messages.length === 0 && !streaming;++ return (+ <section className="flex min-w-0 flex-1 flex-col">+ <header className="flex h-[52px] shrink-0 items-center gap-2 border-b border-line px-4" data-tauri-drag-region>+ <div className="flex min-w-0 flex-1 items-center gap-3">{header}</div>+ <StateLabel state={agent} detail={step?.tool ? `${step.tool}${step.total ? ` ${step.current}/${step.total}` : ""}` : undefined} />+ </header>++ <div+ ref={scroller}+ onScroll={(e) => {+ const el = e.currentTarget;+ stickToBottom.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;+ if (el.scrollTop < 160 && hiddenCount > 0 && !prepend.current) loadEarlier();+ }}+ className={cx("min-h-0 flex-1 overflow-y-auto", isEmpty && "flex items-center justify-center")}+ >+ {isEmpty ? empty : (+ <div className="mx-auto flex w-full max-w-[780px] flex-col gap-7 px-8 py-8">+ {loading && messages.length === 0 && <ThinkingDots label="Loading" />}+ {hiddenCount > 0 && (+ <button onClick={loadEarlier} className="self-center rounded-full border border-line px-3 py-1 text-xs text-ink3 hover:text-ink">+ {hiddenCount} earlier message{hiddenCount === 1 ? "" : "s"}+ </button>+ )}+ {shown.map((m) => <Message key={m.id} message={m} />)}+ {streaming && <StreamingMessage text={streaming} />}+ {!streaming && (agent === "thinking" || agent === "working") && (+ <ThinkingDots label={agent === "working" && step?.tool ? `Running ${step.tool}` : "Thinking"} className="pl-10" />+ )}+ {prompts.map((p) => (+ <div key={p.id} className="pl-10">+ <Approval prompt={p} onAnswer={(v) => answerPrompt(store, p, v)} />+ </div>+ ))}+ </div>+ )}+ </div>++ <Composer {...composer} />+ </section>+ );+}diff --git a/apps/desktop/src/views/chat/ThreadList.tsx b/apps/desktop/src/views/chat/ThreadList.tsxindex f38c097d..47c76f5a 100644--- a/apps/desktop/src/views/chat/ThreadList.tsx+++ b/apps/desktop/src/views/chat/ThreadList.tsx@@ -1,21 +1,26 @@-import { Search, Trash2 } from "lucide-react";+import { Search, SquarePen, Trash2 } from "lucide-react";import { useEffect, useMemo, useRef, useState } from "react";import { cx } from "~/lib/cx";import * as api from "~/api/mercury";import type { ChatThread } from "~/api/types";-import { useChat } from "~/app/store";-import { openThread, refreshThreads } from "~/app/events";+import { refreshThreads } from "~/app/events";const PAGE = 40;/**- * Threads, most recently active first, grouped by day. Renders a page at a- * time and adds the next page as the list scrolls; a filter box searches- * all of them by title.+ * Sessions of one surface, most recently active first, grouped by day, with+ * New and search on top. Renders a page at a time and adds the next page as+ * the list scrolls.*/-export function ThreadList() {- const threads = useChat((s) => s.threads);- const activeId = useChat((s) => s.activeId);+export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchLabel, renderMeta }: {+ threads: ChatThread[];+ activeId: string | null;+ onOpen: (id: string) => void;+ onNew: () => void;+ newLabel: string;+ searchLabel: string;+ renderMeta?: (t: ChatThread) => React.ReactNode;+}) {const [limit, setLimit] = useState(PAGE);const [query, setQuery] = useState("");const sentinel = useRef<HTMLDivElement>(null);@@ -42,28 +47,34 @@ export function ThreadList() {async function remove(t: ChatThread) {try {await api.chat.deleteThread(t.id);- if (activeId === t.id) void openThread(null);+ if (activeId === t.id) onNew();void refreshThreads();} catch { /* keep */ }}return (<aside className="flex h-full w-[300px] shrink-0 flex-col border-r border-line bg-soft">- <div className="flex h-[52px] shrink-0 items-center px-3" data-tauri-drag-region>- <label className="flex h-9 w-full items-center gap-2 rounded-lg border border-line bg-surface px-2.5 text-ink4 focus-within:border-line-strong">+ <div className="flex shrink-0 flex-col gap-2 px-3 pb-2 pt-3" data-tauri-drag-region>+ <button onClick={onNew} className="flex h-10 items-center gap-2 rounded-lg border border-line bg-surface px-3 text-base font-medium text-ink shadow-sm hover:border-line-strong" data-no-drag>+ <SquarePen size={17} aria-hidden="true" />+ <span className="flex-1 text-left">{newLabel}</span>+ <kbd className="font-mono text-xs text-ink4">⌘N</kbd>+ </button>+ <label className="flex h-9 w-full items-center gap-2 rounded-lg px-2.5 text-ink4 hover:bg-ink/[0.04] focus-within:bg-ink/[0.05]"><Search size={16} aria-hidden="true" />- <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search threads" className="w-full bg-transparent text-base text-ink placeholder:text-ink4" aria-label="Search threads" />+ <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={searchLabel} className="w-full bg-transparent text-base text-ink placeholder:text-ink4" aria-label={searchLabel} /></label></div><div className="min-h-0 flex-1 overflow-y-auto px-2 pb-3">- {filtered.length === 0 && <p className="px-3 pt-2 text-base text-ink4">{query ? "No matching threads." : "No threads yet."}</p>}+ {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"><div className="px-3 pb-1.5 text-xs font-medium uppercase tracking-wider text-ink4">{day}</div>{list.map((t) => (<div key={t.id} className={cx("group flex items-center rounded-lg", activeId === t.id ? "bg-ink/[0.07]" : "hover:bg-ink/[0.05]")}>- <button onClick={() => void openThread(t.id)} className="min-w-0 flex-1 truncate px-3 py-2.5 text-left text-base" title={t.title || "Untitled"}>- <span className={activeId === t.id ? "text-ink" : "text-ink2 group-hover:text-ink"}>{t.title || "Untitled"}</span>+ <button onClick={() => onOpen(t.id)} className="min-w-0 flex-1 px-3 py-2.5 text-left text-base" title={t.title || "Untitled"}>+ <span className={cx("block truncate", activeId === t.id ? "text-ink" : "text-ink2 group-hover:text-ink")}>{(t.title || "Untitled").replace(/^Code · /, "")}</span>+ {renderMeta?.(t)}</button><button onClick={() => void remove(t)} className="mr-1 hidden rounded p-1 text-ink4 hover:text-red group-hover:block" aria-label="Delete thread"><Trash2 size={15} />diff --git a/apps/desktop/src/views/code/CodeView.tsx b/apps/desktop/src/views/code/CodeView.tsxindex e29534ef..8307d8dd 100644--- a/apps/desktop/src/views/code/CodeView.tsx+++ b/apps/desktop/src/views/code/CodeView.tsx@@ -1,56 +1,141 @@+import { FolderOpen, GitBranch, PanelLeft, PanelRight } from "lucide-react";import { useEffect, useState } from "react";import * as api from "~/api/mercury";-import type { ChatSettings, CodeMode, CodeStatus } from "~/api/types";-import { Segmented, Mono } from "~/components/ui/bits";+import type { CodeMode } from "~/api/types";+import { useChat, useUi } from "~/app/store";+import { conversations, ConversationContext, useCodeSessions } from "~/app/conversation";+import { openThread, type CodeTurn } from "~/app/events";+import { Button } from "~/components/ui/Button";import { Tooltip } from "~/components/ui/Tooltip";-import { ChatView } from "~/views/chat/ChatView";+import { Segmented } from "~/components/ui/bits";+import { PixelWordmark } from "~/components/PixelWordmark";+import { ThreadList } from "~/views/chat/ThreadList";+import { Conversation } from "~/views/chat/Conversation";+import { useConnections } from "~/shell/connections";+import { ProjectPanel } from "./ProjectPanel";+import { FolderPicker } from "./FolderPicker";-/**- * Code: the same conversation with the runtime's programming mode on,- * driven by /api/code/status and /api/code/set.- * Off plain chat- * Auto Mercury decides when a request is a coding task- * Plan it plans and waits for you before changing anything- * Execute it plans and carries out the plan- */-const MODES: Array<{ value: CodeMode; label: string; hint: string }> = [- { value: "off", label: "Off", hint: "Plain chat" },- { value: "auto", label: "Auto", hint: "Mercury decides when a request is a coding task" },+type Mode = Exclude<CodeMode, "off">;++const MODES: Array<{ value: Mode; label: string; hint: string }> = [+ { value: "auto", label: "Auto", hint: "Plans and builds in one flow" },{ value: "plan", label: "Plan", hint: "Plans first and waits for you" },- { value: "execute", label: "Execute", hint: "Plans and carries it out" },+ { value: "execute", label: "Execute", hint: "Carries out the plan" },];+/**+ * Mercury Code: its own sessions, its own conversation, a project folder+ * per session, and the project on the right (changes in real time, files,+ * preview). Programming is always on here — only how it works (Auto, Plan,+ * Execute) is a choice — and it applies to this session only: the runtime+ * swaps it in per turn, so Chat and the terminal are untouched.+ */export function CodeView() {- const [status, setStatus] = useState<CodeStatus | null>(null);- const [settings, setSettings] = useState<ChatSettings | null>(null);- const [error, setError] = useState<string | null>(null);+ const view = useUi((s) => s.view);+ const threads = useChat((s) => s.threads);+ const sessions = useCodeSessions((s) => s.sessions);+ const upsert = useCodeSessions((s) => s.upsert);+ const loadSessions = useCodeSessions((s) => s.load);+ const activeId = conversations.code((s) => s.activeId);+ const connection = useConnections((s) => s.connections.find((c) => c.id === s.activeId));+ const [listOpen, setListOpen] = useState(true);+ const [panelOpen, setPanelOpen] = useState(true);+ const [mode, setMode] = useState<Mode>("auto");+ const [pendingFolder, setPendingFolder] = useState<string | null>(null);+ const [picking, setPicking] = useState(false);+ const [branch, setBranch] = useState<string>("");- async function load() {- try { setStatus(await api.code.status()); } catch { setStatus(null); }- try { setSettings(await api.chat.settings()); } catch { setSettings(null); }- }- useEffect(() => { void load(); }, []);+ useEffect(() => { if (connection) loadSessions(`${connection.id}@${connection.baseUrl}`); }, [connection?.id, connection?.baseUrl, loadSessions]);++ const session = sessions.find((s) => s.id === activeId) ?? null;+ const folder = session?.folder ?? pendingFolder;++ // Git and file endpoints follow the runtime's workspace root: point it at this session's folder.+ useEffect(() => {+ if (!folder || view !== "code") return;+ void api.workspace.setRoot(folder).then(() => api.workspace.info()).then((i) => setBranch(i.isGit ? i.branch : "")).catch(() => setBranch(""));+ }, [folder, view]);- async function setMode(state: CodeMode) {- setError(null);- try { await api.code.set(state); } catch (err) { setError(err instanceof Error ? err.message : String(err)); }- void load();+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (view !== "code") return;+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "n" && !e.shiftKey) { e.preventDefault(); void openThread("code", null); }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [view]);++ function chooseFolder(path: string) {+ setPicking(false);+ if (session) upsert({ ...session, folder: path });+ else setPendingFolder(path);}- const current = MODES.find((m) => m.value === (status?.state ?? "off"));- const header = (- <div className="flex items-center gap-3">- <Tooltip label={current?.hint ?? ""} side="bottom">- <span>- <Segmented<CodeMode> value={status?.state ?? "off"} onChange={(v) => void setMode(v)} options={MODES.map(({ value, label }) => ({ value, label }))} />- </span>- </Tooltip>- {status?.statusText && <span className="truncate text-xs text-ink3">{status.statusText}</span>}- {settings?.workspace && <Mono className="truncate">{settings.workspace}</Mono>}- {status && !status.available && <span className="text-xs text-ink4">Not available on this runtime.</span>}- {error && <span className="text-xs text-red">{error}</span>}- </div>+ const ids = new Set(sessions.map((s) => s.id));+ const codeThreads = threads.filter((t) => ids.has(t.id));+ const folderOf = (id: string) => sessions.find((s) => s.id === id)?.folder ?? null;+ const turn: CodeTurn = { mode, folder };++ return (+ <ConversationContext.Provider value={conversations.code}>+ <div className="flex h-full min-h-0">+ {listOpen && (+ <ThreadList+ threads={codeThreads}+ activeId={activeId}+ onOpen={(id) => void openThread("code", id)}+ onNew={() => { setPendingFolder(folder); void openThread("code", null); }}+ newLabel="New session"+ searchLabel="Search sessions"+ renderMeta={(t) => { const f = folderOf(t.id); return f ? <span className="block truncate font-mono text-xs text-ink4">{shortPath(f)}</span> : null; }}+ />+ )}++ <Conversation+ header={+ <>+ <Tooltip label={listOpen ? "Hide sessions" : "Show sessions"} side="bottom">+ <Button variant="ghost" size="sm" icon onClick={() => setListOpen((o) => !o)} aria-label="Toggle sessions"><PanelLeft size={16} /></Button>+ </Tooltip>+ <button onClick={() => setPicking(true)} className="flex h-8 min-w-0 items-center gap-2 rounded-lg border border-line bg-surface px-2.5 text-sm hover:border-line-strong" title={folder ?? "Choose a project folder"}>+ <FolderOpen size={15} className="shrink-0 text-ink3" />+ <span className="truncate font-medium text-ink">{folder ? baseName(folder) : "Open a folder…"}</span>+ </button>+ {branch && <span className="flex items-center gap-1 font-mono text-xs text-ink3"><GitBranch size={13} />{branch}</span>}+ <div className="flex-1" />+ <Tooltip label={MODES.find((m) => m.value === mode)?.hint ?? ""} side="bottom">+ <span><Segmented<Mode> value={mode} onChange={setMode} options={MODES.map(({ value, label }) => ({ value, label }))} /></span>+ </Tooltip>+ <Tooltip label={panelOpen ? "Hide project" : "Show project"} side="bottom">+ <Button variant="ghost" size="sm" icon onClick={() => setPanelOpen((o) => !o)} aria-label="Toggle project panel"><PanelRight size={16} /></Button>+ </Tooltip>+ </>+ }+ empty={+ <div className="flex flex-col items-center gap-5 px-6 pb-24 text-center">+ <PixelWordmark />+ <p className="max-w-[480px] text-base text-ink3">+ {folder+ ? <>Working in <span className="font-mono text-ink2">{shortPath(folder)}</span>. Describe what to build or fix; Mercury reads, edits, runs and checks its work.</>+ : "Open a project folder to start. Mercury works inside it: reads, edits, runs, and asks before anything that can't be undone."}+ </p>+ {!folder && <Button variant="primary" size="lg" onClick={() => setPicking(true)}><FolderOpen size={16} /> Open a folder</Button>}+ </div>+ }+ composer={{ surface: "code", placeholder: "Describe the change…", code: turn, blockedReason: folder ? undefined : "Open a project folder first" }}+ />++ {panelOpen && folder && <ProjectPanel folder={folder} />}+ </div>+ <FolderPicker open={picking} onOpenChange={setPicking} onPick={chooseFolder} initial={folder ?? ""} local={connection?.kind === "local"} />+ </ConversationContext.Provider>);+}++function baseName(p: string): string {+ return p.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || p;+}- return <ChatView mode="code" header={header} />;+export function shortPath(p: string): string {+ return p.replace(/^\/Users\/[^/]+/, "~").replace(/^[A-Z]:\\Users\\[^\\]+/i, "~");}diff --git a/apps/desktop/src/views/code/FolderPicker.tsx b/apps/desktop/src/views/code/FolderPicker.tsxnew file mode 100644index 00000000..3d371f64--- /dev/null+++ b/apps/desktop/src/views/code/FolderPicker.tsx@@ -0,0 +1,42 @@+import { useEffect, useState } from "react";+import { Dialog } from "~/components/ui/Dialog";+import { Field, Input } from "~/components/ui/Input";+import { Button } from "~/components/ui/Button";+import { isTauri } from "~/shell/tauri";++/**+ * Pick the project folder. On this computer: the system folder dialog. On a+ * remote runtime the folder lives on that machine, so it's typed as a path+ * there (the runtime checks it exists before the turn starts).+ */+export function FolderPicker({ open, onOpenChange, onPick, initial, local }: { open: boolean; onOpenChange: (o: boolean) => void; onPick: (path: string) => void; initial: string; local: boolean }) {+ const [path, setPath] = useState(initial);+ useEffect(() => { if (open) setPath(initial); }, [open, initial]);++ useEffect(() => {+ if (!open || !local || !isTauri) return;+ let cancelled = false;+ void import("@tauri-apps/plugin-dialog")+ .then((m) => m.open({ directory: true, multiple: false, title: "Open a project folder", defaultPath: initial || undefined }))+ .then((picked) => {+ if (cancelled) return;+ if (typeof picked === "string" && picked) onPick(picked);+ else onOpenChange(false);+ })+ .catch(() => { /* fall back to the typed path below */ });+ return () => { cancelled = true; };+ }, [open, local]);++ if (local && isTauri) return null;+ return (+ <Dialog open={open} onOpenChange={onOpenChange} title="Project folder" description={local ? "The folder on this computer to work in." : "A folder on the remote machine running Mercury."}>+ <form onSubmit={(e) => { e.preventDefault(); if (path.trim()) onPick(path.trim()); }} className="flex flex-col gap-3">+ <Field label="Path" htmlFor="code-folder"><Input id="code-folder" value={path} onChange={(e) => setPath(e.target.value)} placeholder="/home/me/projects/app" mono autoFocus /></Field>+ <div className="flex justify-end gap-2">+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>Cancel</Button>+ <Button type="submit" variant="primary" disabled={!path.trim()}>Open</Button>+ </div>+ </form>+ </Dialog>+ );+}diff --git a/apps/desktop/src/views/code/ProjectPanel.tsx b/apps/desktop/src/views/code/ProjectPanel.tsxnew file mode 100644index 00000000..d5634658--- /dev/null+++ b/apps/desktop/src/views/code/ProjectPanel.tsx@@ -0,0 +1,195 @@+import { ChevronRight, File, Folder, GitCompare, RefreshCw, X } from "lucide-react";+import { useCallback, useEffect, useState } from "react";+import * as api from "~/api/mercury";+import { useUi } from "~/app/store";+import { conversations } from "~/app/conversation";+import { Button } from "~/components/ui/Button";+import { Badge, Segmented, Spinner } from "~/components/ui/bits";+import { cx } from "~/lib/cx";++type Tab = "changes" | "files";+type Selection = { kind: "diff" | "file"; path: string } | null;++interface GitFile { path: string; status: string; staged: boolean }+interface TreeItem { name: string; path: string; isDirectory: boolean }++/**+ * The project beside the conversation: what changed (live), the files, and+ * a preview of whatever is selected — all in this side panel, never in+ * the conversation.+ */+export function ProjectPanel({ folder }: { folder: string }) {+ const view = useUi((s) => s.view);+ const [tab, setTab] = useState<Tab>("changes");+ const [isGit, setIsGit] = useState<boolean | null>(null);+ const [files, setFiles] = useState<GitFile[]>([]);+ const [meta, setMeta] = useState<{ branch: string; ahead: number; behind: number } | null>(null);+ const [selection, setSelection] = useState<Selection>(null);+ const [width, setWidth] = useState(380);++ const loadGit = useCallback(async () => {+ try {+ const info = await api.workspace.info();+ setIsGit(info.isGit);+ if (!info.isGit) { setFiles([]); setMeta(null); return; }+ const s = await api.git.status();+ setFiles(s.files);+ setMeta({ branch: s.branch, ahead: s.ahead, behind: s.behind });+ } catch {+ setIsGit(false);+ }+ }, []);++ // Real time: poll while Code is on screen, and right after every turn.+ useEffect(() => {+ if (view !== "code") return;+ void loadGit();+ const timer = setInterval(() => void loadGit(), 3000);+ const off = conversations.code.subscribe((s, prev) => { if (s.agent === "idle" && prev.agent !== "idle") void loadGit(); });+ return () => { clearInterval(timer); off(); };+ }, [view, folder, loadGit]);++ useEffect(() => { setSelection(null); }, [folder]);++ return (+ <aside className="relative flex shrink-0 flex-col border-l border-line bg-soft" style={{ width }}>+ <Resizer onResize={(dx) => setWidth((w) => Math.min(720, Math.max(300, w - dx)))} />+ <div className="flex h-[52px] shrink-0 items-center gap-2 border-b border-line px-3">+ <Segmented<Tab> value={tab} onChange={setTab} options={[{ value: "changes", label: `Changes${files.length ? ` · ${files.length}` : ""}` }, { value: "files", label: "Files" }]} />+ <div className="flex-1" />+ <Button variant="ghost" size="sm" icon onClick={() => void loadGit()} aria-label="Refresh"><RefreshCw size={14} /></Button>+ </div>++ <div className={cx("min-h-0 overflow-y-auto", selection ? "h-[38%] shrink-0 border-b border-line" : "flex-1")}>+ {tab === "changes" && (+ isGit === null ? <Centered><Spinner size={16} /></Centered>+ : !isGit ? <Centered>This folder is not a Git repository, so changes aren't tracked. Files are still browsable.</Centered>+ : (+ <div className="p-2">+ {meta && <div className="px-2 pb-2 pt-1 font-mono text-xs text-ink3">{meta.branch}{meta.ahead ? ` ↑${meta.ahead}` : ""}{meta.behind ? ` ↓${meta.behind}` : ""}</div>}+ {files.length === 0 && <p className="px-2 py-3 text-sm text-ink3">No changes. Edits Mercury makes appear here as they happen.</p>}+ {files.map((f) => (+ <button key={`${f.path}:${f.staged}`} onClick={() => setSelection({ kind: "diff", path: f.path })}+ className={cx("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm", selection?.path === f.path ? "bg-ink/[0.08]" : "hover:bg-ink/[0.05]")}>+ <StatusLetter status={f.status} />+ <span className="min-w-0 flex-1 truncate text-ink">{f.path.split("/").pop()}</span>+ <span className="max-w-[45%] truncate font-mono text-2xs text-ink4">{f.path.includes("/") ? f.path.slice(0, f.path.lastIndexOf("/")) : ""}</span>+ {f.staged && <Badge>staged</Badge>}+ </button>+ ))}+ </div>+ )+ )}+ {tab === "files" && <FileTree onOpen={(path) => setSelection({ kind: "file", path })} selected={selection?.kind === "file" ? selection.path : null} />}+ </div>++ {selection && <Preview selection={selection} onClose={() => setSelection(null)} />}+ </aside>+ );+}++function StatusLetter({ status }: { status: string }) {+ const s = status.trim().charAt(0) || "?";+ const tone = s === "A" || s === "?" ? "text-accent" : s === "D" ? "text-red" : s === "M" ? "text-amber" : "text-ink3";+ return <span className={cx("w-4 shrink-0 text-center font-mono text-xs font-semibold", tone)} title={status}>{s === "?" ? "U" : s}</span>;+}++function FileTree({ onOpen, selected }: { onOpen: (path: string) => void; selected: string | null }) {+ return <div className="p-2"><Dir path="" depth={0} onOpen={onOpen} selected={selected} initiallyOpen /></div>;+}++function Dir({ path, depth, onOpen, selected, initiallyOpen }: { path: string; depth: number; onOpen: (p: string) => void; selected: string | null; initiallyOpen?: boolean }) {+ const [open, setOpen] = useState(Boolean(initiallyOpen));+ const [items, setItems] = useState<TreeItem[] | null>(null);+ useEffect(() => {+ if (!open || items) return;+ void api.workspace.tree(path || undefined).then((t) => setItems(t.items.filter((i) => !/^(\.git|node_modules|\.DS_Store)$/.test(i.name)))).catch(() => setItems([]));+ }, [open, path, items]);+ const children = items === null && open ? <div className="py-1 pl-6 text-ink4"><Spinner size={12} /></div> : (+ open && items?.map((i) => i.isDirectory+ ? <Dir key={i.path} path={i.path} depth={depth + 1} onOpen={onOpen} selected={selected} />+ : (+ <button key={i.path} onClick={() => onOpen(i.path)} style={{ paddingLeft: 8 + (depth + 1) * 14 }}+ className={cx("flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left text-sm", selected === i.path ? "bg-ink/[0.08] text-ink" : "text-ink2 hover:bg-ink/[0.05] hover:text-ink")}>+ <File size={13} className="shrink-0 text-ink4" /><span className="truncate">{i.name}</span>+ </button>+ ))+ );+ if (depth === 0) return <>{children}</>;+ return (+ <div>+ <button onClick={() => setOpen((o) => !o)} style={{ paddingLeft: 8 + depth * 14 - 14 }} className="flex w-full items-center gap-1 rounded-md py-1 pr-2 text-left text-sm text-ink2 hover:bg-ink/[0.05] hover:text-ink">+ <ChevronRight size={13} className={cx("shrink-0 text-ink4 transition-transform", open && "rotate-90")} />+ <Folder size={13} className="shrink-0 text-ink3" /><span className="truncate">{path.split("/").pop()}</span>+ </button>+ {children}+ </div>+ );+}++function Preview({ selection, onClose }: { selection: NonNullable<Selection>; onClose: () => void }) {+ const [text, setText] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => {+ let live = true;+ setText(null); setError(null);+ const load = selection.kind === "diff"+ ? api.git.diff(selection.path).then((r) => r.diff || "(no diff — the file may be new and untracked)")+ : api.workspace.file(selection.path).then((f) => f.content + (f.truncated ? "\n… (truncated)" : ""));+ load.then((t) => { if (live) setText(t); }).catch((e) => { if (live) setError(e instanceof Error ? e.message : String(e)); });+ return () => { live = false; };+ }, [selection.kind, selection.path]);+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex h-9 shrink-0 items-center gap-2 border-b border-line px-3 text-xs">+ {selection.kind === "diff" ? <GitCompare size={13} className="text-ink3" /> : <File size={13} className="text-ink3" />}+ <span className="min-w-0 flex-1 truncate font-mono text-ink2" title={selection.path}>{selection.path}</span>+ <button onClick={onClose} className="rounded p-0.5 text-ink4 hover:text-ink" aria-label="Close preview"><X size={14} /></button>+ </div>+ <div className="min-h-0 flex-1 overflow-auto bg-bg">+ {error && <p className="p-3 text-sm text-red">{error}</p>}+ {text === null && !error && <div className="p-3 text-ink3"><Spinner size={14} /></div>}+ {text !== null && (selection.kind === "diff" ? <Diff text={text} /> : <pre className="p-3 font-mono text-[12.5px] leading-relaxed text-ink" data-selectable>{text}</pre>)}+ </div>+ </div>+ );+}++function Diff({ text }: { text: string }) {+ return (+ <pre className="py-2 font-mono text-[12.5px] leading-relaxed" data-selectable>+ {text.split("\n").map((line, i) => (+ <div key={i} className={cx("px-3",+ line.startsWith("+") && !line.startsWith("+++") && "bg-accent/10 text-ink",+ line.startsWith("-") && !line.startsWith("---") && "bg-red/10 text-ink",+ line.startsWith("@@") && "text-cyan",+ (line.startsWith("diff ") || line.startsWith("index ") || line.startsWith("+++") || line.startsWith("---")) && "text-ink4",+ !/^[+\-@]|^diff |^index /.test(line) && "text-ink2")}>+ {line || " "}+ </div>+ ))}+ </pre>+ );+}++function Centered({ children }: { children: React.ReactNode }) {+ return <div className="flex h-full items-center justify-center p-6 text-center text-sm text-ink3">{children}</div>;+}++function Resizer({ onResize }: { onResize: (dx: number) => void }) {+ return (+ <div+ className="absolute -left-1 top-0 z-10 h-full w-2 cursor-col-resize"+ onPointerDown={(e) => {+ let last = e.clientX;+ const move = (ev: PointerEvent) => { onResize(ev.clientX - last); last = ev.clientX; };+ const up = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", up); };+ window.addEventListener("pointermove", move);+ window.addEventListener("pointerup", up);+ }}+ role="separator"+ aria-orientation="vertical"+ aria-label="Resize project panel"+ />+ );+}diff --git a/docs/api-contract.md b/docs/api-contract.mdindex 5e886002..f3a4f0aa 100644--- a/docs/api-contract.md+++ b/docs/api-contract.md@@ -66,3 +66,15 @@ tokens, so a hostile page cannot ride the session cookie. Set## Feature flags (apiVersion 1)`auth.devices`, `chat.sse`, `chat.attachments`, `bots`, `plugins`, `mcp`, `boards`, `brain`.++## Session-scoped coding++`POST /api/chat/send` accepts `programming: "auto" | "plan" | "execute"` and+`cwd` (an existing directory). The runtime runs that turn with that session's+programming mode, plan and folder, then restores the global mode and folder,+so a coding session never changes Chat, the terminal or other sessions. A plan+made in a session stays with it for its next turn.++`POST /api/chat/send` returns sent files as `attachments: [{ name, kind, mime, url }]`,+threads return them per message, and `GET /api/chat/uploads/:month/:file`+serves them to an authenticated caller.diff --git a/src/channels/web.ts b/src/channels/web.tsindex a0d4b74f..261f2562 100644--- a/src/channels/web.ts+++ b/src/channels/web.ts@@ -348,7 +348,7 @@ export class WebChannel extends BaseChannel {* `attachments` are files already on disk (see `web/api/uploads.ts`); them being* present is what lets the runtime hand a photo to a vision model instead of a path.*/- emitMessageInThread(content: string, threadId: string, sessionId?: string, requestId?: string, externalConversationId?: string, messageId?: string, attachments?: ChannelAttachment[]): void {+ emitMessageInThread(content: string, threadId: string, sessionId?: string, requestId?: string, externalConversationId?: string, messageId?: string, attachments?: ChannelAttachment[], scope?: { programming?: string; cwd?: string }): void {if (this.restrictUser) {throw new Error('Web user is restricted. Disable restrict mode to continue.');}@@ -367,6 +367,10 @@ export class WebChannel extends BaseChannel {...(externalConversationId ? { externalConversationId } : {}),...(messageId ? { canonicalMessageId: messageId } : {}),...(attachments && attachments.length > 0 ? { attachments } : {}),+ // Session-scoped coding (Mercury Desktop's Code surface): the mode and+ // folder apply to this turn only; the agent restores the rest after.+ ...(scope?.programming ? { programming: scope.programming } : {}),+ ...(scope?.cwd ? { programmingCwd: scope.cwd } : {}),},};this.emit(msg);diff --git a/src/core/agent.ts b/src/core/agent.tsindex 58af55f0..7338d78a 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -18,7 +18,7 @@ import { createProvider, ProviderRegistry as ProviderRegistryImpl } from '../proimport type { BaseProvider } from '../providers/base.js';import { Lifecycle } from './lifecycle.js';import { Scheduler } from './scheduler.js';-import { ProgrammingMode } from './programming-mode.js';+import { ProgrammingMode, scopedProgrammingState, type ProgrammingSnapshot } from './programming-mode.js';import { ResearchMode } from './research-mode.js';import { SaverMode, NORMAL_HISTORY_WINDOW } from './saver-mode.js';import { BackgroundTaskManager } from './background-tasks.js';@@ -1798,6 +1798,45 @@ export class Agent {this.syncBgTasksToTui();}+ /**+ * Session-scoped coding. A message that names a programming mode (Mercury+ * Desktop's Code surface) runs with THAT session's mode, plan and folder;+ * everything else (terminal, chat, other sessions) keeps the global mode.+ * Turns are serial (processQueue), so a swap-run-restore is race-free.+ */+ private readonly sessionProgramming = new Map<string, ProgrammingSnapshot>();++ private async withSessionProgramming(msg: ChannelMessage, run: () => Promise<void>): Promise<void> {+ const requested = scopedProgrammingState(msg.metadata?.programming);+ const sessionKey = typeof msg.metadata?.sessionId === 'string' ? msg.metadata.sessionId : msg.sessionId;+ if (!requested || !sessionKey) return run();+ const globalMode = this.programmingMode.snapshot();+ const globalCwd = this.capabilities.getCwd();+ const cwd = typeof msg.metadata?.programmingCwd === 'string' ? msg.metadata.programmingCwd : null;+ const saved = this.sessionProgramming.get(sessionKey);+ this.programmingMode.restore({+ state: requested,+ projectContext: cwd ?? saved?.projectContext ?? null,+ // A plan made in this session stays with this session.+ lastPlan: saved?.lastPlan ?? null,+ });+ if (cwd) {+ this.capabilities.setCwd(cwd);+ this.capabilities.permissions.addTempScope(cwd, true, true);+ }+ try {+ await run();+ } finally {+ this.sessionProgramming.set(sessionKey, this.programmingMode.snapshot());+ if (this.sessionProgramming.size > 200) {+ const oldest = this.sessionProgramming.keys().next().value;+ if (oldest !== undefined) this.sessionProgramming.delete(oldest);+ }+ this.programmingMode.restore(globalMode);+ if (cwd) this.capabilities.setCwd(globalCwd);+ }+ }+private async processQueue(): Promise<void> {if (this.processing) return;if (this.messageQueue.length === 0) return;@@ -1814,7 +1853,7 @@ export class Agent {this.currentWorkKey = item.workKey ?? null;try {if (item.workKey) this.workLedger.markRunning(item.workKey);- await this.handleMessage(msg);+ await this.withSessionProgramming(msg, () => this.handleMessage(msg));if (item.workKey && this.workLedger.get(item.workKey)?.status === 'running') {this.workLedger.markFailed(item.workKey, 'Work ended without producing a durable final response');}diff --git a/src/core/programming-mode-scope.test.ts b/src/core/programming-mode-scope.test.tsnew file mode 100644index 00000000..2a14e289--- /dev/null+++ b/src/core/programming-mode-scope.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';+import { ProgrammingMode, scopedProgrammingState } from './programming-mode.js';++/**+ * Session-scoped coding: a Code session's mode is swapped in for its turn+ * and the global mode restored after, so Chat and the terminal never see it.+ */+describe('programming mode snapshots', () => {+ it('only accepts on-states for a scoped turn', () => {+ expect(scopedProgrammingState('auto')).toBe('auto');+ expect(scopedProgrammingState('plan')).toBe('plan');+ expect(scopedProgrammingState('execute')).toBe('execute');+ expect(scopedProgrammingState('off')).toBeNull();+ expect(scopedProgrammingState('rm -rf')).toBeNull();+ expect(scopedProgrammingState(undefined)).toBeNull();+ });++ it('swaps a session in and restores the global mode untouched', () => {+ const pm = new ProgrammingMode();+ expect(pm.getState()).toBe('off');+ const global = pm.snapshot();++ pm.restore({ state: 'plan', projectContext: '/work/app', lastPlan: null });+ pm.storePlan('1. do the thing');+ const session = pm.snapshot();+ pm.restore(global);++ expect(pm.getState()).toBe('off');+ expect(pm.getLastPlan()).toBeNull();+ expect(session).toEqual({ state: 'plan', projectContext: '/work/app', lastPlan: '1. do the thing' });++ // The session's plan is still there next turn.+ pm.restore({ ...session, state: 'execute' });+ expect(pm.isExecute()).toBe(true);+ expect(pm.getLastPlan()).toBe('1. do the thing');+ });+});diff --git a/src/core/programming-mode.ts b/src/core/programming-mode.tsindex 1713102e..47b41369 100644--- a/src/core/programming-mode.ts+++ b/src/core/programming-mode.ts@@ -2,6 +2,19 @@ import { logger } from '../utils/logger.js';export type ProgrammingModeState = 'off' | 'auto' | 'plan' | 'execute';+export interface ProgrammingSnapshot {+ state: ProgrammingModeState;+ projectContext: string | null;+ lastPlan: string | null;+}++const SCOPED_STATES: readonly ProgrammingModeState[] = ['auto', 'plan', 'execute'];++/** A per-turn programming mode a client asked for, if it is a valid one. */+export function scopedProgrammingState(value: unknown): ProgrammingModeState | null {+ return typeof value === 'string' && (SCOPED_STATES as readonly string[]).includes(value) ? value as ProgrammingModeState : null;+}+/*** Shared implementation contract for EXECUTE and AUTO modes. Tools are the* ONLY way work happens: narration about future work is the single most@@ -93,6 +106,17 @@ export class ProgrammingMode {this.projectContext = context;}+ /** The whole mode as a value, so one session's mode can be swapped in for a turn. */+ snapshot(): ProgrammingSnapshot {+ return { state: this.state, projectContext: this.projectContext, lastPlan: this.lastPlan };+ }++ restore(snapshot: ProgrammingSnapshot): void {+ this.state = snapshot.state;+ this.projectContext = snapshot.projectContext;+ this.lastPlan = snapshot.lastPlan;+ }+getProjectContext(): string | null {return this.projectContext;}diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex 663a4ba8..3046266f 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -32,6 +32,8 @@ export const API_FEATURES: readonly string[] = Object.freeze(['mcp', // /api/mcp/*'boards', // /api/boards/*'brain', // /api/brain/*+ 'code.session', // POST /api/chat/send { programming, cwd } — per-session coding+ 'chat.uploads', // attachments on messages + GET /api/chat/uploads/:month/:file]);export interface ApiContractInfo {diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex 0352df5c..d4d67db9 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -1,4 +1,5 @@import { Hono } from 'hono';+import { scopedProgrammingState } from '../../core/programming-mode.js';import { storeInlineAttachments, attachmentRefs, resolveUploadRef, uploadMime } from './uploads.js';import type { WebChannel } from '../../channels/web.js';import type { ProgrammingMode, ProgrammingModeState } from '../../core/programming-mode.js';@@ -169,6 +170,10 @@ chat.post('/api/chat/send', async (c) => {threadId?: string;/** Base64 files: photos and PDFs become real attachments for this turn. */attachments?: unknown;+ /** Session-scoped coding: 'auto' | 'plan' | 'execute' for this turn only. */+ programming?: unknown;+ /** Folder the coding turn works in (an existing directory). */+ cwd?: unknown;}>();const content = body.content?.trim() ?? '';const upload = storeInlineAttachments(body.attachments);@@ -193,7 +198,17 @@ chat.post('/api/chat/send', async (c) => {session ??= sessions.getOrCreateBound('web', 'web:default');// Models reject an empty text block, so a photo sent alone says what it is.const text = content || `(Attached: ${upload.attachments.map(a => a.name).join(', ')})`;- webChannel.emitMessageInThread(text, session.id, session.id, undefined, undefined, undefined, upload.attachments);+ const programming = scopedProgrammingState(body.programming);+ let codeCwd: string | undefined;+ if (programming && typeof body.cwd === 'string' && body.cwd.trim()) {+ const resolvedCwd = resolve(body.cwd.trim());+ if (!existsSync(resolvedCwd) || !statSync(resolvedCwd).isDirectory()) {+ for (const a of upload.attachments) rmSync(a.path, { force: true });+ return c.json({ error: `Not a folder: ${resolvedCwd}` }, 400);+ }+ codeCwd = resolvedCwd;+ }+ webChannel.emitMessageInThread(text, session.id, session.id, undefined, undefined, undefined, upload.attachments, programming ? { programming, cwd: codeCwd } : undefined);return c.json({sent: true,sessionId: session.id,diff --git a/src/web/api/uploads-serve.test.ts b/src/web/api/uploads-serve.test.tsindex de752870..ac36902e 100644--- a/src/web/api/uploads-serve.test.ts+++ b/src/web/api/uploads-serve.test.ts@@ -20,7 +20,7 @@ describe('stored uploads', () => {it('round-trips: stored file → ref → resolved path', () => {const upload = storeInlineAttachments([{ name: 'cat.png', data: PNG }], new Date('2026-10-26T00:00:00Z'));- expect(upload.ok).toBe(true);+ if (!upload.ok) throw new Error(upload.error);const refs = attachmentRefs(upload.attachments);expect(refs).toHaveLength(1);expect(refs[0].ref).toMatch(/^2026-10\/[0-9a-f-]{36}-cat\.png$/);@@ -50,6 +50,7 @@ describe('stored uploads', () => {it('serves the bytes with their real type, and 404s anything else', async () => {const { default: chatRoutes } = await import('./chat.js');const upload = storeInlineAttachments([{ name: 'cat.png', data: PNG }]);+ if (!upload.ok) throw new Error(upload.error);const [ref] = attachmentRefs(upload.attachments);const ok = await chatRoutes.request(`http://127.0.0.1:6174/api/chat/uploads/${ref.ref}`);expect(ok.status).toBe(200);