Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(switchdash): drive remote terminal attachment from focus
amaudruz27f7d1195a30
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.test.tsnew file mode 100644index 000000000..93fd6ed0b--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.test.ts@@ -0,0 +1,118 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const listPersistedSessionIds = vi.hoisted(() => vi.fn());+const prunePersisted = vi.hoisted(() => vi.fn(async () => {}));+const loadSessionWithAgent = vi.hoisted(() => vi.fn());+const getLocationById = vi.hoisted(() => vi.fn());+const getLocation = vi.hoisted(() => vi.fn(() => ({}) as unknown));+const openLocation = vi.hoisted(() => vi.fn(async () => ({ success: true })));+const provisionSession = vi.hoisted(() => vi.fn<(id: string) => Promise<void>>(async () => {}));+const hydrateSession = vi.hoisted(() => vi.fn<(id: string) => Promise<void>>(async () => {}));+const ensureSessionAttachable = vi.hoisted(() =>+ vi.fn<(id: string) => Promise<boolean>>(async () => false)+);++vi.mock('./switch-room-service', () => ({+ switchRoomService: { listPersistedSessionIds, prunePersisted },+}));+vi.mock('@main/core/sessions/session-join', () => ({ loadSessionWithAgent }));+vi.mock('@main/core/locations/store', () => ({ getLocationById }));+vi.mock('@main/core/locations/location-manager', () => ({+ locationManager: { getLocation, openLocation },+}));+vi.mock('@main/core/sessions/session-service', () => ({+ sessionService: { provisionSession },+}));+vi.mock('@main/core/sessions/operations/hydrateSession', () => ({ hydrateSession }));+vi.mock('@main/core/sessions/operations/ensureSessionAttachable', () => ({+ ensureSessionAttachable,+}));+vi.mock('@main/lib/logger', () => ({+ log: { info() {}, warn() {}, error() {} },+}));++const { restoreSwitchRoomSessions } = await import('./restore-sessions');++describe('restoreSwitchRoomSessions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getLocation.mockReturnValue({});+ getLocationById.mockResolvedValue({ id: 'location-1', sshHost: null, dir: '/repo' });+ loadSessionWithAgent.mockResolvedValue({+ locationId: 'location-1',+ serverId: 'server-1',+ name: 'agent',+ });+ ensureSessionAttachable.mockResolvedValue(false);+ });++ it('only ensures the sidecar for a remote session, never its terminal', async () => {+ // The agent runs in a tmux pane on the VM and the sidecar injects room+ // messages there. Opening 51 terminals nobody is looking at is what+ // saturated the shared SSH transport.+ listPersistedSessionIds.mockResolvedValue(['session-1']);+ ensureSessionAttachable.mockResolvedValue(true);++ await restoreSwitchRoomSessions();++ expect(provisionSession).toHaveBeenCalledWith('session-1');+ expect(ensureSessionAttachable).toHaveBeenCalledWith('session-1');+ expect(hydrateSession).not.toHaveBeenCalled();+ });++ it('still hydrates a local session, which needs a live TUI for injection', async () => {+ listPersistedSessionIds.mockResolvedValue(['session-1']);+ ensureSessionAttachable.mockResolvedValue(false);++ await restoreSwitchRoomSessions();++ expect(hydrateSession).toHaveBeenCalledWith('session-1');+ });++ it('handles a mix of local and remote sessions', async () => {+ listPersistedSessionIds.mockResolvedValue(['remote-1', 'local-1']);+ ensureSessionAttachable.mockImplementation(async (id: string) => id === 'remote-1');++ await restoreSwitchRoomSessions();++ expect(hydrateSession).toHaveBeenCalledTimes(1);+ expect(hydrateSession).toHaveBeenCalledWith('local-1');+ expect(ensureSessionAttachable).toHaveBeenCalledTimes(2);+ });++ it('prunes sessions whose row has gone', async () => {+ listPersistedSessionIds.mockResolvedValue(['session-1']);+ loadSessionWithAgent.mockResolvedValue(null);++ await restoreSwitchRoomSessions();++ expect(prunePersisted).toHaveBeenCalledWith(['session-1']);+ expect(provisionSession).not.toHaveBeenCalled();+ });++ it('skips an agent whose Switch server was removed', async () => {+ listPersistedSessionIds.mockResolvedValue(['session-1']);+ loadSessionWithAgent.mockResolvedValue({+ locationId: 'location-1',+ serverId: null,+ name: 'agent',+ });++ await restoreSwitchRoomSessions();++ expect(provisionSession).not.toHaveBeenCalled();+ expect(ensureSessionAttachable).not.toHaveBeenCalled();+ });++ it('keeps going when one session fails to restore', async () => {+ listPersistedSessionIds.mockResolvedValue(['bad-1', 'good-1']);+ provisionSession.mockImplementation(async (id: string) => {+ if (id === 'bad-1') throw new Error('provision blew up');+ });+ ensureSessionAttachable.mockResolvedValue(true);++ await restoreSwitchRoomSessions();++ expect(ensureSessionAttachable).toHaveBeenCalledWith('good-1');+ });+});diff --git a/dash/apps/switchdash-desktop/src/renderer/App.tsx b/dash/apps/switchdash-desktop/src/renderer/App.tsxindex 02502b5d1..e803ee39f 100644--- a/dash/apps/switchdash-desktop/src/renderer/App.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/App.tsx@@ -1,6 +1,7 @@import { QueryClientProvider } from '@tanstack/react-query';import { AppMenuEvents } from './app/app-menu-events';import { Workspace } from './app/workspace';+import { SessionFocusReporter } from './features/sessions/session-focus-reporter-mount';import { SessionDeeplinkListener } from './features/switch-rooms/session-deeplink-listener';import { WorkspaceLayoutContextProvider } from './lib/layout/layout-provider';import { WorkspaceViewProvider } from './lib/layout/provider';@@ -18,6 +19,7 @@ function AppContent() {<TerminalPoolProvider><WorkspaceViewProvider><AppMenuEvents />+ <SessionFocusReporter /><SessionDeeplinkListener /><RightSidebarProvider><ThemeProvider>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-attachment-state.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-attachment-state.tsxnew file mode 100644index 000000000..7f984fac5--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-attachment-state.tsx@@ -0,0 +1,103 @@+import { Loader2, MonitorPlay, RefreshCw, TriangleAlert } from 'lucide-react';+import { rpc } from '@renderer/lib/ipc';+import { log } from '@renderer/utils/logger';+import type { AttachState } from './stores/session-agent-store';++/**+ * What a remote session shows instead of a terminal.+ *+ * Only so many sessions per host keep a terminal open at once — they share one+ * SSH connection, and past a handful the slower tunnels stop answering. A+ * detached session is not stopped: its agent is running on the VM and its+ * status in the sidebar stays live. The copy has to say that, or an empty pane+ * reads as a broken session.+ */+export function SessionAttachmentState({+ state,+ sessionId,+ host,+}: {+ state: Exclude<AttachState, 'attached'>;+ sessionId: string;+ host: string | null;+}) {+ const attach = () => {+ void rpc.sessions.attachSession(sessionId).catch((error: unknown) => {+ log.warn('SessionAttachmentState: attach request failed', { sessionId, error });+ });+ };++ if (state === 'attaching') {+ return (+ <Centered>+ <Loader2 className="h-5 w-5 animate-spin text-foreground-muted" />+ <p className="font-mono text-xs text-foreground-muted">+ {host ? `Attaching to ${host}…` : 'Attaching…'}+ </p>+ </Centered>+ );+ }++ if (state === 'failed') {+ return (+ <Centered>+ <TriangleAlert className="h-6 w-6 text-foreground-destructive" />+ <p className="font-mono text-sm font-medium text-foreground-destructive">+ Could not open the terminal+ </p>+ <p className="font-mono text-xs text-foreground-muted">+ The agent is still running{host ? ` on ${host}` : ''}. Only this view failed.+ </p>+ <ActionButton onClick={attach} icon={<RefreshCw className="h-3 w-3" />} label="Try again" />+ </Centered>+ );+ }++ return (+ <Centered>+ <MonitorPlay className="h-6 w-6 text-foreground-muted" />+ <p className="font-mono text-sm font-medium">Terminal not attached</p>+ <p className="font-mono text-xs text-foreground-muted">+ This agent is running{host ? ` on ${host}` : ''} and its status stays live. Attach to watch+ it or type to it.+ </p>+ <ActionButton+ onClick={attach}+ icon={<MonitorPlay className="h-3 w-3" />}+ label="Attach terminal"+ />+ <p className="font-mono text-[11px] text-foreground-muted">+ Scrollback from before attaching is not restored.+ </p>+ </Centered>+ );+}++function Centered({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex h-full w-full flex-col items-center justify-center p-8">+ <div className="flex max-w-xs flex-col items-center gap-3 text-center">{children}</div>+ </div>+ );+}++function ActionButton({+ onClick,+ icon,+ label,+}: {+ onClick: () => void;+ icon: React.ReactNode;+ label: string;+}) {+ return (+ <button+ type="button"+ className="mt-1 inline-flex items-center gap-1.5 text-xs text-foreground-muted underline underline-offset-2 transition-colors hover:text-foreground"+ onClick={onClick}+ >+ {icon}+ {label}+ </button>+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-focus-reporter-mount.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-focus-reporter-mount.tsxnew file mode 100644index 000000000..be6523744--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-focus-reporter-mount.tsx@@ -0,0 +1,8 @@+import { useEffect } from 'react';+import { startSessionFocusReporter } from './stores/session-focus-reporter';++/** Mounts the focus reporter for the lifetime of the app. Renders nothing. */+export function SessionFocusReporter(): null {+ useEffect(() => startSessionFocusReporter(), []);+ return null;+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsxindex 7f8e3ea8f..20eeabce0 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsx@@ -1,6 +1,7 @@import { Loader2 } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect, useRef } from 'react';+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { useIsActiveSession } from '@renderer/features/sessions/hooks/use-is-active-session';import {useSessionAgent,@@ -12,6 +13,7 @@ import { PaneSizingProvider } from '@renderer/lib/pty/pane-sizing-context';import { PtyPane } from '@renderer/lib/pty/pty-pane';import { TerminalSearchOverlay } from '@renderer/lib/pty/terminal-search-overlay';import { useTerminalSearch } from '@renderer/lib/pty/use-terminal-search';+import { SessionAttachmentState } from './session-attachment-state';/*** The entire session view: one `claude` terminal. A switchdash session has@@ -31,6 +33,9 @@ export const SessionTerminal = observer(function SessionTerminal() {const session = agentStore.pty;const ptySessionId = session?.sessionId ?? null;+ const sshHost = getLocationManagerStore().locations.get(locationId)?.data?.sshHost ?? null;+ const isRemote = sshHost !== null;+const containerRef = useRef<HTMLDivElement>(null);const terminalContainerRef = useRef<HTMLDivElement>(null);const terminalRef = useRef<{ focus: () => void }>(null);@@ -107,6 +112,14 @@ export const SessionTerminal = observer(function SessionTerminal() {locationId={locationId}/></div>+ ) : isRemote ? (+ // A remote session without a terminal is a normal resting state, not a+ // loading one — an indefinite spinner here reads as a hung session.+ <SessionAttachmentState+ state={agentStore.attachment === 'attached' ? 'attaching' : agentStore.attachment}+ sessionId={sessionId}+ host={sshHost}+ />) : (<div className="flex h-full w-full items-center justify-center"><Loader2 className="h-5 w-5 animate-spin text-foreground-muted" />diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.tsindex 09901659f..e94d84095 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.ts@@ -13,8 +13,20 @@ vi.mock('@renderer/features/sessions/stores/open-file-in-file-editor', () => ({}),}));+const eventHandlers = vi.hoisted(() => new Map<string, Array<(payload: unknown) => void>>());+vi.mock('@renderer/lib/ipc', () => ({- events: { on: () => () => {} },+ events: {+ on: (channel: { name: string }, handler: (payload: unknown) => void) => {+ const forChannel = eventHandlers.get(channel.name) ?? [];+ forChannel.push(handler);+ eventHandlers.set(channel.name, forChannel);+ return () => {+ const remaining = (eventHandlers.get(channel.name) ?? []).filter((h) => h !== handler);+ eventHandlers.set(channel.name, remaining);+ };+ },+ },rpc: {sessions: {dehydrateSession,@@ -24,6 +36,19 @@ vi.mock('@renderer/lib/ipc', () => ({},}));+const remoteLocations = vi.hoisted(() => new Map<string, string>());++vi.mock('@renderer/features/locations/stores/location-selectors', () => ({+ getLocationManagerStore: () => ({+ locations: {+ get: (locationId: string) => {+ const sshHost = remoteLocations.get(locationId);+ return sshHost ? { data: { sshHost } } : undefined;+ },+ },+ }),+}));+vi.mock('@renderer/lib/pty/pty', () => ({FrontendPty: class {constructor(readonly sessionId: string) {}@@ -40,11 +65,18 @@ describe('SessionAgentStore hydration', () => {frontendConnect.mockReset();frontendDispose.mockReset();+ eventHandlers.clear();+ remoteLocations.clear();+hydrateSession.mockResolvedValue(undefined);dehydrateSession.mockResolvedValue(undefined);frontendConnect.mockResolvedValue(undefined);});+ function emit(channelName: string, payload: unknown): void {+ for (const handler of eventHandlers.get(channelName) ?? []) handler(payload);+ }+const now = '2024-01-01T00:00:00.000Z';const sessionRecord = {id: 'session-1',@@ -105,4 +137,69 @@ describe('SessionAgentStore hydration', () => {store.dispose();});++ it('connects the PTY when the pool reports the terminal attached', async () => {+ const store = new SessionAgentStore('location-1', 'session-1', [sessionRecord]);++ emit('session:attachment-changed', {+ sessionId: 'session-1',+ state: 'attached',+ hostKey: 'agent-ssh:dev-vm',+ });++ // Explicit connect matters: PtySession's onBecomeObserved only fires on the+ // unobserved -> observed edge, so a still-mounted pane would never reconnect.+ expect(store.attachment).toBe('attached');+ await vi.waitFor(() => expect(frontendConnect).toHaveBeenCalledTimes(1));++ store.dispose();+ });++ it('disposes the PTY when the pool reports the terminal detached', async () => {+ const store = new SessionAgentStore('location-1', 'session-1', [sessionRecord]);+ await store.pty?.connect();+ frontendDispose.mockClear();++ emit('session:attachment-changed', {+ sessionId: 'session-1',+ state: 'detached',+ hostKey: 'agent-ssh:dev-vm',+ });++ expect(store.attachment).toBe('detached');+ expect(frontendDispose).toHaveBeenCalledTimes(1);++ store.dispose();+ });++ it('ignores attachment events for other sessions', async () => {+ const store = new SessionAgentStore('location-1', 'session-1', [sessionRecord]);++ emit('session:attachment-changed', {+ sessionId: 'another-session',+ state: 'attached',+ hostKey: 'agent-ssh:dev-vm',+ });++ expect(store.attachment).toBe('detached');+ await Promise.resolve();+ expect(frontendConnect).not.toHaveBeenCalled();++ store.dispose();+ });++ it('does not hydrate a remote session on provision', async () => {+ // Remote terminals are opened by the main-process pool when focused; if+ // provisioning hydrated them, opening a host's worth of sessions would put+ // a terminal on every one of them.+ remoteLocations.set('location-1', 'dev-vm');+ const store = new SessionAgentStore('location-1', 'session-1', [sessionRecord]);++ store.setHydrationDesired(true);+ await Promise.resolve();++ expect(hydrateSession).not.toHaveBeenCalled();++ store.dispose();+ });});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.tsindex 4948b23ff..6ba48a0e0 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.ts@@ -1,5 +1,6 @@import type { IDisposable } from '@switchdash/shared';import { action, computed, makeObservable, observable, reaction, runInAction } from 'mobx';+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { makeFileLinkHandlers } from '@renderer/features/sessions/stores/file-link-handlers';import { events, rpc } from '@renderer/lib/ipc';import { PtySession } from '@renderer/lib/pty/pty-session';@@ -14,6 +15,7 @@ import {import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';import {sessionAgentStatusChangedChannel,+ sessionAttachmentChangedChannel,sessionChangedChannel,} from '@shared/core/sessions/sessionEvents';import { type Session } from '@shared/core/sessions/sessions';@@ -22,6 +24,9 @@ export const DEHYDRATE_RETRY_DELAY_MS = 500;type HydrationState = 'stopped' | 'starting' | 'running' | 'stopping';+/** Mirrors the main-process attachment pool's view of a remote terminal. */+export type AttachState = 'detached' | 'attaching' | 'attached' | 'failed';+/*** Renderer-side handle for a session's single agent: its status store, its PTY* session, and the hydrate/dehydrate lifecycle that connects the agent PTY@@ -32,6 +37,7 @@ export class SessionAgentStore implements IDisposable {private offAgentStatusChanged: (() => void) | null = null;private offSessionExited: (() => void) | null = null;private offSessionChanges: (() => void) | null = null;+ private offAttachmentChanged: (() => void) | null = null;private readonly _disposeReaction: () => void;/** Data layer: the session record loaded from the main process (1:1 with this store). */@@ -40,6 +46,12 @@ export class SessionAgentStore implements IDisposable {agent: AgentStatusStore | null = null;/** The agent's PTY session — created alongside the record, connected lazily. */pty: PtySession | null = null;+ /**+ * Whether this session's terminal is open, for remote sessions. Owned by the+ * main-process attachment pool and pushed here; `detached` is a normal+ * resting state, not an error — the agent keeps running on its VM.+ */+ attachment: AttachState = 'detached';// Hydration lifecycle: desired-vs-actual for the agent PTY, with the same// stale-flip handling and dehydrate retry the old reconciler had.@@ -56,6 +68,7 @@ export class SessionAgentStore implements IDisposable {makeObservable(this, {agent: observable,pty: observable,+ attachment: observable,sessionStatus: computed,});@@ -89,6 +102,37 @@ export class SessionAgentStore implements IDisposable {this.offAgentStatusChanged = this.listenToAgentStatusChanged();this.offSessionExited = this.listenToSessionExited();this.offSessionChanges = this.listenToSessionChanges();+ this.offAttachmentChanged = this.listenToAttachmentChanged();+ }++ /**+ * Remote sessions are attached by the main-process pool when the user focuses+ * them, and only a few per host at a time. Provisioning one must therefore+ * not open its terminal — that eagerness is what put a whole host's worth of+ * channels on a single SSH transport.+ */+ private get attachmentIsPoolManaged(): boolean {+ return getLocationManagerStore().locations.get(this.locationId)?.data?.sshHost != null;+ }++ private listenToAttachmentChanged(): () => void {+ return events.on(sessionAttachmentChangedChannel, (payload) => {+ if (payload.sessionId !== this.sessionId) return;+ runInAction(() => {+ this.attachment = payload.state;+ });++ if (payload.state === 'attached') {+ // Explicit: PtySession connects itself via onBecomeObserved, which only+ // fires on the unobserved -> observed edge. After a dispose the terminal+ // pane is usually still mounted and observing, so it would never re-fire.+ void this.pty?.connect();+ return;+ }+ if (payload.state === 'detached' || payload.state === 'failed') {+ this.pty?.dispose();+ }+ });}private adopt(session: Session | undefined): void {@@ -169,9 +213,17 @@ export class SessionAgentStore implements IDisposable {// --- Hydration lifecycle -------------------------------------------------- /** Keep the agent PTY hydrated while the session view is provisioned. */+ /**+ * Keep the agent PTY hydrated while the session view is provisioned.+ *+ * Local sessions only: their agent process is this app's to run, and it must+ * be live for keystroke injection to reach it. A remote agent runs on its VM+ * regardless, so its terminal is opened on focus by the attachment pool+ * instead — see `attachmentIsPoolManaged`.+ */setHydrationDesired(desired: boolean): void {if (this.hydrationDisposed) return;+ if (this.attachmentIsPoolManaged) return;this.hydrationDesired = desired;if (desired) this.clearDehydrateRetry();this.reconcileHydration();@@ -256,6 +308,8 @@ export class SessionAgentStore implements IDisposable {this.offSessionExited = null;this.offSessionChanges?.();this.offSessionChanges = null;+ this.offAttachmentChanged?.();+ this.offAttachmentChanged = null;this.pty?.destroy();}}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-focus-reporter.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-focus-reporter.tsnew file mode 100644index 000000000..36f1f0381--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-focus-reporter.ts@@ -0,0 +1,53 @@+import { reaction } from 'mobx';+import { rpc } from '@renderer/lib/ipc';+import { appState } from '@renderer/lib/stores/app-state';+import { log } from '@renderer/utils/logger';++/**+ * Debounce before reporting focus. Arrowing down the sidebar walks through+ * sessions the user is not stopping on; without this each one would ask a slow+ * remote host for a terminal and evict the last.+ */+const FOCUS_DEBOUNCE_MS = 150;++/**+ * Tell the main process which session the user is looking at.+ *+ * Remote terminals are capped per host, so the pool needs to know what to keep+ * attached and what may be evicted. The renderer is the only place that knows,+ * and this is the whole of what it tells it: one session id, or null when the+ * user is elsewhere.+ */+export function startSessionFocusReporter(): () => void {+ let timer: ReturnType<typeof setTimeout> | null = null;+ let lastReported: string | null = null;++ const report = (sessionId: string | null) => {+ if (sessionId === lastReported) return;+ lastReported = sessionId;+ void rpc.sessions.focusSession(sessionId).catch((error: unknown) => {+ log.warn('SessionFocusReporter: failed to report focused session', { sessionId, error });+ });+ };++ const dispose = reaction(+ () => {+ const navigation = appState.navigation;+ if (navigation.currentViewId !== 'session') return null;+ return navigation.viewParamsStore.session?.sessionId ?? null;+ },+ (sessionId) => {+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => {+ timer = null;+ report(sessionId);+ }, FOCUS_DEBOUNCE_MS);+ },+ { fireImmediately: true }+ );++ return () => {+ if (timer) clearTimeout(timer);+ dispose();+ };+}