Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(ui): mobile-responsive workbench + shared workbench data hooks (#406)

Call White8a98be1d6084
diff --git a/docs/plans/workbench-shared-hooks.md b/docs/plans/workbench-shared-hooks.md
new file mode 100644
index 000000000..f94531a28
--- /dev/null
+++ b/docs/plans/workbench-shared-hooks.md
@@ -0,0 +1,52 @@
+# Refactor: shared workbench data hooks (kill the parallel reimplementations)
+
+## Why
+`ProjectsPage` + `NewSessionSheet` (mobile) re-derived logic that already exists in
+`WorkbenchSidebar` (projects/sessions load, SSE status/title, paging, dedup, reconnect,
+unread, mark-read) and `Workbench.tsx` (create+navigate+draft). ~15 of ~25 Codex P2s on
+PRs #402/#406 were re-deriving behavior the desktop already had — a reuse-ladder/DRY miss.
+Root fix: extract shared logic; desktop + mobile consume one source of truth.
+
+## Hook A — `WorkbenchProjectsProvider` / `useWorkbenchProjectsTree` (CONTEXT PROVIDER)
+Mounted once at app root next to `WorkbenchInboxProvider` (`App.tsx`). A provider (not a plain
+hook) because `WorkbenchSidebar` is ALWAYS mounted (`md:flex` is CSS-only) and `ProjectsPage`
+mounts on `/projects` — today that's **two** `connectWorkbenchEvents` subscriptions + duplicate
+fetches on mobile. One provider = one EventSource, one cache, one reconcile (mirrors
+`WorkbenchInboxContext`).
+
+API: `projects`, `projectsError`, `refreshProjects`; `sessionsOf(id) → {sessions|null, loading,
+loadingMore, cursor, error}`, `isExpanded`, `expanded`, `toggleExpanded`, `loadMore`;
+`createSessionForProject(id) → WorkbenchSession|null` (optimistic prepend + expand; **returns**
+the session, does NOT navigate), `creatingSession(id)`, `renameProject`, `archiveProject`,
+`renameSession`, `upsertProjectToTop(project)`.
+
+- **Navigation MUST stay in consumers** — the provider is mounted OUTSIDE `<BrowserRouter>`
+ (App.tsx puts BrowserRouter inside WorkbenchInboxProvider), so it cannot call `useNavigate`.
+- **Memoize the `value`** (`useMemo` + `useCallback`) — the iOS-Safari re-render lesson
+ ([[feedback_react_context_value_memoize]]).
+- Unify `PAGE_SIZE` (sidebar 10 vs mobile 50 — pick one), adopt the chunked `reconcileSessions`
+ (mobile's, correct for >200-row windows clamp), standardize SSE patching on scan-by-`session_id`.
+- Preserve the `createSessionForProject` "don't seed a 1-item cache when project unloaded" subtlety.
+- Keep `error: boolean` per-project state (mobile retry needs it; desktop ignores it).
+- Unread stays in `WorkbenchInboxContext` (both already read it directly).
+
+Consumers: `WorkbenchSidebar` keeps ALL its JSX (popover, SessionRow/ProjectRow, context menus,
+rename/archive UI, capabilities nav, brand) + inbox-popover hover machinery; its data layer moves
+to the provider. `ProjectsPage` replaces its whole data layer with `useWorkbenchProjectsTree()`,
+keeps its mobile JSX + `openSession` (markRead+navigate).
+
+## Hook B — `useNewSession` (PLAIN HOOK)
+Home (`/`) and the sheet (modal) are never usefully co-mounted + no live data → plain hook.
+API: `projects` (sorted), `loaded`, `error`, `sending`, `selectedId`/`setSelected`, `target`,
+`needsProject`, `send(text) → {sessionId, initialMessage}|null` (returns nav target, consumer
+navigates), `upsertSelectProject(project)`, `reset()`. Option `active` (sheet passes `open`) to
+re-run load+reset on the open rising-edge with a cancel guard.
+- Draft stash + Radix close-before-open dialog stay in the SHEET (lifecycle, not create-flow).
+- Home's "no project → NewProjectDialog" nudge stays in the consumer (check `needsProject`).
+
+## Order / status
+1. Hook B (`lib/useNewSession.ts`) + refactor `Workbench.tsx` + `NewSessionSheet.tsx`. ← safer, first
+2. Hook A (`context/WorkbenchProjectsContext.tsx`) + mount in App.tsx + refactor
+ `WorkbenchSidebar` + `ProjectsPage`. ← bigger, central; verify both surfaces.
+3. `npm run build` green each step; push onto the #406 branch; Codex re-review (incl. sidebar);
+ fix to approval; then merge #406.
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 3c7ebc5df..92c676e0a 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -29,6 +29,7 @@ import { ApiProvider, useApi, ApiError } from './context/ApiContext';
import { ToastProvider } from './context/ToastContext';
import { ThemeProvider } from './context/ThemeContext';
import { WorkbenchInboxProvider } from './context/WorkbenchInboxContext';
+import { WorkbenchProjectsProvider } from './context/WorkbenchProjectsContext';
import { AgentationToggle } from './components/AgentationToggle';
import { useEffect, useState } from 'react';
import type { ReactNode } from 'react';
@@ -290,10 +291,12 @@ function App() {
<ToastProvider>
<ApiProvider>
<WorkbenchInboxProvider>
- <BrowserRouter>
- <AppRoutes />
- </BrowserRouter>
- <AgentationToggle />
+ <WorkbenchProjectsProvider>
+ <BrowserRouter>
+ <AppRoutes />
+ </BrowserRouter>
+ <AgentationToggle />
+ </WorkbenchProjectsProvider>
</WorkbenchInboxProvider>
</ApiProvider>
</ToastProvider>
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 70a2c6ca4..a4c7e3675 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -12,6 +12,8 @@ import { LanguageSwitcher } from './LanguageSwitcher';
import { ThemeToggle } from './ThemeToggle';
import { VersionBadge } from './VersionBadge';
import { WorkbenchSidebar } from './workbench/WorkbenchSidebar';
+import { NewSessionSheet } from './workbench/NewSessionSheet';
+import { Button } from './ui/button';
import logoImg from '../assets/logo.png';
import { getEnabledPlatforms, platformSupportsChannels } from '../lib/platforms';
@@ -72,7 +74,7 @@ const MobileNavLink: React.FC<{ item: ShellNavItem }> = ({ item }) => {
);
};
-type CenterButton = { to: string; label: string; icon: React.ComponentType<{ className?: string }> };
+type CenterButton = { label: string; icon: React.ComponentType<{ className?: string }>; to?: string; onClick?: () => void };
// Mobile bottom tab bar shared by both shells. Section tabs flank a raised
// center FAB. Workbench: center = + (new session). Control Panel: center =
@@ -88,13 +90,27 @@ const MobileTabBar: React.FC<{ items: ShellNavItem[]; center: CenterButton }> =
<div className="flex items-end justify-between gap-1">
{left.map((item) => <MobileNavLink key={item.to} item={item} />)}
<div className="flex flex-1 justify-center">
- <Link
- to={center.to}
- aria-label={center.label}
- className="grid size-12 -translate-y-1 place-items-center rounded-full bg-mint text-background shadow-[0_8px_20px_-4px_rgba(91,255,160,0.6)] transition active:scale-95"
- >
- <CenterIcon className="size-6" />
- </Link>
+ {center.onClick ? (
+ <Button
+ type="button"
+ variant="brand"
+ onClick={center.onClick}
+ aria-label={center.label}
+ className="size-12 -translate-y-1 rounded-full p-0 shadow-[0_8px_20px_-4px_rgba(91,255,160,0.6)]"
+ >
+ <CenterIcon className="size-6" />
+ </Button>
+ ) : (
+ <Button
+ asChild
+ variant="brand"
+ className="size-12 -translate-y-1 rounded-full p-0 shadow-[0_8px_20px_-4px_rgba(91,255,160,0.6)]"
+ >
+ <Link to={center.to ?? '/'} aria-label={center.label}>
+ <CenterIcon className="size-6" />
+ </Link>
+ </Button>
+ )}
</div>
{right.map((item) => <MobileNavLink key={item.to} item={item} />)}
</div>
@@ -110,6 +126,7 @@ export const AppShell: React.FC = () => {
const location = useLocation();
const [enabledPlatforms, setEnabledPlatforms] = useState<string[]>([]);
const [config, setConfig] = useState<any>(null);
+ const [newSessionOpen, setNewSessionOpen] = useState(false);
useEffect(() => {
api.getConfig().then((c: any) => {
@@ -267,7 +284,7 @@ export const AppShell: React.FC = () => {
</div>
</aside>
- <header className="sticky top-0 z-40 flex h-16 items-center justify-between gap-2 border-b border-border bg-background/92 px-4 backdrop-blur md:hidden">
+ <header className="sticky top-0 z-40 flex h-[calc(4rem+env(safe-area-inset-top))] items-center justify-between gap-2 border-b border-border bg-background/92 px-4 pt-[env(safe-area-inset-top)] backdrop-blur md:hidden">
<div className="flex min-w-0 items-center gap-2">
<img
src={logoImg}
@@ -305,10 +322,16 @@ export const AppShell: React.FC = () => {
) : (
<MobileTabBar
items={workbenchTabs}
- center={{ to: '/', label: t('appShell.newSession'), icon: Plus }}
+ center={{ onClick: () => setNewSessionOpen(true), label: t('appShell.newSession'), icon: Plus }}
/>
)
)}
+
+ <NewSessionSheet
+ open={newSessionOpen}
+ onClose={() => setNewSessionOpen(false)}
+ onOpen={() => setNewSessionOpen(true)}
+ />
</div>
);
};
diff --git a/ui/src/components/Workbench.tsx b/ui/src/components/Workbench.tsx
index 314cf9be6..e5b804928 100644
--- a/ui/src/components/Workbench.tsx
+++ b/ui/src/components/Workbench.tsx
@@ -1,10 +1,9 @@
-import { useCallback, useEffect, useState } from 'react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { Activity, Bot, FolderPlus, Sparkles } from 'lucide-react';
-import { useApi } from '../context/ApiContext';
-import type { WorkbenchProject } from '../context/ApiContext';
+import { useNewSession } from '../lib/useNewSession';
import { NewProjectDialog } from './workbench/NewProjectDialog';
import { Composer } from './workbench/Composer';
@@ -13,72 +12,31 @@ import { Composer } from './workbench/Composer';
// wired to create a new session under the most-recently-active project using
// the default backend, then routes to /chat/<id> with the typed message
// pre-seeded. No project? The send surfaces the NewProjectDialog so the user
-// gets unstuck without bouncing pages.
+// gets unstuck without bouncing pages. The create flow lives in the shared
+// useNewSession hook — one source of truth with the mobile NewSessionSheet.
export const Workbench: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
- const api = useApi();
- const [projects, setProjects] = useState<WorkbenchProject[] | null>(null);
- const [sending, setSending] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [newProjectOpen, setNewProjectOpen] = useState(false);
-
- // Load projects so we know whether the Composer can fire directly or needs
- // to nudge the user to create one first.
- useEffect(() => {
- let cancelled = false;
- api
- .listProjects()
- .then((result) => {
- if (!cancelled) setProjects(result.projects);
- })
- .catch(() => {
- if (!cancelled) setProjects([]);
- });
- return () => {
- cancelled = true;
- };
- }, [api]);
-
- const sortedProjects = (projects ?? []).slice().sort((a, b) => {
- const aTs = a.last_active_at || a.created_at;
- const bTs = b.last_active_at || b.created_at;
- return bTs.localeCompare(aTs);
+ const ns = useNewSession({
+ loadErrorText: t('newSession.loadError'),
+ createFailedText: t('newSession.createFailed'),
});
- const targetProject = sortedProjects[0] || null;
- const hasProjects = !!targetProject;
+ const [newProjectOpen, setNewProjectOpen] = useState(false);
// Returns whether the send actually started, so the Composer only clears the
// box on a real start — a no-project nudge or a transient create error keeps
- // the typed prompt for retry (Codex P2).
- const send = useCallback(
- async (text: string): Promise<boolean> => {
- const trimmed = text.trim();
- if (!trimmed || sending) return false;
- if (!targetProject) {
- setNewProjectOpen(true);
- return false;
- }
- setSending(true);
- setError(null);
- try {
- // Omit agent_backend so the server routes the new chat through the
- // configured agents.default_backend rather than a hard-coded one.
- const session = await api.createSession({ project_id: targetProject.id });
- // Hand the typed message to ChatPage as router state; it replays it
- // through the fire-and-forget compose path so the agent turn starts.
- navigate(`/chat/${encodeURIComponent(session.id)}`, {
- state: { initialMessage: trimmed },
- });
- return true;
- } catch (err: any) {
- setError(err?.message ?? String(err));
- setSending(false);
- return false;
- }
- },
- [api, navigate, sending, targetProject],
- );
+ // the typed prompt for retry. Navigation stays here (the hook is router-free).
+ const send = async (text: string): Promise<boolean> => {
+ const result = await ns.send(text);
+ if (result) {
+ // Hand the typed message to ChatPage as router state; it replays it
+ // through the fire-and-forget compose path so the agent turn starts.
+ navigate(`/chat/${encodeURIComponent(result.sessionId)}`, { state: { initialMessage: result.initialMessage } });
+ return true;
+ }
+ if (text.trim() && ns.needsProject) setNewProjectOpen(true);
+ return false;
+ };
// Quick chips under the hero — three of the most common first moves.
const suggestions = [
@@ -122,15 +80,15 @@ export const Workbench: React.FC = () => {
<Composer
onSend={send}
placeholder={t('workbench.canvas.inputPlaceholder')}
- disabled={sending}
+ disabled={ns.sending}
className="max-w-[640px]"
/>
- {projects !== null && !hasProjects && (
+ {ns.needsProject && (
<div className="px-2 text-[10.5px] text-gold">{t('workbench.canvas.noProjectForChat')}</div>
)}
- {error && (
+ {ns.error && (
<div className="mt-1 rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive">
- {error}
+ {ns.error}
</div>
)}
</div>
@@ -140,14 +98,9 @@ export const Workbench: React.FC = () => {
onClose={() => setNewProjectOpen(false)}
onCreated={(project) => {
setNewProjectOpen(false);
- // create_project is find-or-create by path: this may return an
- // already-tracked project, refreshed. Drop any stale copy and hoist
- // the fresh one to the top so the "most recent" target reflects the
- // folder just opened.
- setProjects((prev) => {
- if (!prev) return [project];
- return [project, ...prev.filter((p) => p.id !== project.id)];
- });
+ // create_project is find-or-create by path: dedup + hoist to top so the
+ // "most recent" target reflects the folder just opened.
+ ns.upsertSelectProject(project);
}}
/>
)}
diff --git a/ui/src/components/ui/dialog.tsx b/ui/src/components/ui/dialog.tsx
index 63aa34fe2..889118967 100644
--- a/ui/src/components/ui/dialog.tsx
+++ b/ui/src/components/ui/dialog.tsx
@@ -33,14 +33,18 @@ export const DialogContent = React.forwardRef<
<DialogPrimitive.Content
ref={ref}
className={cn(
- // Mobile: keep a small gutter (w-calc) and cap height so a tall dialog
- // scrolls inside the viewport instead of overflowing off the top/bottom
- // of a short phone screen. sm+ restores the full-width-capped centered card.
- 'fixed left-1/2 top-1/2 z-50 grid max-h-[calc(100dvh-2rem)] w-[calc(100%-1.5rem)] max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 overflow-y-auto rounded-xl border border-border bg-card p-6 shadow-xl sm:w-full data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
+ // Desktop: centered modal. Mobile (max-md): a bottom sheet — full-width,
+ // slides up from the bottom edge, rounded top + drag handle, capped height
+ // with internal scroll and a safe-area bottom inset. A caller's custom
+ // max-w (e.g. max-w-sm) still applies on desktop; max-md:max-w-none forces
+ // the full-width sheet on phones.
+ 'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 overflow-y-auto rounded-xl border border-border bg-card p-6 shadow-xl data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0 data-[state=open]:zoom-in-95 data-[state=closed]:zoom-out-95 max-md:left-0 max-md:right-0 max-md:top-auto max-md:bottom-0 max-md:w-full max-md:max-w-none max-md:max-h-[88dvh] max-md:translate-x-0 max-md:translate-y-0 max-md:rounded-2xl max-md:rounded-b-none max-md:p-5 max-md:pb-[calc(1.5rem+env(safe-area-inset-bottom))] max-md:data-[state=open]:zoom-in-100 max-md:data-[state=closed]:zoom-out-100 max-md:data-[state=open]:slide-in-from-bottom max-md:data-[state=closed]:slide-out-to-bottom',
className
)}
{...props}
>
+ {/* Bottom-sheet drag handle — mobile only. */}
+ <div className="mx-auto h-1.5 w-10 shrink-0 rounded-full bg-border-strong md:hidden" aria-hidden />
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-md p-1 text-muted opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring">
<X className="size-4" />
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index 999bf2c7a..e931a64d3 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -69,6 +69,9 @@ export const AgentsPage: React.FC = () => {
const [search, setSearch] = useState('');
const [backendFilter, setBackendFilter] = useState<Backend | 'all'>('all');
const [importing, setImporting] = useState<Backend | null>(null);
+ // Mobile drill-down: a row tap opens the detail full-screen. The agent
+ // auto-selected on mount stays in the list view until the user drills in.
+ const [detailOpen, setDetailOpen] = useState(false);
const refresh = useCallback(async () => {
setLoading(true);
@@ -104,11 +107,23 @@ export const AgentsPage: React.FC = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [defaultName, agents]);
+ // If the selection clears (agent deleted, or a refresh dropped it) drop the
+ // mobile drill state too — otherwise the list stays max-lg:hidden with no
+ // detail rendered, leaving the page blank with no way back.
+ useEffect(() => {
+ if (!selected) setDetailOpen(false);
+ }, [selected]);
+
const selectAgent = useCallback(
- async (name: string) => {
+ async (name: string, openDetail = false) => {
try {
const result = await api.getVibeAgent(name);
- if (result.ok) setSelected(result.agent);
+ if (result.ok) {
+ setSelected(result.agent);
+ // Enter the mobile drill-down only once the detail has actually loaded —
+ // never optimistically, or a failed fetch hides the list with no panel.
+ if (openDetail) setDetailOpen(true);
+ }
} catch (err: any) {
setError(err?.message ?? String(err));
}
@@ -243,7 +258,7 @@ export const AgentsPage: React.FC = () => {
/>
{/* Toolbar — design.pen Imduv: search + backend filter + spacer + Import + 新建 Agent */}
- <div className="flex flex-wrap items-center gap-2.5">
+ <div className={clsx('flex flex-wrap items-center gap-2.5', detailOpen && 'max-lg:hidden')}>
<div className="flex h-9 w-full items-center gap-2 rounded-md border border-input bg-background px-3 transition-colors focus-within:border-ring focus-within:ring-2 focus-within:ring-ring sm:w-[320px]">
<Search className="size-3.5 shrink-0 text-muted" />
<input
@@ -285,7 +300,7 @@ export const AgentsPage: React.FC = () => {
selected ? 'grid-cols-1 lg:grid-cols-[minmax(0,1fr)_420px]' : 'grid-cols-1',
)}
>
- <div className="flex min-w-0 flex-col gap-4">
+ <div className={clsx('flex min-w-0 flex-col gap-4', detailOpen && 'max-lg:hidden')}>
{BACKEND_ORDER.map((backend) => {
const items = grouped[backend];
if (!items || items.length === 0) return null;
@@ -307,7 +322,7 @@ export const AgentsPage: React.FC = () => {
agent={agent}
isSelected={selected?.name === agent.name}
isDefault={defaultName === agent.name}
- onSelect={() => selectAgent(agent.name)}
+ onSelect={() => selectAgent(agent.name, true)}
/>
))}
</div>
@@ -334,7 +349,7 @@ export const AgentsPage: React.FC = () => {
</div>
{selected && (
- <div className="self-start rounded-2xl border border-border-strong bg-surface p-5">
+ <div className={clsx('self-start rounded-2xl border border-border-strong bg-surface p-5', !detailOpen && 'max-lg:hidden')}>
<AgentDetailPanel
agent={selected}
isDefault={defaultName === selected.name}
@@ -342,7 +357,7 @@ export const AgentsPage: React.FC = () => {
onSetDefault={onSetDefault}
onRenamed={onRenamed}
onDelete={onDelete}
- onClose={() => setSelected(null)}
+ onClose={() => { setSelected(null); setDetailOpen(false); }}
/>
</div>
)}
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index 153a859ac..440f7cfaa 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
+ ArrowLeft,
Activity,
Calendar,
Eye,
@@ -419,7 +420,7 @@ export const HarnessPage: React.FC = () => {
hasSelection ? 'grid-cols-1 lg:grid-cols-[minmax(0,1fr)_440px]' : 'grid-cols-1',
)}
>
- <div className="flex min-w-0 flex-col gap-2">
+ <div className={clsx('flex min-w-0 flex-col gap-2', hasSelection && 'max-lg:hidden')}>
{tab === 'tasks' && (
<TasksList
tasks={filteredTasks}
@@ -458,6 +459,16 @@ export const HarnessPage: React.FC = () => {
{hasSelection && (
<div className="flex min-w-0 flex-col gap-3 self-start rounded-xl border border-border-strong bg-surface p-5">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setSelection(null)}
+ className="-mt-1 h-auto gap-1.5 self-start px-0 text-[12px] font-medium text-muted hover:bg-transparent hover:text-foreground lg:hidden"
+ >
+ <ArrowLeft className="size-3.5" />
+ {t('common.back')}
+ </Button>
{selectedTask ? (
<TaskDetail
task={selectedTask}
diff --git a/ui/src/components/workbench/NewSessionSheet.tsx b/ui/src/components/workbench/NewSessionSheet.tsx
new file mode 100644
index 000000000..f270af086
--- /dev/null
+++ b/ui/src/components/workbench/NewSessionSheet.tsx
@@ -0,0 +1,150 @@
+import { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { useTranslation } from 'react-i18next';
+import { Folder, FolderOpen, FolderPlus } from 'lucide-react';
+import clsx from 'clsx';
+
+import { useNewSession } from '../../lib/useNewSession';
+import { Dialog, DialogContent, DialogTitle } from '../ui/dialog';
+import { Button } from '../ui/button';
+import { Composer } from './Composer';
+import { NewProjectDialog } from './NewProjectDialog';
+
+interface NewSessionSheetProps {
+ open: boolean;
+ onClose: () => void;
+ onOpen: () => void;
+}
+
+// The workbench center + opens this instead of jumping to the home canvas.
+// Pick a project (chips, most-recent first), describe the task, and it creates
+// the session + routes to /chat with the message pre-seeded — the same flow as
+// the desktop Workbench home, surfaced as a mobile bottom sheet (design.pen KSXXB).
+// The create flow itself lives in the shared useNewSession hook (one source of
+// truth with the home); the sheet only owns its open/close + draft lifecycle.
+export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose, onOpen }) => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ // active: open → the hook reloads + resets per-open (the sheet is permanently
+ // mounted by AppShell, so stale submit/error state must not leak across opens).
+ const ns = useNewSession({
+ active: open,
+ loadErrorText: t('newSession.loadError'),
+ createFailedText: t('newSession.createFailed'),
+ });
+ // Stashed prompt: the no-project path closes the sheet (unmounting the
+ // Composer) to create a project, so we hold the typed text and re-seed it
+ // when the sheet reopens, instead of losing it.
+ const [pendingDraft, setPendingDraft] = useState('');
+ const [newProjectOpen, setNewProjectOpen] = useState(false);
+
+ // Close the sheet first, THEN open the project dialog: the parent Radix Dialog
+ // traps focus/pointer to its own content, so a NewProjectDialog rendered while
+ // the sheet is open would be unreachable. Sheet closed → no trap → accessible.
+ const openNewProject = () => {
+ // Don't tear down the sheet for project creation while a session create is
+ // in flight — the pending success would still navigate, stranding the
+ // project modal over the new chat.
+ if (ns.sending) return;
+ onClose();
+ setNewProjectOpen(true);
+ };
+
+ const send = async (text: string): Promise<boolean> => {
+ const result = await ns.send(text);
+ if (result) {
+ setPendingDraft('');
+ onClose();
+ navigate(`/chat/${encodeURIComponent(result.sessionId)}`, { state: { initialMessage: result.initialMessage } });
+ return true;
+ }
+ // No project to target → stash the prompt and route to the New Project flow.
+ const trimmed = text.trim();
+ if (trimmed && ns.needsProject) {
+ setPendingDraft(trimmed);
+ openNewProject();
+ }
+ return false;
+ };
+
+ return (
+ <>
+ <Dialog open={open} onOpenChange={(o) => { if (!o && !ns.sending) onClose(); }}>
+ <DialogContent className="gap-5" onOpenAutoFocus={(e) => e.preventDefault()}>
+ <DialogTitle className="text-lg font-bold">{t('newSession.title')}</DialogTitle>
+
+ <div className="flex flex-col gap-2">
+ <div className="font-mono text-[11px] font-bold uppercase tracking-[0.08em] text-muted">
+ {t('newSession.project')}
+ </div>
+ <div className="flex flex-wrap gap-2">
+ {ns.projects.slice(0, 6).map((project) => {
+ const active = project.id === ns.target?.id;
+ return (
+ <Button
+ key={project.id}
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => ns.setSelected(project.id)}
+ disabled={ns.sending}
+ className={clsx(
+ 'h-auto gap-1.5 rounded-full px-3 py-1.5 text-[12.5px] font-medium',
+ active ? 'border-mint/40 bg-mint-soft text-mint hover:bg-mint-soft hover:text-mint' : 'text-foreground',
+ )}
+ >
+ {active ? <FolderOpen className="size-3.5" /> : <Folder className="size-3.5" />}
+ <span className="max-w-[140px] truncate">{project.display_name}</span>
+ </Button>
+ );
+ })}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={openNewProject}
+ disabled={ns.sending}
+ className="h-auto gap-1.5 rounded-full px-3 py-1.5 text-[12.5px] font-medium text-muted"
+ >
+ <FolderPlus className="size-3.5" />
+ {t('newSession.newProject')}
+ </Button>
+ </div>
+ </div>
+
+ {ns.error && (
+ <div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive">
+ {ns.error}
+ </div>
+ )}
+
+ {/* Disabled until projects load successfully, so a failed reload can't
+ create a session under a stale/removed cached project. initialDraft
+ re-seeds a prompt stashed when the no-project flow closed the sheet. */}
+ <Composer
+ onSend={send}
+ placeholder={t('newSession.placeholder')}
+ disabled={ns.sending || !ns.loaded}
+ initialDraft={pendingDraft}
+ />
+ </DialogContent>
+ </Dialog>
+
+ {/* Sibling of the sheet's Dialog (and opened only after the sheet closes)
+ so the parent modal's focus trap can't make the folder picker / confirm
+ step unreachable on mobile. */}
+ {newProjectOpen && (
+ <NewProjectDialog
+ onClose={() => setNewProjectOpen(false)}
+ onCreated={(project) => {
+ setNewProjectOpen(false);
+ ns.upsertSelectProject(project);
+ // Reopen the sheet so the user continues the new-session flow with the
+ // freshly created project selected, instead of having to tap + again.
+ onOpen();
+ }}
+ />
+ )}
+ </>
+ );
+};
diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsx
index 068013ded..0f38aadc8 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -1,12 +1,11 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ChevronDown, ChevronRight, Folder, FolderOpen, FolderPlus, Loader2, RotateCw } from 'lucide-react';
import clsx from 'clsx';
-import { useApi } from '../../context/ApiContext';
-import type { WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
+import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { formatRelativeTime } from '../../lib/relativeTime';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
@@ -18,217 +17,37 @@ const DOT: Record<string, string> = {
idle: 'bg-muted',
};
-const PAGE_SIZE = 50;
-
-// Per-project session list: tracks paging cursor + load status so a transient
-// failure can be retried (not cached as an empty list) and projects with >50
-// active sessions can page in the rest — mirroring the desktop sidebar.
-type SessionState = {
- status: 'loading' | 'loaded' | 'error';
- sessions: WorkbenchSession[];
- nextBeforeId: string | null;
-};
-
-// Mobile-only "Projects" tab (workbench). The desktop projects tree
-// (WorkbenchSidebar) flattened into a full-page accordion: tap a project to
-// expand its sessions, tap a session to open the chat. Design: design.pen `FW7cI`.
+// Mobile-only "Projects" tab (workbench): the desktop projects tree
+// (WorkbenchSidebar) flattened into a full-page accordion — tap a project to
+// expand its sessions, tap a session to open the chat. It shares the same data
+// provider (useWorkbenchProjectsTree) as the sidebar, so loading / paging / SSE
+// status+title / reconnect-reconcile / dedupe are one source of truth rather
+// than a parallel reimplementation. Design: design.pen `FW7cI`.
export const ProjectsPage: React.FC = () => {
const { t } = useTranslation();
- const api = useApi();
const navigate = useNavigate();
const { markRead, unreadBySession } = useWorkbenchInbox();
- const [projects, setProjects] = useState<WorkbenchProject[]>([]);
- const [expanded, setExpanded] = useState<Set<string>>(new Set());
- const [sessions, setSessions] = useState<Record<string, SessionState>>({});
+ const {
+ projects,
+ projectsError,
+ refreshProjects,
+ sessionsOf,
+ isExpanded,
+ toggleExpanded,
+ loadMore,
+ reloadSessions,
+ upsertProjectToTop,
+ } = useWorkbenchProjectsTree();
const [showNewProject, setShowNewProject] = useState(false);
- const expandedRef = useRef<Set<string>>(new Set());
- const sessionsRef = useRef<Record<string, SessionState>>({});
- const [projectsError, setProjectsError] = useState(false);
-
- const fetchProjects = useCallback(async () => {
- setProjectsError(false);
- try {
- const res = await api.listProjects();
- setProjects(res.projects);
- } catch {
- // Don't strand the user on an empty-state for a transient failure —
- // surface a retry instead of a false "No projects yet".
- setProjectsError(true);
- }
- }, [api]);
-
- useEffect(() => {
- void fetchProjects();
- }, [fetchProjects]);
-
- // Load (or page) a project's sessions. `beforeId` appends the next page;
- // omitting it loads the first page. On failure we store status:'error' WITHOUT
- // an empty list so the user can retry (re-expand or the Retry button) instead
- // of being stuck on a permanent "No sessions".
- const loadSessions = useCallback(
- async (projectId: string, beforeId?: string) => {
- setSessions((prev) => {
- const cur = prev[projectId];
- return {
- ...prev,
- [projectId]: {
- status: 'loading',
- sessions: cur?.sessions ?? [],
- nextBeforeId: cur?.nextBeforeId ?? null,
- },
- };
- });
- try {
- const res = await api.listSessions({ projectId, status: 'active', limit: PAGE_SIZE, beforeId });
- setSessions((prev) => {
- const existing = beforeId ? prev[projectId]?.sessions ?? [] : [];
- // Dedupe against already-loaded ids: a page can overlap if a session's
- // last_active_at shifts between requests or Load more is double-tapped.
- const seen = new Set(existing.map((s) => s.id));
- const merged = [...existing, ...res.sessions.filter((s) => !seen.has(s.id))];
- return {
- ...prev,
- [projectId]: { status: 'loaded', sessions: merged, nextBeforeId: res.next_before_id },
- };
- });
- } catch {
- setSessions((prev) => ({
- ...prev,
- [projectId]: {
- status: 'error',
- sessions: prev[projectId]?.sessions ?? [],
- nextBeforeId: prev[projectId]?.nextBeforeId ?? null,
- },
- }));
- }
- },
- [api],
- );
-
- const toggle = useCallback(
- (projectId: string) => {
- setExpanded((prev) => {
- const next = new Set(prev);
- next.has(projectId) ? next.delete(projectId) : next.add(projectId);
- return next;
- });
- // Fetch on first expand or after a prior failure; a successful load is cached.
- const cur = sessions[projectId];
- if (!cur || cur.status === 'error') void loadSessions(projectId);
- },
- [sessions, loadSessions],
- );
-
- const openSession = useCallback(
- (sessionId: string) => {
- // Opening a chat marks it read everywhere (matches the desktop tree + Inbox),
- // so unread badges/counts don't linger after a mobile drill-in.
- void markRead(sessionId);
- navigate(`/chat/${sessionId}`);
- },
- [markRead, navigate],
- );
-
- useEffect(() => {
- expandedRef.current = expanded;
- }, [expanded]);
- useEffect(() => {
- sessionsRef.current = sessions;
- }, [sessions]);
+ const openSession = (sessionId: string) => {
+ // Opening a chat marks it read everywhere (matches the desktop tree + Inbox),
+ // so unread badges/counts don't linger after a mobile drill-in.
+ void markRead(sessionId);
+ navigate(`/chat/${sessionId}`);
+ };
- // Refetch a project's already-loaded window (not just page 1) so a reconnect
- // preserves paged-in rows instead of collapsing back to the first page.
- const reconcileSessions = useCallback(
- async (projectId: string, targetCount: number) => {
- try {
- // Page in PAGE_SIZE chunks until the previously-loaded window is rebuilt.
- // The server clamps /api/sessions limit to 200, so a single large
- // request would silently truncate windows >200 rows on reconnect.
- const acc: WorkbenchSession[] = [];
- const seen = new Set<string>();
- let before: string | undefined;
- let nextBeforeId: string | null = null;
- do {
- const res = await api.listSessions({ projectId, status: 'active', limit: PAGE_SIZE, beforeId: before });
- for (const s of res.sessions) {
- if (!seen.has(s.id)) {
- seen.add(s.id);
- acc.push(s);
- }
- }
- nextBeforeId = res.next_before_id;
- before = res.next_before_id ?? undefined;
- } while (before && acc.length < targetCount);
- setSessions((prev) => ({
- ...prev,
- [projectId]: { status: 'loaded', sessions: acc, nextBeforeId },
- }));
- } catch {
- /* keep the current window on a failed reconcile */
- }
- },
- [api],
- );
-
- // Keep /projects live: patch a row's status dot from session.status events and
- // re-pull expanded projects on SSE reconnect, so dots don't go stale like a
- // one-shot listSessions would (mirrors the desktop WorkbenchSidebar).
- useEffect(() => {
- const disconnect = api.connectWorkbenchEvents({
- onSessionStatus: ({ session_id, agent_status }) => {
- setSessions((prev) => {
- let changed = false;
- const next: Record<string, SessionState> = {};
- for (const [pid, st] of Object.entries(prev)) {
- let rowChanged = false;
- const updated = st.sessions.map((s) => {
- if (s.id === session_id && s.agent_status !== agent_status) {
- rowChanged = true;
- return { ...s, agent_status };
- }
- return s;
- });
- next[pid] = rowChanged ? { ...st, sessions: updated } : st;
- if (rowChanged) changed = true;
- }
- return changed ? next : prev;
- });
- },
- onSessionActivity: (data) => {
- // A rename broadcasts session.activity {event:'updated', title}; patch the
- // cached row so the list doesn't show a stale title until remount.
- if (data.event !== 'updated' || !Object.prototype.hasOwnProperty.call(data, 'title')) return;
- const nextTitle = data.title ?? null;
- setSessions((prev) => {
- let changed = false;
- const next: Record<string, SessionState> = {};
- for (const [pid, st] of Object.entries(prev)) {
- let rowChanged = false;
- const updated = st.sessions.map((s) => {
- if (s.id === data.session_id && s.title !== nextTitle) {
- rowChanged = true;
- return { ...s, title: nextTitle };
- }
- return s;
- });
- next[pid] = rowChanged ? { ...st, sessions: updated } : st;
- if (rowChanged) changed = true;
- }
- return changed ? next : prev;
- });
- },
- onConnected: () => {
- // Refetch the already-loaded window per expanded project (not page 1),
- // so paged-in rows survive a reconnect.
- for (const pid of expandedRef.current) {
- const loaded = sessionsRef.current[pid]?.sessions.length ?? 0;
- void reconcileSessions(pid, Math.max(PAGE_SIZE, loaded));
- }
- },
- });
- return disconnect;
- }, [api, reconcileSessions]);
+ const list = projects ?? [];
return (
<div className="mx-auto flex max-w-xl flex-col gap-3">
@@ -246,38 +65,47 @@ export const ProjectsPage: React.FC = () => {
</Button>
</div>
- {projects.length === 0 && projectsError && (
+ {/* The provider often has projects cached already (it's mounted app-wide),
+ so this loading flash only shows on a genuine cold start. */}
+ {projects === null && !projectsError && (
+ <div className="flex items-center justify-center gap-2 rounded-xl border border-border bg-surface px-4 py-10 text-sm text-muted">
+ <Loader2 className="size-4 animate-spin" />
+ {t('common.loading')}
+ </div>
+ )}
+ {projectsError && list.length === 0 && (
<button
type="button"
- onClick={() => void fetchProjects()}
+ onClick={() => void refreshProjects()}
className="flex items-center justify-center gap-2 rounded-xl border border-border bg-surface px-4 py-10 text-sm text-muted transition hover:text-foreground"
>
<RotateCw className="size-4" />
{t('projects.loadFailed')}
</button>
)}
- {projects.length === 0 && !projectsError && (
+ {projects !== null && list.length === 0 && !projectsError && (
<div className="rounded-xl border border-border bg-surface px-4 py-10 text-center text-sm text-muted">
{t('projects.empty')}
</div>
)}
- {projects.map((project) => {
- const open = expanded.has(project.id);
- const state = sessions[project.id];
+ {list.map((project) => {
+ const open = isExpanded(project.id);
+ const state = sessionsOf(project.id);
+ const sessionRows = state.sessions ?? [];
return (
<div key={project.id} className="overflow-hidden rounded-xl border border-border bg-surface">
<button
type="button"
- onClick={() => toggle(project.id)}
+ onClick={() => toggleExpanded(project.id)}
className="flex w-full items-center gap-2.5 px-4 py-3.5 text-left"
>
{open ? <FolderOpen className="size-4 shrink-0 text-cyan" /> : <Folder className="size-4 shrink-0 text-muted" />}
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{project.display_name}</span>
- {state?.status === 'loaded' && (
+ {state.sessions !== null && !state.error && (
<Badge variant="secondary" className="font-mono text-[10px]">
{state.sessions.length}
- {state.nextBeforeId ? '+' : ''}
+ {state.cursor ? '+' : ''}
</Badge>
)}
{open ? <ChevronDown className="size-4 shrink-0 text-muted" /> : <ChevronRight className="size-4 shrink-0 text-muted" />}
@@ -285,26 +113,26 @@ export const ProjectsPage: React.FC = () => {
{open && (
<div className="flex flex-col gap-0.5 border-t border-border px-2 py-2">
- {state?.status === 'loading' && state.sessions.length === 0 && (
+ {state.loading && sessionRows.length === 0 && (
<div className="flex items-center justify-center gap-2 px-3 py-3 text-[13px] text-muted">
<Loader2 className="size-3.5 animate-spin" />
{t('common.loading')}
</div>
)}
- {state?.status === 'error' && state.sessions.length === 0 && (
+ {state.error && sessionRows.length === 0 && (
<button
type="button"
- onClick={() => void loadSessions(project.id)}
+ onClick={() => reloadSessions(project.id)}
className="flex items-center justify-center gap-2 rounded-lg px-3 py-3 text-[13px] text-muted transition hover:text-foreground"
>
<RotateCw className="size-3.5" />
{t('projects.loadFailed')}
</button>
)}
- {state?.status === 'loaded' && state.sessions.length === 0 && (
+ {state.sessions !== null && sessionRows.length === 0 && !state.loading && !state.error && (
<div className="px-3 py-3 text-center text-[13px] text-muted">{t('projects.noSessions')}</div>
)}
- {state?.sessions.map((session) => {
+ {sessionRows.map((session) => {
const unread = unreadBySession[session.id] ?? 0;
return (
<button
@@ -329,14 +157,14 @@ export const ProjectsPage: React.FC = () => {
</button>
);
})}
- {state?.nextBeforeId && (
+ {state.cursor && (
<button
type="button"
- onClick={() => void loadSessions(project.id, state.nextBeforeId!)}
- disabled={state.status === 'loading'}
+ onClick={() => loadMore(project.id)}
+ disabled={state.loadingMore}
className="flex items-center justify-center gap-2 rounded-lg px-3 py-2.5 text-[12px] font-medium text-cyan transition hover:bg-cyan/[0.06] disabled:opacity-50"
>
- {state.status === 'loading' ? <Loader2 className="size-3.5 animate-spin" /> : <ChevronDown className="size-3.5" />}
+ {state.loadingMore ? <Loader2 className="size-3.5 animate-spin" /> : <ChevronDown className="size-3.5" />}
{t('projects.loadMore')}
</button>
)}
@@ -349,9 +177,9 @@ export const ProjectsPage: React.FC = () => {
{showNewProject && (
<NewProjectDialog
onClose={() => setShowNewProject(false)}
- onCreated={() => {
+ onCreated={(project) => {
setShowNewProject(false);
- void fetchProjects();
+ upsertProjectToTop(project);
}}
/>
)}
diff --git a/ui/src/components/workbench/SkillsPage.tsx b/ui/src/components/workbench/SkillsPage.tsx
index 3eb265ed1..dc20dd20d 100644
--- a/ui/src/components/workbench/SkillsPage.tsx
+++ b/ui/src/components/workbench/SkillsPage.tsx
@@ -338,7 +338,7 @@ export const SkillsPage: React.FC = () => {
// shrinking and pushes the fixed detail card past the viewport edge. The
// list column itself also needs `min-w-0` for the same reason.
<div className={clsx('grid gap-5', selected ? 'lg:grid-cols-[minmax(0,1fr)_400px]' : 'grid-cols-1')}>
- <div className="flex min-w-0 flex-col gap-4">
+ <div className={clsx('flex min-w-0 flex-col gap-4', selected && 'max-lg:hidden')}>
{scope === 'global' ? (
<div className="flex flex-col gap-2">{renderRows(filtered)}</div>
) : (
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 6ff2b1611..547259005 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
import {
@@ -23,8 +23,8 @@ import {
import clsx from 'clsx';
import type { LucideIcon } from 'lucide-react';
-import { useApi } from '../../context/ApiContext';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
+import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
import { formatRelativeTime } from '../../lib/relativeTime';
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';
@@ -47,11 +47,6 @@ const CAPABILITY_NAV: CapabilityNavItem[] = [
{ to: '/vaults', i18nKey: 'workbench.nav.vaults', icon: KeyRound },
];
-// How many sessions to load per page under a project. The server caps the page
-// size and returns a cursor (next_before_id); the sidebar appends the next page
-// via the "Load more" control rather than loading every session up front.
-const SESSIONS_PAGE_SIZE = 10;
-
// 360px floating popover that opens when the user hovers the Inbox entry.
// Mirrors design.pen KmQ1L — header + a few session cards + footer "open full
// inbox" link. Pure presentational; data comes from <WorkbenchInboxProvider>.
@@ -548,282 +543,28 @@ const ProjectRow: React.FC<{
export const WorkbenchSidebar: React.FC = () => {
const { t } = useTranslation();
- const api = useApi();
const navigate = useNavigate();
const { totalUnread, unreadSessions, inboxSessions, markRead, unreadBySession } = useWorkbenchInbox();
+ // Projects/sessions tree — shared with the mobile ProjectsPage via the provider
+ // (one EventSource + one cache, not a per-component reimplementation). The
+ // sidebar owns only its inbox popover + the New Project dialog trigger.
+ const {
+ projects,
+ projectsError,
+ sessionsOf,
+ isExpanded,
+ toggleExpanded,
+ loadMore,
+ creatingSession,
+ createSessionForProject,
+ renameProject,
+ archiveProject,
+ renameSession,
+ upsertProjectToTop,
+ } = useWorkbenchProjectsTree();
const [popoverOpen, setPopoverOpen] = useState(false);
const closeTimer = useRef<number | null>(null);
-
- // Projects state
- const [projects, setProjects] = useState<WorkbenchProject[] | null>(null);
- const [projectsError, setProjectsError] = useState<string | null>(null);
- const [expanded, setExpanded] = useState<Set<string>>(new Set());
- const [sessionsByProject, setSessionsByProject] = useState<Record<string, WorkbenchSession[]>>({});
- const [sessionsLoading, setSessionsLoading] = useState<Record<string, boolean>>({});
- const [sessionsLoadingMore, setSessionsLoadingMore] = useState<Record<string, boolean>>({});
- // Cursor (server next_before_id) per project: a string means "more pages
- // exist", null means "fully loaded", absent means "not loaded yet". The ref
- // mirror lets fetchSessions read the latest cursor without going stale inside
- // its memoised closure.
- const [sessionCursor, setSessionCursor] = useState<Record<string, string | null>>({});
- const sessionCursorRef = useRef<Record<string, string | null>>({});
- // Projects with an in-flight session fetch — serialises first-page and
- // load-more calls per project so a refetch can't race or truncate an append.
- const sessionsInFlightRef = useRef<Set<string>>(new Set());
- const [creatingSession, setCreatingSession] = useState<Set<string>>(new Set());
const [showNewProject, setShowNewProject] = useState(false);
- // Mirror the set of projects whose sessions are currently loaded so the
- // (re)connect handler can refetch exactly those without re-subscribing the
- // event stream on every expand (stale-closure-safe, like cursorRef in the
- // inbox context).
- const loadedProjectsRef = useRef<string[]>([]);
- loadedProjectsRef.current = Object.keys(sessionsByProject);
- // Mirror the loaded session rows so the (re)connect reconcile can refetch the
- // SAME already-paged-in window (not just the first page) without a stale closure.
- const sessionsByProjectRef = useRef<Record<string, WorkbenchSession[]>>({});
- sessionsByProjectRef.current = sessionsByProject;
-
- const fetchProjects = useCallback(async () => {
- try {
- const result = await api.listProjects();
- setProjects(result.projects);
- setProjectsError(null);
- } catch (err: any) {
- setProjectsError(err?.message ?? String(err));
- }
- }, [api]);
-
- useEffect(() => {
- fetchProjects();
- }, [fetchProjects]);
-
- const fetchSessions = useCallback(
- async (projectId: string, opts?: { append?: boolean; reconcile?: boolean }) => {
- const append = opts?.append ?? false;
- const reconcile = opts?.reconcile ?? false;
- if (append && !sessionCursorRef.current[projectId]) return; // nothing more to load
- if (sessionsInFlightRef.current.has(projectId)) return; // serialise per project
- sessionsInFlightRef.current.add(projectId);
- if (append) {
- setSessionsLoadingMore((prev) => ({ ...prev, [projectId]: true }));
- } else {
- setSessionsLoading((prev) => ({ ...prev, [projectId]: true }));
- }
- try {
- // A (re)connect reconcile refetches the SAME already-loaded window (every
- // paged-in row), not just the first page — otherwise a transient SSE
- // reconnect / controller restart truncates an expanded project back to the
- // first SESSIONS_PAGE_SIZE rows until the user pages again (Codex P2).
- const loadedCount = sessionsByProjectRef.current[projectId]?.length ?? 0;
- const limit = reconcile ? Math.max(loadedCount, SESSIONS_PAGE_SIZE) : SESSIONS_PAGE_SIZE;
- const result = await api.listSessions({
- projectId,
- status: 'active',
- limit,
- beforeId: append ? sessionCursorRef.current[projectId] ?? undefined : undefined,
- });
- // Mutate the ref in place so a concurrent load for another project
- // can't drop this cursor via a stale read-modify-write snapshot.
- sessionCursorRef.current[projectId] = result.next_before_id;
- setSessionCursor((prev) => ({ ...prev, [projectId]: result.next_before_id }));
- setSessionsByProject((prev) => {
- if (!append) return { ...prev, [projectId]: result.sessions };
- // Cursor pages can overlap if a row's last_active_at shifts between
- // fetches (the cursor is just a row id resolved against current
- // activity); drop ids we already hold so rows never duplicate.
- const existing = prev[projectId] ?? [];
- const seen = new Set(existing.map((s) => s.id));
- return { ...prev, [projectId]: [...existing, ...result.sessions.filter((s) => !seen.has(s.id))] };
- });
- } catch (err) {
- // First-page failure: surface as empty so the user can collapse +
- // re-expand to retry. On a "load more" failure, keep the existing list
- // and cursor so the button stays available for another attempt.
- if (!append) {
- setSessionsByProject((prev) => ({ ...prev, [projectId]: prev[projectId] ?? [] }));
- }
- } finally {
- sessionsInFlightRef.current.delete(projectId);
- if (append) {
- setSessionsLoadingMore((prev) => ({ ...prev, [projectId]: false }));
- } else {
- setSessionsLoading((prev) => ({ ...prev, [projectId]: false }));
- }
- }
- },
- [api],
- );
-
- // Keep cached session rows in sync with edits made elsewhere (e.g. renaming
- // a session from the chat header). The server broadcasts session.activity
- // with event "updated"; patch the matching row's title in place so the
- // sidebar label tracks the chat header without a manual refresh.
- useEffect(() => {
- const disconnect = api.connectWorkbenchEvents({
- // (Re)connect reconciliation: after a controller restart the crash-recovery
- // reset (running → idle) ran server-side with NO event subscriber to
- // broadcast to, and any status events during the drop were missed. The
- // sidebar dots' authoritative source is listSessions, so refetch projects +
- // every already-expanded project's sessions whenever the stream (re)opens.
- onConnected: () => {
- fetchProjects();
- for (const projectId of loadedProjectsRef.current) {
- fetchSessions(projectId, { reconcile: true });
- }
- },
- onSessionActivity: (data) => {
- if (data.event !== 'updated' || !data.scope_id) return;
- const projectId = data.scope_id.split('::').pop();
- if (!projectId) return;
- const nextTitle = data.title ?? null;
- setSessionsByProject((prev) => {
- const list = prev[projectId];
- if (!list) return prev;
- let changed = false;
- const next = list.map((s) => {
- if (s.id === data.session_id && s.title !== nextTitle) {
- changed = true;
- return { ...s, title: nextTitle };
- }
- return s;
- });
- return changed ? { ...prev, [projectId]: next } : prev;
- });
- },
- // Recolor the session dot when its agent-runtime status changes. The
- // event carries only session_id, so find the project list holding it and
- // patch that row in place (mirrors the title patch above).
- onSessionStatus: (data) => {
- setSessionsByProject((prev) => {
- let changed = false;
- const next: Record<string, WorkbenchSession[]> = {};
- for (const [projectId, list] of Object.entries(prev)) {
- let listChanged = false;
- const patched = list.map((s) => {
- if (s.id === data.session_id && s.agent_status !== data.agent_status) {
- listChanged = true;
- return { ...s, agent_status: data.agent_status };
- }
- return s;
- });
- next[projectId] = listChanged ? patched : list;
- if (listChanged) changed = true;
- }
- return changed ? next : prev;
- });
- },
- });
- return disconnect;
- }, [api, fetchProjects, fetchSessions]);
-
- const toggleExpanded = useCallback(
- (projectId: string) => {
- setExpanded((prev) => {
- const next = new Set(prev);
- if (next.has(projectId)) {
- next.delete(projectId);
- } else {
- next.add(projectId);
- if (!sessionsByProject[projectId]) {
- fetchSessions(projectId);
- }
- }
- return next;
- });
- },
- [fetchSessions, sessionsByProject],
- );
-
- const createSessionForProject = useCallback(
- async (projectId: string) => {
- setCreatingSession((prev) => {
- const next = new Set(prev);
- next.add(projectId);
- return next;
- });
- // Whether this project's session list is already cached. If not, we must
- // NOT seed a partial cache below: toggleExpanded treats any cached entry
- // as "already loaded" and would never fetch the project's existing
- // sessions, making them vanish until a full refresh.
- const alreadyLoaded = sessionsByProject[projectId] !== undefined;
- try {
- // Omit agent_backend so the server defers to the configured default
- // Vibe Agent rather than pinning a hard-coded backend.
- const session = await api.createSession({ project_id: projectId });
- if (alreadyLoaded) {
- // Optimistically prepend so the user sees it before any refetch.
- setSessionsByProject((prev) => ({
- ...prev,
- [projectId]: [session, ...(prev[projectId] ?? [])],
- }));
- }
- setExpanded((prev) => {
- if (prev.has(projectId)) return prev;
- const next = new Set(prev);
- next.add(projectId);
- return next;
- });
- if (!alreadyLoaded) {
- // Load the full list (which now includes the new session) instead of
- // seeding a one-item cache that hides the pre-existing sessions.
- fetchSessions(projectId);
- }
- navigate(`/chat/${encodeURIComponent(session.id)}`);
- } catch (err: any) {
- // No toast service available here without prop drilling — fall back
- // to opening the project so the user notices nothing happened.
- console.error('[sidebar] create session failed', err);
- } finally {
- setCreatingSession((prev) => {
- const next = new Set(prev);
- next.delete(projectId);
- return next;
- });
- }
- },
- [api, navigate, fetchSessions, sessionsByProject],
- );
-
- const onSessionMarkRead = useCallback(
- (sessionId: string) => {
- markRead(sessionId);
- },
- [markRead],
- );
-
- const renameProject = useCallback(
- async (projectId: string, newName: string) => {
- try {
- const updated = await api.updateProject(projectId, { display_name: newName });
- setProjects((prev) =>
- prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev,
- );
- } catch (err) {
- console.error('[sidebar] rename project failed', err);
- }
- },
- [api],
- );
-
- const archiveProject = useCallback(
- async (projectId: string) => {
- try {
- await api.archiveProject(projectId);
- // Drop from the visible list. Sessions stay in the DB; user can
- // still reach them by URL or by un-archiving via the CLI for now.
- setProjects((prev) => (prev ? prev.filter((p) => p.id !== projectId) : prev));
- setExpanded((prev) => {
- if (!prev.has(projectId)) return prev;
- const next = new Set(prev);
- next.delete(projectId);
- return next;
- });
- } catch (err) {
- console.error('[sidebar] archive project failed', err);
- }
- },
- [api],
- );
// Small open/close delays so the popover doesn't flicker as the cursor
// brushes through the inbox row on its way somewhere else, and survives
@@ -987,44 +728,34 @@ export const WorkbenchSidebar: React.FC = () => {
</div>
)}
{projects !== null &&
- projects.map((project) => (
- <ProjectRow
- key={project.id}
- project={project}
- expanded={expanded.has(project.id)}
- sessions={sessionsByProject[project.id] ?? null}
- loading={!!sessionsLoading[project.id]}
- loadingMore={!!sessionsLoadingMore[project.id]}
- hasMore={!!sessionCursor[project.id]}
- onLoadMore={() => fetchSessions(project.id, { append: true })}
- onToggle={() => toggleExpanded(project.id)}
- onCreateSession={() => createSessionForProject(project.id)}
- creatingSession={creatingSession.has(project.id)}
- unreadBySession={unreadBySession}
- onSessionMarkRead={onSessionMarkRead}
- onRename={(next) => renameProject(project.id, next)}
- onArchive={() => archiveProject(project.id)}
- onRenameSession={async (sessionId, title) => {
- // Empty string clears to "untitled" server-side; null means
- // "unchanged". Patch from the REST response so the row updates
- // even if the session.activity SSE drops; the broadcast then
- // reconciles the same value (and any open chat header). Only
- // patches on success — a failed rename throws and leaves the
- // old title untouched.
- const updated = await api.updateSession(sessionId, { title });
- setSessionsByProject((prev) => {
- const list = prev[project.id];
- if (!list) return prev;
- return {
- ...prev,
- [project.id]: list.map((s) =>
- s.id === sessionId ? { ...s, title: updated.title } : s,
- ),
- };
- });
- }}
- />
- ))}
+ projects.map((project) => {
+ const state = sessionsOf(project.id);
+ return (
+ <ProjectRow
+ key={project.id}
+ project={project}
+ expanded={isExpanded(project.id)}
+ sessions={state.sessions}
+ loading={state.loading}
+ loadingMore={state.loadingMore}
+ hasMore={!!state.cursor}
+ onLoadMore={() => loadMore(project.id)}
+ onToggle={() => toggleExpanded(project.id)}
+ onCreateSession={async () => {
+ // The provider creates + caches; navigation stays here since
+ // it's mounted above the router.
+ const session = await createSessionForProject(project.id);
+ if (session) navigate(`/chat/${encodeURIComponent(session.id)}`);
+ }}
+ creatingSession={creatingSession(project.id)}
+ unreadBySession={unreadBySession}
+ onSessionMarkRead={markRead}
+ onRename={(next) => renameProject(project.id, next)}
+ onArchive={() => archiveProject(project.id)}
+ onRenameSession={(sessionId, title) => renameSession(project.id, sessionId, title)}
+ />
+ );
+ })}
</div>
</div>
@@ -1033,26 +764,7 @@ export const WorkbenchSidebar: React.FC = () => {
onClose={() => setShowNewProject(false)}
onCreated={(project) => {
setShowNewProject(false);
- // Opening a folder we already track returns the existing project
- // (idempotent by path), refreshed (revived / last_active_at bumped).
- // Drop any stale copy and hoist the fresh one to the top instead of
- // adding a duplicate row.
- setProjects((prev) => {
- if (!prev) return [project];
- return [project, ...prev.filter((p) => p.id !== project.id)];
- });
- setExpanded((prev) => {
- const next = new Set(prev);
- next.add(project.id);
- return next;
- });
- // Load sessions only if we don't already have them cached. A new or
- // restored project has no cache yet, so this fetches its real list;
- // an already-open project keeps the pages the user already paged in
- // instead of being truncated back to the first page.
- if (sessionsByProject[project.id] === undefined) {
- fetchSessions(project.id);
- }
+ upsertProjectToTop(project);
}}
/>
)}
diff --git a/ui/src/context/WorkbenchProjectsContext.tsx b/ui/src/context/WorkbenchProjectsContext.tsx
new file mode 100644
index 000000000..5254df12f
--- /dev/null
+++ b/ui/src/context/WorkbenchProjectsContext.tsx
@@ -0,0 +1,426 @@
+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
+import type { ReactNode } from 'react';
+
+import { useApi } from './ApiContext';
+import type { WorkbenchProject, WorkbenchSession } from './ApiContext';
+
+// How many sessions to load per page under a project. The server clamps the
+// /api/sessions limit (to 200) and returns a cursor (next_before_id); both the
+// desktop sidebar and the mobile Projects page append the next page via a
+// "Load more" control rather than loading every session up front. 20 is a
+// middle ground between the desktop sidebar's old 10 (compact rail) and the
+// mobile page's old 50 (full-screen list) now that one provider serves both.
+const SESSIONS_PAGE_SIZE = 20;
+
+export interface ProjectSessionsState {
+ /** null = not loaded yet. [] = loaded-but-empty (or a first-page failure, with `error`). */
+ sessions: WorkbenchSession[] | null;
+ /** First-page (or retry) fetch in flight. */
+ loading: boolean;
+ /** Load-more (append) fetch in flight. */
+ loadingMore: boolean;
+ /** next_before_id: a string means more pages exist, null means fully loaded. */
+ cursor: string | null;
+ /** The last first-page fetch failed — any rows are kept so the user can retry. */
+ error: boolean;
+}
+
+const EMPTY_SESSIONS: ProjectSessionsState = {
+ sessions: null,
+ loading: false,
+ loadingMore: false,
+ cursor: null,
+ error: false,
+};
+
+export interface WorkbenchProjectsTree {
+ projects: WorkbenchProject[] | null;
+ projectsError: string | null;
+ refreshProjects: () => Promise<void>;
+
+ sessionsOf: (projectId: string) => ProjectSessionsState;
+ expanded: ReadonlySet<string>;
+ isExpanded: (projectId: string) => boolean;
+ toggleExpanded: (projectId: string) => void;
+ loadMore: (projectId: string) => void;
+ /** Re-fetch the first page (mobile retry button / programmatic reload). */
+ reloadSessions: (projectId: string) => void;
+
+ creatingSession: (projectId: string) => boolean;
+ /** Creates a session under a project (optimistic prepend + expand) and RETURNS it;
+ * the caller navigates (this provider is mounted outside the router). null on failure. */
+ createSessionForProject: (projectId: string) => Promise<WorkbenchSession | null>;
+ renameProject: (projectId: string, name: string) => Promise<void>;
+ archiveProject: (projectId: string) => Promise<void>;
+ /** Throws on failure so the row's inline editor can fall back; patches title on success. */
+ renameSession: (projectId: string, sessionId: string, title: string) => Promise<void>;
+ /** After NewProjectDialog: dedup-by-id, hoist to top, expand, fetch sessions if not loaded. */
+ upsertProjectToTop: (project: WorkbenchProject) => void;
+}
+
+// Scan every project's loaded rows for a session id and apply `patch`; returns a
+// new state only when something actually changed (so unrelated consumers don't
+// re-render). Used for both the status-dot and title SSE patches — keyed on
+// session_id, so it doesn't depend on the server's scope_id format.
+function patchSessionRow(
+ prev: Record<string, ProjectSessionsState>,
+ sessionId: string,
+ patch: (session: WorkbenchSession) => WorkbenchSession,
+): Record<string, ProjectSessionsState> {
+ let changed = false;
+ const next: Record<string, ProjectSessionsState> = {};
+ for (const [projectId, state] of Object.entries(prev)) {
+ if (!state.sessions) {
+ next[projectId] = state;
+ continue;
+ }
+ let rowChanged = false;
+ const rows = state.sessions.map((s) => {
+ if (s.id !== sessionId) return s;
+ const updated = patch(s);
+ if (updated !== s) rowChanged = true;
+ return updated;
+ });
+ next[projectId] = rowChanged ? { ...state, sessions: rows } : state;
+ if (rowChanged) changed = true;
+ }
+ return changed ? next : prev;
+}
+
+const WorkbenchProjectsContext = createContext<WorkbenchProjectsTree | null>(null);
+
+// Single source of truth for the workbench projects/sessions tree. The desktop
+// WorkbenchSidebar (always mounted) and the mobile ProjectsPage (route) both
+// consume it, so it's a PROVIDER (one EventSource + one cache) rather than a
+// per-consumer hook — mirroring WorkbenchInboxContext, which made the same call
+// for the same "sidebar + page both need live SSE data" situation. Owns: load +
+// paginate + dedupe sessions, reconnect reconcile (chunked, survives the 200-row
+// server clamp), live status/title via SSE, create/rename/archive. Navigation
+// stays in consumers — this is mounted outside <BrowserRouter>. Unread stays in
+// WorkbenchInboxContext (both consumers read it directly).
+export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
+ const api = useApi();
+ const [projects, setProjects] = useState<WorkbenchProject[] | null>(null);
+ const [projectsError, setProjectsError] = useState<string | null>(null);
+ const [expanded, setExpanded] = useState<Set<string>>(new Set());
+ const [sessions, setSessions] = useState<Record<string, ProjectSessionsState>>({});
+ const [creating, setCreating] = useState<Set<string>>(new Set());
+
+ // Stale-closure-safe mirrors so the SSE (re)connect reconcile reads the current
+ // expanded set + loaded window without re-subscribing the stream on every change.
+ const sessionsRef = useRef<Record<string, ProjectSessionsState>>({});
+ sessionsRef.current = sessions;
+ const expandedRef = useRef<Set<string>>(new Set());
+ expandedRef.current = expanded;
+ // Projects with an in-flight session fetch — serialises first-page / load-more /
+ // reconcile per project so they can't race or truncate an append.
+ const inFlightRef = useRef<Set<string>>(new Set());
+
+ const fetchProjects = useCallback(async () => {
+ try {
+ const result = await api.listProjects();
+ setProjects(result.projects);
+ setProjectsError(null);
+ } catch (err: any) {
+ // Don't strand consumers on an empty-state for a transient failure — keep
+ // any list we had and surface the error (mobile shows a retry).
+ setProjectsError(err?.message ?? String(err));
+ }
+ }, [api]);
+
+ useEffect(() => {
+ void fetchProjects();
+ }, [fetchProjects]);
+
+ // Load the first page (append=false) or the next page (append=true) of a
+ // project's sessions, with dedupe + per-project serialisation.
+ const fetchSessions = useCallback(
+ async (projectId: string, opts?: { append?: boolean }) => {
+ const append = opts?.append ?? false;
+ if (append && !sessionsRef.current[projectId]?.cursor) return; // nothing more to load
+ if (inFlightRef.current.has(projectId)) return; // serialise per project
+ inFlightRef.current.add(projectId);
+ setSessions((prev) => {
+ const cur = prev[projectId] ?? EMPTY_SESSIONS;
+ return {
+ ...prev,
+ [projectId]: append ? { ...cur, loadingMore: true } : { ...cur, loading: true, error: false },
+ };
+ });
+ try {
+ const beforeId = append ? sessionsRef.current[projectId]?.cursor ?? undefined : undefined;
+ const res = await api.listSessions({ projectId, status: 'active', limit: SESSIONS_PAGE_SIZE, beforeId });
+ setSessions((prev) => {
+ const cur = prev[projectId] ?? EMPTY_SESSIONS;
+ const existing = append ? cur.sessions ?? [] : [];
+ // Cursor pages can overlap if a row's last_active_at shifts between
+ // fetches (the cursor is just a row id resolved against current
+ // activity); drop ids we already hold so rows never duplicate.
+ const seen = new Set(existing.map((s) => s.id));
+ const merged = [...existing, ...res.sessions.filter((s) => !seen.has(s.id))];
+ return {
+ ...prev,
+ [projectId]: { sessions: merged, cursor: res.next_before_id, loading: false, loadingMore: false, error: false },
+ };
+ });
+ } catch {
+ setSessions((prev) => {
+ const cur = prev[projectId] ?? EMPTY_SESSIONS;
+ // Load-more failure: keep the list + cursor so the button stays usable.
+ // First-page failure: flag error (mobile retry; re-expand refetches) and
+ // keep `sessions` non-null so the desktop still renders its empty state.
+ return append
+ ? { ...prev, [projectId]: { ...cur, loadingMore: false } }
+ : { ...prev, [projectId]: { ...cur, sessions: cur.sessions ?? [], loading: false, error: true } };
+ });
+ } finally {
+ inFlightRef.current.delete(projectId);
+ }
+ },
+ [api],
+ );
+
+ // (Re)connect reconcile: rebuild a project's ALREADY-paged-in window (not just
+ // page 1) so a transient SSE reconnect / controller restart doesn't truncate an
+ // expanded project back to the first page. Pages in chunks because the server
+ // clamps the limit to 200 — a single large request would silently truncate
+ // windows >200 rows. Silent (no loading flag) so visible rows don't flicker.
+ const reconcileSessions = useCallback(
+ async (projectId: string) => {
+ if (inFlightRef.current.has(projectId)) return;
+ const targetCount = sessionsRef.current[projectId]?.sessions?.length ?? 0;
+ if (targetCount === 0) return; // nothing loaded to reconcile
+ inFlightRef.current.add(projectId);
+ try {
+ const acc: WorkbenchSession[] = [];
+ const seen = new Set<string>();
+ let before: string | undefined;
+ let nextBeforeId: string | null = null;
+ do {
+ const res = await api.listSessions({ projectId, status: 'active', limit: SESSIONS_PAGE_SIZE, beforeId: before });
+ for (const s of res.sessions) {
+ if (!seen.has(s.id)) {
+ seen.add(s.id);
+ acc.push(s);
+ }
+ }
+ nextBeforeId = res.next_before_id;
+ before = res.next_before_id ?? undefined;
+ } while (before && acc.length < targetCount);
+ setSessions((prev) => ({
+ ...prev,
+ [projectId]: { sessions: acc, cursor: nextBeforeId, loading: false, loadingMore: false, error: false },
+ }));
+ } catch {
+ /* keep the current window on a failed reconcile */
+ } finally {
+ inFlightRef.current.delete(projectId);
+ }
+ },
+ [api],
+ );
+
+ // Keep the tree live: patch a row's status dot / title from SSE, and refetch
+ // projects + every loaded project's window when the stream (re)opens (the
+ // crash-recovery reset that runs server-side during a drop has no subscriber to
+ // broadcast to, so listSessions is the authoritative source on reconnect).
+ useEffect(() => {
+ const disconnect = api.connectWorkbenchEvents({
+ onConnected: () => {
+ void fetchProjects();
+ for (const [projectId, state] of Object.entries(sessionsRef.current)) {
+ if (state.sessions !== null) void reconcileSessions(projectId);
+ }
+ },
+ onSessionActivity: (data) => {
+ if (data.event !== 'updated' || !Object.prototype.hasOwnProperty.call(data, 'title')) return;
+ const nextTitle = data.title ?? null;
+ setSessions((prev) => patchSessionRow(prev, data.session_id, (s) => (s.title === nextTitle ? s : { ...s, title: nextTitle })));
+ },
+ onSessionStatus: ({ session_id, agent_status }) => {
+ setSessions((prev) =>
+ patchSessionRow(prev, session_id, (s) => (s.agent_status === agent_status ? s : { ...s, agent_status })),
+ );
+ },
+ });
+ return disconnect;
+ }, [api, fetchProjects, reconcileSessions]);
+
+ const toggleExpanded = useCallback(
+ (projectId: string) => {
+ const willExpand = !expandedRef.current.has(projectId);
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (willExpand) next.add(projectId);
+ else next.delete(projectId);
+ return next;
+ });
+ if (willExpand) {
+ // Fetch the first page if never loaded or the last load failed (a healthy
+ // loaded project keeps the pages the user already paged in).
+ const state = sessionsRef.current[projectId];
+ if (!state || state.sessions === null || state.error) void fetchSessions(projectId);
+ }
+ },
+ [fetchSessions],
+ );
+
+ const createSessionForProject = useCallback(
+ async (projectId: string): Promise<WorkbenchSession | null> => {
+ setCreating((prev) => new Set(prev).add(projectId));
+ // Whether this project's list is already cached. If not, we must NOT seed a
+ // partial cache: toggleExpanded treats any loaded entry as "already loaded"
+ // and would never fetch the project's existing sessions, hiding them.
+ const alreadyLoaded = sessionsRef.current[projectId]?.sessions != null;
+ try {
+ // Omit agent_backend so the server defers to agents.default_backend.
+ const session = await api.createSession({ project_id: projectId });
+ if (alreadyLoaded) {
+ setSessions((prev) => {
+ const cur = prev[projectId] ?? EMPTY_SESSIONS;
+ return { ...prev, [projectId]: { ...cur, sessions: [session, ...(cur.sessions ?? [])] } };
+ });
+ }
+ setExpanded((prev) => {
+ if (prev.has(projectId)) return prev;
+ const next = new Set(prev);
+ next.add(projectId);
+ return next;
+ });
+ if (!alreadyLoaded) void fetchSessions(projectId); // load the full list incl. the new one
+ return session;
+ } catch (err) {
+ console.error('[workbench] create session failed', err);
+ return null;
+ } finally {
+ setCreating((prev) => {
+ const next = new Set(prev);
+ next.delete(projectId);
+ return next;
+ });
+ }
+ },
+ [api, fetchSessions],
+ );
+
+ const renameProject = useCallback(
+ async (projectId: string, name: string) => {
+ try {
+ const updated = await api.updateProject(projectId, { display_name: name });
+ setProjects((prev) => (prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev));
+ } catch (err) {
+ console.error('[workbench] rename project failed', err);
+ }
+ },
+ [api],
+ );
+
+ const archiveProject = useCallback(
+ async (projectId: string) => {
+ try {
+ await api.archiveProject(projectId);
+ setProjects((prev) => (prev ? prev.filter((p) => p.id !== projectId) : prev));
+ setExpanded((prev) => {
+ if (!prev.has(projectId)) return prev;
+ const next = new Set(prev);
+ next.delete(projectId);
+ return next;
+ });
+ } catch (err) {
+ console.error('[workbench] archive project failed', err);
+ }
+ },
+ [api],
+ );
+
+ const renameSession = useCallback(
+ async (projectId: string, sessionId: string, title: string) => {
+ // Empty string clears to "untitled" server-side. Patch from the REST
+ // response so the row updates even if the session.activity SSE drops; the
+ // broadcast then reconciles the same value. Throws on failure (caller's
+ // inline editor catches it) so a failed rename leaves the old title.
+ const updated = await api.updateSession(sessionId, { title });
+ setSessions((prev) => {
+ const state = prev[projectId];
+ if (!state?.sessions) return prev;
+ return {
+ ...prev,
+ [projectId]: {
+ ...state,
+ sessions: state.sessions.map((s) => (s.id === sessionId ? { ...s, title: updated.title } : s)),
+ },
+ };
+ });
+ },
+ [api],
+ );
+
+ const upsertProjectToTop = useCallback(
+ (project: WorkbenchProject) => {
+ // create_project is find-or-create by path: opening a tracked folder returns
+ // the existing project, refreshed. Drop any stale copy, hoist to top, expand.
+ setProjects((prev) => (prev ? [project, ...prev.filter((p) => p.id !== project.id)] : [project]));
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ next.add(project.id);
+ return next;
+ });
+ // New / restored project → load its real list; an already-open one keeps its
+ // paged-in window instead of being truncated to the first page.
+ const state = sessionsRef.current[project.id];
+ if (!state || state.sessions === null || state.error) void fetchSessions(project.id);
+ },
+ [fetchSessions],
+ );
+
+ const sessionsOf = useCallback((projectId: string) => sessions[projectId] ?? EMPTY_SESSIONS, [sessions]);
+ const isExpanded = useCallback((projectId: string) => expanded.has(projectId), [expanded]);
+ const creatingSession = useCallback((projectId: string) => creating.has(projectId), [creating]);
+ const loadMore = useCallback((projectId: string) => void fetchSessions(projectId, { append: true }), [fetchSessions]);
+ const reloadSessions = useCallback((projectId: string) => void fetchSessions(projectId), [fetchSessions]);
+
+ const value = useMemo<WorkbenchProjectsTree>(
+ () => ({
+ projects,
+ projectsError,
+ refreshProjects: fetchProjects,
+ sessionsOf,
+ expanded,
+ isExpanded,
+ toggleExpanded,
+ loadMore,
+ reloadSessions,
+ creatingSession,
+ createSessionForProject,
+ renameProject,
+ archiveProject,
+ renameSession,
+ upsertProjectToTop,
+ }),
+ [
+ projects,
+ projectsError,
+ fetchProjects,
+ sessionsOf,
+ expanded,
+ isExpanded,
+ toggleExpanded,
+ loadMore,
+ reloadSessions,
+ creatingSession,
+ createSessionForProject,
+ renameProject,
+ archiveProject,
+ renameSession,
+ upsertProjectToTop,
+ ],
+ );
+
+ return <WorkbenchProjectsContext.Provider value={value}>{children}</WorkbenchProjectsContext.Provider>;
+};
+
+export function useWorkbenchProjectsTree(): WorkbenchProjectsTree {
+ const ctx = useContext(WorkbenchProjectsContext);
+ if (!ctx) throw new Error('useWorkbenchProjectsTree must be used within a WorkbenchProjectsProvider');
+ return ctx;
+}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index d99db486d..24bafa88c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -99,6 +99,14 @@
"loadMore": "Load more",
"loadFailed": "Couldn't load — tap to retry"
},
+ "newSession": {
+ "title": "New session",
+ "project": "Project",
+ "newProject": "New",
+ "placeholder": "Describe what you want the agent to do…",
+ "loadError": "Couldn't load projects — close and reopen to retry.",
+ "createFailed": "Couldn't start the session. Please try again."
+ },
"showPages": {
"title": "Show Pages",
"subtitle": "Every agent session has a Show Page. Make it public, keep it private, or take it offline.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b1961ef7e..65733af73 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -99,6 +99,14 @@
"loadMore": "加载更多",
"loadFailed": "加载失败,点击重试"
},
+ "newSession": {
+ "title": "新建会话",
+ "project": "选择项目",
+ "newProject": "新项目",
+ "placeholder": "描述你想让 agent 做什么…",
+ "loadError": "项目加载失败,关掉重开可重试。",
+ "createFailed": "会话创建失败,请重试。"
+ },
"showPages": {
"title": "展示页面",
"subtitle": "每个 Agent 会话都有一个展示页面。可以将其公开、保持私有,或下线。",
diff --git a/ui/src/lib/useNewSession.ts b/ui/src/lib/useNewSession.ts
new file mode 100644
index 000000000..3a3bbc1f0
--- /dev/null
+++ b/ui/src/lib/useNewSession.ts
@@ -0,0 +1,106 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+
+import { useWorkbenchProjectsTree } from '../context/WorkbenchProjectsContext';
+import type { WorkbenchProject } from '../context/ApiContext';
+
+interface UseNewSessionOptions {
+ /** Re-run the per-open reset on the rising edge — sheets pass their `open`. Default true. */
+ active?: boolean;
+ /** Pre-translated copy: the hook stays i18n-free, callers pass t(...) strings. */
+ loadErrorText: string;
+ createFailedText: string;
+}
+
+export interface NewSessionState {
+ projects: WorkbenchProject[];
+ loaded: boolean;
+ error: string | null;
+ sending: boolean;
+ selectedId: string | null;
+ setSelected: (id: string) => void;
+ target: WorkbenchProject | null;
+ needsProject: boolean;
+ /** Creates a session under `target` and returns the nav target; null if it couldn't start
+ * (empty / in-flight / not loaded / no project / error). The hook never navigates — the
+ * caller does, since the projects provider is mounted outside the router. */
+ send: (text: string) => Promise<{ sessionId: string; initialMessage: string } | null>;
+ upsertSelectProject: (project: WorkbenchProject) => void;
+}
+
+const sortByRecent = (list: WorkbenchProject[]) =>
+ list
+ .slice()
+ .sort((a, b) => (b.last_active_at || b.created_at).localeCompare(a.last_active_at || a.created_at));
+
+// Shared new-session create flow for the desktop Workbench home (`Workbench.tsx`)
+// and the mobile NewSessionSheet. It's a thin layer over the shared projects
+// provider — the project LIST and the create itself come from there, so a
+// project/session created here shows up in the sidebar + Projects tree without a
+// separate fetch (one source of truth). The hook only adds the picker selection,
+// the transient sending/error state, and the most-recent target resolution.
+// Navigation + draft handling + the sheet's open/close lifecycle stay in the consumer.
+export function useNewSession({ active = true, loadErrorText, createFailedText }: UseNewSessionOptions): NewSessionState {
+ const { projects: rawProjects, projectsError, createSessionForProject, upsertProjectToTop } = useWorkbenchProjectsTree();
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [sending, setSending] = useState(false);
+
+ const projects = useMemo(() => (rawProjects ? sortByRecent(rawProjects) : []), [rawProjects]);
+ const loaded = rawProjects !== null;
+
+ // Clear transient state when the sheet (re)opens so a prior submit / error
+ // doesn't leak into the next open. The home passes active=true (runs once).
+ useEffect(() => {
+ if (!active) return;
+ setSending(false);
+ setError(null);
+ }, [active]);
+
+ // selectedId is the explicit pick; fall back to the most-recent project so a
+ // null or now-hidden selection still resolves a sane target.
+ const target = projects.find((p) => p.id === selectedId) ?? projects[0] ?? null;
+ const needsProject = loaded && !target;
+
+ const send = useCallback(
+ async (text: string): Promise<{ sessionId: string; initialMessage: string } | null> => {
+ const trimmed = text.trim();
+ // Never create from a stale/empty/in-flight state; no target → caller opens New Project.
+ if (!trimmed || sending || !loaded || !target) return null;
+ setSending(true);
+ setError(null);
+ const session = await createSessionForProject(target.id);
+ setSending(false);
+ if (!session) {
+ setError(createFailedText);
+ return null;
+ }
+ return { sessionId: session.id, initialMessage: trimmed };
+ },
+ [sending, loaded, target, createSessionForProject, createFailedText],
+ );
+
+ const upsertSelectProject = useCallback(
+ (project: WorkbenchProject) => {
+ upsertProjectToTop(project); // updates the shared tree (sidebar + Projects page) too
+ setSelectedId(project.id);
+ },
+ [upsertProjectToTop],
+ );
+
+ // Surface a project-load failure (provider-level) when we have no list, plus any
+ // create error raised here.
+ const visibleError = error ?? (!loaded && projectsError != null ? loadErrorText : null);
+
+ return {
+ projects,
+ loaded,
+ error: visibleError,
+ sending,
+ selectedId,
+ setSelected: setSelectedId,
+ target,
+ needsProject,
+ send,
+ upsertSelectProject,
+ };
+}