A local-first multi-agent app development platform, built on PenguinHarness
refactor(web): migrate hand-rolled state containers to zustand vanilla (#295)
Myriad-Dreamin236f256576c1
diff --git a/packages/web/package.json b/packages/web/package.jsonindex 447cb008..66c8b094 100644--- a/packages/web/package.json+++ b/packages/web/package.json@@ -19,7 +19,8 @@"react-markdown": "^10.1.0","react-router": "^8.3.0","remark-gfm": "^4.0.0",- "shiki": "^4.3.1"+ "shiki": "^4.3.1",+ "zustand": "^5.0.15"},"devDependencies": {"@playwright/test": "^1.61.1",diff --git a/packages/web/src/components/ui/toast.tsx b/packages/web/src/components/ui/toast.tsxindex 1066c473..27d8fa79 100644--- a/packages/web/src/components/ui/toast.tsx+++ b/packages/web/src/components/ui/toast.tsx@@ -10,11 +10,12 @@** Usage: call `toastSuccess("Saved")` / `toastInfo("Already up to date")` /* `toastError("Connection failed: ...")` from anywhere, no context needed — a- * module-level subscriber list plus a single `<Toaster />` mounted at the app+ * module-level store plus a single `<Toaster />` mounted at the app* root is all it takes.*/-import { useEffect, useState } from "react";import { createPortal } from "react-dom";+import { useStore } from "zustand/react";+import { createStore } from "zustand/vanilla";type ToastKind = "success" | "error" | "info";@@ -29,34 +30,28 @@ interface ToastItem {/** Display duration: error messages are usually longer and more important to read, so give them more time; info sits in between. */const DURATION: Record<ToastKind, number> = { success: 2500, info: 4000, error: 6000 };-let items: ToastItem[] = [];+const toastStore = createStore<{ items: ToastItem[] }>(() => ({ items: [] }));let nextId = 1;-const listeners = new Set<(items: ToastItem[]) => void>();--function emit(): void {- for (const l of listeners) l(items);-}/** Exit animation duration (matches toast-out in styles.css). */const LEAVE_MS = 160;function dismiss(id: number): void {- const item = items.find((i) => i.id === id);+ const item = toastStore.getState().items.find((i) => i.id === id);if (!item || item.leaving) return;// Mark as leaving first (triggering the exit animation), then actually remove it once the animation ends — otherwise the toast would just vanish abruptly.- items = items.map((i) => (i.id === id ? { ...i, leaving: true } : i));- emit();+ toastStore.setState((s) => ({+ items: s.items.map((i) => (i.id === id ? { ...i, leaving: true } : i)),+ }));setTimeout(() => {- items = items.filter((i) => i.id !== id);- emit();+ toastStore.setState((s) => ({ items: s.items.filter((i) => i.id !== id) }));}, LEAVE_MS);}function push(kind: ToastKind, text: string): void {if (!text) return;const id = nextId++;- items = [...items, { id, kind, text }];- emit();+ toastStore.setState((s) => ({ items: [...s.items, { id, kind, text }] }));setTimeout(() => dismiss(id), DURATION[kind]);}@@ -74,13 +69,7 @@ const KIND_CLASS: Record<ToastKind, string> = {/** Toast container: mount once at the app root. */export function Toaster() {- const [list, setList] = useState<ToastItem[]>(items);- useEffect(() => {- listeners.add(setList);- return () => {- listeners.delete(setList);- };- }, []);+ const list = useStore(toastStore, (s) => s.items);if (list.length === 0) return null;return createPortal(<div className="pointer-events-none fixed inset-x-0 top-3 z-[100] flex flex-col items-center gap-2 px-4">diff --git a/packages/web/src/features/chat/draft-sessions.ts b/packages/web/src/features/chat/draft-sessions.tsindex abf20880..3da4ac30 100644--- a/packages/web/src/features/chat/draft-sessions.ts+++ b/packages/web/src/features/chat/draft-sessions.ts@@ -14,11 +14,12 @@* Ids are `draft-<8 hex>`: real Session ids start with `session-` and the new-chat route* uses the literal `new`, so the chat route dispatches on the prefix alone.*- * The in-memory copy is a module-level store (useSyncExternalStore) so the sidebar list+ * The in-memory copy is a module-level store so the sidebar list* and the draft page react to every mutation in this tab; parseDraft validates each* entry's content field-by-field on load, exactly like the caches it mirrors.*/-import { useSyncExternalStore } from "react";+import { useStore } from "zustand/react";+import { createStore } from "zustand/vanilla";import { clearDraft, draftFromUnknown, draftKey, loadDraft, saveDraft } from "./draft-cache";import type { DraftCache, DraftStorage } from "./draft-cache";@@ -68,8 +69,12 @@ function parseEntries(raw: string | null): DraftSessionEntry[] {// —— Module-level store: storage key → entries, every subscriber re-renders on change ——-const cache = new Map<string, DraftSessionEntry[]>();-const listeners = new Set<() => void>();+// The Map doubles as the lazy parse cache: readEntries seeds a missing key IN PLACE (no new+// reference, no notification — it may run inside a render via useDraftSessions' selector),+// while writeEntries swaps in a new Map so subscribers are notified.+const draftsStore = createStore<{ cache: Map<string, DraftSessionEntry[]> }>(() => ({+ cache: new Map(),+}));const EMPTY: DraftSessionEntry[] = [];function storageOf(injected?: DraftStorage): DraftStorage | null {@@ -82,6 +87,7 @@ function storageOf(injected?: DraftStorage): DraftStorage | null {}function readEntries(key: string, storage?: DraftStorage): DraftSessionEntry[] {+ const { cache } = draftsStore.getState();const hit = cache.get(key);if (hit) return hit;const s = storageOf(storage);@@ -98,7 +104,6 @@ function readEntries(key: string, storage?: DraftStorage): DraftSessionEntry[] {}function writeEntries(key: string, entries: DraftSessionEntry[], storage?: DraftStorage): void {- cache.set(key, entries);const s = storageOf(storage);if (s) {try {@@ -108,12 +113,7 @@ function writeEntries(key: string, entries: DraftSessionEntry[], storage?: Draft// Quota/private mode: the in-memory copy still serves this tab.}}- for (const listener of listeners) listener();-}--function subscribe(listener: () => void): () => void {- listeners.add(listener);- return () => listeners.delete(listener);+ draftsStore.setState((prev) => ({ cache: new Map(prev.cache).set(key, entries) }));}/** Reactive list of a user × Project's parked drafts, newest first (EMPTY constant when signed out / none). */@@ -121,10 +121,8 @@ export function useDraftSessions(userId: string | null,projectId: string | null,): DraftSessionEntry[] {- return useSyncExternalStore(- subscribe,- () => (userId && projectId ? readEntries(draftSessionsKey(userId, projectId)) : EMPTY),- () => EMPTY,+ return useStore(draftsStore, () =>+ userId && projectId ? readEntries(draftSessionsKey(userId, projectId)) : EMPTY,);}diff --git a/packages/web/src/features/chat/use-panel-width.ts b/packages/web/src/features/chat/use-panel-width.tsindex 9facbd68..1f313933 100644--- a/packages/web/src/features/chat/use-panel-width.ts+++ b/packages/web/src/features/chat/use-panel-width.ts@@ -9,14 +9,15 @@** "Immediately" is what rules out two `useState`s over one storage key: only the panel that was* mounted and dragged would update, and the other would keep a stale copy until its next- * remount. So the value lives in a module-level store both hooks subscribe to via- * useSyncExternalStore, and the persisted preference is written once per drag (mouseup), not- * per frame.+ * remount. So the value lives in a module-level store both hooks subscribe to, and the+ * persisted preference is written once per drag (mouseup), not per frame.** Width is a layout preference, not session data: it is never reset on a Session switch.*/-import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import type { MouseEvent as ReactMouseEvent, RefObject } from "react";+import { useStore } from "zustand/react";+import { createStore } from "zustand/vanilla";const MIN_WIDTH = 320;const WIDTH_STORAGE_KEY = "penguin.panelWidth";@@ -80,23 +81,24 @@ function initialWidth(): number {// —— Module-level store: one width, every subscriber re-renders on change ——-let sharedWidth: number | null = null;-const listeners = new Set<() => void>();+// null = not initialized yet: the width stays lazy (computed on the first read, i.e. the+// first mounted panel's render), exactly like the pre-zustand module variable — an eager+// initialWidth() at module load would run the legacy-key migration on every page load.+const widthStore = createStore<{ width: number | null }>(() => ({ width: null }));function readWidth(): number {- sharedWidth ??= initialWidth();- return sharedWidth;+ const { width } = widthStore.getState();+ if (width !== null) return width;+ // First read happens during the first subscriber's render, before anything subscribed:+ // seeding via setState here notifies nobody, so it is safe inside a render.+ const initial = initialWidth();+ widthStore.setState({ width: initial });+ return initial;}function writeWidth(next: number): void {- if (next === sharedWidth) return;- sharedWidth = next;- for (const listener of listeners) listener();-}--function subscribe(listener: () => void): () => void {- listeners.add(listener);- return () => listeners.delete(listener);+ if (next === widthStore.getState().width) return;+ widthStore.setState({ width: next });}export interface PanelWidthState {@@ -114,7 +116,7 @@ export interface PanelWidthState {* (each panel has its own DOM node and its own handle); only the width crosses between them.*/export function usePanelWidth(): PanelWidthState {- const width = useSyncExternalStore(subscribe, readWidth, readWidth);+ const width = useStore(widthStore, () => readWidth());const [resizing, setResizing] = useState(false);const panelRef = useRef<HTMLDivElement>(null);diff --git a/packages/web/src/state/project.tsx b/packages/web/src/state/project.tsxindex 25a85c87..82357bb6 100644--- a/packages/web/src/state/project.tsx+++ b/packages/web/src/state/project.tsx@@ -4,10 +4,16 @@* synced to server-side prefs (lastProjectId, best-effort);* - the current Project's Agent list and current Agent (switched via the top-bar breadcrumb* dropdown; remembered per Project).+ *+ * State lives in a zustand vanilla store (one instance per Provider mount, so an unmount+ * still resets everything); the Provider is a thin lifecycle component that triggers the+ * initial fetches and republishes the store's state through the same context value as before.*/-import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";+import { createContext, useContext, useEffect, useMemo, useState } from "react";import type { ReactNode } from "react";import type { AgentSummary, ProjectSummary } from "@prismshadow/penguin-server/api";+import { useStore } from "zustand/react";+import { createStore } from "zustand/vanilla";import * as api from "../api/endpoints";const PROJECT_KEY = "penguin.lastProjectId";@@ -39,115 +45,124 @@ export function agentDisplayName(a: AgentSummary): string {return a.name ?? a.agentId;}-export function ProjectProvider({ children }: { children: ReactNode }) {- const [projects, setProjects] = useState<ProjectSummary[]>([]);- const [projectsLoading, setProjectsLoading] = useState(true);- const [currentProjectId, setCurrentProjectIdState] = useState<string | null>(null);-- const [agents, setAgents] = useState<AgentSummary[]>([]);- const [agentsLoading, setAgentsLoading] = useState(true);- const [currentAgentId, setCurrentAgentIdState] = useState<string | null>(null);-- const reloadProjects = useCallback(async () => {- setProjectsLoading(true);- try {- const res = await api.listProjects();- setProjects(res.projects);- setCurrentProjectIdState((prev) => {- const wanted = prev ?? localStorage.getItem(PROJECT_KEY);- const found = res.projects.find((p) => p.projectId === wanted);- return (found ?? res.projects[0])?.projectId ?? null;- });- } finally {- setProjectsLoading(false);- }- }, []);+/** Store state: the context value's raw ingredients (currentProject/currentAgent are derived in the Provider) plus the mutation functions. */+interface ProjectStoreState {+ projects: ProjectSummary[];+ projectsLoading: boolean;+ currentProjectId: string | null;- useEffect(() => {- void reloadProjects();- }, [reloadProjects]);+ agents: AgentSummary[];+ agentsLoading: boolean;+ currentAgentId: string | null;++ setCurrentProjectId: (projectId: string) => void;+ reloadProjects: () => Promise<void>;+ setCurrentAgentId: (agentId: string) => void;+ reloadAgents: () => Promise<void>;+}++function createProjectStore() {+ return createStore<ProjectStoreState>((set, get) => ({+ projects: [],+ projectsLoading: true,+ currentProjectId: null,++ agents: [],+ agentsLoading: true,+ currentAgentId: null,++ reloadProjects: async () => {+ set({ projectsLoading: true });+ try {+ const res = await api.listProjects();+ const wanted = get().currentProjectId ?? localStorage.getItem(PROJECT_KEY);+ const found = res.projects.find((p) => p.projectId === wanted);+ set({+ projects: res.projects,+ currentProjectId: (found ?? res.projects[0])?.projectId ?? null,+ });+ } finally {+ set({ projectsLoading: false });+ }+ },- const setCurrentProjectId = useCallback(- (projectId: string) => {+ setCurrentProjectId: (projectId) => {// If the selection is already the current Project, return immediately. Otherwise the// code below would clear agents and set loading back to true while currentProjectId- // stays unchanged — reloadAgents' effect depends on it and wouldn't rerun, so the Agent- // list (and the Session list mounted under it) would disappear for good (reproducible- // by clicking the already-current Project in the dropdown).- if (projectId === currentProjectId) return;+ // stays unchanged — the Provider's reloadAgents effect depends on it and wouldn't rerun,+ // so the Agent list (and the Session list mounted under it) would disappear for good+ // (reproducible by clicking the already-current Project in the dropdown).+ if (projectId === get().currentProjectId) return;localStorage.setItem(PROJECT_KEY, projectId);- setCurrentProjectIdState(projectId);- setCurrentAgentIdState(null);// Clear the Agent list in sync: avoids a transient render with "new projectId + old// Project's agents" that would make downstream consumers (Sessions) fetch with the// wrong Agent set (which could create spurious Sessions under the new Project).- setAgents([]);- setAgentsLoading(true);+ set({+ currentProjectId: projectId,+ currentAgentId: null,+ agents: [],+ agentsLoading: true,+ });// Sync server-side prefs (best-effort; failure doesn't affect the local experience).void api.putPrefs({ lastProjectId: projectId }).catch(() => undefined);},- [currentProjectId],- );-- const reloadAgents = useCallback(async () => {- if (!currentProjectId) return;- setAgentsLoading(true);- try {- const res = await api.listAgents(currentProjectId);- setAgents(res.agents);- setCurrentAgentIdState((prev) => {- const wanted = prev ?? localStorage.getItem(agentKey(currentProjectId));++ reloadAgents: async () => {+ const currentProjectId = get().currentProjectId;+ if (!currentProjectId) return;+ set({ agentsLoading: true });+ try {+ const res = await api.listAgents(currentProjectId);+ const wanted = get().currentAgentId ?? localStorage.getItem(agentKey(currentProjectId));const found = res.agents.find((a) => a.agentId === wanted);// Default to conversing with default_agent.const fallback =res.agents.find((a) => a.agentId === "default_agent") ?? res.agents[0] ?? null;- return (found ?? fallback)?.agentId ?? null;- });- } finally {- setAgentsLoading(false);- }- }, [currentProjectId]);-- useEffect(() => {- setAgents([]);- void reloadAgents();- }, [reloadAgents]);+ set({ agents: res.agents, currentAgentId: (found ?? fallback)?.agentId ?? null });+ } finally {+ set({ agentsLoading: false });+ }+ },- const setCurrentAgentId = useCallback(- (agentId: string) => {+ setCurrentAgentId: (agentId) => {+ const currentProjectId = get().currentProjectId;if (currentProjectId) localStorage.setItem(agentKey(currentProjectId), agentId);- setCurrentAgentIdState(agentId);+ set({ currentAgentId: agentId });},- [currentProjectId],- );+ }));+}++export function ProjectProvider({ children }: { children: ReactNode }) {+ const [store] = useState(createProjectStore);+ const state = useStore(store);++ useEffect(() => {+ void store.getState().reloadProjects();+ }, [store]);++ const { currentProjectId } = state;+ useEffect(() => {+ store.setState({ agents: [] });+ void store.getState().reloadAgents();+ }, [store, currentProjectId]);const value = useMemo<ProjectContextValue>(() => {- const currentProject = projects.find((p) => p.projectId === currentProjectId) ?? null;- const currentAgent = agents.find((a) => a.agentId === currentAgentId) ?? null;+ const currentProject =+ state.projects.find((p) => p.projectId === state.currentProjectId) ?? null;+ const currentAgent = state.agents.find((a) => a.agentId === state.currentAgentId) ?? null;return {- projects,- projectsLoading,+ projects: state.projects,+ projectsLoading: state.projectsLoading,currentProject,- setCurrentProjectId,- reloadProjects,- agents,- agentsLoading,+ setCurrentProjectId: state.setCurrentProjectId,+ reloadProjects: state.reloadProjects,+ agents: state.agents,+ agentsLoading: state.agentsLoading,currentAgent,- setCurrentAgentId,- reloadAgents,+ setCurrentAgentId: state.setCurrentAgentId,+ reloadAgents: state.reloadAgents,};- }, [- projects,- projectsLoading,- currentProjectId,- setCurrentProjectId,- reloadProjects,- agents,- agentsLoading,- currentAgentId,- setCurrentAgentId,- reloadAgents,- ]);+ }, [state]);return <ProjectContext.Provider value={value}>{children}</ProjectContext.Provider>;}diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsxindex 542e7006..56994a87 100644--- a/packages/web/src/state/sessions.tsx+++ b/packages/web/src/state/sessions.tsx@@ -17,16 +17,13 @@* and the Session is only actually created when the first message is sent — after landing, the user* may still switch models or configure an API key first, so persisting the Session early would both* lock in the model and fail outright when no credential is configured yet.+ *+ * State lives in a zustand vanilla store (one instance per Provider mount); the Provider is a+ * thin lifecycle component (initial fetch, refetch on Project/Agent-set/filter changes, the+ * user-event subscription) and republishes the store's state through the same context value+ * as before. Mutations read current values via store.getState() (the old refs' job).*/-import {- createContext,- useCallback,- useContext,- useEffect,- useMemo,- useRef,- useState,-} from "react";+import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";import type { ReactNode } from "react";import type {SessionCategory,@@ -34,6 +31,8 @@ import type {SessionInfo,SessionStatus,} from "@prismshadow/penguin-server/api";+import { useStore } from "zustand/react";+import { createStore } from "zustand/vanilla";import * as api from "../api/endpoints";import { openUserEvents } from "../api/sse";import {@@ -95,325 +94,351 @@ interface PagePosition {fetched: number;}-export function SessionsProvider({ children }: { children: ReactNode }) {- const { currentProject, agents } = useProject();- const projectId = currentProject?.projectId ?? null;- // Stable key for the Agent set: the list object is a new reference on every reload,- // so join the ids to avoid unnecessary reloads.- const agentIdsKey = agents.map((a) => a.agentId).join(",");+/** Store state: the context value's raw ingredients plus the mutation functions (byAgent / isLoadedFor / hasMoreFor are derived in the Provider). */+interface SessionsStoreState {+ /** Provider-synced fetch context: the current Project and its Agent set (what reload() targets). */+ projectId: string | null;+ agentIds: string[];- const [sessions, setSessions] = useState<SessionInfo[]>([]);+ sessions: SessionInfo[];/** pageKey → that pair's paging cursor; a key is present iff its first page has been fetched. */- const [pageState, setPageState] = useState<ReadonlyMap<string, PagePosition>>(new Map());- const [countsByAgent, setCountsByAgent] = useState<ReadonlyMap<string, SessionCategoryCounts>>(- new Map(),- );- const [workspaceCountsByAgent, setWorkspaceCountsByAgent] = useState<- ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>- >(new Map());- const [loading, setLoading] = useState(true);- // "Show CLI sessions" preference: server-persisted per user (ui_prefs); hydrated once on- // mount, default off. Changing it recreates reload(), and the reset effect below refetches- // the whole list under the new filter.- const [showCliSessions, setShowCliSessionsState] = useState(false);- useEffect(() => {- let cancelled = false;- void api- .getPrefs()- .then((res) => {- if (!cancelled && res.prefs.showCliSessions === true) setShowCliSessionsState(true);- })- .catch(() => undefined); // Unreachable prefs: stay with the default (web only).- return () => {- cancelled = true;- };- }, []);- const setShowCliSessions = useCallback((value: boolean) => {- setShowCliSessionsState(value);- // Fire-and-forget: PUT /me/prefs merges shallowly; a lost write only costs persistence,- // the in-memory toggle already took effect.- void api.putPrefs({ showCliSessions: value }).catch(() => undefined);- }, []);+ pageState: ReadonlyMap<string, PagePosition>;+ countsByAgent: ReadonlyMap<string, SessionCategoryCounts>;+ workspaceCountsByAgent: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>;+ loading: boolean;+ // "Show CLI sessions" preference: server-persisted per user (ui_prefs); hydrated once by the+ // Provider on mount, default off. Changing it makes the Provider's reset effect refetch the+ // whole list under the new filter.+ showCliSessions: boolean;++ reload: () => Promise<void>;+ loadMoreFor: (agentIds: string[], category: SessionCategory) => Promise<void>;+ add: (session: SessionInfo) => void;+ remove: (sessionId: string) => void;+ replace: (session: SessionInfo) => void;+ setStatus: (sessionId: string, status: SessionStatus) => void;+ setTitle: (sessionId: string, title: string) => void;+ setShowCliSessions: (value: boolean) => void;+}++function createSessionsStore() {// Generation counter: invalidates any in-flight response once the Project/Agent set// changes or a reload happens.- const gen = useRef(0);- // Current values for loadMoreFor (offsets are computed from what is actually loaded).- const sessionsRef = useRef<SessionInfo[]>([]);- sessionsRef.current = sessions;- const pageStateRef = useRef<ReadonlyMap<string, PagePosition>>(pageState);- pageStateRef.current = pageState;- const countsRef = useRef<ReadonlyMap<string, SessionCategoryCounts>>(countsByAgent);- countsRef.current = countsByAgent;+ let gen = 0;- const reload = useCallback(async () => {- const agentIds = agentIdsKey === "" ? [] : agentIdsKey.split(",");- if (!projectId || agentIds.length === 0) return;- const g = ++gen.current;- setLoading(true);- try {- const results = await Promise.all(- agentIds.map(async (agentId) => {- // Active first page (with per-category totals) always; plus the first page of- // every folder category already on screen — a reload triggered by a server- // event must refresh, not blank, an open folder.- const categories: SessionCategory[] = [- "active",- ...FOLDER_CATEGORIES.filter((cat) => pageStateRef.current.has(pageKey(agentId, cat))),- ];- try {- const pages = await Promise.all(- categories.map(async (category) => {- const res = await api.listSessions(projectId, agentId, {- offset: 0,- limit: SIDEBAR_PAGE_SIZE + 1,- category,- ...(category === "active" ? { withCounts: true } : {}),- ...(showCliSessions ? { cli: true } : {}),- });- return {- category,- counts: res.counts,- workspaceCounts: res.workspaceCounts,- ...splitPage(res.sessions, SIDEBAR_PAGE_SIZE),- };- }),- );- return { agentId, pages };- } catch {- // A single Agent's fetch failure shouldn't bring down the whole batch (e.g. its directory was deleted externally).- return { agentId, pages: [] };- }- }),- );- if (g !== gen.current) return;- const nextSessions: SessionInfo[] = [];- const seen = new Set<string>();- const nextPageState = new Map<string, PagePosition>();- const nextCounts = new Map<string, SessionCategoryCounts>();- const nextWorkspaceCounts = new Map<- string,- Readonly<Record<string, SessionCategoryCounts>>- >();- for (const r of results) {- for (const p of r.pages) {- nextPageState.set(pageKey(r.agentId, p.category), {- hasMore: p.hasMore,- fetched: p.items.length,- });- if (p.counts) nextCounts.set(r.agentId, p.counts);- if (p.workspaceCounts) nextWorkspaceCounts.set(r.agentId, p.workspaceCounts);- for (const s of p.items) {- if (!seen.has(s.sessionId)) {- seen.add(s.sessionId);- nextSessions.push(s);- }- }- }+ return createStore<SessionsStoreState>((set, get) => {+ /** Keeps an Agent's category totals — overall and per Workspace — in step with a local list mutation of `session` (no-op while its counts are unknown). */+ const adjustCount = (session: SessionInfo, category: SessionCategory, delta: number) => {+ const { agentId, workspace } = session;+ const counts = get().countsByAgent;+ const cur = counts.get(agentId);+ if (cur) {+ const next = new Map(counts);+ next.set(agentId, { ...cur, [category]: Math.max(0, cur[category] + delta) });+ set({ countsByAgent: next });}- setSessions(nextSessions);- setPageState(nextPageState);- setCountsByAgent(nextCounts);- setWorkspaceCountsByAgent(nextWorkspaceCounts);- } finally {- if (g === gen.current) setLoading(false);- }- }, [projectId, agentIdsKey, showCliSessions]);+ const workspaceCounts = get().workspaceCountsByAgent;+ const wsCur = workspaceCounts.get(agentId);+ if (wsCur) {+ const ws = wsCur[workspace] ?? { active: 0, subagent: 0, schedule: 0, archived: 0 };+ const next = new Map(workspaceCounts);+ next.set(agentId, {+ ...wsCur,+ [workspace]: { ...ws, [category]: Math.max(0, ws[category] + delta) },+ });+ set({ workspaceCountsByAgent: next });+ }+ };- useEffect(() => {- setSessions([]);- // reload() reads the ref synchronously to pick the categories to refetch — reset it- // in place so a Project switch can't carry folder page state across via shared Agent- // ids (default_agent exists in every Project).- pageStateRef.current = new Map();- setPageState(pageStateRef.current);- setCountsByAgent(new Map());- setWorkspaceCountsByAgent(new Map());- void reload();- }, [reload]);+ return {+ projectId: null,+ agentIds: [],- /**- * Category page fetch for each given Agent: the first page when the pair is unloaded- * (skipped unless the counts say the category holds anything), the next page when- * loaded with more. The offset is the pair's `fetched` cursor — rows actually- * consumed from the server's stream, never rows `add()` slipped in. A session- * created since the last page still shifts server offsets, so appended rows are- * deduplicated by sessionId (a short page is fine — `hasMore` comes from the server- * response, and the next click continues from the advanced cursor).- */- const loadMoreFor = useCallback(- async (agentIds: string[], category: SessionCategory) => {- if (!projectId) return;- const targets = [...new Set(agentIds)].filter((agentId) => {- const position = pageStateRef.current.get(pageKey(agentId, category));- if (position === undefined) return (countsRef.current.get(agentId)?.[category] ?? 0) > 0;- return position.hasMore;- });- if (targets.length === 0) return;- const g = gen.current;- const results = await Promise.all(- targets.map(async (agentId) => {- const offset = pageStateRef.current.get(pageKey(agentId, category))?.fetched ?? 0;- try {- const fetched = (- await api.listSessions(projectId, agentId, {- offset,- limit: SIDEBAR_PAGE_SIZE + 1,- category,- ...(showCliSessions ? { cli: true } : {}),- })- ).sessions;- return { agentId, ...splitPage(fetched, SIDEBAR_PAGE_SIZE) };- } catch {- // Transient failure: leave the pair's state untouched (still unloaded / still- // has-more), so the affordance stays and the user can retry.- return null;+ sessions: [],+ pageState: new Map(),+ countsByAgent: new Map(),+ workspaceCountsByAgent: new Map(),+ loading: true,+ showCliSessions: false,++ reload: async () => {+ const { projectId, agentIds, showCliSessions } = get();+ if (!projectId || agentIds.length === 0) return;+ const g = ++gen;+ set({ loading: true });+ try {+ const results = await Promise.all(+ agentIds.map(async (agentId) => {+ // Active first page (with per-category totals) always; plus the first page of+ // every folder category already on screen — a reload triggered by a server+ // event must refresh, not blank, an open folder.+ const categories: SessionCategory[] = [+ "active",+ ...FOLDER_CATEGORIES.filter((cat) => get().pageState.has(pageKey(agentId, cat))),+ ];+ try {+ const pages = await Promise.all(+ categories.map(async (category) => {+ const res = await api.listSessions(projectId, agentId, {+ offset: 0,+ limit: SIDEBAR_PAGE_SIZE + 1,+ category,+ ...(category === "active" ? { withCounts: true } : {}),+ ...(showCliSessions ? { cli: true } : {}),+ });+ return {+ category,+ counts: res.counts,+ workspaceCounts: res.workspaceCounts,+ ...splitPage(res.sessions, SIDEBAR_PAGE_SIZE),+ };+ }),+ );+ return { agentId, pages };+ } catch {+ // A single Agent's fetch failure shouldn't bring down the whole batch (e.g. its directory was deleted externally).+ return { agentId, pages: [] };+ }+ }),+ );+ if (g !== gen) return;+ const nextSessions: SessionInfo[] = [];+ const seen = new Set<string>();+ const nextPageState = new Map<string, PagePosition>();+ const nextCounts = new Map<string, SessionCategoryCounts>();+ const nextWorkspaceCounts = new Map<+ string,+ Readonly<Record<string, SessionCategoryCounts>>+ >();+ for (const r of results) {+ for (const p of r.pages) {+ nextPageState.set(pageKey(r.agentId, p.category), {+ hasMore: p.hasMore,+ fetched: p.items.length,+ });+ if (p.counts) nextCounts.set(r.agentId, p.counts);+ if (p.workspaceCounts) nextWorkspaceCounts.set(r.agentId, p.workspaceCounts);+ for (const s of p.items) {+ if (!seen.has(s.sessionId)) {+ seen.add(s.sessionId);+ nextSessions.push(s);+ }+ }+ }}- }),- );- if (g !== gen.current) return; // Project switch / reload raced this page: drop it.- const ok = results.filter((r) => r !== null);- setSessions((prev) => {+ set({+ sessions: nextSessions,+ pageState: nextPageState,+ countsByAgent: nextCounts,+ workspaceCountsByAgent: nextWorkspaceCounts,+ });+ } finally {+ if (g === gen) set({ loading: false });+ }+ },++ /**+ * Category page fetch for each given Agent: the first page when the pair is unloaded+ * (skipped unless the counts say the category holds anything), the next page when+ * loaded with more. The offset is the pair's `fetched` cursor — rows actually+ * consumed from the server's stream, never rows `add()` slipped in. A session+ * created since the last page still shifts server offsets, so appended rows are+ * deduplicated by sessionId (a short page is fine — `hasMore` comes from the server+ * response, and the next click continues from the advanced cursor).+ */+ loadMoreFor: async (agentIds, category) => {+ const { projectId, showCliSessions } = get();+ if (!projectId) return;+ const targets = [...new Set(agentIds)].filter((agentId) => {+ const position = get().pageState.get(pageKey(agentId, category));+ if (position === undefined)+ return (get().countsByAgent.get(agentId)?.[category] ?? 0) > 0;+ return position.hasMore;+ });+ if (targets.length === 0) return;+ const g = gen;+ const results = await Promise.all(+ targets.map(async (agentId) => {+ const offset = get().pageState.get(pageKey(agentId, category))?.fetched ?? 0;+ try {+ const fetched = (+ await api.listSessions(projectId, agentId, {+ offset,+ limit: SIDEBAR_PAGE_SIZE + 1,+ category,+ ...(showCliSessions ? { cli: true } : {}),+ })+ ).sessions;+ return { agentId, ...splitPage(fetched, SIDEBAR_PAGE_SIZE) };+ } catch {+ // Transient failure: leave the pair's state untouched (still unloaded / still+ // has-more), so the affordance stays and the user can retry.+ return null;+ }+ }),+ );+ if (g !== gen) return; // Project switch / reload raced this page: drop it.+ const ok = results.filter((r) => r !== null);+ const prev = get().sessions;const seen = new Set(prev.map((s) => s.sessionId));const appended = ok.flatMap((r) => r.items.filter((s) => !seen.has(s.sessionId)));- return appended.length > 0 ? [...prev, ...appended] : prev;- });- setPageState((prev) => {- const next = new Map(prev);+ const prevPageState = get().pageState;+ const nextPageState = new Map(prevPageState);for (const r of ok) {const key = pageKey(r.agentId, category);- next.set(key, {+ nextPageState.set(key, {hasMore: r.hasMore,- fetched: (prev.get(key)?.fetched ?? 0) + r.items.length,+ fetched: (prevPageState.get(key)?.fetched ?? 0) + r.items.length,});}- return next;- });- },- [projectId, showCliSessions],- );+ set({+ ...(appended.length > 0 ? { sessions: [...prev, ...appended] } : {}),+ pageState: nextPageState,+ });+ },- const isLoadedFor = useCallback(- (agentId: string, category: SessionCategory) => pageState.has(pageKey(agentId, category)),- [pageState],- );+ add: (session) => {+ // Invalidate any in-flight reload: the newly created entry mustn't be wiped by a stale snapshot.+ gen += 1;+ // Count the row only when the pair's fetched pages provably held its whole category+ // (loaded, no more): the row is then genuinely new to the server totals. Otherwise+ // (deep-link self-heal of an unfetched row) the counts already include it — a+ // possible one-off drift self-heals on the next reload.+ const existed = get().sessions.some((s) => s.sessionId === session.sessionId);+ if (+ !existed &&+ get().pageState.get(pageKey(session.agentId, sessionCategory(session)))?.hasMore === false+ ) {+ adjustCount(session, sessionCategory(session), 1);+ }+ set({+ sessions: [session, ...get().sessions.filter((s) => s.sessionId !== session.sessionId)],+ });+ },- const hasMoreFor = useCallback(- (agentId: string, category: SessionCategory) => {- const position = pageState.get(pageKey(agentId, category));- if (position !== undefined) return position.hasMore;- // Unloaded pair: anything the counts report is by definition still unfetched.- return (countsByAgent.get(agentId)?.[category] ?? 0) > 0;- },- [pageState, countsByAgent],- );+ remove: (sessionId) => {+ // Invalidate any in-flight reload: the deletion mustn't be undone by a stale snapshot.+ gen += 1;+ const row = get().sessions.find((s) => s.sessionId === sessionId);+ if (row) adjustCount(row, sessionCategory(row), -1);+ set({ sessions: get().sessions.filter((s) => s.sessionId !== sessionId) });+ },- /** Keeps an Agent's category totals — overall and per Workspace — in step with a local list mutation of `session` (no-op while its counts are unknown). */- const adjustCount = useCallback(- (session: SessionInfo, category: SessionCategory, delta: number) => {- const { agentId, workspace } = session;- setCountsByAgent((prev) => {- const cur = prev.get(agentId);- if (!cur) return prev;- const next = new Map(prev);- next.set(agentId, { ...cur, [category]: Math.max(0, cur[category] + delta) });- return next;- });- setWorkspaceCountsByAgent((prev) => {- const cur = prev.get(agentId);- if (!cur) return prev;- const ws = cur[workspace] ?? { active: 0, subagent: 0, schedule: 0, archived: 0 };- const next = new Map(prev);- next.set(agentId, {- ...cur,- [workspace]: { ...ws, [category]: Math.max(0, ws[category] + delta) },+ replace: (session) => {+ // An archive toggle moves the row across categories: keep the folder totals in step.+ const old = get().sessions.find((s) => s.sessionId === session.sessionId);+ if (old && sessionCategory(old) !== sessionCategory(session)) {+ adjustCount(session, sessionCategory(old), -1);+ adjustCount(session, sessionCategory(session), 1);+ }+ set({+ sessions: get().sessions.map((s) => (s.sessionId === session.sessionId ? session : s)),});- return next;- });- },- [],- );+ },++ setStatus: (sessionId, status) => {+ const prev = get().sessions;+ const target = prev.find((s) => s.sessionId === sessionId);+ if (!target || target.status === status) return;+ set({ sessions: prev.map((s) => (s.sessionId === sessionId ? { ...s, status } : s)) });+ },++ setTitle: (sessionId, title) => {+ set({+ sessions: get().sessions.map((s) => (s.sessionId === sessionId ? { ...s, title } : s)),+ });+ },++ setShowCliSessions: (value) => {+ set({ showCliSessions: value });+ // Fire-and-forget: PUT /me/prefs merges shallowly; a lost write only costs persistence,+ // the in-memory toggle already took effect.+ void api.putPrefs({ showCliSessions: value }).catch(() => undefined);+ },+ };+ });+}++export function SessionsProvider({ children }: { children: ReactNode }) {+ const { currentProject, agents } = useProject();+ const projectId = currentProject?.projectId ?? null;+ // Stable key for the Agent set: the list object is a new reference on every reload,+ // so join the ids to avoid unnecessary reloads.+ const agentIdsKey = agents.map((a) => a.agentId).join(",");++ const [store] = useState(createSessionsStore);+ const state = useStore(store);++ // Hydrate the "show CLI sessions" preference once on mount (a bare setState, not the+ // setShowCliSessions action: hydration must not write the preference back).+ useEffect(() => {+ let cancelled = false;+ void api+ .getPrefs()+ .then((res) => {+ if (!cancelled && res.prefs.showCliSessions === true)+ store.setState({ showCliSessions: true });+ })+ .catch(() => undefined); // Unreachable prefs: stay with the default (web only).+ return () => {+ cancelled = true;+ };+ }, [store]);++ const { showCliSessions } = state;+ useEffect(() => {+ // Sync the fetch context and reset the loaded pages in the same synchronous step:+ // reload() picks the categories to refetch from pageState, so a Project switch can't+ // carry folder page state across via shared Agent ids (default_agent exists in every+ // Project). Also reruns on a showCliSessions flip: refetch the whole list under the+ // new filter.+ store.setState({+ projectId,+ agentIds: agentIdsKey === "" ? [] : agentIdsKey.split(","),+ sessions: [],+ pageState: new Map(),+ countsByAgent: new Map(),+ workspaceCountsByAgent: new Map(),+ });+ void store.getState().reload();+ }, [store, projectId, agentIdsKey, showCliSessions]);// User-level event stream (/api/events): a scheduled task firing may have created a new// Session (new-session mode); reload the list so it appears immediately. schedule_queued// doesn't change the list (the target Session already exists), so it's ignored.- // refs hold the current values: the connection stays a single one for the whole login- // session and doesn't reconnect on Project switches.- const reloadRef = useRef(reload);- reloadRef.current = reload;- const projectIdRef = useRef(projectId);- projectIdRef.current = projectId;+ // store.getState() serves the current values: the connection stays a single one for the+ // whole login session and doesn't reconnect on Project switches.useEffect(() => {const conn = openUserEvents({onOmniMessage: () => undefined,onServerEvent: (ev) => {if (ev.type !== "schedule_fired") return;// The event carries projectId: a trigger from another Project is unrelated to the current list.- if (ev.projectId === projectIdRef.current) void reloadRef.current();+ if (ev.projectId === store.getState().projectId) void store.getState().reload();},});return () => conn.close();- }, []);+ }, [store]);- const add = useCallback(- (session: SessionInfo) => {- // Invalidate any in-flight reload: the newly created entry mustn't be wiped by a stale snapshot.- gen.current += 1;- // Count the row only when the pair's fetched pages provably held its whole category- // (loaded, no more): the row is then genuinely new to the server totals. Otherwise- // (deep-link self-heal of an unfetched row) the counts already include it — a- // possible one-off drift self-heals on the next reload.- const existed = sessionsRef.current.some((s) => s.sessionId === session.sessionId);- if (- !existed &&- pageStateRef.current.get(pageKey(session.agentId, sessionCategory(session)))?.hasMore ===- false- ) {- adjustCount(session, sessionCategory(session), 1);- }- setSessions((prev) => [session, ...prev.filter((s) => s.sessionId !== session.sessionId)]);- },- [adjustCount],- );-- const remove = useCallback(- (sessionId: string) => {- // Invalidate any in-flight reload: the deletion mustn't be undone by a stale snapshot.- gen.current += 1;- const row = sessionsRef.current.find((s) => s.sessionId === sessionId);- if (row) adjustCount(row, sessionCategory(row), -1);- setSessions((prev) => prev.filter((s) => s.sessionId !== sessionId));- },- [adjustCount],+ const { pageState, countsByAgent } = state;+ const isLoadedFor = useCallback(+ (agentId: string, category: SessionCategory) => pageState.has(pageKey(agentId, category)),+ [pageState],);- const replace = useCallback(- (session: SessionInfo) => {- // An archive toggle moves the row across categories: keep the folder totals in step.- const old = sessionsRef.current.find((s) => s.sessionId === session.sessionId);- if (old && sessionCategory(old) !== sessionCategory(session)) {- adjustCount(session, sessionCategory(old), -1);- adjustCount(session, sessionCategory(session), 1);- }- setSessions((prev) => prev.map((s) => (s.sessionId === session.sessionId ? session : s)));+ const hasMoreFor = useCallback(+ (agentId: string, category: SessionCategory) => {+ const position = pageState.get(pageKey(agentId, category));+ if (position !== undefined) return position.hasMore;+ // Unloaded pair: anything the counts report is by definition still unfetched.+ return (countsByAgent.get(agentId)?.[category] ?? 0) > 0;},- [adjustCount],+ [pageState, countsByAgent],);- const setStatus = useCallback((sessionId: string, status: SessionStatus) => {- setSessions((prev) => {- const target = prev.find((s) => s.sessionId === sessionId);- if (!target || target.status === status) return prev;- return prev.map((s) => (s.sessionId === sessionId ? { ...s, status } : s));- });- }, []);-- const setTitle = useCallback((sessionId: string, title: string) => {- setSessions((prev) => prev.map((s) => (s.sessionId === sessionId ? { ...s, title } : s)));- }, []);-const value = useMemo<SessionsContextValue>(() => {const byAgent = new Map<string, SessionInfo[]>();- for (const s of sessions) {+ for (const s of state.sessions) {const list = byAgent.get(s.agentId);if (list) list.push(s);else byAgent.set(s.agentId, [s]);@@ -427,40 +452,24 @@ export function SessionsProvider({ children }: { children: ReactNode }) {);}return {- sessions,+ sessions: state.sessions,byAgent,- countsByAgent,- workspaceCountsByAgent,+ countsByAgent: state.countsByAgent,+ workspaceCountsByAgent: state.workspaceCountsByAgent,isLoadedFor,hasMoreFor,- loading,- reload,- loadMoreFor,- add,- remove,- replace,- setStatus,- setTitle,- showCliSessions,- setShowCliSessions,+ loading: state.loading,+ reload: state.reload,+ loadMoreFor: state.loadMoreFor,+ add: state.add,+ remove: state.remove,+ replace: state.replace,+ setStatus: state.setStatus,+ setTitle: state.setTitle,+ showCliSessions: state.showCliSessions,+ setShowCliSessions: state.setShowCliSessions,};- }, [- sessions,- countsByAgent,- workspaceCountsByAgent,- isLoadedFor,- hasMoreFor,- loading,- reload,- loadMoreFor,- add,- remove,- replace,- setStatus,- setTitle,- showCliSessions,- setShowCliSessions,- ]);+ }, [state, isLoadedFor, hasMoreFor]);return <SessionsContext.Provider value={value}>{children}</SessionsContext.Provider>;}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b09172ec..a2b4e41c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -348,6 +348,9 @@ importers:shiki:specifier: ^4.3.1version: 4.3.1+ zustand:+ specifier: ^5.0.15+ version: 5.0.15(@types/[email protected])([email protected])devDependencies:'@playwright/test':specifier: ^1.61.1@@ -1495,6 +1498,7 @@ packages:'@xmldom/[email protected]':resolution: {integrity: sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==}engines: {node: '>=10.0.0'}+ deprecated: this version has critical issues, please update to the latest versionresolution: {integrity: sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==}@@ -3689,6 +3693,24 @@ packages:resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}+ resolution: {integrity: sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A==}+ engines: {node: '>=12.20.0'}+ peerDependencies:+ '@types/react': '>=18.0.0'+ immer: '>=9.0.6'+ react: '>=18.0.0'+ use-sync-external-store: '>=1.2.0'+ peerDependenciesMeta:+ '@types/react':+ optional: true+ immer:+ optional: true+ react:+ optional: true+ use-sync-external-store:+ optional: true+resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}@@ -7662,4 +7684,9 @@ snapshots:+ optionalDependencies:+ '@types/react': 19.2.17+ react: 19.2.7+