Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased — desktop keyboard focus after navigation

- Keep keyboard and screen-reader users in place after changing pages, Macs or onboarding steps: when the control they used disappears, focus moves to the new page's or step's heading instead of falling back to the top of the window. Controls that survive navigation keep focus. The window title follows the rendered page heading, including delayed initial data and account changes, without moving focus on ordinary state refreshes.

## Unreleased — desktop hardware load

- Serve real whole-machine load to the desktop app over the authenticated loopback control API: per-core CPU load with the chip's tier and cluster layout (including M5 Super cores), GPU utilization and memory, ANE activity, memory use and pressure, thermal state, and Darkbloom's share of GPU time. Sampling runs in the desktop API process only while the app is looking, without root, and never reaches heartbeats, logs or the coordinator.
Expand Down
11 changes: 11 additions & 0 deletions desktop-app/src/renderer/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { Earnings } from './features/Earnings';
import { Appearance } from './components/Appearance';
import { AccountControl } from './components/AccountControl';
import { SocialLinks } from './components/SocialLinks';
import { useFocusRecovery } from './useFocusRecovery';
const navigation = [
{ id: 'home', label: 'Home', icon: HomeIcon },
{ id: 'machines', label: 'My Macs', icon: Monitor },
Expand Down Expand Up @@ -41,6 +42,16 @@ export default function App() {
setOnboarding(false);
};
useEffect(() => api?.onNavigate(navigate), [navigate]);
useFocusRecovery(`${route}:${machine ?? ''}`, () =>
document.querySelector<HTMLElement>('main h1'),
);
// Initial data and account updates can change the rendered page without navigation. Keep
// its title current after every render without re-running navigation's focus recovery.
useEffect(() => {
const heading = document.querySelector('main h1')?.textContent?.trim();
const title = heading ? `${heading} · Darkbloom` : 'Darkbloom';
if (document.title !== title) document.title = title;
});
if (!backend.state || onboarding)
return (
<>
Expand Down
2 changes: 2 additions & 0 deletions desktop-app/src/renderer/components/Onboarding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { scanTiming } from './onboarding/scanScript';
import { StartServing } from './onboarding/StartServing';
import { useMacScan } from './onboarding/useMacScan';
import { Welcome } from './onboarding/Welcome';
import { useFocusRecovery } from '../useFocusRecovery';

type Step = 'welcome' | 'scan' | 'start';

Expand All @@ -16,6 +17,7 @@ export function Onboarding({ backend, done }: { backend: BackendState; done: ()
const scan = useMacScan(backend, step === 'scan', () => setStep('start'));
const joined = step === 'start' || (scan.settled && scan.result?.verdict === 'eligible');
const leaving = step === 'scan' && scan.frame.phase === 'leaving';
useFocusRecovery(step, () => document.querySelector<HTMLElement>('.onboarding-step h2'));
const grid =
step === 'welcome'
? 'idle'
Expand Down
6 changes: 6 additions & 0 deletions desktop-app/src/renderer/styles/base.css
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,9 @@ a {
svg {
flex-shrink: 0;
}

/* Headings take focus only programmatically, after the control that had it disappears. */
h1[tabindex='-1']:focus,
h2[tabindex='-1']:focus {
outline: none;
}
26 changes: 26 additions & 0 deletions desktop-app/src/renderer/useFocusRecovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useEffect, useRef } from 'react';

/**
* After `key` changes (a new page, Mac or onboarding step), the control that had focus is often
* gone, and focus falls to the page body: keyboard users restart from the top and screen readers
* announce nothing. Move focus to the new content's heading in that case. Focus that survived the
* change (a sidebar button, a tab) is left where it is.
*/
export function useFocusRecovery(key: string, heading: () => HTMLElement | null | undefined) {
const first = useRef(true);
useEffect(() => {
const initial = first.current;
first.current = false;
const frame = requestAnimationFrame(() => {
if (initial) return;
const active = document.activeElement;
if (active && active !== document.body) return;
const target = heading();
if (!target) return;
if (!target.hasAttribute('tabindex')) target.setAttribute('tabindex', '-1');
target.focus({ preventScroll: true });
});
return () => cancelAnimationFrame(frame);
// The callback reads the DOM after render; only the key decides when to run.
}, [key]);
}
49 changes: 49 additions & 0 deletions desktop-app/tests/focusRecovery.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// @vitest-environment jsdom
import React from 'react';
import { afterEach, beforeAll, expect, it } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import '@testing-library/jest-dom/vitest';
import { backendWith, snapshot } from './onboardingFixtures';

// useBackend reads ?preview when it first loads, so the app is imported after setting it.
let App: typeof import('../src/renderer/App').default;
let Onboarding: typeof import('../src/renderer/components/Onboarding').Onboarding;
beforeAll(async () => {
window.history.replaceState({}, '', '/?preview');
App = (await import('../src/renderer/App')).default;
({ Onboarding } = await import('../src/renderer/components/Onboarding'));
});
afterEach(cleanup);

it('moves focus to the new page heading when the focused control disappears', async () => {
render(<App />);
const fleet = await screen.findByRole('region', { name: 'Fleet earnings' });
const earnings = within(fleet).getByRole('button', { name: /View earnings/ });
earnings.focus();
fireEvent.click(earnings);
const heading = await screen.findByRole('heading', { name: 'Earnings', level: 1 });
await waitFor(() => expect(document.activeElement).toBe(heading));
expect(document.title).toBe('Earnings · Darkbloom');
});

it('keeps focus that survived navigation, such as a sidebar button', async () => {
render(<App />);
await screen.findByRole('heading', { name: 'Your contribution' });
const updates = within(screen.getByRole('navigation', { name: 'Main navigation' })).getByRole(
'button',
{ name: 'Updates' },
);
updates.focus();
fireEvent.click(updates);
await screen.findByRole('heading', { name: 'Updates', level: 1 });
await new Promise((resolve) => setTimeout(resolve, 50));
expect(document.activeElement).toBe(updates);
});

it('moves focus to the next onboarding step’s heading', async () => {
render(<Onboarding backend={backendWith(snapshot())} done={() => {}} />);
const start = screen.getByRole('button', { name: /^Start/ });
start.focus();
fireEvent.click(start);
await waitFor(() => expect(document.activeElement?.tagName).toBe('H2'));
});
123 changes: 123 additions & 0 deletions desktop-app/tests/pageTitle.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// @vitest-environment jsdom
import { afterAll, afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import '@testing-library/jest-dom/vitest';
import type { CloudData, DesktopAPI, Resource, Snapshot } from '../src/shared/contracts';
import { operation, snapshot } from './onboardingFixtures';

let App: typeof import('../src/renderer/App').default;
let state: Snapshot;
let cloud: CloudData;
let initialState: () => Promise<Snapshot>;
let receiveState: ((state: Snapshot) => void) | undefined;
const read = vi.fn(async (resource: Resource): Promise<unknown> => {
if (resource === 'state') return initialState();
if (resource === 'cloud') return cloud;
if (resource === 'network') return {};
if (resource === 'cooling') return { supported: false, mode: 'unavailable', fans: [] };
throw new Error(`No fixture for ${resource}`);
});
const bridge: DesktopAPI = {
read: <T,>(resource: Resource) => read(resource) as Promise<T>,
act: vi.fn(async () => operation('succeeded')),
status: async () => ({ state: 'ready' }),
install: async () => {},
openExternal: async () => {},
copy: async () => {},
updateStatus: async () => ({ state: 'idle' }),
checkUpdate: async () => ({ state: 'idle' }),
applyUpdate: async () => {},
onState: (callback) => {
receiveState = callback;
return () => {
receiveState = undefined;
};
},
onStatus: () => () => {},
onNavigate: () => () => {},
onHardware: () => () => {},
};

beforeAll(async () => {
window.history.replaceState({}, '', '/');
window.darkbloom = bridge;
App = (await import('../src/renderer/App')).default;
});
beforeEach(() => {
localStorage.setItem('darkbloom.onboardingComplete', '1');
document.title = 'Darkbloom';
state = snapshot({ account_revision: 'signed-in', account: { signed_in: true } });
cloud = {
linked: true,
observed_at: state.observed_at,
machines: [{ ...state.machine, id: 'remote-studio', name: 'Mac Studio' }],
};
initialState = async () => state;
});
afterEach(() => {
cleanup();
localStorage.clear();
vi.clearAllMocks();
});
afterAll(() => {
delete window.darkbloom;
});

const frame = () =>
act(async () => {
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
});

it('sets the Home title when the first snapshot arrives after the initial frame', async () => {
let deliver!: (state: Snapshot) => void;
initialState = () =>
new Promise((resolve) => {
deliver = resolve;
});
render(<App />);
await waitFor(() => expect(read).toHaveBeenCalledWith('state'));
await frame();
expect(document.title).toBe('Darkbloom');

await act(async () => deliver(state));
await screen.findByRole('heading', { level: 1, name: 'Your contribution' });
await frame();
expect(document.title).toBe('Your contribution · Darkbloom');
expect(document.body).toHaveFocus();
});

it.each(['sign-out', 'cloud removal'])(
'updates the title to the local fallback after same-route %s without refocusing',
async (change) => {
render(<App />);
await screen.findByRole('heading', { level: 1, name: 'Your contribution' });
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
fireEvent.click(within(nav).getByRole('button', { name: 'My Macs' }));
const remote = await screen.findByRole('button', { name: 'Select Mac Studio, View only' });
remote.focus();
fireEvent.click(remote);
await frame();
expect(document.title).toBe('Mac Studio View only · Darkbloom');

const home = within(nav).getByRole('button', { name: 'Home' });
home.focus();
if (change === 'sign-out') {
state = { ...state, account_revision: 'signed-out', account: { signed_in: false } };
} else {
cloud = { ...cloud, machines: [] };
state = { ...state, resource_revision: 'cloud-removed' };
}
act(() => receiveState!(state));
await screen.findByRole('heading', { level: 1, name: 'MacBook Pro This Mac' });
await frame();
expect(document.title).toBe('MacBook Pro This Mac · Darkbloom');
expect(home).toHaveFocus();

// Even when focus is on the body, a routine snapshot must not re-run navigation recovery.
home.blur();
act(() => receiveState!({ ...state, observed_at: state.observed_at + 1 }));
await frame();
expect(document.body).toHaveFocus();
expect(document.title).toBe('MacBook Pro This Mac · Darkbloom');
},
);
Loading