Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(chat): the agent-chat client and store know their surface

rubenluetke10-beep8edebc0b025b
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts
index f6fe79d650..8e49cfc892 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts
@@ -108,6 +108,20 @@ describe("agent-chat reduce", () => {
expect(turn.blocks[1]).toMatchObject({ kind: "tool", output: "hit", durationMs: 340 });
});
+ it("carries a turn run by the brain — the front page's Jarvis — untouched", () => {
+ // The typed front page is Jarvis on a keyboard: its turns are announced
+ // with runner "brain" instead of a CLI's or the API runner's name. The
+ // reducer keeps the word as given; nothing here decides what it means.
+ const tl = reduceEvents(EMPTY_TIMELINE, [
+ ev("user_message", { text: "what did I plan for today?" }),
+ ev("turn_started", { turn_id: "t8", provider: "jarvis", model: "", effort: "", runner: "brain" }),
+ ]);
+ const turn = tl.items[1] as TurnItem;
+ expect(turn.runner).toBe("brain");
+ expect(turn.provider).toBe("jarvis");
+ expect(runningTurn(tl)?.id).toBe("t8");
+ });
+
it("counts tokens live and keeps them when the finished turn brings no usage", () => {
let tl = reduceEvents(EMPTY_TIMELINE, [
ev("turn_started", { turn_id: "t7" }),
diff --git a/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx b/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx
index e8f69ae5ad..aea8e593b3 100644
--- a/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx
@@ -59,6 +59,7 @@ describe("RecentChats", () => {
effort: "high",
cwd: "C:\work",
permission_mode: "acceptEdits",
+ surface: "jarvis",
vendor_session: null,
created_ms: 500,
updated_ms: 900,
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index 2b7c1cd676..64c107503f 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -50,6 +50,14 @@ export interface AgentChatCatalog {
shell: string;
}
+/**
+ * Where a session lives: the front page's typed chat (`jarvis` — the same
+ * assistant as the microphone, on a keyboard) or a coding session listed by
+ * the Agentic IDE (`agent`). Each surface asks the backend for its own list
+ * and catalog, so the two never mix in a sidebar.
+ */
+export type AgentChatSurface = "jarvis" | "agent";
+
export interface AgentChatSession {
session_id: string;
title: string;
@@ -58,6 +66,8 @@ export interface AgentChatSession {
effort: string;
cwd: string;
permission_mode: string;
+ /** Absent on a backend older than the surface split; the store keeps such rows. */
+ surface?: AgentChatSurface;
vendor_session: string | null;
created_ms: number;
updated_ms: number;
@@ -109,8 +119,9 @@ async function json<T>(res: Response, what: string): Promise<T> {
return (await res.json()) as T;
}
-export async function fetchAgentChatCatalog(): Promise<AgentChatCatalog> {
- return json(await fetch("/api/agent-chat/catalog"), "catalog-failed");
+export async function fetchAgentChatCatalog(surface?: AgentChatSurface): Promise<AgentChatCatalog> {
+ const query = surface ? `?surface=${encodeURIComponent(surface)}` : "";
+ return json(await fetch(`/api/agent-chat/catalog${query}`), "catalog-failed");
}
export async function fetchAgentConnections(): Promise<AgentConnectionRow[]> {
@@ -144,9 +155,13 @@ export async function fetchProviderModels(providerId: string): Promise<LiveModel
.filter((m): m is LiveModel => m !== null);
}
-export async function fetchAgentChatSessions(limit = 200): Promise<AgentChatSession[]> {
+export async function fetchAgentChatSessions(
+ limit = 200,
+ surface?: AgentChatSurface,
+): Promise<AgentChatSession[]> {
+ const query = surface ? `&surface=${encodeURIComponent(surface)}` : "";
const data = await json<{ sessions: AgentChatSession[] }>(
- await fetch(`/api/agent-chat/sessions?limit=${limit}`),
+ await fetch(`/api/agent-chat/sessions?limit=${limit}${query}`),
"sessions-failed",
);
return data.sessions;
@@ -159,6 +174,7 @@ export interface CreateSessionInput {
cwd?: string | null;
permission_mode?: string;
title?: string;
+ surface?: AgentChatSurface;
}
export async function createAgentChatSession(input: CreateSessionInput): Promise<AgentChatSession> {
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.test.ts b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
new file mode 100644
index 0000000000..b718a5886b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
@@ -0,0 +1,135 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { AgentChatSession } from "@/lib/agentChatApi";
+import { createAgentChatStore, draftKey } from "@/store/agentChat";
+
+/**
+ * The store knows its surface: the front page's store speaks for the typed
+ * Jarvis chat (`jarvis`), an IDE's for its coding sessions (`agent`). Each
+ * asks the backend for its own list and catalog, stamps the surface on the
+ * sessions it creates, and keeps its draft under its own key.
+ */
+
+function session(id: string, surface?: AgentChatSession["surface"]): AgentChatSession {
+ return {
+ session_id: id,
+ title: id,
+ provider: "claude-api",
+ model: "",
+ effort: "high",
+ cwd: "C:\\work",
+ permission_mode: "ask",
+ ...(surface === undefined ? {} : { surface }),
+ vendor_session: null,
+ created_ms: 1,
+ updated_ms: 2,
+ message_count: 1,
+ preview: id,
+ };
+}
+
+interface Call {
+ url: string;
+ method: string;
+ body: Record<string, unknown> | null;
+}
+
+/** A fetch that answers every agent-chat route with something plausible and records what was asked. */
+function stubFetch(sessions: AgentChatSession[]): Call[] {
+ const calls: Call[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: string, init?: RequestInit) => {
+ const url = String(input);
+ const method = init?.method ?? "GET";
+ const body = typeof init?.body === "string" ? (JSON.parse(init.body) as Record<string, unknown>) : null;
+ calls.push({ url, method, body });
+ const reply = (data: unknown) => new Response(JSON.stringify(data), { status: 200 });
+ if (url.startsWith("/api/agent-chat/catalog")) return reply({ providers: [], default_cwd: "C:\\work", shell: "pwsh" });
+ if (url.startsWith("/api/jarvis-agent/status")) return reply({ mapping: [] });
+ if (url.startsWith("/api/agent-chat/sessions?")) return reply({ sessions });
+ if (url === "/api/agent-chat/sessions" && method === "POST") {
+ return reply({ ...session("new"), ...(body ?? {}) });
+ }
+ if (url.endsWith("/messages")) return reply({ turn_id: "t1" });
+ return new Response(null, { status: 404 });
+ }),
+ );
+ return calls;
+}
+
+/** jsdom's WebSocket would try to reach a real host; a silent stand-in is enough here. */
+class FakeSocket {
+ onopen: (() => void) | null = null;
+ onmessage: ((msg: { data: string }) => void) | null = null;
+ onclose: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ close() {}
+}
+
+describe("agent-chat store surfaces", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ vi.stubGlobal("WebSocket", FakeSocket);
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("names the front page's draft key as it always was, and gives the IDE its own", () => {
+ expect(draftKey("jarvis")).toBe("jarvis.agentChat.draft.v1");
+ expect(draftKey("agent")).toBe("jarvis.agentChat.draft.agent.v1");
+ });
+
+ it("creates a front-page session stamped with its surface", async () => {
+ const calls = stubFetch([]);
+ const store = createAgentChatStore("jarvis");
+ store.setState({
+ draft: { provider: "claude-api", model: "", effort: "high", permissionMode: "ask", buildMode: "ask", cwd: "C:\\work" },
+ });
+ await store.getState().send("hello");
+ const create = calls.find((c) => c.url === "/api/agent-chat/sessions" && c.method === "POST");
+ expect(create?.body).toMatchObject({ provider: "claude-api", permission_mode: "ask", surface: "jarvis" });
+ expect(store.getState().activeSessionId).toBe("new");
+ expect(store.getState().sessions[0]?.surface).toBe("jarvis");
+ });
+
+ it("asks the list for its own surface and drops rows of the other", async () => {
+ const calls = stubFetch([session("mine", "agent"), session("theirs", "jarvis")]);
+ const store = createAgentChatStore("agent");
+ await store.getState().loadSessions();
+ const list = calls.find((c) => c.url.startsWith("/api/agent-chat/sessions?"));
+ expect(list?.url).toContain("surface=agent");
+ expect(store.getState().sessions.map((s) => s.session_id)).toEqual(["mine"]);
+ });
+
+ it("keeps rows that name no surface — an older backend still lists its chats", async () => {
+ stubFetch([session("old"), session("front", "jarvis"), session("ide", "agent")]);
+ const store = createAgentChatStore("jarvis");
+ await store.getState().loadSessions();
+ expect(store.getState().sessions.map((s) => s.session_id)).toEqual(["old", "front"]);
+ });
+
+ it("asks the catalog for its surface", async () => {
+ const calls = stubFetch([]);
+ const store = createAgentChatStore("jarvis");
+ await store.getState().loadCatalog();
+ const catalog = calls.find((c) => c.url.startsWith("/api/agent-chat/catalog"));
+ expect(catalog?.url).toBe("/api/agent-chat/catalog?surface=jarvis");
+ });
+
+ it("keeps one draft per surface, under separate keys", async () => {
+ stubFetch([]);
+ const front = createAgentChatStore("jarvis");
+ const ide = createAgentChatStore("agent");
+ await front.getState().setDraft({ cwd: "C:\\front" });
+ await ide.getState().setDraft({ cwd: "C:\\ide" });
+ expect(front.getState().draft.cwd).toBe("C:\\front");
+ expect(ide.getState().draft.cwd).toBe("C:\\ide");
+ expect(JSON.parse(window.localStorage.getItem(draftKey("jarvis")) ?? "{}")).toMatchObject({ cwd: "C:\\front" });
+ expect(JSON.parse(window.localStorage.getItem(draftKey("agent")) ?? "{}")).toMatchObject({ cwd: "C:\\ide" });
+ // A fresh store of each surface reads back its own, not the other's.
+ expect(createAgentChatStore("jarvis").getState().draft.cwd).toBe("C:\\front");
+ expect(createAgentChatStore("agent").getState().draft.cwd).toBe("C:\\ide");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.ts
index 7d322728bf..06fccace86 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -16,6 +16,7 @@ import {
type AgentChatEvent,
type AgentChatProvider,
type AgentChatSession,
+ type AgentChatSurface,
type AgentConnectionRow,
type ApprovalDecision,
type CuratedModel,
@@ -41,7 +42,14 @@ import { EMPTY_TIMELINE, reduceEvent, reduceEvents, type Timeline } from "@/comp
* otherwise. The one marked active on the Agents tab is the draft's default.
*/
-const DRAFT_KEY = "jarvis.agentChat.draft.v1";
+/**
+ * Where the composer's draft survives a reload. The front page keeps the key
+ * it has always had, so picks made before the surface split still load; an
+ * IDE store gets its own so the two never overwrite each other's picks.
+ */
+export function draftKey(surface: AgentChatSurface): string {
+ return surface === "jarvis" ? "jarvis.agentChat.draft.v1" : `jarvis.agentChat.draft.${surface}.v1`;
+}
const RECONNECT_MS = 1500;
/** How many sessions the list holds — the "All chats" archive shows them all. */
const SESSION_LIST_LIMIT = 500;
@@ -63,7 +71,9 @@ export interface ProviderOption extends AgentChatProvider {
active: boolean;
}
-interface AgentChatStore {
+export interface AgentChatStore {
+ /** Which list and catalog this store speaks for; fixed at creation. */
+ readonly surface: AgentChatSurface;
catalog: AgentChatCatalog | null;
connections: AgentConnectionRow[];
catalogError: string | null;
@@ -103,7 +113,7 @@ interface AgentChatStore {
disconnect: () => void;
}
-function readDraft(): ComposerDraft {
+function readDraft(key: string): ComposerDraft {
const empty: ComposerDraft = {
provider: "",
model: "",
@@ -113,7 +123,7 @@ function readDraft(): ComposerDraft {
cwd: "",
};
try {
- const raw = window.localStorage.getItem(DRAFT_KEY);
+ const raw = window.localStorage.getItem(key);
if (!raw) return empty;
const parsed = JSON.parse(raw) as Partial<ComposerDraft>;
return { ...empty, ...parsed };
@@ -122,9 +132,9 @@ function readDraft(): ComposerDraft {
}
}
-function writeDraft(draft: ComposerDraft): void {
+function writeDraft(key: string, draft: ComposerDraft): void {
try {
- window.localStorage.setItem(DRAFT_KEY, JSON.stringify(draft));
+ window.localStorage.setItem(key, JSON.stringify(draft));
} catch {
/* storage blocked — the draft just does not survive a reload */
}
@@ -155,365 +165,384 @@ function draftFromSession(session: AgentChatSession, prev: ComposerDraft): Compo
};
}
-let socket: WebSocket | null = null;
-let socketSession: string | null = null;
-let reconnectTimer: number | null = null;
+/**
+ * One store per surface. Each holds its own socket, its own draft key and
+ * its own session list, so the front page's chat and an IDE's coding
+ * sessions can be open at the same time without sharing a connection.
+ */
+export function createAgentChatStore(surface: AgentChatSurface) {
+ const DRAFT_KEY = draftKey(surface);
-function closeSocket(): void {
- if (reconnectTimer !== null) {
- window.clearTimeout(reconnectTimer);
- reconnectTimer = null;
- }
- const s = socket;
- socket = null;
- socketSession = null;
- if (s) {
- s.onclose = null;
- s.onmessage = null;
- s.onerror = null;
- s.onopen = null;
- try {
- s.close();
- } catch {
- /* already closed */
- }
- }
-}
+ let socket: WebSocket | null = null;
+ let socketSession: string | null = null;
+ let reconnectTimer: number | null = null;
-export const useAgentChatStore = create<AgentChatStore>((set, get) => {
- function connect(sessionId: string, afterSeq: number): void {
- if (typeof WebSocket === "undefined") return;
- closeSocket();
- socketSession = sessionId;
- set({ socketState: "connecting" });
- const ws = new WebSocket(agentChatSocketUrl(sessionId, afterSeq));
- socket = ws;
- ws.onopen = () => {
- if (socket === ws) set({ socketState: "open" });
- };
- ws.onmessage = (msg) => {
- if (socket !== ws) return;
- let frame: { type?: string; session?: AgentChatSession; events?: AgentChatEvent[]; event?: AgentChatEvent };
+ function closeSocket(): void {
+ if (reconnectTimer !== null) {
+ window.clearTimeout(reconnectTimer);
+ reconnectTimer = null;
+ }
+ const s = socket;
+ socket = null;
+ socketSession = null;
+ if (s) {
+ s.onclose = null;
+ s.onmessage = null;
+ s.onerror = null;
+ s.onopen = null;
try {
- frame = JSON.parse(String(msg.data));
+ s.close();
} catch {
- return;
- }
- if (frame.type === "snapshot" && frame.session) {
- const prev = get();
- // A snapshot after a reconnect only carries events past `after`;
- // fold them onto what is already there, else start fresh.
- const base = afterSeq > 0 && prev.activeSessionId === sessionId ? prev.timeline : EMPTY_TIMELINE;
- const tl = reduceEvents(base, frame.events ?? []);
- set({
- activeSession: frame.session,
- timeline: { ...tl, sessionPatch: null },
- draft: draftFromSession(frame.session, prev.draft),
- });
- writeDraft(get().draft);
- return;
+ /* already closed */
}
- if (frame.type === "event" && frame.event) get().ingest(frame.event);
- };
- ws.onclose = () => {
- if (socket !== ws) return;
- socket = null;
- set({ socketState: "closed" });
- // Reconnect while this session is still the open one; the backend
- // replays what was missed from the last seq.
- reconnectTimer = window.setTimeout(() => {
- reconnectTimer = null;
- const st = get();
- if (st.activeSessionId === sessionId && socketSession === sessionId) {
- connect(sessionId, st.timeline.lastSeq);
- }
- }, RECONNECT_MS);
- };
- ws.onerror = () => {
- /* onclose follows and schedules the reconnect */
- };
+ }
}
- return {
- catalog: null,
- connections: [],
- catalogError: null,
- backendOutdated: false,
- liveModels: {},
- sessions: [],
- activeSessionId: null,
- activeSession: null,
- timeline: EMPTY_TIMELINE,
- socketState: "idle",
- draft: readDraft(),
- busy: false,
- lastError: null,
-
- loadCatalog: async () => {
- try {
- const [raw, connections] = await Promise.all([
- fetchAgentChatCatalog(),
- fetchAgentConnections().catch(() => [] as AgentConnectionRow[]),
- ]);
- // A backend older than this bundle (the app not yet restarted after
- // an update) may lack the newer arrays; an empty ladder is honest,
- // a crash is not — and the composer tells the person to restart.
- // `permission_modes` is the tell: every row of the current route
- // carries the array (possibly empty); only the older route omits it.
- const providersRaw = raw.providers ?? [];
- const backendOutdated =
- providersRaw.length > 0 && providersRaw.some((p) => !Array.isArray(p.permission_modes));
- const catalog: AgentChatCatalog = {
- ...raw,
- providers: providersRaw.map((p) => ({
- ...p,
- curated_models: Array.isArray(p.curated_models) ? p.curated_models : [],
- effort_levels: Array.isArray(p.effort_levels) ? p.effort_levels : [],
- permission_modes: Array.isArray(p.permission_modes) ? p.permission_modes : [],
- default_permission_mode: p.default_permission_mode ?? "",
- default_effort: p.default_effort ?? "",
- default_model: p.default_model ?? "",
- })),
- };
- set({ catalog, connections, catalogError: null, backendOutdated });
- // Settle the draft: an empty or unknown provider becomes the active
- // sub-agent (else the first connected one); blank picks take the
- // provider's defaults.
- const st = get();
- const options = st.providerOptions();
- let draft = st.draft;
- const known = options.find((o) => o.id === draft.provider);
- if (!known) {
- const pick = options.find((o) => o.active && o.connected) ?? options.find((o) => o.connected) ?? options[0];
- if (pick) {
+ return create<AgentChatStore>((set, get) => {
+ function connect(sessionId: string, afterSeq: number): void {
+ if (typeof WebSocket === "undefined") return;
+ closeSocket();
+ socketSession = sessionId;
+ set({ socketState: "connecting" });
+ const ws = new WebSocket(agentChatSocketUrl(sessionId, afterSeq));
+ socket = ws;
+ ws.onopen = () => {
+ if (socket === ws) set({ socketState: "open" });
+ };
+ ws.onmessage = (msg) => {
+ if (socket !== ws) return;
+ let frame: { type?: string; session?: AgentChatSession; events?: AgentChatEvent[]; event?: AgentChatEvent };
+ try {
+ frame = JSON.parse(String(msg.data));
+ } catch {
+ return;
+ }
+ if (frame.type === "snapshot" && frame.session) {
+ const prev = get();
+ // A snapshot after a reconnect only carries events past `after`;
+ // fold them onto what is already there, else start fresh.
+ const base = afterSeq > 0 && prev.activeSessionId === sessionId ? prev.timeline : EMPTY_TIMELINE;
+ const tl = reduceEvents(base, frame.events ?? []);
+ set({
+ activeSession: frame.session,
+ timeline: { ...tl, sessionPatch: null },
+ draft: draftFromSession(frame.session, prev.draft),
+ });
+ writeDraft(DRAFT_KEY, get().draft);
+ return;
+ }
+ if (frame.type === "event" && frame.event) get().ingest(frame.event);
+ };
+ ws.onclose = () => {
+ if (socket !== ws) return;
+ socket = null;
+ set({ socketState: "closed" });
+ // Reconnect while this session is still the open one; the backend
+ // replays what was missed from the last seq.
+ reconnectTimer = window.setTimeout(() => {
+ reconnectTimer = null;
+ const st = get();
+ if (st.activeSessionId === sessionId && socketSession === sessionId) {
+ connect(sessionId, st.timeline.lastSeq);
+ }
+ }, RECONNECT_MS);
+ };
+ ws.onerror = () => {
+ /* onclose follows and schedules the reconnect */
+ };
+ }
+
+ return {
+ surface,
+ catalog: null,
+ connections: [],
+ catalogError: null,
+ backendOutdated: false,
+ liveModels: {},
+ sessions: [],
+ activeSessionId: null,
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ socketState: "idle",
+ draft: readDraft(DRAFT_KEY),
+ busy: false,
+ lastError: null,
+
+ loadCatalog: async () => {
+ try {
+ const [raw, connections] = await Promise.all([
+ fetchAgentChatCatalog(surface),
+ fetchAgentConnections().catch(() => [] as AgentConnectionRow[]),
+ ]);
+ // A backend older than this bundle (the app not yet restarted after
+ // an update) may lack the newer arrays; an empty ladder is honest,
+ // a crash is not — and the composer tells the person to restart.
+ // `permission_modes` is the tell: every row of the current route
+ // carries the array (possibly empty); only the older route omits it.
+ const providersRaw = raw.providers ?? [];
+ const backendOutdated =
+ providersRaw.length > 0 && providersRaw.some((p) => !Array.isArray(p.permission_modes));
+ const catalog: AgentChatCatalog = {
+ ...raw,
+ providers: providersRaw.map((p) => ({
+ ...p,
+ curated_models: Array.isArray(p.curated_models) ? p.curated_models : [],
+ effort_levels: Array.isArray(p.effort_levels) ? p.effort_levels : [],
+ permission_modes: Array.isArray(p.permission_modes) ? p.permission_modes : [],
+ default_permission_mode: p.default_permission_mode ?? "",
+ default_effort: p.default_effort ?? "",
+ default_model: p.default_model ?? "",
+ })),
+ };
+ set({ catalog, connections, catalogError: null, backendOutdated });
+ // Settle the draft: an empty or unknown provider becomes the active
+ // sub-agent (else the first connected one); blank picks take the
+ // provider's defaults.
+ const st = get();
+ const options = st.providerOptions();
+ let draft = st.draft;
+ const known = options.find((o) => o.id === draft.provider);
+ if (!known) {
+ const pick = options.find((o) => o.active && o.connected) ?? options.find((o) => o.connected) ?? options[0];
+ if (pick) {
+ draft = {
+ provider: pick.id,
+ model: pick.default_model,
+ effort: pick.default_effort,
+ permissionMode: pick.default_permission_mode,
+ buildMode: pick.default_permission_mode,
+ cwd: draft.cwd || catalog.default_cwd,
+ };
+ }
+ } else {
draft = {
- provider: pick.id,
- model: pick.default_model,
- effort: pick.default_effort,
- permissionMode: pick.default_permission_mode,
- buildMode: pick.default_permission_mode,
+ ...draft,
+ effort: draft.effort || known.default_effort,
+ permissionMode: draft.permissionMode || known.default_permission_mode,
+ buildMode: draft.buildMode || known.default_permission_mode,
cwd: draft.cwd || catalog.default_cwd,
};
}
- } else {
- draft = {
- ...draft,
- effort: draft.effort || known.default_effort,
- permissionMode: draft.permissionMode || known.default_permission_mode,
- buildMode: draft.buildMode || known.default_permission_mode,
- cwd: draft.cwd || catalog.default_cwd,
- };
+ if (draft !== st.draft) {
+ set({ draft });
+ writeDraft(DRAFT_KEY, draft);
+ }
+ if (draft.provider) void get().loadModels(draft.provider);
+ } catch (err) {
+ set({ catalogError: errorText(err) });
}
- if (draft !== st.draft) {
- set({ draft });
- writeDraft(draft);
+ },
+
+ loadSessions: async () => {
+ try {
+ const rows = await fetchAgentChatSessions(SESSION_LIST_LIMIT, surface);
+ // The backend filters by surface; a row that names another surface
+ // anyway is dropped here too. A row with no surface at all comes
+ // from a backend older than the split — those are kept, so an
+ // update never makes a person's chats vanish until the restart.
+ const sessions = rows.filter((row) => row.surface === undefined || row.surface === surface);
+ set({ sessions });
+ } catch {
+ /* offline / headless — keep the list as-is */
}
- if (draft.provider) void get().loadModels(draft.provider);
- } catch (err) {
- set({ catalogError: errorText(err) });
- }
- },
+ },
- loadSessions: async () => {
- try {
- const sessions = await fetchAgentChatSessions(SESSION_LIST_LIMIT);
- set({ sessions });
- } catch {
- /* offline / headless — keep the list as-is */
- }
- },
+ loadModels: async (providerId) => {
+ const provider = get().catalog?.providers.find((p) => p.id === providerId);
+ if (!provider || provider.models_source !== "live") return;
+ if (get().liveModels[providerId]) return;
+ try {
+ const models = await fetchProviderModels(providerId);
+ const rows: CuratedModel[] = models.map((m) => ({ id: m.id, label: m.label ?? m.name ?? m.id }));
+ set((s) => ({ liveModels: { ...s.liveModels, [providerId]: rows } }));
+ } catch {
+ /* the curated list stays */
+ }
+ },
- loadModels: async (providerId) => {
- const provider = get().catalog?.providers.find((p) => p.id === providerId);
- if (!provider || provider.models_source !== "live") return;
- if (get().liveModels[providerId]) return;
- try {
- const models = await fetchProviderModels(providerId);
- const rows: CuratedModel[] = models.map((m) => ({ id: m.id, label: m.label ?? m.name ?? m.id }));
- set((s) => ({ liveModels: { ...s.liveModels, [providerId]: rows } }));
- } catch {
- /* the curated list stays */
- }
- },
-
- providerOptions: () => {
- const { catalog, connections } = get();
- if (!catalog) return [];
- return catalog.providers.map((p) => {
- const row = connectionFor(p, connections);
- const credentialed = p.keyless || Boolean(row?.key_set);
- const installed = p.cli_installed === null ? true : p.cli_installed;
- return {
- ...p,
- connected: credentialed && installed,
- active: Boolean(row?.is_active_brain),
- };
- });
- },
-
- providerById: (id) => get().providerOptions().find((p) => p.id === id) ?? null,
-
- setDraft: async (patch) => {
- const st = get();
- let draft: ComposerDraft = { ...st.draft, ...patch };
- // A provider change re-seats model / effort / permission on the new
- // provider's defaults unless the caller set them explicitly.
- if (patch.provider && patch.provider !== st.draft.provider) {
- const p = st.providerById(patch.provider);
- if (p) {
- draft = {
- ...draft,
- model: patch.model ?? p.default_model,
- effort: patch.effort ?? p.default_effort,
- permissionMode: patch.permissionMode ?? p.default_permission_mode,
- buildMode: patch.permissionMode ?? p.default_permission_mode,
+ providerOptions: () => {
+ const { catalog, connections } = get();
+ if (!catalog) return [];
+ return catalog.providers.map((p) => {
+ const row = connectionFor(p, connections);
+ const credentialed = p.keyless || Boolean(row?.key_set);
+ const installed = p.cli_installed === null ? true : p.cli_installed;
+ return {
+ ...p,
+ connected: credentialed && installed,
+ active: Boolean(row?.is_active_brain),
};
+ });
+ },
+
+ providerById: (id) => get().providerOptions().find((p) => p.id === id) ?? null,
+
+ setDraft: async (patch) => {
+ const st = get();
+ let draft: ComposerDraft = { ...st.draft, ...patch };
+ // A provider change re-seats model / effort / permission on the new
+ // provider's defaults unless the caller set them explicitly.
+ if (patch.provider && patch.provider !== st.draft.provider) {
+ const p = st.providerById(patch.provider);
+ if (p) {
+ draft = {
+ ...draft,
+ model: patch.model ?? p.default_model,
+ effort: patch.effort ?? p.default_effort,
+ permissionMode: patch.permissionMode ?? p.default_permission_mode,
+ buildMode: patch.permissionMode ?? p.default_permission_mode,
+ };
+ }
+ void get().loadModels(patch.provider);
+ } else if (patch.permissionMode && patch.permissionMode !== "plan") {
+ draft = { ...draft, buildMode: patch.permissionMode };
}
- void get().loadModels(patch.provider);
- } else if (patch.permissionMode && patch.permissionMode !== "plan") {
- draft = { ...draft, buildMode: patch.permissionMode };
- }
- set({ draft });
- writeDraft(draft);
- // With a session open, the pick applies to it right away.
- const sid = st.activeSessionId;
- if (sid) {
- const body: PatchSessionInput = {};
- if (patch.provider !== undefined) body.provider = draft.provider;
- if (patch.provider !== undefined || patch.model !== undefined) body.model = draft.model;
- if (patch.provider !== undefined || patch.effort !== undefined) body.effort = draft.effort;
- if (patch.provider !== undefined || patch.permissionMode !== undefined) {
- body.permission_mode = draft.permissionMode;
+ set({ draft });
+ writeDraft(DRAFT_KEY, draft);
+ // With a session open, the pick applies to it right away.
+ const sid = st.activeSessionId;
+ if (sid) {
+ const body: PatchSessionInput = {};
+ if (patch.provider !== undefined) body.provider = draft.provider;
+ if (patch.provider !== undefined || patch.model !== undefined) body.model = draft.model;
+ if (patch.provider !== undefined || patch.effort !== undefined) body.effort = draft.effort;
+ if (patch.provider !== undefined || patch.permissionMode !== undefined) {
+ body.permission_mode = draft.permissionMode;
+ }
+ if (patch.cwd !== undefined) body.cwd = draft.cwd;
+ try {
+ const session = await patchAgentChatSession(sid, body);
+ set((s) => ({
+ activeSession: s.activeSessionId === sid ? session : s.activeSession,
+ sessions: s.sessions.map((x) => (x.session_id === sid ? { ...x, ...session } : x)),
+ }));
+ } catch (err) {
+ set({ lastError: errorText(err) });
+ }
+ }
+ },
+
+ setPlan: async (on) => {
+ const st = get();
+ if (on) {
+ await st.setDraft({ permissionMode: "plan" });
+ } else {
+ const p = st.providerById(st.draft.provider);
+ const back = st.draft.buildMode && st.draft.buildMode !== "plan" ? st.draft.buildMode : p?.default_permission_mode ?? "";
+ await st.setDraft({ permissionMode: back });
}
- if (patch.cwd !== undefined) body.cwd = draft.cwd;
+ },
+
+ newChat: () => {
+ closeSocket();
+ set({
+ activeSessionId: null,
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ socketState: "idle",
+ lastError: null,
+ });
+ },
+
+ openSession: (sessionId) => {
+ if (get().activeSessionId === sessionId && socket) return;
+ set({
+ activeSessionId: sessionId,
+ activeSession: get().sessions.find((s) => s.session_id === sessionId) ?? null,
+ timeline: EMPTY_TIMELINE,
+ lastError: null,
+ });
+ connect(sessionId, 0);
+ },
+
+ removeSession: async (sessionId) => {
try {
- const session = await patchAgentChatSession(sid, body);
- set((s) => ({
- activeSession: s.activeSessionId === sid ? session : s.activeSession,
- sessions: s.sessions.map((x) => (x.session_id === sid ? { ...x, ...session } : x)),
- }));
+ await deleteAgentChatSession(sessionId);
} catch (err) {
set({ lastError: errorText(err) });
}
- }
- },
-
- setPlan: async (on) => {
- const st = get();
- if (on) {
- await st.setDraft({ permissionMode: "plan" });
- } else {
- const p = st.providerById(st.draft.provider);
- const back = st.draft.buildMode && st.draft.buildMode !== "plan" ? st.draft.buildMode : p?.default_permission_mode ?? "";
- await st.setDraft({ permissionMode: back });
- }
- },
+ if (get().activeSessionId === sessionId) get().newChat();
+ set((s) => ({ sessions: s.sessions.filter((x) => x.session_id !== sessionId) }));
+ void get().loadSessions();
+ },
- newChat: () => {
- closeSocket();
- set({
- activeSessionId: null,
- activeSession: null,
- timeline: EMPTY_TIMELINE,
- socketState: "idle",
- lastError: null,
- });
- },
-
- openSession: (sessionId) => {
- if (get().activeSessionId === sessionId && socket) return;
- set({
- activeSessionId: sessionId,
- activeSession: get().sessions.find((s) => s.session_id === sessionId) ?? null,
- timeline: EMPTY_TIMELINE,
- lastError: null,
- });
- connect(sessionId, 0);
- },
-
- removeSession: async (sessionId) => {
- try {
- await deleteAgentChatSession(sessionId);
- } catch (err) {
- set({ lastError: errorText(err) });
- }
- if (get().activeSessionId === sessionId) get().newChat();
- set((s) => ({ sessions: s.sessions.filter((x) => x.session_id !== sessionId) }));
- void get().loadSessions();
- },
-
- send: async (text) => {
- const content = text.trim();
- if (!content) return;
- const st = get();
- set({ busy: true, lastError: null });
- try {
- let sid = st.activeSessionId;
- if (!sid) {
- const d = st.draft;
- const session = await createAgentChatSession({
- provider: d.provider,
- model: d.model,
- effort: d.effort,
- cwd: d.cwd || null,
- permission_mode: d.permissionMode,
- });
- sid = session.session_id;
- set({
- activeSessionId: sid,
- activeSession: session,
- timeline: EMPTY_TIMELINE,
- sessions: [session, ...get().sessions],
- });
- connect(sid, 0);
+ send: async (text) => {
+ const content = text.trim();
+ if (!content) return;
+ const st = get();
+ set({ busy: true, lastError: null });
+ try {
+ let sid = st.activeSessionId;
+ if (!sid) {
+ const d = st.draft;
+ const session = await createAgentChatSession({
+ provider: d.provider,
+ model: d.model,
+ effort: d.effort,
+ cwd: d.cwd || null,
+ permission_mode: d.permissionMode,
+ surface,
+ });
+ sid = session.session_id;
+ set({
+ activeSessionId: sid,
+ activeSession: session,
+ timeline: EMPTY_TIMELINE,
+ sessions: [session, ...get().sessions],
+ });
+ connect(sid, 0);
+ }
+ await sendAgentChatMessage(sid, content);
+ void get().loadSessions();
+ } catch (err) {
+ set({ lastError: errorText(err) });
+ } finally {
+ set({ busy: false });
}
- await sendAgentChatMessage(sid, content);
- void get().loadSessions();
- } catch (err) {
- set({ lastError: errorText(err) });
- } finally {
- set({ busy: false });
- }
- },
+ },
- cancel: async () => {
- const sid = get().activeSessionId;
- if (!sid) return;
- try {
- await cancelAgentChatTurn(sid);
- } catch (err) {
- set({ lastError: errorText(err) });
- }
- },
+ cancel: async () => {
+ const sid = get().activeSessionId;
+ if (!sid) return;
+ try {
+ await cancelAgentChatTurn(sid);
+ } catch (err) {
+ set({ lastError: errorText(err) });
+ }
+ },
- decide: async (approvalId, decision) => {
- const sid = get().activeSessionId;
- if (!sid) return;
- try {
- await resolveAgentChatApproval(sid, approvalId, decision);
- } catch (err) {
- set({ lastError: errorText(err) });
- }
- },
-
- ingest: (event) => {
- const st = get();
- const tl = reduceEvent(st.timeline, event);
- if (tl === st.timeline) return;
- const patch: Partial<AgentChatStore> = { timeline: tl };
- if (tl.sessionPatch && st.activeSession) {
- const session = { ...st.activeSession, ...tl.sessionPatch } as AgentChatSession;
- patch.activeSession = session;
- patch.draft = draftFromSession(session, st.draft);
- writeDraft(patch.draft);
- }
- set(patch);
- if (event.kind === "turn_finished" || event.kind === "user_message") void st.loadSessions();
- },
+ decide: async (approvalId, decision) => {
+ const sid = get().activeSessionId;
+ if (!sid) return;
+ try {
+ await resolveAgentChatApproval(sid, approvalId, decision);
+ } catch (err) {
+ set({ lastError: errorText(err) });
+ }
+ },
- disconnect: () => {
- closeSocket();
- set({ socketState: "idle" });
- },
- };
-});
+ ingest: (event) => {
+ const st = get();
+ const tl = reduceEvent(st.timeline, event);
+ if (tl === st.timeline) return;
+ const patch: Partial<AgentChatStore> = { timeline: tl };
+ if (tl.sessionPatch && st.activeSession) {
+ const session = { ...st.activeSession, ...tl.sessionPatch } as AgentChatSession;
+ patch.activeSession = session;
+ patch.draft = draftFromSession(session, st.draft);
+ writeDraft(DRAFT_KEY, patch.draft);
+ }
+ set(patch);
+ if (event.kind === "turn_finished" || event.kind === "user_message") void st.loadSessions();
+ },
+
+ disconnect: () => {
+ closeSocket();
+ set({ socketState: "idle" });
+ },
+ };
+ });
+}
+
+/** The front page's store — every existing call site reads this one. */
+export const useAgentChatStore = createAgentChatStore("jarvis");