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.

fix(society): switch agent chats without showing the previous transcript

rubenluetke10-beep29bf0bb69bd9
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
index 369a504d3b..a1be6764dd 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
@@ -87,7 +87,7 @@ export function AgentCardOverlay({
aria-label={t("society.card.chat")}
data-testid="agent-card-chat"
>
- <AgentChatPanel agent={agent} roster={roster} />
+ <AgentChatPanel key={agent.agentId} agent={agent} roster={roster} />
</section>
<OptionsRail agent={agent} onRetired={onClose} sample={sample} />
</div>
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx
new file mode 100644
index 0000000000..e8821f0197
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx
@@ -0,0 +1,135 @@
+import { act, cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+import { EMPTY_TIMELINE, type Timeline, type UserItem } from "@/components/agentchat/reduce";
+import type { SocietyAgent } from "../data";
+import {
+ AgentChatPanel,
+ itemsForOpenSession,
+ useSocietyChatStore,
+} from "./AgentChatPanel";
+
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));
+vi.mock("./AgentModelPicker", () => ({ AgentModelPicker: () => null }));
+vi.mock("../data", async (original) => ({
+ ...(await original<typeof import("../data")>()),
+ useSocietyCapabilities: () => ({ isLoading: false, data: [] }),
+}));
+vi.mock("@/components/agentchat/useComposerDictation", () => ({
+ useComposerDictation: () => ({ dictating: false, stop() {}, toggle() {} }),
+}));
+vi.mock("@/components/agentchat/DictationStatus", () => ({ DictationStatus: () => null }));
+vi.mock("@/components/agentchat/useChatAttachments", () => ({
+ useChatAttachments: () => ({
+ attachments: [],
+ analyzing: 0,
+ dragging: false,
+ dragHandlers: {},
+ clear() {},
+ remove() {},
+ attachFiles() {},
+ }),
+}));
+
+class FakeSocket {
+ onopen: (() => void) | null = null;
+ onmessage: ((msg: { data: string }) => void) | null = null;
+ onclose: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ close() {}
+}
+
+function agent(over: Partial<SocietyAgent> & Pick<SocietyAgent, "agentId" | "name">): SocietyAgent {
+ return {
+ title: "",
+ description: "",
+ tier: "specialist",
+ provider: "openai",
+ providerLabel: "OpenAI",
+ model: "gpt",
+ effort: "medium",
+ figure: null,
+ palette: { primary: "#000", secondary: "#000", accent: "#000" },
+ grantMode: "all",
+ toolGrants: [],
+ focus: [],
+ denies: [],
+ approvalRules: { requireApproval: [], alwaysAllow: [] },
+ permissionCeiling: "ask",
+ dailyBudgetUsd: 0,
+ checkpoint: "idle",
+ state: "idle",
+ lifecycle: "active",
+ createdMs: 0,
+ maxConcurrentRuns: 1,
+ workspaceDir: "",
+ wikiNamespace: "",
+ chatSessionId: `society:${over.agentId}`,
+ routines: [],
+ stats: { runs: 0, totalCostUsd: 0, spentTodayUsd: 0, lastActiveMs: null },
+ ...over,
+ };
+}
+
+function timelineWith(text: string): Timeline {
+ const item: UserItem = { type: "user", id: text, tsMs: 1, text, attachments: [] };
+ return { ...EMPTY_TIMELINE, items: [item], lastSeq: 1 };
+}
+
+const visual = agent({ agentId: "visual-qa", name: "Visual QA" });
+const gmail = agent({ agentId: "gmail-agent", name: "Gmail Agent" });
+
+beforeEach(() => {
+ Element.prototype.scrollIntoView = vi.fn();
+ vi.stubGlobal("WebSocket", FakeSocket);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response(JSON.stringify({ providers: [], sessions: [], mapping: [] }), { status: 200 })),
+ );
+ useSocietyChatStore.getState().disconnect();
+ useSocietyChatStore.setState({
+ activeSessionId: null,
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ busy: false,
+ lastError: null,
+ sessions: [],
+ });
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+it("hides another session's items until that session is the open one", () => {
+ const visualItems = timelineWith("visual-qa-flowchart").items;
+ expect(itemsForOpenSession("society:gmail-agent", "society:visual-qa", visualItems)).toEqual([]);
+ expect(itemsForOpenSession("society:gmail-agent", "society:gmail-agent", visualItems)).toEqual(visualItems);
+ expect(itemsForOpenSession(null, "society:visual-qa", visualItems)).toEqual([]);
+});
+
+it("does not paint the previous specialist's transcript after a click onto another agent", () => {
+ useSocietyChatStore.setState({
+ activeSessionId: visual.chatSessionId,
+ timeline: timelineWith("UNIQUE_VISUAL_QA_FLOWCHART"),
+ });
+ render(<AgentChatPanel agent={gmail} roster={[visual, gmail]} />);
+ expect(screen.queryByText("UNIQUE_VISUAL_QA_FLOWCHART")).toBeNull();
+ expect(screen.getByTestId("society-chat").getAttribute("data-session-id")).toBe(gmail.chatSessionId);
+ expect(screen.getByTestId("society-chat").getAttribute("data-session-ready")).toBe("true");
+});
+
+it("shows the previous specialist's own chat again the moment you switch back", () => {
+ useSocietyChatStore.setState({
+ activeSessionId: visual.chatSessionId,
+ timeline: timelineWith("UNIQUE_VISUAL_QA_FLOWCHART"),
+ });
+ const view = render(<AgentChatPanel agent={gmail} roster={[visual, gmail]} />);
+ act(() => {
+ useSocietyChatStore.setState({ timeline: timelineWith("UNIQUE_GMAIL_INBOX") });
+ });
+ view.rerender(<AgentChatPanel agent={visual} roster={[visual, gmail]} />);
+ expect(screen.queryByText("UNIQUE_GMAIL_INBOX")).toBeNull();
+ expect(screen.getByText("UNIQUE_VISUAL_QA_FLOWCHART")).toBeTruthy();
+ expect(screen.getByTestId("society-chat").getAttribute("data-session-id")).toBe(visual.chatSessionId);
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
index d5a52932b9..cbd6090ca9 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
@@ -93,7 +93,21 @@ export interface AgentChatPanelProps {
* The brain is the roster's choice, so the column shows it instead of the
* front page's pickers.
*/
-const useSocietyChatStore = createAgentChatStore("society");
+export const useSocietyChatStore = createAgentChatStore("society");
+
+/**
+ * The transcript a specialist column may paint. One store serves every
+ * specialist, so the chrome (name, rail, composer) can already show the
+ * agent you clicked while the socket is still on the previous session —
+ * those items must not appear under the new name.
+ */
+export function itemsForOpenSession(
+ sessionId: string | null,
+ activeSessionId: string | null,
+ items: TimelineItem[],
+): TimelineItem[] {
+ return sessionId !== null && sessionId === activeSessionId ? items : [];
+}
export function AgentChatPanel({ agent, roster }: AgentChatPanelProps) {
if (agent.tier === "lead") {
@@ -140,53 +154,70 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {
const decide = useAgentChat((s) => s.decide);
const [bindError, setBindError] = useState<string | null>(null);
const sessionId = agent.chatSessionId;
+ const sessionReady = Boolean(sessionId) && activeSessionId === sessionId;
+ const visibleItems = itemsForOpenSession(sessionId, activeSessionId, items);
- // Bind first (idempotent, no spend), then open: the socket needs the row to exist.
- useEffect(() => {
+ // Open the agent's own session before the browser paints. Waiting on bind /
+ // catalog / sessions left the previous specialist's transcript on screen
+ // under the new name.
+ useLayoutEffect(() => {
if (!sessionId) return;
+ openSession(sessionId);
+ }, [sessionId, openSession]);
+
+ useEffect(() => {
+ void loadCatalog();
+ void loadSessions();
+ }, [loadCatalog, loadSessions]);
+
+ // Bind is idempotent and the session id is already on the roster row; a
+ // failure must not replace a chat that is already open.
+ useEffect(() => {
let alive = true;
setBindError(null);
- void (async () => {
- try {
- await bindAgentChat(agent.agentId);
- await loadCatalog();
- await loadSessions();
- if (alive) openSession(sessionId);
- } catch (err) {
- if (alive) setBindError(err instanceof Error ? err.message : String(err));
- }
- })();
+ void bindAgentChat(agent.agentId).catch((err) => {
+ if (alive) setBindError(err instanceof Error ? err.message : String(err));
+ });
return () => {
alive = false;
};
- }, [agent.agentId, sessionId, loadCatalog, loadSessions, openSession]);
+ }, [agent.agentId]);
const mentionable = useMemo(
() => roster.filter((a) => a.agentId !== agent.agentId && a.tier !== "lead"),
[roster, agent.agentId],
);
- if (bindError) return <NotBoundYet detail={`${t("society.card.chat_bind_failed")} (${bindError})`} />;
-
return (
- <div className="flex h-full min-h-0 flex-col" data-testid="society-chat">
+ <div
+ className="flex h-full min-h-0 flex-col"
+ data-testid="society-chat"
+ data-session-id={sessionId ?? ""}
+ data-session-ready={sessionReady ? "true" : "false"}
+ >
<div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2 text-xs text-muted-foreground">
{agent.provider ? <ProviderLogo providerId={agent.provider} label={agent.providerLabel} size="sm" /> : null}
<span className="truncate text-foreground">{agent.providerLabel || t("society.chat.model_default")}</span>
{agent.model ? <span className="truncate font-mono">{agent.model}</span> : null}
{agent.effort ? <span className="ml-auto rounded-full border border-border px-2 py-0.5">{agent.effort}</span> : null}
</div>
- <Transcript items={items} agent={agent} busy={busy} onDecide={decide} />
- {lastError ? (
+ <Transcript key={sessionId ?? agent.agentId} items={visibleItems} agent={agent} busy={sessionReady && busy} onDecide={decide} />
+ {lastError && sessionReady ? (
<p role="alert" className="px-4 pb-1 text-xs text-destructive">
{lastError}
</p>
) : null}
+ {bindError ? (
+ <p role="alert" className="px-4 pb-1 text-xs text-destructive">
+ {`${t("society.card.chat_bind_failed")} (${bindError})`}
+ </p>
+ ) : null}
<Composer
+ key={agent.agentId}
agent={agent}
mentionable={mentionable}
- busy={busy || activeSessionId !== sessionId}
- sessionId={activeSessionId}
+ busy={busy || !sessionReady}
+ sessionId={sessionReady ? activeSessionId : sessionId}
cwd=""
provider={agent.provider}
surface="society"
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.test.ts b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
index 497a861f1b..7a3cf68d8f 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.test.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentChatSession } from "@/lib/agentChatApi";
import { providerKind } from "@/components/agentchat/AgentComposer";
+import { EMPTY_TIMELINE, type Timeline, type UserItem } from "@/components/agentchat/reduce";
import { createAgentChatStore, draftKey } from "@/store/agentChat";
/**
@@ -274,3 +275,46 @@ describe("agent-chat store surfaces", () => {
expect(createAgentChatStore("agent").getState().draft.cwd).toBe("C:\\ide");
});
});
+
+function timelineWith(text: string): Timeline {
+ const item: UserItem = { type: "user", id: text, tsMs: 1, text, attachments: [] };
+ return { ...EMPTY_TIMELINE, items: [item], lastSeq: 1 };
+}
+
+describe("agent-chat store session switch", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ vi.stubGlobal("WebSocket", FakeSocket);
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("drops the previous transcript the moment another session opens", () => {
+ const store = createAgentChatStore("society");
+ store.setState({
+ activeSessionId: "society:visual-qa",
+ timeline: timelineWith("visual-qa-flowchart"),
+ sessions: [session("society:visual-qa", "society"), session("society:gmail", "society")],
+ });
+ store.getState().openSession("society:gmail");
+ expect(store.getState().activeSessionId).toBe("society:gmail");
+ expect(store.getState().timeline.items).toEqual([]);
+ expect(store.getState().busy).toBe(false);
+ });
+
+ it("restores a visited session's transcript immediately on switch-back", () => {
+ const store = createAgentChatStore("society");
+ store.setState({
+ activeSessionId: "society:visual-qa",
+ timeline: timelineWith("visual-qa-flowchart"),
+ sessions: [session("society:visual-qa", "society"), session("society:gmail", "society")],
+ });
+ store.getState().openSession("society:gmail");
+ store.setState({ timeline: timelineWith("gmail-inbox") });
+ store.getState().openSession("society:visual-qa");
+ expect(store.getState().timeline.items[0]).toMatchObject({ text: "visual-qa-flowchart" });
+ store.getState().openSession("society:gmail");
+ expect(store.getState().timeline.items[0]).toMatchObject({ text: "gmail-inbox" });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.ts
index 8fabe38004..1a236367b6 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -265,6 +265,9 @@ function onLadder(value: string, ladder: readonly string[], fallback: string): s
return ladder.includes(value) ? value : fallback;
}
+/** How many left-behind transcripts the store keeps for an instant switch-back. */
+const TIMELINE_CACHE_LIMIT = 24;
+
export function createAgentChatStore(surface: AgentChatSurface) {
const DRAFT_KEY = draftKey(surface);
@@ -274,6 +277,25 @@ export function createAgentChatStore(surface: AgentChatSurface) {
let cancelReconnect: (() => void) | null = null;
/** Consecutive failed reconnects — the exponent under the jitter. */
let reconnectAttempt = 0;
+ /**
+ * Last-known transcript per session. Switching chats (or society agents)
+ * used to keep painting the previous session until the new socket's
+ * snapshot arrived; this cache is restored synchronously in `openSession`
+ * so the column never shows another conversation, and a return visit
+ * paints immediately while the socket refreshes.
+ */
+ const timelineCache = new Map<string, Timeline>();
+
+ function rememberTimeline(sessionId: string, timeline: Timeline): void {
+ if (timeline.lastSeq <= 0 && timeline.items.length === 0) return;
+ timelineCache.delete(sessionId);
+ timelineCache.set(sessionId, timeline);
+ while (timelineCache.size > TIMELINE_CACHE_LIMIT) {
+ const oldest = timelineCache.keys().next().value;
+ if (oldest === undefined) break;
+ timelineCache.delete(oldest);
+ }
+ }
function closeSocket(): void {
cancelReconnect?.();
@@ -576,10 +598,15 @@ export function createAgentChatStore(surface: AgentChatSurface) {
openSession: (sessionId) => {
if (get().activeSessionId === sessionId && socket) return;
+ const prev = get();
+ if (prev.activeSessionId && prev.activeSessionId !== sessionId) {
+ rememberTimeline(prev.activeSessionId, prev.timeline);
+ }
set({
activeSessionId: sessionId,
- activeSession: get().sessions.find((s) => s.session_id === sessionId) ?? null,
- timeline: EMPTY_TIMELINE,
+ activeSession: prev.sessions.find((s) => s.session_id === sessionId) ?? null,
+ timeline: timelineCache.get(sessionId) ?? EMPTY_TIMELINE,
+ busy: false,
lastError: null,
});
connect(sessionId, 0);
@@ -591,6 +618,7 @@ export function createAgentChatStore(surface: AgentChatSurface) {
} catch (err) {
set({ lastError: errorText(err) });
}
+ timelineCache.delete(sessionId);
if (get().activeSessionId === sessionId) get().newChat();
set((s) => ({ sessions: s.sessions.filter((x) => x.session_id !== sessionId) }));
void get().loadSessions();
@@ -603,8 +631,8 @@ export function createAgentChatStore(surface: AgentChatSurface) {
if (!content && attachments.length === 0) return;
const st = get();
set({ busy: true, lastError: null });
+ let sid = st.activeSessionId;
try {
- let sid = st.activeSessionId;
if (!sid) {
const d = st.draft;
const session = await createAgentChatSession({
@@ -625,11 +653,13 @@ export function createAgentChatStore(surface: AgentChatSurface) {
connect(sid, 0);
}
await sendAgentChatMessage(sid, content, attachments, toolChoices);
- void get().loadSessions();
+ if (get().activeSessionId === sid) void get().loadSessions();
} catch (err) {
- set({ lastError: errorText(err) });
+ if (get().activeSessionId === sid) set({ lastError: errorText(err) });
} finally {
- set({ busy: false });
+ // A switch away from this session already cleared `busy`; do not
+ // unlock (or error) the chat that is on screen now.
+ if (get().activeSessionId === sid) set({ busy: false });
}
},