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.

fix(ui): preserve unread desktop chat notifications (#1252)

Call Whiteb0a7151191ee
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index ea9379e89..211f95989 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -56,6 +56,7 @@ import {
REMOTE_AUTH_REQUIRED_EVENT,
shouldDeferRemoteAuthRedirect,
} from './lib/remoteAuth';
+import { useIsDesktop } from './lib/useIsDesktop';
// Apps layer pages are lazy: they share their chunk with the windowed app bodies
// (registry.tsx) instead of being pulled into the main entry by these routes, so
@@ -376,21 +377,6 @@ const AppsRouteFallback = () => {
return <div className="grid min-h-[40vh] place-items-center text-[12px] text-muted">{t('common.loading')}</div>;
};
-// Reactive desktop (≥ md) check for the mobile-vs-window split.
-function useIsDesktop(): boolean {
- const [isDesktop, setIsDesktop] = useState(
- () => typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(min-width: 768px)').matches,
- );
- useEffect(() => {
- if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
- const mql = window.matchMedia('(min-width: 768px)');
- const onChange = () => setIsDesktop(mql.matches);
- mql.addEventListener('change', onChange);
- return () => mql.removeEventListener('change', onChange);
- }, []);
- return isDesktop;
-}
-
// /apps/library — the App Library route and the redirect target for the retired
// /admin/show-pages page. On desktop the Library is a workbench window, so open
// (or focus) it and hand back to the canvas; on mobile there are no windows, so
diff --git a/ui/src/apps/LibraryApp.tsx b/ui/src/apps/LibraryApp.tsx
index 302e6b738..22419eb99 100644
--- a/ui/src/apps/LibraryApp.tsx
+++ b/ui/src/apps/LibraryApp.tsx
@@ -26,6 +26,7 @@ import { Badge } from '../components/ui/badge';
import { Button } from '../components/ui/button';
import { SearchField } from '../components/settings/SettingsPrimitives';
import { openLinkInNewContext } from '../lib/pwaNavigation';
+import { isDesktopViewport } from '../lib/useIsDesktop';
// The App Library: the app manager, itself a built-in app (§7.1). Two views over
// the two-layer state (§7.1c): the INSTALLED set (Apps) and the full Show Pages
@@ -67,7 +68,7 @@ function useOpenApp() {
return;
}
}
- const desktop = typeof window !== 'undefined' && !!window.matchMedia?.('(min-width: 768px)').matches;
+ const desktop = isDesktopViewport();
if (desktop) {
wm.openApp(appId, {
title: opts?.title,
diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsx
index f6ac554ff..36cbc664e 100644
--- a/ui/src/components/apps/AppWindow.tsx
+++ b/ui/src/components/apps/AppWindow.tsx
@@ -230,16 +230,21 @@ export const AppWindow: React.FC<{
// and React/the browser moves focus out automatically.
inert={win.minimized}
tabIndex={-1}
- onPointerDown={(e) => {
+ onPointerDownCapture={() => {
+ // Capture runs before toolbar controls stop propagation, so every pointer
+ // activation claims the window without stealing DOM focus from the target.
wm.focus(win.id);
+ }}
+ onPointerDown={(e) => {
// Give the window DOM focus (so ⌘W/⌘M target it) — but don't steal focus from
- // an inner control/editor/terminal the click lands in (xterm's screen isn't a
- // textarea, so it needs an explicit exemption or terminal input would break).
+ // an inner control/editor/terminal the click lands in. FocusCapture below
+ // then gives the same window foreground ownership and raises its z-order.
const tgt = e.target as HTMLElement;
if (!tgt.closest('input,textarea,select,button,a,[contenteditable="true"],.monaco-editor,.xterm')) {
rootRef.current?.focus({ preventScroll: true });
}
}}
+ onFocusCapture={() => wm.focus(win.id)}
onAnimationEnd={(e) => {
// Only the root's own close animation drives the unmount (ignore the
// entrance, and any child animation bubbling up). Minimize doesn't animate
diff --git a/ui/src/components/apps/ShowPageRoute.tsx b/ui/src/components/apps/ShowPageRoute.tsx
index b607851ad..e7837ae76 100644
--- a/ui/src/components/apps/ShowPageRoute.tsx
+++ b/ui/src/components/apps/ShowPageRoute.tsx
@@ -9,6 +9,7 @@ import { useWindowManager } from '../../context/WindowManagerContext';
import { appTabHref } from '../../apps/appLaunch';
import { showPageAvatar, showPagePrivatePath } from '../../apps/showPageAvatar';
import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';
+import { useIsDesktop } from '../../lib/useIsDesktop';
// The `/apps/show/:sessionId` route — a pinned Show Page opened as an app on the
// current surface. Desktop keeps windows (mirrors LibraryRoute): focus an
@@ -19,25 +20,6 @@ import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';
// desktop window uses. Opening only READS: a missing/archived page shows a
// friendly placeholder, never a dead frame or an auto-created page.
-// Reactive desktop (≥ md) check — the same media query the whole shell splits on
-// (App.tsx's LibraryRoute uses the identical private hook).
-function useIsDesktop(): boolean {
- const [isDesktop, setIsDesktop] = useState(
- () =>
- typeof window !== 'undefined' &&
- typeof window.matchMedia === 'function' &&
- window.matchMedia('(min-width: 768px)').matches,
- );
- useEffect(() => {
- if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
- const mql = window.matchMedia('(min-width: 768px)');
- const onChange = () => setIsDesktop(mql.matches);
- mql.addEventListener('change', onChange);
- return () => mql.removeEventListener('change', onChange);
- }, []);
- return isDesktop;
-}
-
export const ShowPageRoute: React.FC = () => {
const { sessionId = '' } = useParams();
const isDesktop = useIsDesktop();
diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsx
index 05bb87ec9..01dceaaea 100644
--- a/ui/src/components/apps/WindowLayer.tsx
+++ b/ui/src/components/apps/WindowLayer.tsx
@@ -17,6 +17,7 @@ import {
} from './showPageWindowState';
import { inTerminalSurface, inTextEntrySurface, windowIdForKeyboardTarget } from './windowChords';
import { shouldGuardUnload } from './windowUnload';
+import { isDesktopViewport } from '../../lib/useIsDesktop';
const ShowPageWindow: React.FC<{
archived: boolean;
@@ -161,7 +162,7 @@ export const WindowLayer: React.FC = () => {
// The window layer is desktop-only (`hidden md:block`); on a narrowed
// viewport the windows are hidden, so a stale non-minimized window must not
// prompt on tab-close. Gate on the same md breakpoint, checked at unload time.
- if (!window.matchMedia?.('(min-width: 768px)').matches) return;
+ if (!isDesktopViewport()) return;
e.preventDefault();
e.returnValue = '';
};
@@ -175,7 +176,7 @@ export const WindowLayer: React.FC = () => {
// for character entry; the Windows layer is desktop-only.
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
- if (!window.matchMedia?.('(min-width: 768px)').matches) return;
+ if (!isDesktopViewport()) return;
const index = dockIndexFromShortcut(e);
const target = e.target instanceof Element ? e.target : document.activeElement;
if (index === null || inTextEntrySurface(target)) return;
diff --git a/ui/src/components/workbench/AgentGraphTab.tsx b/ui/src/components/workbench/AgentGraphTab.tsx
index 236c92f37..7a4e7964a 100644
--- a/ui/src/components/workbench/AgentGraphTab.tsx
+++ b/ui/src/components/workbench/AgentGraphTab.tsx
@@ -24,6 +24,7 @@ import {
} from '../../lib/agentGraph';
import { searchGraph, type GraphSearchResult } from '../../lib/graphSearch';
import { readGraphShowDisabled, writeGraphShowDisabled } from '../../lib/graphViewPrefs';
+import { useIsDesktop } from '../../lib/useIsDesktop';
import { AgentGraphCanvas } from './AgentGraphCanvas';
import { AgentGraphMobileList } from './AgentGraphMobileList';
import { AgentGraphDetail } from './AgentGraphDetail';
@@ -38,21 +39,6 @@ const LIVENESS_POLL_INTERVAL_MS = 30000;
type GraphPayload = AgentGraphResult & { live_unreachable?: boolean };
-// Desktop ⇒ React Flow canvas; mobile ⇒ grouped list (contract §4).
-function useIsDesktop(): boolean {
- const [desktop, setDesktop] = useState(
- () => typeof window !== 'undefined' && window.matchMedia?.('(min-width: 768px)').matches,
- );
- useEffect(() => {
- if (typeof window === 'undefined' || !window.matchMedia) return;
- const mql = window.matchMedia('(min-width: 768px)');
- const onChange = () => setDesktop(mql.matches);
- mql.addEventListener('change', onChange);
- return () => mql.removeEventListener('change', onChange);
- }, []);
- return !!desktop;
-}
-
// Desktop-only fill height for the canvas + detail panel (design.pen KfgtJ —
// fill_container). The desktop app shell is document-flow (no bounded-height
// ancestor to inherit `h-full` from), so we size the graph area to the viewport
diff --git a/ui/src/components/workbench/AppsEditorPage.tsx b/ui/src/components/workbench/AppsEditorPage.tsx
index 4f381bdb4..600e84272 100644
--- a/ui/src/components/workbench/AppsEditorPage.tsx
+++ b/ui/src/components/workbench/AppsEditorPage.tsx
@@ -7,17 +7,13 @@ import { Button } from '../ui/button';
import { useUnsavedChanges } from '../../context/useUnsavedChanges';
import { FileEditorPane } from './FileEditorPane';
import { EditorFontSizePopover } from './EditorFontSizePopover';
+import { isDesktopViewport } from '../../lib/useIsDesktop';
// The Editor app as a full-page route (sibling of /apps/files and /apps/terminal). On desktop it
// mounts the same full Editor IDE the Dock window uses; on phones — where there is no window layer —
// it renders a slim single-file editor. Design: `dnYPx` (IDE) + `w0qoC` (welcome).
const EditorApp = lazy(() => import('./EditorApp').then((m) => ({ default: m.EditorApp })));
-// The desktop IDE (dnYPx) is designed dark and forces Monaco dark; below this the phone gets the
-// slim editor instead. Matches the File Browser's window-vs-page breakpoint so a tablet (≥768) gets
-// the same full IDE it gets a resizable window for.
-const DESKTOP_QUERY = '(min-width: 768px)';
-
// A file handed to the editor when navigating in from the File Browser (mobile) or a direct link.
// Carried in router state — like the window params `wm.openApp` passes — so absolute paths stay out
// of the URL; a refresh (no state) just lands on the empty/welcome state.
@@ -51,7 +47,7 @@ function readLaunch(state: unknown): LaunchFile | null {
// desktop IDE on a mid-edit resize/rotate would unmount whichever holds the buffer and silently drop
// unsaved edits. A phone that rotates keeps the surface it opened with.
function useDesktopAtMount(): boolean {
- return useState(() => window.matchMedia(DESKTOP_QUERY).matches)[0];
+ return useState(isDesktopViewport)[0];
}
// Warn before a hard unload (refresh / tab close / leaving the SPA) while there are unsaved edits.
diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsx
index a9d9ead96..57fc1e790 100644
--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx
+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx
@@ -34,6 +34,7 @@ import {
X,
type LucideIcon,
} from 'lucide-react';
+import { isDesktopViewport } from '../../lib/useIsDesktop';
import clsx from 'clsx';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
@@ -390,7 +391,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
// routes correctly regardless of where it's called from.
const openInEditor = useCallback(
(path: string, filename: string, mtime: number | null) => {
- if (window.matchMedia('(min-width: 768px)').matches) {
+ if (isDesktopViewport()) {
wm.openApp('editor', { title: filename, params: { path, filename, mtime } });
} else {
routerNavigate('/apps/editor', { state: { path, filename, mtime } });
@@ -403,7 +404,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
// supplies resolved metadata when it has already been fetched (content hits / ambiguous names).
const openPreview = useCallback(
(item: RowItem, entry: FsEntry = item.entry, editable = isEditableFile(entry), mtime = entry.mtime) => {
- if (window.matchMedia('(min-width: 768px)').matches) {
+ if (isDesktopViewport()) {
wm.openApp('preview', { title: entry.name, params: { path: item.full, name: entry.name } });
} else {
setPreview({ path: item.full, name: entry.name, mtime, editable });
@@ -417,7 +418,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
// route with the dir in router state. Mirrors openInEditor.
const openTerminalHere = useCallback(
(dir: string) => {
- if (window.matchMedia('(min-width: 768px)').matches) {
+ if (isDesktopViewport()) {
wm.openApp('terminal', { params: { cwd: dir } });
} else {
routerNavigate('/apps/terminal', { state: { cwd: dir } });
@@ -522,7 +523,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
// hidden, so fall back to the inline create row so a file can still be made.
const onNewFile = useCallback(() => {
if (!cwd) return;
- if (window.matchMedia('(min-width: 768px)').matches) {
+ if (isDesktopViewport()) {
wm.openApp('editor', { title: t('apps.fileBrowser.newFile'), params: { newFileDir: cwd } });
} else {
startNewEntry('file');
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index f7c4eb4ca..e8e4296dd 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -35,6 +35,8 @@ import { isEditableFile, isEditableMeta, previewOverlayKind } from '../../lib/fi
import { recentPathLabel } from '../../lib/editorRecents';
import type { LocalFileLinkTarget } from '../../lib/localFileLinks';
import { formatLocalDateTime, formatRelativeTime } from '../../lib/relativeTime';
+import { canMarkConversationRead, readPageActivity } from '../../lib/pageActivity';
+import { isDesktopViewport, useIsDesktop } from '../../lib/useIsDesktop';
import { resultFooterParts } from '../../lib/resultFooter';
import {
activityItemKind,
@@ -203,6 +205,24 @@ export const ChatPage: React.FC = () => {
const showChatSignal = searchParams.get('view') === 'chat';
const api = useApi();
const { unreadBySession, markRead: markInboxRead } = useWorkbenchInbox();
+ const { focusedId: foregroundAppWindowId, focusCanvas } = useWindowManager();
+ const isDesktop = useIsDesktop();
+ const [pageActive, setPageActive] = useState(() => readPageActivity());
+ useEffect(() => {
+ const syncPageActivity = () => setPageActive(readPageActivity());
+ document.addEventListener('visibilitychange', syncPageActivity);
+ window.addEventListener('focus', syncPageActivity);
+ window.addEventListener('blur', syncPageActivity);
+ window.addEventListener('pageshow', syncPageActivity);
+ window.addEventListener('pagehide', syncPageActivity);
+ return () => {
+ document.removeEventListener('visibilitychange', syncPageActivity);
+ window.removeEventListener('focus', syncPageActivity);
+ window.removeEventListener('blur', syncPageActivity);
+ window.removeEventListener('pageshow', syncPageActivity);
+ window.removeEventListener('pagehide', syncPageActivity);
+ };
+ }, []);
// The mobile chat surface is a fixed full-screen flex column; this keeps the
// composer glued to the iOS keyboard (settle-then-correct; see the hook).
const chatSurfaceRef = useRef<HTMLDivElement>(null);
@@ -242,6 +262,7 @@ export const ChatPage: React.FC = () => {
// before the composer bridge target, which depends on showPageMode.
const [showPageMode, setShowPageMode] = useState(false);
const [showPageBusy, setShowPageBusy] = useState(false);
+ const [showPageViewResolved, setShowPageViewResolved] = useState(false);
// One authority invalidates an in-flight restore/open when the user explicitly
// chooses Chat (including a same-session ?view=chat navigation).
const showPageRequestRef = useRef(0);
@@ -311,6 +332,7 @@ export const ChatPage: React.FC = () => {
// once the new session row loads, the restore effect below applies its own
// remembered view through the same open path as a user click.
showPageRestoreAttemptRef.current = null;
+ setShowPageViewResolved(false);
selectChatView(sessionId ?? '', false);
setShowPageUrl(null);
}, [selectChatView, sessionId]);
@@ -324,6 +346,7 @@ export const ChatPage: React.FC = () => {
const sid = sessionId ?? '';
showPageRestoreAttemptRef.current = sid || null;
selectChatView(sid, true);
+ setShowPageViewResolved(true);
const next = new URLSearchParams(window.location.search);
next.delete('view');
setSearchParams(next, { replace: true });
@@ -1900,10 +1923,18 @@ export const ChatPage: React.FC = () => {
showPageRestoreAttemptRef.current = sid;
if (readOnly) {
writeChatViewMode(sid, 'chat');
+ setShowPageViewResolved(true);
return;
}
- if (showChatSignal || deepLinkMessageId || readChatViewMode(sid) !== 'show-page') return;
- void openShowPage(sid);
+ if (showChatSignal || deepLinkMessageId || readChatViewMode(sid) !== 'show-page') {
+ setShowPageViewResolved(true);
+ return;
+ }
+ void openShowPage(sid).finally(() => {
+ if (sessionIdRef.current === sid && showPageRestoreAttemptRef.current === sid) {
+ setShowPageViewResolved(true);
+ }
+ });
}, [deepLinkMessageId, openShowPage, readOnly, session?.id, sessionId, showChatSignal]);
// When the share control resolves the page (open) or flips its visibility, the
@@ -2171,18 +2202,37 @@ export const ChatPage: React.FC = () => {
};
}, []);
- // The user is actively viewing this session, so an agent reply here is seen,
+ // The user is actively viewing this session's live transcript, so an agent reply is seen,
// not "new". Clear unread whenever it appears — on open, or when a realtime
// inbox.session.updated lands after a reply — so the Inbox/sidebar never badge
// the chat you're looking at. Reactive to the unread map, so it's race-free
// against the cross-process event ordering. Owning this on the mounted route
// also keeps a canceled blocked navigation from clearing unread state early.
useEffect(() => {
- if (historicalWindow) return;
+ if (!canMarkConversationRead({
+ pageActive,
+ sessionReady: !loading && session?.id === sessionId,
+ viewResolved: showPageViewResolved,
+ historicalWindow,
+ showPageActive,
+ foregroundAppWindow: isDesktop && foregroundAppWindowId !== null,
+ })) return;
if (sessionId && (unreadBySession[sessionId] ?? 0) > 0) {
void markInboxRead(sessionId);
}
- }, [sessionId, unreadBySession, markInboxRead, historicalWindow]);
+ }, [
+ sessionId,
+ unreadBySession,
+ markInboxRead,
+ loading,
+ session?.id,
+ showPageViewResolved,
+ historicalWindow,
+ pageActive,
+ showPageActive,
+ isDesktop,
+ foregroundAppWindowId,
+ ]);
// The Workbench canvas creates the session and hands its first message over
// as router state. Replay it once through the compose path so the agent turn
@@ -2440,6 +2490,7 @@ export const ChatPage: React.FC = () => {
<div
ref={chatSurfaceRef}
className="fixed inset-0 z-40 flex flex-col bg-background pt-[env(safe-area-inset-top)] md:relative md:inset-auto md:z-auto md:-mx-10 md:-my-8 md:h-[var(--app-vvh)] md:bg-transparent md:pt-0"
+ onPointerDownCapture={focusCanvas}
{...fileDropHandlers}
>
{/* Drag-and-drop overlay: shown while files hover anywhere over the chat
@@ -3380,7 +3431,7 @@ const Transcript: React.FC<TranscriptProps> = ({
const fileViewer = useFileViewer();
const openLocalFile = useCallback(async (target: LocalFileLinkTarget) => {
const pathLabel = recentPathLabel(target.path);
- const desktop = window.matchMedia('(min-width: 768px)').matches;
+ const desktop = isDesktopViewport();
const openPreview = (name: string, size: number | null, mime: string | null, ext: string | null) => {
if (desktop) {
openApp('preview', { title: name, params: { path: target.path, name } });
diff --git a/ui/src/components/workbench/ShowPageLaunchControl.tsx b/ui/src/components/workbench/ShowPageLaunchControl.tsx
index 9e4ef8e50..14d7d5ef4 100644
--- a/ui/src/components/workbench/ShowPageLaunchControl.tsx
+++ b/ui/src/components/workbench/ShowPageLaunchControl.tsx
@@ -19,6 +19,7 @@ import {
showPageWindowOrigin,
type ViewportPoint,
} from '../../lib/showPageLaunch';
+import { isDesktopViewport } from '../../lib/useIsDesktop';
import { Button } from '../ui/button';
import { Popover, PopoverAnchor, PopoverContent } from '../ui/popover';
@@ -222,7 +223,7 @@ export const ShowPageLaunchControl: React.FC<ShowPageLaunchControlProps> = ({
}}
draggable={canLaunch}
onDragStart={(event) => {
- if (!canLaunch || !window.matchMedia?.('(min-width: 768px)').matches) {
+ if (!canLaunch || !isDesktopViewport()) {
event.preventDefault();
return;
}
diff --git a/ui/src/components/workbench/search/useAppSearch.ts b/ui/src/components/workbench/search/useAppSearch.ts
index 53f9432b1..ac0da8414 100644
--- a/ui/src/components/workbench/search/useAppSearch.ts
+++ b/ui/src/components/workbench/search/useAppSearch.ts
@@ -8,6 +8,7 @@ import { showAppRoutePath } from '../../apps/mobileDock';
import { useShowPageInventory } from '../../useShowPages';
import { useWindowManager } from '../../../context/WindowManagerContext';
import { openLinkInNewContext } from '../../../lib/pwaNavigation';
+import { isDesktopViewport } from '../../../lib/useIsDesktop';
import { filterAppSearchResults, type AppSearchResult } from './appSearch';
export function useAppSearchResults(query: string, enabled = true) {
@@ -61,7 +62,7 @@ export function useOpenSearchApp() {
return;
}
}
- const desktop = typeof window !== 'undefined' && !!window.matchMedia?.('(min-width: 768px)').matches;
+ const desktop = isDesktopViewport();
if (desktop) {
wm.openApp(result.appId, {
title: result.kind === 'showpage' ? result.title : undefined,
diff --git a/ui/src/context/WindowManagerContext.ts b/ui/src/context/WindowManagerContext.ts
index 3b56ddc76..ddfa8110c 100644
--- a/ui/src/context/WindowManagerContext.ts
+++ b/ui/src/context/WindowManagerContext.ts
@@ -35,11 +35,13 @@ export interface OpenAppOptions {
export interface WindowManagerValue {
windows: WindowInstance[];
- /** The current top window id (highest z, not minimized), or null. */
+ /** The app window that owns foreground focus, or null while the canvas owns it. */
focusedId: string | null;
openApp: (appId: AppId, opts?: OpenAppOptions) => string;
close: (id: string) => void;
focus: (id: string) => void;
+ /** Return foreground focus to the workbench canvas without hiding windows. */
+ focusCanvas: () => void;
minimize: (id: string) => void;
/** Un-minimize and bring to front. */
restore: (id: string) => void;
diff --git a/ui/src/context/WindowManagerProvider.test.tsx b/ui/src/context/WindowManagerProvider.test.tsx
new file mode 100644
index 000000000..3d5fadacb
--- /dev/null
+++ b/ui/src/context/WindowManagerProvider.test.tsx
@@ -0,0 +1,75 @@
+// @vitest-environment jsdom
+
+import { act, render } from '@testing-library/react';
+import { useEffect } from 'react';
+import { describe, expect, it } from 'vitest';
+
+import { useWindowManager, type WindowManagerValue } from './WindowManagerContext';
+import { WindowManagerProvider } from './WindowManagerProvider';
+
+describe('WindowManagerProvider focus ownership', () => {
+ it('returns focus to the canvas without hiding the active window', () => {
+ let manager: WindowManagerValue | null = null;
+ const Probe = () => {
+ const value = useWindowManager();
+ useEffect(() => {
+ manager = value;
+ }, [value]);
+ return null;
+ };
+
+ render(
+ <WindowManagerProvider>
+ <Probe />
+ </WindowManagerProvider>,
+ );
+
+ let windowId = '';
+ act(() => {
+ windowId = manager!.openApp('files');
+ });
+ expect(manager!.focusedId).toBe(windowId);
+ expect(manager!.windows.find((window) => window.id === windowId)?.minimized).toBe(false);
+
+ act(() => manager!.focusCanvas());
+ expect(manager!.focusedId).toBeNull();
+ expect(manager!.windows.find((window) => window.id === windowId)?.minimized).toBe(false);
+ });
+
+ it('transfers focus to the highest visible window when the owner closes or minimizes', () => {
+ let manager: WindowManagerValue | null = null;
+ const Probe = () => {
+ const value = useWindowManager();
+ useEffect(() => {
+ manager = value;
+ }, [value]);
+ return null;
+ };
+
+ render(
+ <WindowManagerProvider>
+ <Probe />
+ </WindowManagerProvider>,
+ );
+
+ let firstId = '';
+ let secondId = '';
+ act(() => {
+ firstId = manager!.openApp('files');
+ secondId = manager!.openApp('files');
+ });
+ expect(manager!.focusedId).toBe(secondId);
+
+ act(() => manager!.close(secondId));
+ expect(manager!.focusedId).toBe(firstId);
+
+ let thirdId = '';
+ act(() => {
+ thirdId = manager!.openApp('files');
+ });
+ expect(manager!.focusedId).toBe(thirdId);
+
+ act(() => manager!.minimize(thirdId));
+ expect(manager!.focusedId).toBe(firstId);
+ });
+});
diff --git a/ui/src/context/WindowManagerProvider.tsx b/ui/src/context/WindowManagerProvider.tsx
index 1e65d8ecb..b1c5e857c 100644
--- a/ui/src/context/WindowManagerProvider.tsx
+++ b/ui/src/context/WindowManagerProvider.tsx
@@ -10,6 +10,7 @@ import {
type PersistedWindow,
} from '../lib/workbenchPersistence';
import { useLatestRef } from '@/lib/useLatestRef';
+import { DESKTOP_MEDIA_QUERY, isDesktopViewport } from '../lib/useIsDesktop';
import {
WindowManagerContext,
type WindowBounds,
@@ -22,16 +23,16 @@ const DEFAULT_SIZE = { width: 760, height: 520 };
const CASCADE_STEP = 32;
const CASCADE_WRAP = 6;
+function highestVisibleWindow(windows: readonly WindowInstance[]): WindowInstance | null {
+ return windows
+ .filter((window) => !window.minimized)
+ .reduce<WindowInstance | null>((top, window) => (!top || window.z > top.z ? window : top), null);
+}
+
// Persistence is desktop-only: the window layer is `hidden md:block` and windowed apps open only
// from the desktop-only launcher/Dock, so restoring windows below md would mount invisible bodies
// and a `[]` save from a phone would clobber a real desktop layout. Read live (not frozen at mount)
// so a desktop tab that starts narrow and is widened still restores/saves once it crosses md.
-function isDesktopViewport(): boolean {
- return typeof window !== 'undefined' && typeof window.matchMedia === 'function'
- ? window.matchMedia('(min-width: 768px)').matches
- : false;
-}
-
/**
* `standalone`: this document is a single-app tab (`appTabHref` + `isStandaloneAppTab`).
* Such a tab neither RESTORES the saved layout — the app it was opened for must not
@@ -84,6 +85,12 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa
restoredRef.current = true;
return loadAndSeed();
});
+ const [focusedId, setFocusedId] = useState<string | null>(() => {
+ const visible = windows.filter((window) => !window.minimized);
+ return visible.length > 0
+ ? visible.reduce((top, window) => (window.z > top.z ? window : top)).id
+ : null;
+ });
// Latest windows for the debounced/pagehide save closures (which fire after render).
const windowsRef = useLatestRef(windows);
@@ -158,6 +165,7 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa
}, []);
const focus = useCallback((id: string) => {
+ setFocusedId(id);
setWindows((prev) => {
const target = prev.find((w) => w.id === id);
if (!target) return prev;
@@ -168,6 +176,12 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa
});
}, []);
+ const focusCanvas = useCallback(() => {
+ setFocusedId(null);
+ const active = typeof document === 'undefined' ? null : document.activeElement;
+ if (active instanceof HTMLElement && active.closest('[data-window-id]')) active.blur();
+ }, []);
+
const openApp = useCallback<WindowManagerValue['openApp']>((appId, opts) => {
const def = APP_REGISTRY[appId];
const size = { ...DEFAULT_SIZE, ...def?.defaultSize };
@@ -196,6 +210,7 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa
maximized: false,
},
]);
+ setFocusedId(id);
return id;
}, []);
@@ -203,12 +218,16 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa
closeGuards.current.delete(id);
stateProviders.current.delete(id);
closingIds.current.delete(id);
- setWindows((prev) => prev.filter((w) => w.id !== id));
- }, []);
+ const nextWindows = windowsRef.current.filter((window) => window.id !== id);
+ setFocusedId((current) => (current === id ? highestVisibleWindow(nextWindows)?.id ?? null : current));
+ setWindows(nextWindows);
+ }, [windowsRef]);
const minimize = useCallback((id: string) => {
- setWindows((prev) => prev.map((w) => (w.id === id ? { ...w, minimized: true } : w)));
- }, []);
+ const nextWindows = windowsRef.current.map((window) => (window.id === id ? { ...window, minimized: true } : window));
+ setFocusedId((current) => (current === id ? highestVisibleWindow(nextWindows)?.id ?? null : current));
+ setWindows(nextWindows);
+ }, [windowsRef]);
const restore = useCallback(
(id: string) => {
@@ -256,12 +275,19 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa
useEffect(() => {
if (restoredRef.current) return;
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
- const mql = window.matchMedia('(min-width: 768px)');
+ const mql = window.matchMedia(DESKTOP_MEDIA_QUERY);
const restoreOnce = () => {
if (restoredRef.current || !mql.matches) return;
restoredRef.current = true;
const restored = loadAndSeed();
setWindows((cur) => (cur.length ? cur : restored));
+ setFocusedId((current) => {
+ if (current) return current;
+ const visible = restored.filter((window) => !window.minimized);
+ return visible.length > 0
+ ? visible.reduce((top, window) => (window.z > top.z ? window : top)).id
+ : null;
+ });
};
restoreOnce(); // may have crossed to desktop between the initial render and this effect
mql.addEventListener('change', restoreOnce);
@@ -287,12 +313,6 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa
};
}, [flushSave]);
- const focusedId = useMemo(() => {
- const visible = windows.filter((w) => !w.minimized);
- if (visible.length === 0) return null;
- return visible.reduce((top, w) => (w.z > top.z ? w : top)).id;
- }, [windows]);
-
// True while ANY window is mid drag/resize. A transient shared flag (not persisted)
// that arms the per-window iframe shield during a gesture (§7.1i).
const [gestureActive, setGestureActive] = useState(false);
@@ -304,6 +324,7 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa
openApp,
close,
focus,
+ focusCanvas,
minimize,
restore,
toggleMaximize,
@@ -317,7 +338,7 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa
gestureActive,
setGestureActive,
}),
- [windows, focusedId, openApp, close, focus, minimize, restore, toggleMaximize, setBounds, setTitle, setParams, setCloseGuard, setStateProvider, markClosing, confirmClose, gestureActive],
+ [windows, focusedId, openApp, close, focus, focusCanvas, minimize, restore, toggleMaximize, setBounds, setTitle, setParams, setCloseGuard, setStateProvider, markClosing, confirmClose, gestureActive],
);
return <WindowManagerContext.Provider value={value}>{children}</WindowManagerContext.Provider>;
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index dc8401ebf..0745ae650 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -5,6 +5,7 @@ import { useApi } from './ApiContext';
import type { InboxSession } from './ApiContext';
import { WorkbenchInboxContext, type InboxState } from './WorkbenchInboxContext';
import { sessionActivityInboxAction } from '../lib/inboxActivity';
+import { syncFaviconBadge } from '../lib/faviconBadge';
const PAGE_SIZE = 30;
@@ -301,6 +302,13 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
void op?.catch?.(() => {});
}, [totalUnread, unreadLoaded]);
+ // Browser tabs have no Badging API. Keep their favicon useful while the
+ // Inbox map is authoritative, and restore the original icon after reading.
+ useEffect(() => {
+ if (!unreadLoaded) return;
+ syncFaviconBadge(totalUnread);
+ }, [totalUnread, unreadLoaded]);
+
const value = useMemo<InboxState>(
() => ({
inboxSessions,
diff --git a/ui/src/lib/faviconBadge.test.ts b/ui/src/lib/faviconBadge.test.ts
new file mode 100644
index 000000000..6484bd267
--- /dev/null
+++ b/ui/src/lib/faviconBadge.test.ts
@@ -0,0 +1,27 @@
+// @vitest-environment jsdom
+
+import { describe, expect, it } from 'vitest';
+
+import { createFaviconBadgeDataUrl, formatFaviconBadgeCount, syncFaviconBadge } from './faviconBadge';
+
+describe('favicon unread badge', () => {
+ it('formats large counts compactly', () => {
+ expect(formatFaviconBadgeCount(4)).toBe('4');
+ expect(formatFaviconBadgeCount(100)).toBe('99+');
+ });
+
+ it('writes a self-contained badge and restores the original icon at zero', () => {
+ const targetDocument = document.implementation.createHTMLDocument('favicon');
+ const link = targetDocument.createElement('link');
+ link.rel = 'icon';
+ link.href = '/logo.png';
+ targetDocument.head.appendChild(link);
+
+ syncFaviconBadge(3, targetDocument);
+ expect(link.href).toContain('data:image/svg+xml');
+ expect(decodeURIComponent(link.href)).toContain('>3</text>');
+ syncFaviconBadge(0, targetDocument);
+ expect(link.getAttribute('href')).toBe('/logo.png');
+ expect(createFaviconBadgeDataUrl(12)).toContain('data:image/svg+xml');
+ });
+});
diff --git a/ui/src/lib/faviconBadge.ts b/ui/src/lib/faviconBadge.ts
new file mode 100644
index 000000000..88ebd1c05
--- /dev/null
+++ b/ui/src/lib/faviconBadge.ts
@@ -0,0 +1,32 @@
+const DEFAULT_FAVICON_PATH = '/logo.png';
+const FAVICON_SELECTOR = 'link[rel="icon"]';
+const BASE_HREF_ATTRIBUTE = 'data-avibe-base-href';
+
+export function formatFaviconBadgeCount(count: number): string {
+ const normalized = Number.isFinite(count) ? Math.max(0, Math.trunc(count)) : 0;
+ return normalized > 99 ? '99+' : String(normalized);
+}
+/** Build a small self-contained favicon so the browser can render the badge. */
+export function createFaviconBadgeDataUrl(count: number): string {
+ const label = formatFaviconBadgeCount(count);
+ const fontSize = label.length > 2 ? 15 : 19;
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#1b0f45"/><path d="M6 34h10c5 0 5-14 10-14s5 25 10 25 5-33 10-33 5 22 10 22h2" fill="none" stroke="#fff" stroke-linecap="round" stroke-linejoin="round" stroke-width="5"/><circle cx="51" cy="13" r="12" fill="#ff5368" stroke="#080812" stroke-width="3"/><text x="51" y="18" fill="#fff" font-family="Arial,sans-serif" font-size="${fontSize}" font-weight="700" text-anchor="middle">${label}</text></svg>`;
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
+}
+
+/** Keep the regular favicon until a badge is needed, then restore it exactly. */
+export function syncFaviconBadge(count: number, targetDocument: Document | null = typeof document === 'undefined' ? null : document): void {
+ if (!targetDocument) return;
+
+ let link = targetDocument.querySelector<HTMLLinkElement>(FAVICON_SELECTOR);
+ if (!link) {
+ link = targetDocument.createElement('link');
+ link.rel = 'icon';
+ link.href = DEFAULT_FAVICON_PATH;
+ targetDocument.head?.appendChild(link);
+ }
+
+ const baseHref = link.getAttribute(BASE_HREF_ATTRIBUTE) || link.getAttribute('href') || DEFAULT_FAVICON_PATH;
+ link.setAttribute(BASE_HREF_ATTRIBUTE, baseHref);
+ link.href = count > 0 ? createFaviconBadgeDataUrl(count) : baseHref;
+}
diff --git a/ui/src/lib/pageActivity.test.ts b/ui/src/lib/pageActivity.test.ts
new file mode 100644
index 000000000..25853ec90
--- /dev/null
+++ b/ui/src/lib/pageActivity.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { canMarkConversationRead, isPageActive } from './pageActivity';
+
+describe('isPageActive', () => {
+ it('requires both a visible document and window focus', () => {
+ expect(isPageActive({ visibilityState: 'visible', hasFocus: true })).toBe(true);
+ expect(isPageActive({ visibilityState: 'visible', hasFocus: false })).toBe(false);
+ expect(isPageActive({ visibilityState: 'hidden', hasFocus: true })).toBe(false);
+ });
+});
+
+describe('canMarkConversationRead', () => {
+ it('requires the visible chat transcript to be current and active', () => {
+ const visibleTranscript = {
+ pageActive: true,
+ sessionReady: true,
+ viewResolved: true,
+ historicalWindow: false,
+ showPageActive: false,
+ foregroundAppWindow: false,
+ };
+
+ expect(canMarkConversationRead(visibleTranscript)).toBe(true);
+ expect(canMarkConversationRead({ ...visibleTranscript, pageActive: false })).toBe(false);
+ expect(canMarkConversationRead({ ...visibleTranscript, sessionReady: false })).toBe(false);
+ expect(canMarkConversationRead({ ...visibleTranscript, viewResolved: false })).toBe(false);
+ expect(canMarkConversationRead({ ...visibleTranscript, historicalWindow: true })).toBe(false);
+ expect(canMarkConversationRead({ ...visibleTranscript, showPageActive: true })).toBe(false);
+ expect(canMarkConversationRead({ ...visibleTranscript, foregroundAppWindow: true })).toBe(false);
+ });
+});
diff --git a/ui/src/lib/pageActivity.ts b/ui/src/lib/pageActivity.ts
new file mode 100644
index 000000000..e5360f14c
--- /dev/null
+++ b/ui/src/lib/pageActivity.ts
@@ -0,0 +1,42 @@
+export type PageActivitySnapshot = {
+ visibilityState: DocumentVisibilityState;
+ hasFocus: boolean;
+};
+
+/** A page is actively presented only while its document is visible and focused. */
+export function isPageActive(snapshot: PageActivitySnapshot): boolean {
+ return snapshot.visibilityState === 'visible' && snapshot.hasFocus;
+}
+
+export function canMarkConversationRead({
+ pageActive,
+ sessionReady,
+ viewResolved,
+ historicalWindow,
+ showPageActive,
+ foregroundAppWindow,
+}: {
+ pageActive: boolean;
+ sessionReady: boolean;
+ viewResolved: boolean;
+ historicalWindow: boolean;
+ showPageActive: boolean;
+ foregroundAppWindow: boolean;
+}): boolean {
+ return (
+ pageActive &&
+ sessionReady &&
+ viewResolved &&
+ !historicalWindow &&
+ !showPageActive &&
+ !foregroundAppWindow
+ );
+}
+
+export function readPageActivity(): boolean {
+ if (typeof document === 'undefined') return false;
+ return isPageActive({
+ visibilityState: document.visibilityState,
+ hasFocus: typeof document.hasFocus !== 'function' || document.hasFocus(),
+ });
+}
diff --git a/ui/src/lib/useIsDesktop.test.ts b/ui/src/lib/useIsDesktop.test.ts
new file mode 100644
index 000000000..326f77675
--- /dev/null
+++ b/ui/src/lib/useIsDesktop.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from 'vitest';
+
+import { DESKTOP_MEDIA_QUERY, isDesktopViewport } from './useIsDesktop';
+
+describe('isDesktopViewport', () => {
+ it('uses the shell desktop breakpoint', () => {
+ const targetWindow = {
+ matchMedia: (query: string) => ({ matches: query === DESKTOP_MEDIA_QUERY }) as MediaQueryList,
+ };
+
+ expect(isDesktopViewport(targetWindow)).toBe(true);
+ expect(isDesktopViewport(null)).toBe(false);
+ });
+});
diff --git a/ui/src/lib/useIsDesktop.ts b/ui/src/lib/useIsDesktop.ts
new file mode 100644
index 000000000..ff5900d9e
--- /dev/null
+++ b/ui/src/lib/useIsDesktop.ts
@@ -0,0 +1,27 @@
+import { useEffect, useState } from 'react';
+
+export const DESKTOP_MEDIA_QUERY = '(min-width: 768px)';
+
+type MatchMediaOwner = Pick<Window, 'matchMedia'>;
+
+export function isDesktopViewport(
+ targetWindow: MatchMediaOwner | null = typeof window === 'undefined' ? null : window,
+): boolean {
+ return Boolean(targetWindow?.matchMedia?.(DESKTOP_MEDIA_QUERY).matches);
+}
+
+/** Reactive counterpart to the shell's `md` desktop breakpoint. */
+export function useIsDesktop(): boolean {
+ const [isDesktop, setIsDesktop] = useState(isDesktopViewport);
+
+ useEffect(() => {
+ if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
+ const media = window.matchMedia(DESKTOP_MEDIA_QUERY);
+ const sync = () => setIsDesktop(media.matches);
+ sync();
+ media.addEventListener('change', sync);
+ return () => media.removeEventListener('change', sync);
+ }, []);
+
+ return isDesktop;
+}