The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): share the floating composer across chat panes
brooklyn!087fbe3847fc
diff --git a/apps/desktop/DESIGN.md b/apps/desktop/DESIGN.mdindex 84f2cea564c..7518ef37ca3 100644--- a/apps/desktop/DESIGN.md+++ b/apps/desktop/DESIGN.md@@ -321,6 +321,16 @@ so glass and message-bubble transparency do not reveal scrolling text.pause/resume preserve the user's disclosure choice. Error banners meet thestack's top edge without a blank padding strip. File and preview links remainvisible at the bottom of the stack, below the queue and all status groups.+- Popping out a composer makes it the window's only visible composer. It keeps+ its viewport placement while hover or keyboard focus selects a chat pane;+ moving back into the editor retains that recipient. Drafts, attachments and+ queues stay session-owned. Docking restores the individual pane composers.+ In either placement, moving into a chat pane gives its editor typing focus+ immediately and preserves its caret. Layout-only hover events and delayed+ focus callbacks cannot replace that choice. Movement within the same pane+ must not flush React; deliberate Tab navigation and clicked controls still work.+ Active dictation or voice conversation pins the recipient until capture ends,+ keeping the microphone's stop controls and shortcut attached to its owner.- Status-stack rows use `StatusRow` with a leading `dismiss` action, a stateicon and optional trailing actions. `StatusDismissButton` owns the Codiconclose button for previews, background tasks and queued prompts; do not swap@@ -406,6 +416,8 @@ long transcript or a busy terminal.- Focusing the Sessions sidebar preserves the last active chat's visual emphasis.Dimming still distinguishes session panes; sidebar navigation must not desaturatethe chat or transfer its active highlight to a hidden primary tab.+- Focused and hovered chat panes both retain full color and opacity. Only panes+ that are neither focused nor hovered recede, with 20% desaturation.- Register global shortcuts through the shared layer, not ad-hoc listeners.- One cancel gesture does one thing: cancel the active interaction, or close thetopmost dismissable surface — never both, never the control underneath.diff --git a/apps/desktop/src/app/chat/composer/floating-state.ts b/apps/desktop/src/app/chat/composer/floating-state.tsnew file mode 100644index 00000000000..881e1d5d4f2--- /dev/null+++ b/apps/desktop/src/app/chat/composer/floating-state.ts@@ -0,0 +1,12 @@+import { atom } from 'nanostores'++import type { ComposerTarget } from './focus'++export interface FloatingComposerOwner {+ id: string+ groupId: string+ target: ComposerTarget+}++/** User intent, not whichever editor happened to receive a delayed DOM focus. */+export const $floatingComposerOwner = atom<FloatingComposerOwner | null>(null)diff --git a/apps/desktop/src/app/chat/composer/floating-surface.tsx b/apps/desktop/src/app/chat/composer/floating-surface.tsxnew file mode 100644index 00000000000..f88de98f92e--- /dev/null+++ b/apps/desktop/src/app/chat/composer/floating-surface.tsx@@ -0,0 +1,83 @@+import { useStore } from '@nanostores/react'+import { type ReactNode, useLayoutEffect, useRef, useState } from 'react'+import { createPortal } from 'react-dom'++import { hiddenPaneProps, usePaneGroup, usePaneVisible } from '@/components/pane-shell/pane-visibility'+import { useStoreSelector } from '@/lib/use-session-slice'+import { $composerPopout, $composerPopoutGesturesEnabled } from '@/store/composer-popout'+import { isSecondaryWindow } from '@/store/windows'++import { $floatingComposerOwner } from './floating-state'+import { registerFloatingComposer } from './floating-target'+import { useComposerScope, useComposerSurfaceId } from './scope'+import { ComposerVisibleContext } from './visibility'++interface ComposerSurfaceProps {+ children: ReactNode+}++/** Keep each session's editor, drafts and queue alive, but expose only the+ * recipient while floating. Moving a stable portal host avoids editor remounts. */+export function FloatingComposerSurface({ children }: ComposerSurfaceProps) {+ const anchorRef = useRef<HTMLDivElement>(null)+ const id = useComposerSurfaceId()!+ const groupId = usePaneGroup()++ // Identity must exist before descendant layout effects publish measurements.+ const [host] = useState(() => {+ const element = document.createElement('div')+ element.dataset.composerOwner = id+ element.dataset.treeGroup = groupId++ return element+ })++ const { target } = useComposerScope()+ const paneVisible = usePaneVisible()+ const enabled = useStore($composerPopoutGesturesEnabled)+ const floating = useStoreSelector($composerPopout, state => state.poppedOut) && enabled && !isSecondaryWindow()+ const selected = useStoreSelector($floatingComposerOwner, owner => owner?.id === id)+ const visible = paneVisible && (!floating || selected)++ useLayoutEffect(() => {+ const surface = anchorRef.current?.closest<HTMLElement>('[data-chat-surface]')++ if (!surface || !paneVisible) {+ return undefined+ }++ return registerFloatingComposer(id, { groupId, target })+ // Re-register when Fast Refresh replaces the module-local recipient registry.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [groupId, id, paneVisible, registerFloatingComposer, target])++ useLayoutEffect(() => {+ host.dataset.composerOwner = id+ host.dataset.treeGroup = groupId++ if (floating) {+ host.dataset.floatingComposerTarget = target+ } else {+ delete host.dataset.floatingComposerTarget+ }++ host.style.display = visible ? 'contents' : 'none'+ host.toggleAttribute('data-pane-hidden', !visible)+ host.inert = !visible++ const parent = floating ? document.body : anchorRef.current++ if (parent && host.parentElement !== parent) {+ parent.appendChild(host)+ }+ }, [floating, groupId, host, id, target, visible])++ useLayoutEffect(() => () => host.remove(), [host])++ return (+ <>+ <div className="contents" ref={anchorRef} {...hiddenPaneProps(!visible)} />+ {createPortal(<ComposerVisibleContext value={visible}>{children}</ComposerVisibleContext>, host)}+ </>+ )+}diff --git a/apps/desktop/src/app/chat/composer/floating-target.ts b/apps/desktop/src/app/chat/composer/floating-target.tsnew file mode 100644index 00000000000..a36b2e826d2--- /dev/null+++ b/apps/desktop/src/app/chat/composer/floating-target.ts@@ -0,0 +1,258 @@+import { flushSync } from 'react-dom'++import { $activeTreeGroup, $hoveredTreeGroup, noteActiveTreeGroup } from '@/components/pane-shell/tree/store'+import { $composerPopout } from '@/store/composer-popout'++import { $floatingComposerOwner, type FloatingComposerOwner } from './floating-state'+import { focusComposerInput, markActiveComposer } from './focus'+import { placeCaretEnd } from './rich-editor'++const surfaces = new Map<string, Omit<FloatingComposerOwner, 'id'>>()+const captureOwners = new Set<string>()+const carets = new WeakMap<HTMLElement, Range>()+let pointer: { x: number; y: number } | null = null+let pointerDownTarget: Element | null = null+let keyboardNavigation = false+let reconcileQueued = false++function rememberCaret(editor: EventTarget | null) {+ const selection = window.getSelection()++ if (editor instanceof HTMLElement && editor.dataset.slot === 'composer-rich-input' && selection?.rangeCount) {+ const range = selection.getRangeAt(0)++ if (editor.contains(range.commonAncestorContainer)) {+ carets.set(editor, range.cloneRange())+ }+ }+}++const trackBlur = (event: FocusEvent) => rememberCaret(event.target)++const releasePointer = () => {+ pointerDownTarget = null+}++function focusSelectedComposer() {+ const owner = $floatingComposerOwner.get()++ if (!owner) {+ return+ }++ const host = [...document.querySelectorAll<HTMLElement>('[data-composer-owner]')].find(+ el => el.dataset.composerOwner === owner.id+ )++ const editor = host?.querySelector<HTMLElement>('[data-slot="composer-rich-input"]')++ if (editor && document.activeElement !== editor) {+ focusComposerInput(editor)+ const caret = carets.get(editor)+ const selection = window.getSelection()++ if (caret && editor.contains(caret.startContainer) && editor.contains(caret.endContainer) && selection) {+ selection.removeAllRanges()+ selection.addRange(caret)+ } else {+ placeCaretEnd(editor)+ }+ }+}++function selectSurface(id: string) {+ const captureOwner = [...captureOwners].find(owner => surfaces.has(owner))+ const surface = surfaces.get(id)++ if (!surface || ($composerPopout.get().poppedOut && captureOwner && captureOwner !== id)) {+ return+ }++ if ($floatingComposerOwner.get()?.id !== id) {+ rememberCaret(document.activeElement)+ $floatingComposerOwner.set({ id, ...surface })+ }++ markActiveComposer(surface.target)+}++function surfaceAt(target: Element): string | undefined {+ const host = target.closest<HTMLElement>('[data-composer-owner]')++ if (host) {+ return host.hasAttribute('data-floating-composer-target') ? undefined : host.dataset.composerOwner+ }++ const id = target.closest<HTMLElement>('[data-chat-surface]')?.dataset.composerSurfaceId++ if (id && surfaces.has(id)) {+ return id+ }++ const groupId = target.closest<HTMLElement>('[data-tree-group]')?.dataset.treeGroup++ return [...surfaces].find(([, surface]) => surface.groupId === groupId)?.[0]+}++function trackPointer(event: PointerEvent) {+ const target = event.target instanceof Element ? event.target : null++ if (event.type === 'pointerdown') {+ pointerDownTarget = target+ keyboardNavigation = false+ } else {+ if (pointer?.x === event.clientX && pointer.y === event.clientY) {+ return+ }++ pointer = { x: event.clientX, y: event.clientY }+ pointerDownTarget = null+ keyboardNavigation = false+ }++ if (!target || (event.type === 'pointermove' && event.buttons !== 0)) {+ return+ }++ const id = surfaceAt(target)++ if (!id) {+ return+ }++ // Commit the recipient and expose its existing editor before the very next+ // key event. Pointerover can fire on layout changes with a stationary mouse;+ // only actual movement or a click is user intent.+ const changed = $floatingComposerOwner.get()?.id !== id++ if (changed) {+ flushSync(() => selectSurface(id))+ }++ const active = document.activeElement++ const alreadyTyping =+ active instanceof HTMLElement &&+ active.dataset.slot === 'composer-rich-input' &&+ active.closest<HTMLElement>('[data-composer-owner]')?.dataset.composerOwner === id++ if (event.type === 'pointermove' && !alreadyTyping) {+ focusSelectedComposer()+ }+}++function trackKey(event: KeyboardEvent) {+ keyboardNavigation = event.type === 'keydown' && event.key === 'Tab' && !event.ctrlKey && !event.metaKey+}++function trackFocus(event: FocusEvent) {+ const target = event.target instanceof Element ? event.target : null++ if (!target) {+ return+ }++ const hostId = target.closest<HTMLElement>('[data-composer-owner]')?.dataset.composerOwner++ if (hostId === $floatingComposerOwner.get()?.id) {+ return+ }++ const id = hostId ?? surfaceAt(target)++ if (!id) {+ return+ }++ // A delayed focus/restore isn't a navigation gesture. A clicked control or+ // keyboard Tab still keeps its normal focus, without redirecting to the input.+ if (keyboardNavigation || (pointerDownTarget && target.contains(pointerDownTarget))) {+ flushSync(() => selectSurface(id))+ } else {+ event.stopImmediatePropagation()+ const owner = $floatingComposerOwner.get()++ if (owner) {+ noteActiveTreeGroup(owner.groupId)+ }++ focusSelectedComposer()+ }+}++function reconcile() {+ const owner = $floatingComposerOwner.get()+ const groupId = owner?.groupId ?? $hoveredTreeGroup.get() ?? $activeTreeGroup.get()+ const replacement = [...surfaces].find(([, surface]) => surface.groupId === groupId)?.[0]+ const next = replacement ?? (owner && surfaces.has(owner.id) ? owner.id : surfaces.keys().next().value)++ if (!next) {+ $floatingComposerOwner.set(null)+ } else {+ selectSurface(next)+ }+}++/** Registration can span an old tab's cleanup and its replacement's mount.+ * Reconcile after that commit, never temporarily select an unrelated split. */+export function registerFloatingComposer(id: string, surface: Omit<FloatingComposerOwner, 'id'>): () => void {+ surfaces.set(id, surface)++ if (surfaces.size === 1) {+ window.addEventListener('pointermove', trackPointer, true)+ window.addEventListener('pointerdown', trackPointer, true)+ window.addEventListener('focusin', trackFocus, true)+ window.addEventListener('focusout', trackBlur, true)+ window.addEventListener('pointerup', releasePointer, true)+ window.addEventListener('keydown', trackKey, true)+ window.addEventListener('keyup', trackKey, true)+ }++ if (!$floatingComposerOwner.get() || $floatingComposerOwner.get()?.groupId === surface.groupId) {+ selectSurface(id)+ }++ return () => {+ surfaces.delete(id)++ if (!reconcileQueued) {+ reconcileQueued = true+ queueMicrotask(() => {+ reconcileQueued = false+ flushSync(reconcile)+ })+ }++ if (surfaces.size === 0) {+ window.removeEventListener('pointermove', trackPointer, true)+ window.removeEventListener('pointerdown', trackPointer, true)+ window.removeEventListener('focusin', trackFocus, true)+ window.removeEventListener('focusout', trackBlur, true)+ window.removeEventListener('pointerup', releasePointer, true)+ window.removeEventListener('keydown', trackKey, true)+ window.removeEventListener('keyup', trackKey, true)+ pointer = null+ pointerDownTarget = null+ keyboardNavigation = false+ }+ }+}++export function claimFloatingComposer(id: string) {+ selectSurface(id)+ const owner = $floatingComposerOwner.get()++ if (owner) {+ markActiveComposer(owner.target)+ }+}++/** Keep the microphone's stop controls and hotkey on its real owner. */+export function pinFloatingComposerCapture(id: string): () => void {+ captureOwners.add(id)+ claimFloatingComposer(id)++ return () => {+ captureOwners.delete(id)+ }+}diff --git a/apps/desktop/src/app/chat/composer/focus.ts b/apps/desktop/src/app/chat/composer/focus.tsindex dc72c10e591..1f596e423b2 100644--- a/apps/desktop/src/app/chat/composer/focus.ts+++ b/apps/desktop/src/app/chat/composer/focus.ts@@ -13,6 +13,7 @@import { isElementInHiddenPane, queryAllVisible, queryVisible } from '@/components/pane-shell/pane-visibility'import { $hoveredTreeGroup } from '@/components/pane-shell/tree/store'+import { $floatingComposerOwner } from './floating-state'import type { InlineRefInput } from './inline-refs'import { RICH_INPUT_SLOT } from './rich-editor'@@ -136,6 +137,14 @@ const targetIsReachable = (target: ComposerTarget): boolean => {* voice / soft `/` agree with the keyboard path.*/const resolveActive = (): ComposerTarget => {+ const owner = $floatingComposerOwner.get()?.target++ if (owner && (activeTarget !== 'edit' || !targetIsReachable('edit'))) {+ activeTarget = owner++ return owner+ }+if (targetIsReachable(activeTarget)) {return activeTarget}@@ -242,7 +251,22 @@ export const getActiveComposer = (): ComposerTarget => resolveActive()export const requestComposerFocus = (target: ComposerTarget | 'active' = 'active',{ typeChar }: { typeChar?: string } = {}-) => dispatch<FocusDetail>(FOCUS_EVENT, { target: resolve(target), typeChar })+) => {+ const detail = { target: resolve(target), typeChar }+ const owner = $floatingComposerOwner.get()++ // A first character must land before subsequent native input events, not+ // behind a timer that can reorder fast typing or a pane handoff.+ if (typeChar) {+ dispatchNow<FocusDetail>(FOCUS_EVENT, detail)+ } else if (typeof window !== 'undefined') {+ window.setTimeout(() => {+ if (!owner || $floatingComposerOwner.get() === owner) {+ dispatchNow<FocusDetail>(FOCUS_EVENT, detail)+ }+ }, 0)+ }+}export const requestComposerInsert = (text: string,@@ -399,14 +423,26 @@ export const focusComposerInput = (el: HTMLElement | null) => {// Also skip when another VISIBLE composer holds the caret — a keep-alive// remount must not yank typing. A hidden tab that still has DOM focus must// not block the pane the user just switched to.+ const owner = $floatingComposerOwner.get()+ const surfaceId = el.closest<HTMLElement>('[data-composer-owner]')?.dataset.composerOwner+const focus = () => {- if (document.activeElement === el) {+ if (owner && (owner !== $floatingComposerOwner.get() || (surfaceId && surfaceId !== owner.id))) {+ return+ }++ if (!el.isConnected || isElementInHiddenPane(el) || document.activeElement === el) {return}const active = document.activeElement- if (active instanceof HTMLElement && active.dataset.slot === RICH_INPUT_SLOT && !isElementInHiddenPane(active)) {+ if (+ active instanceof HTMLElement &&+ active.dataset.slot === RICH_INPUT_SLOT &&+ !isElementInHiddenPane(active) &&+ (!owner || surfaceId !== owner.id)+ ) {return}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.tsindex 7692cf60cd9..772f5e5c8e9 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts@@ -10,8 +10,9 @@ import { useAui, useAuiState, useComposerRuntime } from '@assistant-ui/react'import { SLASH_COMMAND_RE } from '@hermes/shared'import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'-import { usePaneVisible } from '@/components/pane-shell/pane-visibility'+import { isElementInHiddenPane } from '@/components/pane-shell/pane-visibility'import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'+import { useStoreSelector } from '@/lib/use-session-slice'import {type ComposerAttachment,type ComposerDraftSyncMode,@@ -21,6 +22,7 @@ import {takeSessionDraft} from '@/store/composer'import { isBrowsingHistory } from '@/store/composer-input-history'+import { $composerPopout } from '@/store/composer-popout'import { clearDraftSuggestions, sampleComposerDraft } from '@/store/composer-suggestions'import {@@ -32,6 +34,7 @@ import {import {type ComposerInsertMode,focusComposerInput,+ getActiveComposer,markActiveComposer,onComposerFocusRequest,onComposerInsertRefsRequest,@@ -48,6 +51,7 @@ import {} from '../rich-editor'import { useComposerScope } from '../scope'import type { ChatBarProps } from '../types'+import { useComposerVisible } from '../visibility'interface UseComposerDraftArgs {activeQueueSessionKey: string | null@@ -76,7 +80,10 @@ export function useComposerDraft({}: UseComposerDraftArgs) {const aui = useAui()const composerRuntime = useComposerRuntime()- const paneVisible = usePaneVisible()+ const paneVisible = useComposerVisible()+ const visibleRef = useRef(paneVisible)+ visibleRef.current = paneVisible+ const floating = useStoreSelector($composerPopout, state => state.poppedOut)// Which composer this is on the focus bus + which attachment set it owns.const { attachments: attachmentScope, target } = useComposerScope()@@ -126,6 +133,12 @@ export function useComposerDraft({const [focusRequestId, setFocusRequestId] = useState(0)const focusInput = useCallback(() => {+ const editor = editorRef.current++ if (!visibleRef.current || (editor && (!editor.isConnected || isElementInHiddenPane(editor)))) {+ return+ }+focusComposerInput(editorRef.current)markActiveComposer(target)}, [target])@@ -153,16 +166,16 @@ export function useComposerDraft({// here steals the selection from the visible composer without changing// document.activeElement. The foreground then still looks focused while// printable keydowns produce no input.- if (paneVisible) {+ if (visibleRef.current && getActiveComposer() === target && !isElementInHiddenPane(editor)) {placeCaretEnd(editor)}}- if (focus) {+ if (focus && visibleRef.current) {requestMainFocus()}},- [paneVisible, requestMainFocus, setComposerText]+ [requestMainFocus, setComposerText, target])const appendExternalText = useCallback(@@ -196,10 +209,24 @@ export function useComposerDraft({// effect and steal the caret. usePaneVisible defaults true outside a tab// stack, so tiles, pop-outs, and secondary windows still auto-focus.useEffect(() => {+ if (!inputDisabled && paneVisible && !floating) {+ focusInput()+ }+ }, [floating, focusInput, focusKey, inputDisabled, paneVisible])++ const previousFocusRequest = useRef(focusRequestId)+ // eslint-disable-next-line no-restricted-syntax -- handled request token, not a mirrored atom+ useEffect(() => {+ if (previousFocusRequest.current === focusRequestId) {+ return+ }++ previousFocusRequest.current = focusRequestId+if (!inputDisabled && paneVisible) {focusInput()}- }, [focusInput, focusKey, focusRequestId, inputDisabled, paneVisible])+ }, [focusInput, focusRequestId, inputDisabled, paneVisible])// The mirror of the `markActiveComposer` above: give the key back when this// composer goes away (a session tile closing, a pane unmounting). Covers both@@ -222,7 +249,8 @@ export function useComposerDraft({// Type-to-focus appends at end; bare Enter just focuses.if (typeChar) {- paintDraft(`${draftRef.current}${typeChar}`, true)+ paintDraft(`${draftRef.current}${typeChar}`, false)+ focusInput()return}@@ -240,7 +268,7 @@ export function useComposerDraft({offFocus()offInsert()}- }, [appendExternalText, inputDisabled, paintDraft, target])+ }, [appendExternalText, focusInput, inputDisabled, paintDraft, target])const stashAt = (scope: string | null, text = draftRef.current, attachments = attachmentScope.$attachments.get()) =>stashSessionDraft(scope, text, attachments)@@ -272,11 +300,11 @@ export function useComposerDraft({if (editorRef.current) {renderComposerContents(editorRef.current, '')- if (paneVisible) {+ if (visibleRef.current && getActiveComposer() === target && !isElementInHiddenPane(editorRef.current)) {placeCaretEnd(editorRef.current)}}- }, [paneVisible, setComposerText])+ }, [setComposerText, target])// Read the editor's current plain text into draftRef + composer state. This// closes the "queued rAF flush hasn't run yet" window so scope-swap/pagehide@@ -375,7 +403,8 @@ export function useComposerDraft({return false}- const nextDraft = insertInlineRefsIntoEditor(editor, refs, { interactive: paneVisible })+ const interactive = visibleRef.current && getActiveComposer() === target && !isElementInHiddenPane(editor)+ const nextDraft = insertInlineRefsIntoEditor(editor, refs, { interactive })if (nextDraft === null) {return false@@ -384,7 +413,7 @@ export function useComposerDraft({draftRef.current = nextDraftsetComposerText(nextDraft)- if (paneVisible) {+ if (interactive) {requestMainFocus()}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.tsindex dbc0ab24b06..644f0a30367 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts@@ -125,20 +125,6 @@ export function useComposerMetrics({return}- // Floating composer is out of the thread's flow — it must not reserve any- // bottom clearance. Zero the measured vars so the thread reclaims the space.- // Read through a ref so the callback stays stable, and read THIS surface's- // own state: pop-out is per layout zone, so a float in the left split must- // not zero the right split's clearance.- if (poppedOutRef.current) {- lastBucketedHeightRef.current = 0- lastBucketedSurfaceHeightRef.current = 0- setSurfaceVar(composer, COMPOSER_HEIGHT_VAR, '0px')- setSurfaceVar(composer, COMPOSER_SURFACE_HEIGHT_VAR, '0px')-- return- }-const { height } = dock.getBoundingClientRect()const { width } = composer.getBoundingClientRect()const surfaceHeight = composerSurfaceRef.current?.getBoundingClientRect().height@@ -164,6 +150,17 @@ export function useComposerMetrics({setExpanded(true)}+ // Floats still need their width-driven controls, but no pane reserves+ // bottom clearance while the shared composer is detached.+ if (poppedOutRef.current) {+ lastBucketedHeightRef.current = 0+ lastBucketedSurfaceHeightRef.current = 0+ setSurfaceVar(composer, COMPOSER_HEIGHT_VAR, '0px')+ setSurfaceVar(composer, COMPOSER_SURFACE_HEIGHT_VAR, '0px')++ return+ }+if (height > 0) {const bucket = Math.round(height / 8) * 8diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-popout.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-popout.tsindex c304a712795..cc7e8e5dd32 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-popout.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-popout.ts@@ -1,62 +1,41 @@import { useStore } from '@nanostores/react'-import { type RefObject, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'+import { type RefObject, useCallback, useLayoutEffect, useState } from 'react'-import { usePaneGroup, usePaneVisible } from '@/components/pane-shell/pane-visibility'import { useResizeObserver } from '@/hooks/use-resize-observer'import { triggerHaptic } from '@/lib/haptics'import {+ $composerPopout,$composerPopoutGesturesEnabled,- $composerPopoutZone,clampPopoutPosition,- getComposerPopoutZone,- popoutBoundsElement,type PopoutPosition,- readPopoutBounds,setComposerPoppedOut} from '@/store/composer-popout'import { isSecondaryWindow } from '@/store/windows'+import { claimFloatingComposer } from '../floating-target'+import { requestComposerFocus } from '../focus'+import { useComposerSurfaceId } from '../scope'+import { useComposerVisible } from '../visibility'+import { useComposerPopoutGestures } from './use-popout-drag'interface UseComposerPopoutOptions {composerRef: RefObject<HTMLFormElement | null>}-/**- * This surface's on-screen placement, derived from its zone's drag intent.- *- * A zone stores one intent for its whole tab stack — drag the box in any tab and- * it moves in all of them — but each surface owns a different rect, so the- * intent is clamped per surface. Clamping into the store instead would have- * every keep-alive-mounted tab overwrite the others with a position bounded by- * ITS geometry, last writer winning: that's how a drag in one tab used to get- * lost in another.- *- * Re-placing is skipped while this surface drags (the gesture already clamped- * against this rect) and while it's an inactive tab (still mounted, so a live- * drag would otherwise force a reflow per background tab per frame).- */+/** Only the visible recipient measures its box. Placement is viewport-wide;+ * hidden tabs must not overwrite the shared drag intent. */function usePopoutPlacement(composerRef: RefObject<HTMLFormElement | null>,- groupId: string,intent: PopoutPosition,dragging: boolean,poppedOut: boolean): PopoutPosition {const [placement, setPlacement] = useState(intent)- const visible = usePaneVisible()+ const visible = useComposerVisible()// Re-place while this surface is the visible tab and isn't itself dragging.const live = poppedOut && visible && !dragging- // Resolved before the shared ResizeObserver below registers (hook order puts- // this layout effect first), so the observer always has this surface's own- // bounds element rather than a document-wide first match.- const boundsRef = useRef<Element | null>(null)-- useLayoutEffect(() => {- boundsRef.current = popoutBoundsElement(composerRef.current)- })-const reclamp = useCallback(() => {const el = composerRef.current@@ -65,24 +44,20 @@ function usePopoutPlacement(}const size = { height: el.offsetHeight, width: el.offsetWidth }- const next = clampPopoutPosition(getComposerPopoutZone(groupId).position, size, readPopoutBounds(el))+ const next = clampPopoutPosition($composerPopout.get().position, size)- // Bail on an unchanged placement: a sash drag resizes the surface every- // frame, and a fresh object each time re-renders the whole composer.+ // Preserve identity when a resize leaves the placement unchanged.setPlacement(prev => (prev.bottom === next.bottom && prev.right === next.right ? prev : next))- }, [composerRef, groupId])+ }, [composerRef])- // The surface resizing (sash drag, sidebar open, tab split) re-places the box- // against its new rect; the composer resizing (a growing draft) re-places it- // against its new height.+ // A growing draft must stay within the viewport too.useResizeObserver(useCallback(() => {if (live) {reclamp()}}, [live, reclamp]),- composerRef,- boundsRef+ composerRef)// useLayoutEffect, not useEffect: a tab revealed after the box was dragged in@@ -109,37 +84,32 @@ function usePopoutPlacement(return dragging ? intent : placement}-/**- * Pop-out engine: the docked↔floating state, the dock/float/toggle actions, the- * drag gestures, and this surface's placement.- *- * State is scoped to the surface's layout ZONE (its tab stack): tabs in the same- * zone share one float, so switching tabs keeps the box exactly where you put- * it, while a split zone beside them keeps its own — popping out on the left- * doesn't fling a composer out of the right.- *- * Secondary windows (the tiny Ctrl+Shift+N window, subagent watch windows) stay- * docked: a floating composer makes no sense in a scratch window.- */+/** Window-wide dock/float gestures. Secondary scratch/watch windows stay docked. */export function useComposerPopout({ composerRef }: UseComposerPopoutOptions) {- const groupId = usePaneGroup()+ const surfaceId = useComposerSurfaceId()const gesturesEnabled = useStore($composerPopoutGesturesEnabled)const popoutAllowed = gesturesEnabled && !isSecondaryWindow()- const zone = useStore(useMemo(() => $composerPopoutZone(groupId), [groupId]))- const poppedOut = zone.poppedOut && popoutAllowed+ const state = useStore($composerPopout)+ const poppedOut = state.poppedOut && popoutAllowedconst handleComposerPopOut = useCallback(() => {triggerHaptic('open')- setComposerPoppedOut(groupId, true)- }, [groupId])++ if (surfaceId) {+ claimFloatingComposer(surfaceId)+ }++ setComposerPoppedOut(true)+ requestComposerFocus()+ }, [surfaceId])const handleComposerDock = useCallback(() => {triggerHaptic('success')- setComposerPoppedOut(groupId, false)- }, [groupId])+ setComposerPoppedOut(false)+ }, [])// Double-click the grab area toggles dock/float. Undocking restores the last- // position (a zone's stored position is never cleared on dock).+ // position (docking never clears the shared placement).const handleComposerToggle = useCallback(() => {poppedOut ? handleComposerDock() : handleComposerPopOut()}, [handleComposerDock, handleComposerPopOut, poppedOut])@@ -150,14 +120,13 @@ export function useComposerPopout({ composerRef }: UseComposerPopoutOptions) {onPointerDown: onComposerGesturePointerDown} = useComposerPopoutGestures({composerRef,- groupId,onDock: handleComposerDock,onPopOut: handleComposerPopOut,poppedOut,- position: zone.position+ position: state.position})- const popoutPosition = usePopoutPlacement(composerRef, groupId, zone.position, dragging, poppedOut)+ const popoutPosition = usePopoutPlacement(composerRef, state.position, dragging, poppedOut)return {dockProximity,diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.tsindex f000c7b9ab6..1798952e0f2 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts@@ -1,5 +1,5 @@import { useStore } from '@nanostores/react'-import { useCallback, useEffect, useRef, useState } from 'react'+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'import { useI18n } from '@/i18n'import { chatMessageText, collectUnspokenTurnSpeech } from '@/lib/chat-messages'@@ -16,9 +16,10 @@ import { $voiceLiveStatus, refreshVoiceLiveStatus, selectedVoiceChatMode } fromimport { $autoSpeakReplies, $voiceStopPhrase, setAutoSpeakReplies } from '@/store/voice-prefs'import { resumeWakeAfterVoice } from '@/store/wake-word'+import { pinFloatingComposerCapture } from '../floating-target'import type { ComposerTarget } from '../focus'import { onComposerVoiceToggleRequest } from '../focus'-import { useComposerScope } from '../scope'+import { useComposerScope, useComposerSurfaceId } from '../scope'import type { ChatBarProps } from '../types'import { useAutoSpeakReplies } from './use-auto-speak-replies'@@ -87,6 +88,15 @@ export function useComposerVoice({onTranscribeAudio})+ const surfaceId = useComposerSurfaceId()+ const capturing = voiceConversationActive || voiceStatus !== 'idle'++ useLayoutEffect(() => {+ if (surfaceId && capturing) {+ return pinFloatingComposerCapture(surfaceId)+ }+ }, [capturing, surfaceId])+/** Auto-speak selector: the latest unspoken reply only — a backlog collapses to the newest. */const pendingResponse = () => {const messages = $messages.get()diff --git a/apps/desktop/src/app/chat/composer/hooks/use-popout-drag.ts b/apps/desktop/src/app/chat/composer/hooks/use-popout-drag.tsindex a1f3ce3c9cd..f48ce6ef9b8 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-popout-drag.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-popout-drag.ts@@ -36,8 +36,6 @@ interface PressState {interface ComposerPopoutGesturesOptions {composerRef: RefObject<HTMLFormElement | null>- /** Layout zone this composer belongs to — the scope its float is stored under. */- groupId: stringonDock: () => voidonPopOut: () => voidpoppedOut: boolean@@ -128,7 +126,6 @@ function popoutPositionUnderPointer(*/export function useComposerPopoutGestures({composerRef,- groupId,onDock,onPopOut,poppedOut,@@ -163,10 +160,7 @@ export function useComposerPopoutGestures({(state: PressState, clientX: number, clientY: number, next: PopoutPosition, size?: PopoutSize) => {clearTimer()- const clamped = setComposerPopoutPosition(groupId, next, {- area: readPopoutBounds(composerRef.current),- size- })+ const clamped = setComposerPopoutPosition(next, { size })liveRef.current = clamped@@ -179,7 +173,7 @@ export function useComposerPopoutGestures({setDragging(true)},- [clearTimer, composerRef, groupId]+ [clearTimer])const peelOffFromDock = useCallback(@@ -287,12 +281,11 @@ export function useComposerPopoutGestures({const area = readPopoutBounds(composer)liveRef.current = setComposerPopoutPosition(- groupId,{bottom: state.startBottom - (pending.y - state.startY),right: state.startRight - (pending.x - state.startX)},- { area, size }+ { size })if (composer) {@@ -355,7 +348,7 @@ export function useComposerPopoutGestures({} else {// Persist the resting position once, on release — never per move.const size = composer ? { height: composer.offsetHeight, width: composer.offsetWidth } : undefined- setComposerPopoutPosition(groupId, liveRef.current, { area, persist: true, size })+ setComposerPopoutPosition(liveRef.current, { persist: true, size })}}@@ -372,7 +365,7 @@ export function useComposerPopoutGestures({window.removeEventListener('pointerup', handleUp)window.removeEventListener('pointercancel', handleUp)}- }, [composerRef, groupId, onDock, peelOffFromDock, resetGesture])+ }, [composerRef, onDock, peelOffFromDock, resetGesture])useEffect(() => clearTimer, [clearTimer])diff --git a/apps/desktop/src/app/chat/composer/visibility.ts b/apps/desktop/src/app/chat/composer/visibility.tsnew file mode 100644index 00000000000..6a15293cb4e--- /dev/null+++ b/apps/desktop/src/app/chat/composer/visibility.ts@@ -0,0 +1,14 @@+import { createContext, useContext } from 'react'++import { usePaneVisible } from '@/components/pane-shell/pane-visibility'++/** Editor visibility is narrower than chat visibility while a shared float is+ * active. Background queues and explicit session actions still belong to the pane. */+export const ComposerVisibleContext = createContext<boolean | null>(null)++export function useComposerVisible(): boolean {+ const composer = useContext(ComposerVisibleContext)+ const pane = usePaneVisible()++ return composer ?? pane+}diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex ccc9182d3bc..704fd00f93a 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -13,8 +13,8 @@ import { Thread } from '@/components/assistant-ui/thread'import { TranscriptWindowProvider } from '@/components/assistant-ui/thread/transcript-window'import { Backdrop } from '@/components/Backdrop'import { COMPOSER_HEART_CONFIG, HeartField } from '@/components/chat/vibe-hearts'-import { usePaneVisible } from '@/components/pane-shell/pane-visibility'-import { $sessionTileDragging, $sessionTileEdgeHover } from '@/components/pane-shell/tree/store'+import { usePaneGroup, usePaneVisible } from '@/components/pane-shell/pane-visibility'+import { $hoveredTreeGroup, $sessionTileDragging, $sessionTileEdgeHover } from '@/components/pane-shell/tree/store'import { PromptOverlays } from '@/components/prompt-overlays'import { Button } from '@/components/ui/button'import { ErrorState } from '@/components/ui/error-state'@@ -59,6 +59,7 @@ import { titlebarHeaderBaseClass, titlebarHeaderShadowClass, titlebarHeaderTitleimport { ChatDropOverlay } from './chat-drop-overlay'import { ChatSwapOverlay, ChatSyncBadge } from './chat-swap-overlay'import { ChatBar, ChatBarFallback } from './composer'+import { FloatingComposerSurface } from './composer/floating-surface'import { requestComposerInsert } from './composer/focus'import { droppedFileInlineRefs } from './composer/inline-refs'import { ComposerSurfaceProvider, useComposerScope, useComposerSurfaceId } from './composer/scope'@@ -473,6 +474,8 @@ const ChatViewContent = memo(function ChatViewContent({// always focused (the atom falls back to the primary's selection), so a// single-pane workspace never dims.const surfaceFocused = useStoreSelector($focusedStoredSessionId, focused => focused === storedId)+ const groupId = usePaneGroup()+ const surfaceHovered = useStoreSelector($hoveredTreeGroup, hovered => hovered === groupId)// Dock anchor for a session drop onto this surface: the workspace pane for the// primary, this tile's pane id for a tile. Read by the session-drop bridge.const sessionAnchor = isPrimary ? 'workspace' : `session-tile:${storedId ?? ''}`@@ -720,7 +723,7 @@ const ChatViewContent = memo(function ChatViewContent({className)}data-chat-surface=""- data-chat-unfocused={surfaceFocused ? undefined : ''}+ data-chat-unfocused={surfaceFocused || surfaceHovered ? undefined : ''}data-composer-surface-id={composerSurfaceId}data-composer-target={composerScope.target}data-session-anchor={sessionAnchor}@@ -806,44 +809,40 @@ const ChatViewContent = memo(function ChatViewContent({settling in the background — subtle badge, not an overlay. */}{isPrimary && !gatewaySwapTarget && <ChatSyncBadge profile={hydrationSyncProfile} />}</div>- {/* Composer renders OUTSIDE the contain:[layout paint] wrapper above:- that wrapper is a containing block for — and clips — position:fixed- descendants, so the popped-out (fixed) composer would anchor to the- chat column (which shifts/resizes with the sidebars) and get clipped- off-screen instead of floating against the viewport. As a sibling it- anchors to the outer relative container instead: docked is absolute- (identical placement), floating resolves against the viewport. Both- states stay mounted here, so dock⇄float never remounts the editor. */}+ {/* Docked composers overlay their pane; the shared float escapes pane+ clipping through a stable portal host without remounting its editor. */}{showChatBar && (- <Suspense fallback={<ChatBarFallback />}>- <ChatBar- busy={busy}- cwd={currentCwd}- disabled={!gatewayOpen}- focusKey={activeSessionId}- gateway={gateway}- maxRecordingSeconds={maxVoiceRecordingSeconds}- onAddContextRef={onAddContextRef}- onAddUrl={onAddUrl}- onAttachDroppedItems={onAttachDroppedItems}- onAttachImageBlob={onAttachImageBlob}- onAttachPastedText={onAttachPastedText}- onAttachPrCommentUrl={onAttachPrCommentUrl}- onCancel={onCancel}- onPasteClipboardImage={onPasteClipboardImage}- onPickFiles={onPickFiles}- onPickFolders={onPickFolders}- onPickImages={onPickImages}- onRemoveAttachment={onRemoveAttachment}- onSteer={onSteer}- onSteerHidden={onSteerHidden}- onSubmit={onSubmit}- onTranscribeAudio={onTranscribeAudio}- queueSessionKey={queueSessionKey}- sessionId={activeSessionId}- state={chatBarState}- />- </Suspense>+ <FloatingComposerSurface>+ <Suspense fallback={<ChatBarFallback />}>+ <ChatBar+ busy={busy}+ cwd={currentCwd}+ disabled={!gatewayOpen}+ focusKey={activeSessionId}+ gateway={gateway}+ maxRecordingSeconds={maxVoiceRecordingSeconds}+ onAddContextRef={onAddContextRef}+ onAddUrl={onAddUrl}+ onAttachDroppedItems={onAttachDroppedItems}+ onAttachImageBlob={onAttachImageBlob}+ onAttachPastedText={onAttachPastedText}+ onAttachPrCommentUrl={onAttachPrCommentUrl}+ onCancel={onCancel}+ onPasteClipboardImage={onPasteClipboardImage}+ onPickFiles={onPickFiles}+ onPickFolders={onPickFolders}+ onPickImages={onPickImages}+ onRemoveAttachment={onRemoveAttachment}+ onSteer={onSteer}+ onSteerHidden={onSteerHidden}+ onSubmit={onSubmit}+ onTranscribeAudio={onTranscribeAudio}+ queueSessionKey={queueSessionKey}+ sessionId={activeSessionId}+ state={chatBarState}+ />+ </Suspense>+ </FloatingComposerSurface>)}</ChatRuntimeBoundary></div>diff --git a/apps/desktop/src/app/chat/surface-vars.ts b/apps/desktop/src/app/chat/surface-vars.tsindex 45ff7bf91b8..397fd1deb6b 100644--- a/apps/desktop/src/app/chat/surface-vars.ts+++ b/apps/desktop/src/app/chat/surface-vars.ts@@ -30,14 +30,24 @@ export const COMPOSER_SURFACE_HEIGHT_VAR = '--composer-surface-measured-height'/*** The surface owning `el`, or null when `el` is detached or outside one.*- * Null is the honest answer, not a failure to be papered over. Every publisher- * lives inside a `[data-chat-surface]` for its whole visible life (a- * popped-out composer is `position: fixed`, still a descendant), so the only- * way to miss is a node React already removed — whose measurement is stale by- * definition.+ * Floating editors are portaled outside the pane's clipping/filter layer.+ * Their stable host carries the exact owning surface id; missing owners never+ * publish measurements to another pane or the document root.*/export function chatSurfaceRoot(el: Element | null): HTMLElement | null {- return el?.closest<HTMLElement>('[data-chat-surface]') ?? null+ const local = el?.closest<HTMLElement>('[data-chat-surface]')++ if (local) {+ return local+ }++ const owner = el?.closest<HTMLElement>('[data-composer-owner]')?.dataset.composerOwner++ return owner+ ? ([...document.querySelectorAll<HTMLElement>('[data-chat-surface]')].find(+ surface => surface.dataset.composerSurfaceId === owner+ ) ?? null)+ : null}/** Publish a measured-height var on the surface owning `el`. No owner, no write. */diff --git a/apps/desktop/src/app/contrib/controller.tsx b/apps/desktop/src/app/contrib/controller.tsxindex 86b90375077..0b7b39215ad 100644--- a/apps/desktop/src/app/contrib/controller.tsx+++ b/apps/desktop/src/app/contrib/controller.tsx@@ -11,7 +11,7 @@ import { InlinePreviewDirective } from '@/components/assistant-ui/inline-previewimport { IdleMount } from '@/components/idle-mount'import { OnboardingChatDirective } from '@/components/onboarding-chat/directive'import { $layoutEditMode, toggleLayoutEditMode } from '@/components/pane-shell/edit-mode'-import { allPaneIds, groupLeafIds } from '@/components/pane-shell/tree/model'+import { allPaneIds } from '@/components/pane-shell/tree/model'import { LayoutTreeRoot } from '@/components/pane-shell/tree/renderer'import {$layoutTree,@@ -48,7 +48,6 @@ import { type KeybindContribution, KEYBINDS_AREA } from '@/lib/keybinds/actions'import { isOnboardingEnabled } from '@/lib/onboarding-enabled'import { TRANSCRIPT_DIRECTIVE_AREA, type TranscriptDirectiveContribution } from '@/lib/transcript-directives'import { setYoloEnabled } from '@/lib/yolo-session'-import { pruneComposerPopoutZones } from '@/store/composer-popout'import {$fileBrowserOpen,$panesFlipped,@@ -437,15 +436,6 @@ if (!isBrowserWindow() && !isHudWindow()) {watchPreviewTiles()}-// Composer pop-out state is keyed by layout zone, so drop entries for zones the-// user has since closed or merged away — otherwise a long-lived install keeps a-// row for every split it has ever had.-$layoutTree.subscribe(tree => {- if (tree) {- pruneComposerPopoutZones(groupLeafIds(tree))- }-})-// Mirror sidebar pins into the backend keep-flag so the auto-archive sweep// never hides a pinned chat (and pre-existing pins migrate transparently).watchSessionPins()diff --git a/apps/desktop/src/store/composer-popout.ts b/apps/desktop/src/store/composer-popout.tsindex ea6ec7e4649..23d9053a3e2 100644--- a/apps/desktop/src/store/composer-popout.ts+++ b/apps/desktop/src/store/composer-popout.ts@@ -1,133 +1,110 @@-import { atom, computed, type ReadableAtom } from 'nanostores'+import { atom } from 'nanostores'+import { chatSurfaceRoot } from '@/app/chat/surface-vars'import { persistBoolean, persistString, storedBoolean, storedString } from '@/lib/storage'-const POPOUT_STORAGE_KEY = 'hermes.desktop.composerPopout.zones.v1'+const POPOUT_STORAGE_KEY = 'hermes.desktop.composerPopout.window.v1'const POPOUT_GESTURES_ENABLED_STORAGE_KEY = 'hermes.desktop.composerPopout.gesturesEnabled'--// Pre-zone keys: one flag + one position for the whole window. Read at load to-// seed the first zone the user touches (see `legacySeed`), never written again.+const ZONES_STORAGE_KEY = 'hermes.desktop.composerPopout.zones.v1'const LEGACY_ENABLED_KEY = 'hermes.desktop.composerPopout.enabled'const LEGACY_POSITION_KEY = 'hermes.desktop.composerPopout.position'-const gesturesEnabledAtLoad = storedBoolean(POPOUT_GESTURES_ENABLED_STORAGE_KEY, true)--/** Where the floating composer's bottom-right corner sits, measured as an inset- * from the viewport's bottom/right edges. Anchoring to the bottom-right keeps- * the box visually pinned to its default corner as the window resizes and as- * the box grows upward while typing (the corner stays put, height climbs). */+/** Viewport-relative bottom/right insets keep the resting corner stable as a draft grows. */export interface PopoutPosition {bottom: numberright: number}-/** One layout zone's pop-out state. */-export interface PopoutZoneState {+export interface ComposerPopoutState {poppedOut: boolean- /** The user's intended placement for this zone, UNCLAMPED — every surface in- * the zone renders `clampPopoutPosition` of it against its own rect. */position: PopoutPosition}-// Floating composer width (rem). Shared by the inline style that sets-// --composer-popout-width and the peel-off drag math.export const POPOUT_WIDTH_REM = 19.5--// Default pop-out placement: tucked into the bottom-right of the thread, clear-// of the window chrome. Matches the brief's "default to the right bottom".+export const POPOUT_ESTIMATED_HEIGHT = 56const DEFAULT_POSITION: PopoutPosition = { bottom: 24, right: 24 }--const DEFAULT_ZONE: PopoutZoneState = { poppedOut: false, position: DEFAULT_POSITION }+const EDGE_MARGIN = 8+const gesturesEnabledAtLoad = storedBoolean(POPOUT_GESTURES_ENABLED_STORAGE_KEY, true)const isPosition = (value: unknown): value is PopoutPosition => {- const r = value as null | Partial<PopoutPosition>+ const position = value as Partial<PopoutPosition> | null- return typeof r?.bottom === 'number' && typeof r?.right === 'number'+ return Number.isFinite(position?.bottom) && Number.isFinite(position?.right)}-/** The pre-zone position, if the user had one. */-function legacyPosition(): PopoutPosition {+function readState(key: string): unknown {try {- const parsed = JSON.parse(storedString(LEGACY_POSITION_KEY) || 'null') as unknown-- return isPosition(parsed) ? { bottom: parsed.bottom, right: parsed.right } : DEFAULT_POSITION+ return JSON.parse(storedString(key) || 'null')} catch {- return DEFAULT_POSITION+ return null}}-function load(): Record<string, PopoutZoneState> {- const out: Record<string, PopoutZoneState> = {}+function isState(value: unknown): value is ComposerPopoutState {+ const state = value as Partial<ComposerPopoutState> | null- try {- const parsed = JSON.parse(storedString(POPOUT_STORAGE_KEY) || 'null') as unknown+ return typeof state?.poppedOut === 'boolean' && isPosition(state.position)+}++function load(): ComposerPopoutState {+ const saved = readState(POPOUT_STORAGE_KEY)++ if (isState(saved)) {+ return { ...saved, poppedOut: gesturesEnabledAtLoad && saved.poppedOut }+ }- for (const [id, value] of Object.entries((parsed as Record<string, unknown>) ?? {})) {- const zone = value as null | Partial<PopoutZoneState>+ // Upgrade existing floats without resurrecting a stale singleton preference+ // after the user has already expressed per-zone intent.+ const zones = readState(ZONES_STORAGE_KEY)- if (typeof zone?.poppedOut === 'boolean' && isPosition(zone.position)) {- out[id] = { poppedOut: gesturesEnabledAtLoad && zone.poppedOut, position: { ...zone.position } }- }+ if (zones && typeof zones === 'object') {+ const states = Object.values(zones).filter(isState)+ const state = states.find(zone => zone.poppedOut) ?? states[0]++ return {+ poppedOut: gesturesEnabledAtLoad && Boolean(state?.poppedOut),+ position: state?.position ?? DEFAULT_POSITION}- } catch {- // Treat unparseable persisted state as missing.}- return out+ const position = readState(LEGACY_POSITION_KEY)++ return {+ poppedOut: gesturesEnabledAtLoad && storedBoolean(LEGACY_ENABLED_KEY, false),+ position: isPosition(position) ? position : DEFAULT_POSITION+ }}-/** Every zone's pop-out state, keyed by layout-tree group id.- *- * A GROUP is one stack of tabs, so this is the scope the user experiences:- * tabs in the same zone share a float (switch tabs, the box stays where you- * put it), while a split zone beside them keeps its own — popping out on the- * left doesn't fling a composer out of the right. */-export const $composerPopoutZones = atom<Record<string, PopoutZoneState>>(load())+/** One floating placement per window; drafts and runtimes remain session-owned. */+export const $composerPopout = atom<ComposerPopoutState>(load())export const $composerPopoutGesturesEnabled = atom(gesturesEnabledAtLoad)-/** Write-through to storage. Called explicitly — NOT on every store change: a- * drag updates the position once per frame, and serializing every zone to- * localStorage at 60Hz is exactly the IO the drag path was built to avoid. */-const persistZones = () => persistString(POPOUT_STORAGE_KEY, JSON.stringify($composerPopoutZones.get()))--/** Whether the user had a float before zones existed. Seeds a zone's first read- * so an upgrade doesn't silently dock someone who left their composer floating- * — but ONLY until they touch any zone. Once real per-zone state exists, that- * is the truth, and a zone split later starts docked like any other. */-let legacySeed: PopoutZoneState | null =- gesturesEnabledAtLoad && storedString(LEGACY_ENABLED_KEY) === 'true'- ? { poppedOut: true, position: legacyPosition() }- : null--const zoneState = (zones: Record<string, PopoutZoneState>, groupId: string): PopoutZoneState =>- zones[groupId] ?? legacySeed ?? DEFAULT_ZONE--// Cached per-zone derived atoms keep useStore subscriptions referentially stable-// (and keep one zone's drag from re-rendering the composers in another).-const zoneCache = new Map<string, ReadableAtom<PopoutZoneState>>()--export function $composerPopoutZone(groupId: string): ReadableAtom<PopoutZoneState> {- let cached = zoneCache.get(groupId)-- if (!cached) {- cached = computed($composerPopoutZones, zones => zoneState(zones, groupId))- zoneCache.set(groupId, cached)+const persist = () => persistString(POPOUT_STORAGE_KEY, JSON.stringify($composerPopout.get()))++export function setComposerPoppedOut(poppedOut: boolean) {+ const state = $composerPopout.get()++ if (state.poppedOut !== poppedOut) {+ $composerPopout.set({ ...state, poppedOut })}- return cached+ persist()}-export const getComposerPopoutZone = (groupId: string): PopoutZoneState =>- zoneState($composerPopoutZones.get(), groupId)+export function setComposerPopoutGesturesEnabled(value: boolean) {+ $composerPopoutGesturesEnabled.set(value)+ persistBoolean(POPOUT_GESTURES_ENABLED_STORAGE_KEY, value)++ if (!value) {+ setComposerPoppedOut(false)+ }+}export interface PopoutSize {height: numberwidth: number}-/** Viewport-space rect the floating composer is confined to. Defaults to the- * whole window; pass the thread area so the box can't slide under a pinned- * sidebar or behind the header. */export interface PopoutBounds {bottom: numberleft: number@@ -136,36 +113,17 @@ export interface PopoutBounds {}interface SetPositionOptions {- /** Thread-area rect to confine the box to; falls back to the full window. */area?: PopoutBoundspersist?: boolean- /** Measured box size; falls back to the compact width + a min height so the- * box stays grabbable even when the caller can't measure it. */size?: PopoutSize}-// Keep at least this much between the box and every edge of its bounds, so the-// floating composer can never be dragged (or restored) out of reach.-const EDGE_MARGIN = 8-// Height floor used when the real box height is unknown (init / load / peel-off).-export const POPOUT_ESTIMATED_HEIGHT = 56-const MIN_VISIBLE_HEIGHT = POPOUT_ESTIMATED_HEIGHT-const clampRange = (value: number, lo: number, hi: number) => Math.min(Math.max(value, lo), Math.max(lo, hi))-const rootFontSize = () => parseFloat(getComputedStyle(document.documentElement).fontSize) || 16-/** The chat surface a composer belongs to — the element whose rect bounds its- * floating box. Resolved from the composer's OWN surface root, so each mounted- * chat surface (primary, session tile, background tab) gets its own area- * instead of a document-wide first match. */-export const popoutBoundsElement = (composer: Element | null): Element | null =>- (composer?.closest('[data-chat-surface]') ?? document).querySelector('[data-slot="composer-bounds"]')--/** The thread area's viewport rect (excludes a pinned sidebar + the header), or- * undefined before it mounts — callers then fall back to the full window. */+/** The dock target stays in the owning pane even though the float spans the window. */export function readPopoutBounds(composer: Element | null): PopoutBounds | undefined {- const el = popoutBoundsElement(composer)+ const el = chatSurfaceRoot(composer)?.querySelector('[data-slot="composer-bounds"]')if (!el) {return undefined@@ -173,29 +131,17 @@ export function readPopoutBounds(composer: Element | null): PopoutBounds | undefconst { bottom, height, left, right, top, width } = el.getBoundingClientRect()- // Pre-layout (mount before first layout) the rect is empty — fall back to the- // window rather than clamping the box into a collapsed area.return width > 0 && height > 0 ? { bottom, left, right, top } : undefined}-/**- * Bound the bottom/right inset so the WHOLE box stays inside `area` (the chat- * surface's region, or the window by default) — the corner anchor alone would- * let the box's width/height push it past the opposite edges.- *- * PURE and per-surface: a zone stores the user's INTENT, and each mounted- * composer in it runs that through here against its own rect to get the- * placement it actually renders. Tabs in a zone are keep-alive mounted, so- * clamping into the store instead would have every tab overwrite the others- * with a value bounded by ITS geometry.- */+/** Clamp the whole box, not just its anchor. Never write a hidden tab's measurement into shared intent. */export function clampPopoutPosition({ bottom, right }: PopoutPosition,size?: PopoutSize,area?: PopoutBounds): PopoutPosition {const width = size?.width || POPOUT_WIDTH_REM * rootFontSize()- const height = size?.height || MIN_VISIBLE_HEIGHT+ const height = size?.height || POPOUT_ESTIMATED_HEIGHTconst { innerHeight: vh, innerWidth: vw } = windowconst a = area ?? { bottom: vh, left: 0, right: vw, top: 0 }@@ -205,83 +151,21 @@ export function clampPopoutPosition(}}-function patchZone(groupId: string, patch: Partial<PopoutZoneState>) {- const zones = $composerPopoutZones.get()- const stored = zones[groupId]- const next = { ...zoneState(zones, groupId), ...patch }-- if (- stored?.poppedOut === next.poppedOut &&- stored.position.bottom === next.position.bottom &&- stored.position.right === next.position.right- ) {- return- }-- // The user has now expressed per-zone intent; the pre-zone value stops- // standing in for zones they haven't touched.- legacySeed = null- $composerPopoutZones.set({ ...zones, [groupId]: next })-}--export function setComposerPoppedOut(groupId: string, value: boolean) {- patchZone(groupId, { poppedOut: value })- persistZones()-}--export function setComposerPopoutGesturesEnabled(value: boolean) {- $composerPopoutGesturesEnabled.set(value)- persistBoolean(POPOUT_GESTURES_ENABLED_STORAGE_KEY, value)-- if (value) {- return- }-- // Turning the feature off is an immediate lock-to-dock action for every- // layout zone, not merely a promise to ignore the next gesture. Keep each- // zone's resting position so opting back in restores where the user put it.- const zones = $composerPopoutZones.get()-- const docked = Object.fromEntries(- Object.entries(zones).map(([groupId, zone]) => [groupId, { ...zone, poppedOut: false }])- )-- legacySeed = null- $composerPopoutZones.set(docked)- persistZones()-- // Neutralize the pre-zone singleton migration seed too, otherwise a reload- // with no materialized zones could revive an old floating composer.- persistBoolean(LEGACY_ENABLED_KEY, false)-}--/** Move this zone's box. Used per-frame during a drag, so it only writes the- * in-memory store by default; pass `persist` for the resting position on- * release. Returns the clamped position so callers can sync their live ref. */+/** Drag updates stay in memory; only the release writes storage. */export function setComposerPopoutPosition(- groupId: string,position: PopoutPosition,- { area, persist, size }: SetPositionOptions = {}+ { area, persist: shouldPersist, size }: SetPositionOptions = {}): PopoutPosition {const next = clampPopoutPosition(position, size, area)- patchZone(groupId, { position: next })+ const state = $composerPopout.get()- if (persist) {- persistZones()+ if (state.position.bottom !== next.bottom || state.position.right !== next.right) {+ $composerPopout.set({ ...state, position: next })}- return next-}--/** Drop state for zones that no longer exist, so a long-lived install doesn't- * accumulate an entry per zone the user ever split and closed. */-export function pruneComposerPopoutZones(liveGroupIds: Iterable<string>) {- const live = new Set(liveGroupIds)- const zones = $composerPopoutZones.get()- const next = Object.fromEntries(Object.entries(zones).filter(([id]) => live.has(id)))-- if (Object.keys(next).length !== Object.keys(zones).length) {- $composerPopoutZones.set(next)- persistZones()+ if (shouldPersist) {+ persist()}++ return next}diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.cssindex 6f7357bd63e..08f7343920e 100644--- a/apps/desktop/src/styles.css+++ b/apps/desktop/src/styles.css@@ -1824,7 +1824,7 @@ body.guest-pointer-lock :is(webview, iframe) {already-painted layer instead of repainting descendants. */[data-chat-surface][data-chat-unfocused] {opacity: var(--chat-unfocused-opacity);- filter: grayscale(1);+ filter: grayscale(0.2);}[data-chat-surface] {