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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): clear chat views without resetting context
rubenluetke10-beep0281557684e9
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.tsxindex 824243a3f0..c3041de236 100644--- 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@@ -12,6 +12,7 @@ import {import { useAgentChatStore } from "@/store/agentChat";import { useEventStore } from "@/store/events";import type { AgentChatSession } from "@/lib/agentChatApi";+import { useTranscriptViewStore } from "./useTranscriptView";vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));vi.mock("./AgentModelPicker", () => ({ AgentModelPicker: () => null }));@@ -85,11 +86,12 @@ const visual = agent({ agentId: "visual-qa", name: "Visual QA" });const gmail = agent({ agentId: "gmail-agent", name: "Gmail Agent" });beforeEach(() => {+ useTranscriptViewStore.setState({ boundaries: {} });Element.prototype.scrollIntoView = vi.fn();vi.stubGlobal("WebSocket", FakeSocket);vi.stubGlobal("fetch",- vi.fn(async () => new Response(JSON.stringify({ providers: [], sessions: [], mapping: [] }), { status: 200 })),+ vi.fn(async () => new Response(JSON.stringify({ providers: [], sessions: [], mapping: [], events: [] }), { status: 200 })),);useSocietyChatStore.getState().disconnect();useSocietyChatStore.setState({@@ -113,6 +115,35 @@ it("hides another session's items until that session is the open one", () => {expect(itemsForOpenSession(null, "society:visual-qa", visualItems)).toEqual([]);});+it.each(["specialist", "lead"] as const)("/clear empties only the %s view and keeps its session and context", (tier) => {+ const current = tier === "lead" ? agent({ agentId: "jarvis", name: "Jarvis", tier }) : gmail;+ const store = tier === "lead" ? useAgentChatStore : useSocietyChatStore;+ const original = timelineWith("PREVIOUS_CONTEXT_TO_KEEP");+ store.getState().openSession(current.chatSessionId!);+ store.setState({ activeSessionId: current.chatSessionId, timeline: original, busy: false });+ setJarvisCardMode("chat");+ const view = render(<AgentChatPanel agent={current} roster={[current]} />);+ expect(screen.getByText("PREVIOUS_CONTEXT_TO_KEEP")).toBeTruthy();+ const input = screen.getByRole("textbox");+ input.textContent = " /clear ";+ fireEvent.input(input);+ fireEvent.keyDown(input, { key: "Enter", code: "Enter" });+ expect(screen.queryByText("PREVIOUS_CONTEXT_TO_KEEP")).toBeNull();+ expect(input.textContent).toBe("");+ expect(store.getState().activeSessionId).toBe(current.chatSessionId);+ expect(store.getState().timeline).toBe(original);+ expect(vi.mocked(fetch).mock.calls.some(([url, options]) =>+ String(url).includes("/messages") || options?.method === "DELETE",+ )).toBe(false);+ act(() => store.setState({ timeline: { ...original, items: [...original.items, ...timelineWith("FIRST_VISIBLE_MESSAGE").items] } }));+ expect(screen.getByText("FIRST_VISIBLE_MESSAGE")).toBeTruthy();+ expect(screen.queryByText("PREVIOUS_CONTEXT_TO_KEEP")).toBeNull();+ view.unmount();+ render(<AgentChatPanel agent={current} roster={[current]} />);+ expect(screen.getByText("FIRST_VISIBLE_MESSAGE")).toBeTruthy();+ expect(screen.queryByText("PREVIOUS_CONTEXT_TO_KEEP")).toBeNull();+});+it("does not paint the previous specialist's transcript after a click onto another agent", () => {useSocietyChatStore.setState({activeSessionId: 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.tsxindex 9b976f57d7..9af7e228c0 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -57,6 +57,7 @@ import { useResolveProposal, useSocietyCapabilities, type SocietyAgent } from ".import { MentionPicker } from "./MentionPicker";import { AgentModelPicker } from "./AgentModelPicker";import { mentionChoice, messageChoices } from "./mentionChoices";+import { useTranscriptView } from "./useTranscriptView";import {buildMentionCatalog,filterMentions,@@ -201,6 +202,7 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {const sessionId = agent.chatSessionId;const sessionReady = Boolean(sessionId) && activeSessionId === sessionId;const visibleItems = itemsForOpenSession(sessionId, activeSessionId, items);+ const view = useTranscriptView(sessionReady ? sessionId : null, visibleItems);// Open the agent's own session before the browser paints. Waiting on bind /// catalog / sessions left the previous specialist's transcript on screen@@ -246,7 +248,7 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {{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 key={sessionId ?? agent.agentId} items={visibleItems} agent={agent} roster={roster} onDecide={decide} />+ <Transcript key={`${sessionId ?? agent.agentId}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide} />{lastError && sessionReady ? (<p role="alert" className="px-4 pb-1 text-xs text-destructive">{lastError}@@ -266,6 +268,7 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {cwd=""provider={agent.provider}surface="society"+ onClear={view.clear}onSend={send}onCancel={cancel}/>@@ -290,6 +293,7 @@ function JarvisChat({ agent, roster }: AgentChatPanelProps) {const send = useAgentChat((s) => s.send);const cancel = useAgentChat((s) => s.cancel);const decide = useAgentChat((s) => s.decide);+ const view = useTranscriptView(activeSessionId, items);useEffect(() => {void loadCatalog();@@ -393,7 +397,7 @@ function JarvisChat({ agent, roster }: AgentChatPanelProps) {return (<div className="flex h-full min-h-0 flex-col" data-testid="society-chat" data-mode="chat">{header}- <Transcript items={items} agent={agent} roster={roster} onDecide={decide} />+ <Transcript key={`${activeSessionId ?? ""}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide} />{lastError ? (<p role="alert" className="px-4 pb-1 text-xs text-destructive">{lastError}@@ -406,6 +410,7 @@ function JarvisChat({ agent, roster }: AgentChatPanelProps) {sessionId={activeSessionId}cwd={draft.cwd}provider={draft.provider}+ onClear={view.clear}onSend={send}onCancel={cancel}/>@@ -962,6 +967,7 @@ function Prose({ text, muted }: { text: string; muted?: boolean }) {// ---------------------------------------------------------------------------interface ComposerProps {+ onClear?: () => void;agent: SocietyAgent;mentionable: SocietyAgent[];busy: boolean;@@ -974,7 +980,7 @@ interface ComposerProps {onCancel: () => Promise<void>;}-export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, surface = "jarvis", onSend, onCancel }: ComposerProps) {+export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, surface = "jarvis", onClear, onSend, onCancel }: ComposerProps) {const t = useT();const [modelSaving, setModelSaving] = useState(false);const [value, setValue] = useState("");@@ -1044,6 +1050,15 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, sconst selected = selectedTools;const text = draftText;if (!text || busy || modelSaving) return;+ if (text === "/clear" && onClear) {+ onClear();+ setValue("");+ fieldRef.current?.clear();+ setSelectedTools([]);+ setMention(null);+ setProblem(null);+ return;+ }const named = mentionsInText(text, catalog);const lines: string[] = [];if (named.agents.length > 0 && surface === "society") {diff --git a/jarvis/ui/web/frontend/src/components/society/chat/useTranscriptView.test.ts b/jarvis/ui/web/frontend/src/components/society/chat/useTranscriptView.test.tsnew file mode 100644index 0000000000..15a23bbe4a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/useTranscriptView.test.ts@@ -0,0 +1,75 @@+import { act, cleanup, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { TimelineItem } from "@/components/agentchat/reduce";+import { readClearedViews, useTranscriptView, useTranscriptViewStore } from "./useTranscriptView";++const message = (id: string, tsMs = 1): TimelineItem => ({ type: "user", id, tsMs, text: id, attachments: [] });++beforeEach(() => {+ localStorage.clear();+ useTranscriptViewStore.setState({ boundaries: {} });+});+afterEach(() => { cleanup(); vi.restoreAllMocks(); });++it("hides previous items without changing the transcript and shows new items in order", () => {+ const items = [message("first"), message("second")];+ const { result, rerender } = renderHook(({ history }) => useTranscriptView("chat-a", history), { initialProps: { history: items } });+ act(() => result.current.clear());+ expect(result.current.items).toEqual([]);+ expect(items.map((item) => item.id)).toEqual(["first", "second"]);+ // The server may emit several events in the same millisecond.+ rerender({ history: [...items, message("third"), message("fourth")] });+ expect(result.current.items.map((item) => item.id)).toEqual(["third", "fourth"]);+ act(() => result.current.clear());+ expect(result.current.items).toEqual([]);+});++it("keeps the boundary per chat, across reopening, storage reload and snapshot replay", () => {+ const items = [message("first")];+ const first = renderHook(() => useTranscriptView("chat-a", items));+ act(() => first.result.current.clear());+ first.unmount();+ const saved = readClearedViews();+ expect(saved).toEqual({ "chat-a": { id: "first", tsMs: 1 } });+ useTranscriptViewStore.setState({ boundaries: saved });+ const reopened = renderHook(({ id }) => useTranscriptView(id, items), { initialProps: { id: "chat-a" } });+ expect(reopened.result.current.items).toEqual([]);+ reopened.rerender({ id: "chat-b" });+ expect(reopened.result.current.items).toEqual(items);+ reopened.rerender({ id: "chat-a" });+ expect(reopened.result.current.items).toEqual([]);+});++it("hides old partial snapshots until the boundary arrives again", () => {+ const items = [message("old", 1), message("boundary", 2)];+ const { result, rerender } = renderHook(({ history }) => useTranscriptView("chat-a", history), { initialProps: { history: items } });+ act(() => result.current.clear());+ rerender({ history: [message("old", 1)] });+ expect(result.current.items).toEqual([]);+ rerender({ history: [message("new", 3)] });+ expect(result.current.items.map((item) => item.id)).toEqual(["new"]);+});++it("does nothing for a fresh or empty chat", () => {+ const { result, rerender } = renderHook(({ id, history }) => useTranscriptView(id, history), {+ initialProps: { id: null as string | null, history: [message("old")] },+ });+ act(() => result.current.clear());+ rerender({ id: "empty", history: [] });+ act(() => result.current.clear());+ expect(useTranscriptViewStore.getState().boundaries).toEqual({});+});++it("still clears the view when browser storage is unavailable", () => {+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("storage disabled"); });+ const { result } = renderHook(() => useTranscriptView("chat-a", [message("old")]));+ act(() => result.current.clear());+ expect(result.current.items).toEqual([]);+});++it("ignores corrupt browser preferences", () => {+ localStorage.setItem("jarvis.chatView.cleared.v1", "not json");+ expect(readClearedViews()).toEqual({});+ localStorage.setItem("jarvis.chatView.cleared.v1", '{"bad":null,"also-bad":{"id":1,"tsMs":2}}');+ expect(readClearedViews()).toEqual({});+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/useTranscriptView.ts b/jarvis/ui/web/frontend/src/components/society/chat/useTranscriptView.tsnew file mode 100644index 0000000000..412695d2bf--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/useTranscriptView.ts@@ -0,0 +1,56 @@+import { useCallback, useMemo } from "react";+import { create } from "zustand";+import type { TimelineItem } from "@/components/agentchat/reduce";++const STORAGE_KEY = "jarvis.chatView.cleared.v1";+interface ViewBoundary { id: string; tsMs: number }+type Boundaries = Record<string, ViewBoundary>;++export function readClearedViews(): Boundaries {+ try {+ const raw: unknown = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "{}");+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};+ return Object.fromEntries(Object.entries(raw).filter(([, value]) =>+ value && typeof value.id === "string" && typeof value.tsMs === "number" && Number.isFinite(value.tsMs),+ ));+ } catch {+ // A corrupt or unavailable browser preference must not prevent opening a chat.+ return {};+ }+}++/** Only display boundaries are stored here; the chat store and server history stay intact. */+export const useTranscriptViewStore = create<{ boundaries: Boundaries }>(() => ({+ boundaries: readClearedViews(),+}));++function timestamp(item: TimelineItem): number {+ return item.type === "turn" ? item.startedMs : item.tsMs;+}++function afterBoundary(items: TimelineItem[], boundary: ViewBoundary | undefined): TimelineItem[] {+ if (!boundary) return items;+ const at = items.findIndex((item) => item.id === boundary.id);+ // The item ID preserves ordering even when several messages share a timestamp.+ if (at >= 0) return items.slice(at + 1);+ // A reconnect can temporarily provide only a partial snapshot.+ return items.filter((item) => timestamp(item) > boundary.tsMs);+}++export function useTranscriptView(sessionId: string | null, items: TimelineItem[]) {+ const boundary = useTranscriptViewStore((s) => sessionId ? s.boundaries[sessionId] : undefined);+ const visibleItems = useMemo(() => afterBoundary(items, boundary), [items, boundary]);+ const clear = useCallback(() => {+ const last = items.at(-1);+ if (!sessionId || !last) return;+ useTranscriptViewStore.setState((state) => ({+ boundaries: { ...state.boundaries, [sessionId]: { id: last.id, tsMs: timestamp(last) } },+ }));+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(useTranscriptViewStore.getState().boundaries));+ } catch {+ // Clearing still works for this app session when browser storage is disabled/full.+ }+ }, [sessionId, items]);+ return { items: visibleItems, clear, boundaryId: boundary?.id ?? "" };+}