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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(workbench): add "Hide to background" to sidebar session-row menu (#970)
Call White4e9df6610ec1
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsxindex e24c9f345..1bd182b63 100644--- a/ui/src/components/workbench/WorkbenchSidebar.tsx+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx@@ -10,6 +10,7 @@ import {ChevronRight,CodeXml,Ellipsis,+ EyeOff,FileText,Folder,FolderOpen,@@ -33,7 +34,9 @@ import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContextimport { useWindowManager } from '../../context/WindowManagerContext';import { useComposerInsertTarget } from '../../context/ComposerBridgeContext';import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';+import { useApi } from '../../context/ApiContext';import type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';+import { useToast } from '../../context/ToastContext';import { formatRelativeTime } from '../../lib/relativeTime';import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';import { ArchiveSessionDialog } from './ArchiveSessionDialog';@@ -210,6 +213,8 @@ const SessionRow: React.FC<{}> = ({ session, unread, onForkSession, onRenameSession, onArchiveSession }) => {const { t } = useTranslation();const navigate = useNavigate();+ const api = useApi();+ const { showToast } = useToast();const authorizeRouteAction = useUnsavedChangesActionGuard();const location = useLocation();const active = location.pathname === `/chat/${session.id}`;@@ -369,6 +374,32 @@ const SessionRow: React.FC<{<Pencil className="size-3 text-muted" />{t('workbench.sessionRename')}</button>+ <button+ type="button"+ onClick={async () => {+ setMenuOpen(false);+ try {+ // Move to background (M1 PATCH). The row leaves the list on its own+ // via the A6 session.activity pipeline — no client-side removal. Not+ // a delete: offer an immediate Undo and say where it went. Hiding the+ // currently-open chat is fine — we don't navigate; it just leaves the+ // list while the chat stays usable.+ await api.setSessionVisibility(session.id, 'background');+ showToast(t('workbench.sessionHiddenToast'), 'success', {+ label: t('common.undo'),+ onClick: () => {+ void api.setSessionVisibility(session.id, 'foreground');+ },+ });+ } catch (err) {+ showToast(err instanceof Error ? err.message : String(err), 'error');+ }+ }}+ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"+ >+ <EyeOff className="size-3 text-muted" />+ {t('workbench.sessionHideToBackground')}+ </button><Buttontype="button"variant="ghost"diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 4e6184de7..db02ffb3f 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -4,6 +4,7 @@ import { useToast } from './ToastContext';import { apiFetch } from '../lib/apiFetch';import type { TurnActivityGroupWire } from '../lib/agentActivity';import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';+import { visibilityActivityEvents } from '../lib/sessionVisibilityEvents';import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';import {WorkbenchEventReconnectLoop,@@ -938,6 +939,9 @@ export type WorkbenchEventHandlers = {event: string;title?: string | null;visibility?: 'foreground' | 'background';+ // Client-synthesized marker (never on a real backend event): a foreground+ // restore, so the projects tree grows its window to bring the row back.+ restored?: boolean;}) => void;onInboxUnreadChanged?: (data: {session_id?: string;@@ -1907,6 +1911,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children}};+ // Feed a locally-synthesized session.activity event through the SAME handler+ // set + read-cache invalidation the SSE 'session.activity' listener uses, so a+ // client-originated change (e.g. a visibility PATCH) reconciles every workbench+ // cache via its own reducer even when the SSE stream is down. Idempotent with a+ // later real SSE event carrying the same change.+ const emitLocalSessionActivity = (data: Parameters<NonNullable<WorkbenchEventHandlers['onSessionActivity']>>[0]) => {+ if (data.session_id) clearSessionReadCache(data.session_id);+ dispatchToWorkbenchHandlers((handlers) => handlers.onSessionActivity?.(data));+ };+const setWorkbenchEventConnectionState = (state: WorkbenchEventConnectionState) => {if (eventConnectionStateRef.current === state) return;eventConnectionStateRef.current = state;@@ -2881,8 +2895,26 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst qs = search.toString();return getJson(qs ? `/api/agents-graph?${qs}` : '/api/agents-graph');},- setSessionVisibility: (sessionId, visibility) =>- patchJson(`/api/sessions/${encodeURIComponent(sessionId)}`, { visibility }),+ setSessionVisibility: async (sessionId, visibility) => {+ const session = (await patchJson(`/api/sessions/${encodeURIComponent(sessionId)}`, {+ visibility,+ })) as WorkbenchSession;+ // Single chokepoint: replay the committed PATCH as the same session.activity+ // event sequence the backend emits, through the existing workbench-event+ // pipeline, so the projects tree AND the inbox reconcile via their own+ // reducers even when the SSE stream is down (remote/mobile). Any caller+ // (sidebar hide, graph toggle) inherits this; a real SSE event arriving+ // later is an idempotent no-op.+ for (const event of visibilityActivityEvents({+ sessionId,+ scopeId: session.scope_id,+ title: session.title,+ visibility,+ })) {+ emitLocalSessionActivity(event);+ }+ return session;+ },getRunningAgents: async () => {const res = await apiFetch('/api/running-agents');// 503/504 means controller is down; surface as unreachable instead of throwing.diff --git a/ui/src/context/ToastContext.tsx b/ui/src/context/ToastContext.tsxindex 06ee76c81..61e52ced8 100644--- a/ui/src/context/ToastContext.tsx+++ b/ui/src/context/ToastContext.tsx@@ -1,6 +1,8 @@import React, { createContext, useContext, useState, useCallback, useMemo, useRef } from 'react';import { AlertTriangle, CheckCircle, XCircle, X } from 'lucide-react';+import { shouldCoalesceToast, type ToastAction } from './toastCoalesce';+type ToastType = 'success' | 'error' | 'warning';interface Toast {@@ -12,10 +14,11 @@ interface Toast {// 503-ing endpoint during a daemon restart) we coalesce instead of// stacking 5+ identical popups.repeats: number;+ action?: ToastAction;}interface ToastContextType {- showToast: (message: string, type?: ToastType) => void;+ showToast: (message: string, type?: ToastType, action?: ToastAction) => void;}const ToastContext = createContext<ToastContextType | null>(null);@@ -26,37 +29,46 @@ let toastId = 0;// existing toast's repeat counter instead of stacking a new toast.const DEDUPE_WINDOW_MS = 4000;+// Actionable toasts stay a bit longer so there is time to hit the action (undo).+const ACTION_TOAST_MS = 6000;+const PLAIN_TOAST_MS = 3000;+export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {const [toasts, setToasts] = useState<Toast[]>([]);// Ref so dedupe lookups don't rerender. Maps message -> {id, expiresAt}// for currently-visible toasts; we evict on auto-dismiss.const recentRef = useRef<Map<string, { id: number; expiresAt: number }>>(new Map());- const showToast = useCallback((message: string, type: ToastType = 'success') => {- // Coalesce duplicate messages from polling / retry loops. The user- // sees one toast with a "(×N)" badge instead of a wall of identical- // popups; this matters most for transient 503s during daemon restarts.- const now = Date.now();- const existing = recentRef.current.get(message);- if (existing && existing.expiresAt > now) {- setToasts((prev) =>- prev.map((t) => (t.id === existing.id ? { ...t, repeats: t.repeats + 1, type } : t)),- );- return;- }- const id = ++toastId;- recentRef.current.set(message, { id, expiresAt: now + DEDUPE_WINDOW_MS });- setToasts((prev) => [...prev, { id, message, type, repeats: 0 }]);+ const showToast = useCallback(+ (message: string, type: ToastType = 'success', action?: ToastAction) => {+ // Coalesce duplicate messages from polling / retry loops. The user+ // sees one toast with a "(×N)" badge instead of a wall of identical+ // popups; this matters most for transient 503s during daemon restarts.+ // Actionable toasts opt out (see shouldCoalesceToast).+ const now = Date.now();+ const existing = recentRef.current.get(message);+ if (shouldCoalesceToast(!!action, existing, now)) {+ setToasts((prev) =>+ prev.map((t) => (t.id === existing!.id ? { ...t, repeats: t.repeats + 1, type } : t)),+ );+ return;+ }+ const id = ++toastId;+ // Only track plain toasts for dedupe; actionable ones are always distinct.+ if (!action) recentRef.current.set(message, { id, expiresAt: now + DEDUPE_WINDOW_MS });+ setToasts((prev) => [...prev, { id, message, type, repeats: 0, action }]);- // Auto dismiss after 3 seconds- setTimeout(() => {- setToasts((prev) => prev.filter((t) => t.id !== id));- // Best-effort cleanup of the dedupe map — the entry may have been- // re-issued under a different id during the window.- const tracked = recentRef.current.get(message);- if (tracked && tracked.id === id) recentRef.current.delete(message);- }, 3000);- }, []);+ // Auto dismiss (longer for actionable toasts so undo is reachable).+ setTimeout(() => {+ setToasts((prev) => prev.filter((t) => t.id !== id));+ // Best-effort cleanup of the dedupe map — the entry may have been+ // re-issued under a different id during the window.+ const tracked = recentRef.current.get(message);+ if (tracked && tracked.id === id) recentRef.current.delete(message);+ }, action ? ACTION_TOAST_MS : PLAIN_TOAST_MS);+ },+ [],+ );const dismissToast = useCallback((id: number) => {setToasts((prev) => prev.filter((t) => t.id !== id));@@ -96,6 +108,17 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childre×{toast.repeats + 1}</span>)}+ {toast.action && (+ <button+ onClick={() => {+ toast.action!.onClick();+ dismissToast(toast.id);+ }}+ className="ml-1 shrink-0 rounded px-1.5 py-0.5 text-xs font-semibold underline underline-offset-2 hover:opacity-80"+ >+ {toast.action.label}+ </button>+ )}<buttononClick={() => dismissToast(toast.id)}className="ml-2 opacity-60 hover:opacity-100 transition-opacity"diff --git a/ui/src/context/WorkbenchProjectsContext.tsx b/ui/src/context/WorkbenchProjectsContext.tsxindex be3018bff..5e3cf58d0 100644--- a/ui/src/context/WorkbenchProjectsContext.tsx+++ b/ui/src/context/WorkbenchProjectsContext.tsx@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';import { useApi } from './ApiContext';import type { ProjectDefaultAgent, WorkbenchProject, WorkbenchSession, WorkbenchSessionCreate } from './ApiContext';+import { createdReconcileMinCount } from '../lib/sessionVisibilityEvents';// 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@@ -412,7 +413,17 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ cif (!REORDER_ACTIVITY_EVENTS.has(data.event)) return;const projectId = projectsRef.current?.find((project) => project.scope_id === data.scope_id)?.id;if (!projectId) return;- void reconcileSessions(projectId, { minCount: data.event === 'created' ? 1 : 0 });+ // Grow the window ONLY for a synthesized foreground-restore (`data.restored`,+ // set by visibilityActivityEvents on Undo): reconcile one past the loaded+ // page so a restored row ranked just past it returns (a flat minCount 1 stops+ // at the first page → Undo looks broken). A real backend `created` (a new+ // session, never marked) keeps the original minCount 1 — otherwise repeated+ // local create/fork, which already prepend the row before this event fires,+ // would inflate the window by one each time (Codex r3). See createdReconcileMinCount.+ const loaded = sessionsRef.current[projectId]?.sessions?.length ?? 0;+ const minCount =+ data.event === 'created' ? createdReconcileMinCount(!!data.restored, loaded) : 0;+ void reconcileSessions(projectId, { minCount });},onSessionStatus: ({ session_id, agent_status }) => {setSessions((prev) =>diff --git a/ui/src/context/toastCoalesce.test.ts b/ui/src/context/toastCoalesce.test.tsnew file mode 100644index 000000000..127591a28--- /dev/null+++ b/ui/src/context/toastCoalesce.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import { shouldCoalesceToast } from './toastCoalesce';++describe('shouldCoalesceToast (dedupe vs. per-instance action)', () => {+ const now = 1000;++ it('coalesces a plain duplicate still within its dedupe window', () => {+ expect(shouldCoalesceToast(false, { expiresAt: now + 100 }, now)).toBe(true);+ });++ it('never coalesces an actionable toast — its undo must target its own item', () => {+ expect(shouldCoalesceToast(true, { expiresAt: now + 100 }, now)).toBe(false);+ });++ it('does not coalesce a new (untracked) message', () => {+ expect(shouldCoalesceToast(false, undefined, now)).toBe(false);+ });++ it('does not coalesce once the dedupe window has expired', () => {+ expect(shouldCoalesceToast(false, { expiresAt: now - 1 }, now)).toBe(false);+ });+});diff --git a/ui/src/context/toastCoalesce.ts b/ui/src/context/toastCoalesce.tsnew file mode 100644index 000000000..487af200f--- /dev/null+++ b/ui/src/context/toastCoalesce.ts@@ -0,0 +1,16 @@+// Pure toast-coalescing predicate + action type, kept out of ToastContext.tsx so+// that provider file only exports its component + hook (react-refresh HMR rule).++// Optional one-tap action (e.g. an Undo) rendered inside a toast.+export type ToastAction = { label: string; onClick: () => void };++// A toast carrying an action targets ONE specific item (e.g. undo THIS hide), so+// it must never fold into an earlier toast's repeat counter — that would strand+// the action on the wrong item. Only plain duplicates within the window coalesce.+export function shouldCoalesceToast(+ hasAction: boolean,+ existing: { expiresAt: number } | undefined,+ now: number,+): boolean {+ return !hasAction && existing !== undefined && existing.expiresAt > now;+}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex fefee934d..2533107ce 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -38,6 +38,7 @@"confirm": "Confirm","clear": "Clear","retry": "Retry",+ "undo": "Undo","loading": "Loading...","saving": "Saving...","saved": "Saved",@@ -997,6 +998,8 @@"sessionReference": "Reference this session","sessionFork": "Fork session","sessionForkUnavailable": "This session has no native agent session to fork yet.",+ "sessionHideToBackground": "Hide to background",+ "sessionHiddenToast": "Hidden to background · Find it in Agents → Runs","sessionArchive": "Archive session","archiveSession": {"title": "Archive this session permanently?",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 49ab761aa..13ae69385 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -38,6 +38,7 @@"confirm": "确定","clear": "清除","retry": "重试",+ "undo": "撤销","loading": "加载中...","saving": "保存中...","saved": "已保存",@@ -997,6 +998,8 @@"sessionReference": "引用该会话","sessionFork": "复刻会话","sessionForkUnavailable": "此会话还没有可复刻的原生 Agent 会话。",+ "sessionHideToBackground": "隐藏到后台",+ "sessionHiddenToast": "已隐藏到后台 · 可在 Agents→Runs 找回","sessionArchive": "归档会话","archiveSession": {"title": "永久归档此会话?",diff --git a/ui/src/lib/sessionVisibilityEvents.test.ts b/ui/src/lib/sessionVisibilityEvents.test.tsnew file mode 100644index 000000000..cfa9388f6--- /dev/null+++ b/ui/src/lib/sessionVisibilityEvents.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest';++import { createdReconcileMinCount, visibilityActivityEvents } from './sessionVisibilityEvents';++describe('visibilityActivityEvents (replay a visibility PATCH as A6 session.activity events)', () => {+ it('hide → updated(visibility=background) + user_message placement on the same scope', () => {+ expect(+ visibilityActivityEvents({ sessionId: 'ses1', scopeId: 'scope1', title: 'T', visibility: 'background' }),+ ).toEqual([+ { session_id: 'ses1', scope_id: 'scope1', event: 'updated', title: 'T', visibility: 'background' },+ { session_id: 'ses1', scope_id: 'scope1', event: 'user_message' },+ ]);+ });++ it('undo/restore → updated(visibility=foreground) + a `created` placement marked `restored`', () => {+ expect(+ visibilityActivityEvents({ sessionId: 'ses1', scopeId: 'scope1', title: null, visibility: 'foreground' }),+ ).toEqual([+ { session_id: 'ses1', scope_id: 'scope1', event: 'updated', title: null, visibility: 'foreground' },+ // `restored: true` is the marker a real backend `created` never carries; it+ // lets the tree grow its window to bring a restored row back.+ { session_id: 'ses1', scope_id: 'scope1', event: 'created', restored: true },+ ]);+ });++ it('carries visibility only on the updated event (the Inbox driver) and passes a null scope through', () => {+ const [updated, placement] = visibilityActivityEvents({+ sessionId: 's',+ scopeId: null,+ title: null,+ visibility: 'background',+ });+ expect(updated).toMatchObject({ event: 'updated', visibility: 'background', scope_id: null });+ // The placement event is a REORDER event with no visibility, so the Inbox+ // listener ignores it and only the projects-tree listener reconciles.+ expect(placement.visibility).toBeUndefined();+ });+});++describe('createdReconcileMinCount (marker gates window growth)', () => {+ it('a real `created` (unmarked new session) keeps minCount 1 → no window inflation', () => {+ // targetCount = max(loaded, 1) = loaded, so repeated local create/fork (which+ // already prepend the row) do NOT grow the loaded window each time.+ expect(createdReconcileMinCount(false, 8)).toBe(1);+ expect(createdReconcileMinCount(false, 0)).toBe(1);+ });++ it('a synthesized restore (`restored`) fetches one past the window → row past the page returns', () => {+ // targetCount = max(loaded, loaded + 1) = loaded + 1, so a restored row ranked+ // just past the loaded page is included even at a page boundary.+ expect(createdReconcileMinCount(true, 8)).toBe(9);+ expect(createdReconcileMinCount(true, 0)).toBe(1);+ });+});diff --git a/ui/src/lib/sessionVisibilityEvents.ts b/ui/src/lib/sessionVisibilityEvents.tsnew file mode 100644index 000000000..daadca159--- /dev/null+++ b/ui/src/lib/sessionVisibilityEvents.ts@@ -0,0 +1,58 @@+// Synthesize the `session.activity` event sequence the backend emits for a+// visibility change (see _publish_session_update_activity in ui_server.py), so+// the client can replay a successful visibility PATCH through the SAME workbench-+// event pipeline the SSE stream feeds. That single chokepoint lets every+// visibility-keyed cache reconcile via its own existing reducer even when the SSE+// stream is down (remote/mobile) — instead of each cache being hand-synced at the+// call site. A real SSE event arriving later is an idempotent no-op.+//+// Two events, matching the backend, each consumed by a different listener:+// - `updated` carries `visibility` → the Inbox listener drops the card on+// background / reconciles it on foreground (sessionActivityInboxAction).+// - the placement event is a REORDER event → the projects-tree listener+// reconciles that scope's window. Foreground/undo emits a `created` placement+// carrying `restored: true` (a marker a real backend SSE event never sets), so+// the tree reconciles one past the loaded window and a row ranked past the page+// still returns; `user_message` (background) drops it via the foreground-only+// re-read.+//+// A pure visibility toggle never changes scope, so the placement event rides the+// same scope_id. Pure + exported so it can be unit-tested without the provider.++// Matches the WorkbenchEventHandlers.onSessionActivity payload shape in ApiContext.+export type SessionActivityEvent = {+ session_id: string;+ scope_id: string | null;+ event: string;+ title?: string | null;+ visibility?: 'foreground' | 'background';+ // Client-only marker: set on a synthesized foreground-restore `created` event+ // so the tree grows its window to bring a restored (previously-hidden) row back.+ // Real backend `created` events never carry it, so a genuine new session keeps+ // the original reconcile semantics and does not inflate the window.+ restored?: boolean;+};++export function visibilityActivityEvents(args: {+ sessionId: string;+ scopeId: string | null;+ title: string | null;+ visibility: 'foreground' | 'background';+}): SessionActivityEvent[] {+ const { sessionId, scopeId, title, visibility } = args;+ return [+ { session_id: sessionId, scope_id: scopeId, event: 'updated', title, visibility },+ visibility === 'background'+ ? { session_id: sessionId, scope_id: scopeId, event: 'user_message' }+ : { session_id: sessionId, scope_id: scopeId, event: 'created', restored: true },+ ];+}++// minCount for the tree's `created`-placement reconcile. A synthesized restore+// (`restored`) grows the window to `loaded + 1` so a row ranked just past the+// loaded page returns; a real `created` (new session, no marker) keeps the+// original `1` floor so repeated local creates don't inflate the window+// (targetCount stays `max(loaded, 1)`).+export function createdReconcileMinCount(restored: boolean, loaded: number): number {+ return restored ? loaded + 1 : 1;+}