- {clockTime(record.started_at, now)}
+ {clockTime(requestTime(record), now)}
{names.get(record.model) || record.model}
{count(record.input_tokens)}
{count(record.output_tokens)}
- {duration(record.duration_ms)}
- {speed === undefined ? '—' : speed.toFixed(1)}
+ {timing && (
+ <>
+
+ {record.duration_ms === undefined ? '—' : duration(record.duration_ms)}
+
+
+ {speed === undefined ? '—' : speed.toFixed(1)}
+
+ >
+ )}
{outcomes[record.outcome]}
diff --git a/desktop-app/src/renderer/features/stats/activity/requests.ts b/desktop-app/src/renderer/features/stats/activity/requests.ts
index 6b7b14c4bf..fcd8a18bc1 100644
--- a/desktop-app/src/renderer/features/stats/activity/requests.ts
+++ b/desktop-app/src/renderer/features/stats/activity/requests.ts
@@ -6,6 +6,7 @@ export interface RequestFilter {
outcome: Outcome | 'all';
}
export const outcomes: Record = {
+ settled: 'Settled',
completed: 'Completed',
cancelled: 'Cancelled',
failed: 'Failed',
@@ -22,12 +23,14 @@ function parseRecord(value: unknown): RequestRecord {
const earnings = optional(record.earnings_micro_usd);
if (
typeof record.id !== 'string' ||
- !finite(record.started_at) ||
+ !(finite(record.started_at) || finite(record.settled_at) || finite(record.completed_at)) ||
+ (record.started_at !== undefined && !finite(record.started_at)) ||
+ (record.completed_at !== undefined && !finite(record.completed_at)) ||
+ (record.settled_at !== undefined && !finite(record.settled_at)) ||
typeof record.model !== 'string' ||
!tokenCount(record.input_tokens) ||
!tokenCount(record.output_tokens) ||
- !finite(record.duration_ms) ||
- record.duration_ms < 0 ||
+ (record.duration_ms !== undefined && (!finite(record.duration_ms) || record.duration_ms < 0)) ||
typeof record.outcome !== 'string' ||
!Object.hasOwn(outcomes, record.outcome) ||
(earnings !== undefined && (typeof earnings !== 'string' || !/^\d+$/.test(earnings)))
@@ -35,11 +38,13 @@ function parseRecord(value: unknown): RequestRecord {
throw new Error('Invalid request record');
return {
id: record.id,
- started_at: record.started_at,
+ ...(record.started_at !== undefined ? { started_at: record.started_at as number } : {}),
+ ...(record.settled_at !== undefined ? { settled_at: record.settled_at as number } : {}),
+ ...(record.completed_at !== undefined ? { completed_at: record.completed_at as number } : {}),
model: record.model,
input_tokens: record.input_tokens,
output_tokens: record.output_tokens,
- duration_ms: record.duration_ms,
+ duration_ms: record.duration_ms as number | undefined,
outcome: record.outcome as Outcome,
earnings_micro_usd: earnings,
};
@@ -58,7 +63,7 @@ export function parseRequestHistory(value: unknown): RequestHistory {
return {
observed_at: data.observed_at,
since,
- records: data.records.map(parseRecord).sort((a, b) => b.started_at - a.started_at),
+ records: data.records.map(parseRecord).sort((a, b) => requestTime(b) - requestTime(a)),
};
}
@@ -72,8 +77,13 @@ export const filterRequests = (records: RequestRecord[], { model, outcome }: Req
export const requestModels = (records: RequestRecord[]) =>
[...new Set(records.map((record) => record.model))].sort();
+export const requestTime = (record: RequestRecord) =>
+ record.settled_at ?? record.completed_at ?? record.started_at!;
+
export const tokensPerSecond = ({ output_tokens, duration_ms }: RequestRecord) =>
- output_tokens > 0 && duration_ms > 0 ? output_tokens / (duration_ms / 1000) : undefined;
+ output_tokens > 0 && duration_ms !== undefined && duration_ms > 0
+ ? output_tokens / (duration_ms / 1000)
+ : undefined;
export function duration(ms: number) {
if (ms < 1000) return `${Math.round(ms)} ms`;
diff --git a/desktop-app/src/renderer/features/stats/activity/useRequestHistory.ts b/desktop-app/src/renderer/features/stats/activity/useRequestHistory.ts
index 84ccde6512..6785d25798 100644
--- a/desktop-app/src/renderer/features/stats/activity/useRequestHistory.ts
+++ b/desktop-app/src/renderer/features/stats/activity/useRequestHistory.ts
@@ -3,32 +3,44 @@ import type { RequestHistory } from '../../../../shared/contracts';
import { api } from '../../../useBackend';
import { parseRequestHistory } from './requests';
-// Read when the Activity view opens and on manual refresh, never in the
-// periodic refresh: the history grows with every request served.
-export function useRequestHistory() {
+export function useRequestHistory(scope = 'current', revision?: string) {
const [result, setResult] = useState<{
+ scope: string;
history?: RequestHistory;
loading: boolean;
failed: boolean;
- }>({ loading: true, failed: false });
+ }>({ scope, loading: true, failed: false });
const latest = useRef(0);
const load = useCallback(async () => {
const request = ++latest.current;
- setResult((previous) => ({ ...previous, loading: true }));
+ setResult((previous) => ({
+ scope,
+ history: previous.scope === scope ? previous.history : undefined,
+ loading: true,
+ failed: false,
+ }));
try {
if (!api) throw new Error('The runtime is not connected');
const history = parseRequestHistory(await api.read('request-history'));
- if (request === latest.current) setResult({ history, loading: false, failed: false });
+ if (request === latest.current) setResult({ scope, history, loading: false, failed: false });
} catch {
if (request === latest.current)
- setResult((previous) => ({ history: previous.history, loading: false, failed: true }));
+ setResult((previous) => ({
+ scope,
+ history: previous.scope === scope ? previous.history : undefined,
+ loading: false,
+ failed: true,
+ }));
}
- }, []);
+ }, [scope]);
useEffect(() => {
void load();
return () => {
latest.current++;
};
- }, [load]);
- return { ...result, refresh: load };
+ }, [load, revision]);
+ return {
+ ...(result.scope === scope ? result : { history: undefined, loading: true, failed: false }),
+ refresh: load,
+ };
}
diff --git a/desktop-app/src/renderer/features/stats/data.ts b/desktop-app/src/renderer/features/stats/data.ts
index da7b63b183..92aa2ea3c7 100644
--- a/desktop-app/src/renderer/features/stats/data.ts
+++ b/desktop-app/src/renderer/features/stats/data.ts
@@ -1,4 +1,4 @@
-import type { ActivitySample, Snapshot } from '../../../shared/contracts';
+import type { ActivitySample, Snapshot, RequestRecord } from '../../../shared/contracts';
export interface TrafficPoint {
at: number;
requests: number;
@@ -43,6 +43,30 @@ export function observedTraffic(state: Snapshot): TrafficPoint[] {
];
});
}
+/** Settlement times are reported by the API; no start time or decode speed is inferred. */
+export function recordedTraffic(records: RequestRecord[]): TrafficPoint[] {
+ const interval = 1800;
+ const buckets = new Map();
+ for (const record of records) {
+ const time = record.settled_at ?? record.started_at!;
+ const at = Math.floor(time / interval) * interval;
+ const point = buckets.get(at) ?? { at, requests: 0, tokens: 0, input: 0 };
+ point.requests++;
+ point.tokens += record.output_tokens;
+ point.input! += record.input_tokens;
+ buckets.set(at, point);
+ }
+ if (!buckets.size) return [];
+ const times = [...buckets.keys()];
+ const first = Math.min(...times),
+ last = Math.max(...times);
+ const points: TrafficPoint[] = [];
+ // Bound the view if a future runtime returns a longer journal.
+ for (let at = Math.max(first, last - interval * 47); at <= last; at += interval) {
+ points.push(buckets.get(at) ?? { at, requests: 0, tokens: 0, input: 0 });
+ }
+ return points;
+}
export function activityFresh(state: Snapshot, now: number) {
return (
['running', 'draining'].includes(state.state) &&
diff --git a/desktop-app/src/renderer/features/updates/RuntimeVersion.tsx b/desktop-app/src/renderer/features/updates/RuntimeVersion.tsx
index e5a915a4f6..c12138f766 100644
--- a/desktop-app/src/renderer/features/updates/RuntimeVersion.tsx
+++ b/desktop-app/src/renderer/features/updates/RuntimeVersion.tsx
@@ -38,7 +38,7 @@ export function RuntimeVersion({ backend }: { backend: BackendState }) {
- This Mac’s runtime
+ Installed provider version
{installed}
diff --git a/desktop-app/src/renderer/features/updates/version.ts b/desktop-app/src/renderer/features/updates/version.ts
index 690d20d755..967dbeda04 100644
--- a/desktop-app/src/renderer/features/updates/version.ts
+++ b/desktop-app/src/renderer/features/updates/version.ts
@@ -51,11 +51,12 @@ export function releaseStatus(
export const publishedVersions = (sources: {
release?: ReleaseData;
releaseHistory?: ReleaseHistory;
+ cloud?: { minimum_provider_version?: string };
}) => ({
latest: sources.release?.error ? undefined : sources.release?.version,
- minimum: sources.releaseHistory?.error
- ? undefined
- : sources.releaseHistory?.minimum_provider_version,
+ minimum:
+ sources.cloud?.minimum_provider_version ??
+ (sources.releaseHistory?.error ? undefined : sources.releaseHistory?.minimum_provider_version),
});
export const runtimeVersion = (state: Snapshot) =>
diff --git a/desktop-app/src/renderer/models/facts.ts b/desktop-app/src/renderer/models/facts.ts
index f5349bb424..e1f86ec526 100644
--- a/desktop-app/src/renderer/models/facts.ts
+++ b/desktop-app/src/renderer/models/facts.ts
@@ -13,7 +13,7 @@ export function modelFacts(model: NativeModel) {
if (!model.eligible) return model.reason || 'Not available on this Mac.';
return [
`${gigabytes(model.size_gb)} ${model.downloaded ? 'on disk' : 'download'}`,
- model.memory_gb !== undefined && `needs ${gigabytes(model.memory_gb)} memory`,
+ model.memory_gb != null && `needs ${gigabytes(model.memory_gb)} memory`,
]
.filter(Boolean)
.join(' · ');
diff --git a/desktop-app/src/renderer/models/selection.ts b/desktop-app/src/renderer/models/selection.ts
index 2de7a02503..e12f940794 100644
--- a/desktop-app/src/renderer/models/selection.ts
+++ b/desktop-app/src/renderer/models/selection.ts
@@ -17,10 +17,13 @@ export function startingModel(snapshot: Snapshot): NativeModel | undefined {
// known only for models the runtime has measured; an unmeasured pin can't be counted.
export function pinnedMemory(snapshot: Snapshot, pinned: string[]) {
const chosen = snapshot.models.filter((model) => pinned.includes(model.id));
- const needed = chosen.reduce((total, model) => total + (model.memory_gb ?? 0), 0);
+ const needed = chosen.reduce((total, model) => total + (model.memory_gb ?? model.size_gb), 0);
return {
needed,
- measured: chosen.every((model) => model.memory_gb !== undefined),
- exceeds: needed > snapshot.memory.total_gb,
+ measured: chosen.every((model) => model.memory_gb != null),
+ exceeds:
+ needed > (snapshot.memory.pin_budget_gb ?? snapshot.memory.total_gb) ||
+ (snapshot.memory.max_model_slots !== undefined &&
+ chosen.length > snapshot.memory.max_model_slots),
};
}
diff --git a/desktop-app/src/renderer/presentation/status.ts b/desktop-app/src/renderer/presentation/status.ts
new file mode 100644
index 0000000000..4eb855fa7b
--- /dev/null
+++ b/desktop-app/src/renderer/presentation/status.ts
@@ -0,0 +1,39 @@
+// Product labels never echo protocol states or event messages verbatim.
+export function machineStatus(status: string): string {
+ switch (status) {
+ case 'running':
+ case 'online':
+ case 'serving':
+ return 'Online';
+ case 'stopped':
+ return 'Stopped';
+ case 'offline':
+ return 'Offline';
+ case 'starting':
+ return 'Starting';
+ case 'draining':
+ return 'Finishing requests';
+ case 'idle':
+ return 'Ready';
+ case 'untrusted':
+ return 'Verification needed';
+ default:
+ return 'Status unavailable';
+ }
+}
+
+export function modelActivity(state: string, running: number): string {
+ switch (state) {
+ case 'running':
+ case 'idle':
+ return running > 0 ? `${running} processing` : 'Ready';
+ case 'crashed':
+ return 'Needs restart';
+ case 'reloading':
+ return 'Loading';
+ case 'idle_shutdown':
+ return 'Unloaded';
+ default:
+ return 'Status unavailable';
+ }
+}
diff --git a/desktop-app/src/renderer/previewResources.ts b/desktop-app/src/renderer/previewResources.ts
index 93df3b8a28..f83c52995d 100644
--- a/desktop-app/src/renderer/previewResources.ts
+++ b/desktop-app/src/renderer/previewResources.ts
@@ -40,6 +40,7 @@ export function previewResources(): Partial
> {
},
cooling: {
supported: true,
+ enabled: true,
mode: 'automatic',
temperature: 52,
fans: [
diff --git a/desktop-app/src/renderer/styles/components.css b/desktop-app/src/renderer/styles/components.css
index b829a9b51c..66ff9eba0b 100644
--- a/desktop-app/src/renderer/styles/components.css
+++ b/desktop-app/src/renderer/styles/components.css
@@ -207,6 +207,15 @@
color: var(--negative);
}
+.operation > details {
+ min-width: 0;
+ flex: 1;
+}
+
+.operation > svg {
+ flex-shrink: 0;
+}
+
.operation summary {
cursor: pointer;
}
@@ -218,6 +227,7 @@
.operation pre {
white-space: pre-wrap;
+ overflow-wrap: anywhere;
overflow: auto;
max-height: 180px;
max-width: 600px;
@@ -275,18 +285,6 @@
margin-top: 26px;
}
-.operation.operation-inline {
- inset: auto;
- transform: none;
- min-width: 0;
- position: relative;
- overflow: hidden;
- width: 100%;
- max-width: none;
- margin: 0 0 20px;
- box-shadow: none;
- border-radius: 8px;
-}
.model-extra summary {
font-size: 11px;
color: var(--muted);
@@ -296,27 +294,3 @@
.model-extra summary:hover {
color: var(--text-primary);
}
-
-.operation-inline > details {
- min-width: 0;
- flex: 1;
-}
-.operation-inline pre {
- overflow-wrap: anywhere;
- max-width: 100%;
-}
-
-.operation-progress {
- position: absolute;
- top: 0;
- left: 0;
- height: 2px;
- width: 35%;
- background: var(--accent-brand);
- animation: operation-progress 1.8s ease-in-out infinite alternate;
-}
-@keyframes operation-progress {
- to {
- left: 65%;
- }
-}
diff --git a/desktop-app/src/renderer/styles/layout.css b/desktop-app/src/renderer/styles/layout.css
index 1c9aa10035..567ab26cca 100644
--- a/desktop-app/src/renderer/styles/layout.css
+++ b/desktop-app/src/renderer/styles/layout.css
@@ -79,56 +79,6 @@
padding-top: 40px;
}
-.local-profile {
- border-top: 1px solid var(--line);
- display: flex;
- gap: 10px;
- text-align: left;
- align-items: center;
- margin-top: 25px;
- padding: 22px 6px 6px;
- width: 100%;
-}
-
-.local-profile:hover .profile-icon {
- background: rgba(var(--contrast-rgb), 0.07);
- color: var(--text-primary);
-}
-
-.local-profile:hover small {
- color: var(--text-secondary);
-}
-
-.profile-icon {
- height: 32px;
- width: 32px;
- background: rgba(var(--contrast-rgb), 0.031);
- display: grid;
- place-items: center;
- border-radius: 6px;
- transition:
- background var(--hover-duration),
- color var(--hover-duration);
-}
-
-.local-profile strong {
- font-weight: 500;
- font-size: 12px;
- display: block;
-}
-
-.local-profile small {
- font-size: 10px;
- color: var(--muted);
- display: block;
- margin-top: 5px;
- transition: color var(--hover-duration);
-}
-
-.local-profile i {
- margin-left: auto;
-}
-
.online-dot,
.status.online i {
background: var(--positive) !important;
@@ -146,7 +96,7 @@
padding: 0 40px;
display: flex;
align-items: center;
- justify-content: space-between;
+ justify-content: flex-end;
font-size: 11px;
color: var(--muted);
-webkit-app-region: drag;
@@ -163,8 +113,7 @@
font-weight: 400;
}
-.topbar i,
-.local-profile i {
+.topbar i {
width: 5px;
height: 5px;
border-radius: 50%;
@@ -244,9 +193,6 @@
}
}
-.social-links + .local-profile {
- margin-top: 12px;
-}
.home-page {
padding: 24px 32px 18px;
}
diff --git a/desktop-app/src/renderer/styles/models.css b/desktop-app/src/renderer/styles/models.css
index a153d7d203..2f20627599 100644
--- a/desktop-app/src/renderer/styles/models.css
+++ b/desktop-app/src/renderer/styles/models.css
@@ -186,3 +186,17 @@
.warning-text {
color: var(--warning);
}
+
+.model-earnings-order {
+ display: flex;
+ justify-content: space-between;
+ color: var(--text-secondary);
+ font-size: 11px;
+ padding: 0 0 12px;
+}
+.model-earned {
+ margin-left: auto;
+ white-space: nowrap;
+ font-variant-numeric: tabular-nums;
+ font-size: 13px;
+}
diff --git a/desktop-app/src/renderer/styles/onboarding.css b/desktop-app/src/renderer/styles/onboarding.css
index edb8b753fe..20a787bd8b 100644
--- a/desktop-app/src/renderer/styles/onboarding.css
+++ b/desktop-app/src/renderer/styles/onboarding.css
@@ -267,17 +267,6 @@
font-size: 11px;
}
-.onboarding-error {
- position: fixed;
- bottom: 30px;
- left: 30px;
- right: 30px;
-}
-
-.onboarding-error .notice {
- margin: 0;
-}
-
.onboarding .text-link {
font-size: 11px;
}
diff --git a/desktop-app/src/renderer/styles/responsive.css b/desktop-app/src/renderer/styles/responsive.css
index fa78a69667..8cc10c1c68 100644
--- a/desktop-app/src/renderer/styles/responsive.css
+++ b/desktop-app/src/renderer/styles/responsive.css
@@ -73,8 +73,7 @@
display: none;
}
.sidebar nav span,
- .sidebar nav small,
- .local-profile {
+ .sidebar nav small {
display: none;
}
.sidebar nav button {
diff --git a/desktop-app/src/renderer/styles/theme.css b/desktop-app/src/renderer/styles/theme.css
index 68bc000326..57488ffe7d 100644
--- a/desktop-app/src/renderer/styles/theme.css
+++ b/desktop-app/src/renderer/styles/theme.css
@@ -90,10 +90,6 @@
.sidebar-bottom {
padding-top: 16px;
}
- .local-profile {
- margin-top: 12px;
- padding-top: 12px;
- }
}
.empty-state {
padding: 50px 0;
diff --git a/desktop-app/src/renderer/useBackend.ts b/desktop-app/src/renderer/useBackend.ts
index 430944df62..70badd9123 100644
--- a/desktop-app/src/renderer/useBackend.ts
+++ b/desktop-app/src/renderer/useBackend.ts
@@ -12,6 +12,8 @@ import type {
Route,
Snapshot,
} from '../shared/contracts';
+import { submitAction } from './actions';
+import { pageResources } from './data/pageResources';
import { previewAPI } from './preview';
import { parseReleaseHistory } from './features/updates/version';
import { parseLeaderboard } from './features/leaderboard/data';
@@ -21,9 +23,9 @@ export const isPreview = import.meta.env.DEV && new URLSearchParams(location.sea
export const api: DesktopAPI | undefined = isPreview ? previewAPI : window.darkbloom;
// Cooling status spawns a `darkbloom fan status` process in the native backend,
// so it is read only while a screen that displays it is shown: Cooling and
-// This Mac's Overview.
+// This Mac's Overview, and Home's fan indicator.
export const showsCooling = (route: Route, machine: MachineSelection = null) =>
- route === 'cooling' || showsLocalOverview(route, machine);
+ route === 'home' || route === 'cooling' || showsLocalOverview(route, machine);
export function useBackend(route: Route = 'home', machine: MachineSelection = null) {
const [status, setStatus] = useState({ state: 'connecting' });
const [state, setState] = useState();
@@ -36,7 +38,23 @@ export function useBackend(route: Route = 'home', machine: MachineSelection = nu
const [leaderError, setLeaderError] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
+ const accountGeneration = useRef(0);
+ const accountRevision = useRef(undefined);
+ const observeState = useCallback((snapshot: Snapshot) => {
+ if (
+ accountRevision.current !== undefined &&
+ snapshot.account_revision !== accountRevision.current
+ ) {
+ accountGeneration.current++;
+ setCloud(undefined);
+ }
+ accountRevision.current = snapshot.account_revision;
+ setState(snapshot);
+ }, []);
const coolingVisible = useRef(showsCooling(route, machine));
+ coolingVisible.current = showsCooling(route, machine);
+ const visibleResources = useRef(pageResources(route));
+ visibleResources.current = pageResources(route);
const readCooling = useCallback(async () => {
if (!api) return;
await api
@@ -51,51 +69,92 @@ export function useBackend(route: Route = 'home', machine: MachineSelection = nu
}),
);
}, []);
+ const refreshVisible = useCallback(
+ async (includeCooling = true) => {
+ if (!api) return;
+ const generation = accountGeneration.current;
+ const accept =
+ (setter: (value: T) => void) =>
+ (value: T) => {
+ if (generation === accountGeneration.current) setter(value);
+ };
+ await Promise.allSettled([
+ ...(visibleResources.current.includes('cloud')
+ ? [
+ api
+ .read('cloud')
+ .then(accept(setCloud))
+ .catch(() => {
+ if (generation !== accountGeneration.current) return;
+ setCloud((previous) => ({
+ linked: previous?.linked || false,
+ observed_at: previous?.observed_at || 0,
+ machines: previous?.machines || [],
+ ...previous,
+ error: previous?.observed_at
+ ? 'Account data unavailable. Last update: ' +
+ new Date(previous.observed_at * 1000).toLocaleTimeString([], {
+ hour: 'numeric',
+ minute: '2-digit',
+ })
+ : 'Account data unavailable.',
+ }));
+ }),
+ ]
+ : []),
+ ...(visibleResources.current.includes('network')
+ ? [
+ api
+ .read('network')
+ .then(setNetwork)
+ .catch(() =>
+ setNetwork((previous) => ({
+ ...previous,
+ error: 'Network statistics are unavailable.',
+ })),
+ ),
+ ]
+ : []),
+ ...(includeCooling && coolingVisible.current ? [readCooling()] : []),
+ ...(visibleResources.current.includes('release')
+ ? [
+ api
+ .read('release')
+ .then(setRelease)
+ .catch(() => setRelease({ error: 'Release information is unavailable.' })),
+ ]
+ : []),
+ ...(visibleResources.current.includes('release-history')
+ ? [
+ api
+ .read('release-history')
+ .then((value) => setReleaseHistory(parseReleaseHistory(value)))
+ .catch(() =>
+ setReleaseHistory({
+ history: [],
+ error: 'Release history and support policy are unavailable.',
+ }),
+ ),
+ ]
+ : []),
+ ...(visibleResources.current.includes('leaderboard')
+ ? [
+ api
+ .read('leaderboard')
+ .then((data) => {
+ setLeaders(parseLeaderboard(data));
+ setLeaderError('');
+ })
+ .catch(() => setLeaderError('Rankings could not refresh.')),
+ ]
+ : []),
+ ]);
+ },
+ [readCooling],
+ );
const refresh = useCallback(async () => {
- if (!api) return;
- await Promise.allSettled([
- api.read('state').then(setState),
- api
- .read('cloud')
- .then(setCloud)
- .catch(() =>
- setCloud((previous) => ({
- linked: previous?.linked || false,
- observed_at: previous?.observed_at || 0,
- machines: previous?.machines || [],
- ...previous,
- error: 'Account data is unavailable. Showing the last observation.',
- })),
- ),
- api
- .read('network')
- .then(setNetwork)
- .catch(() =>
- setNetwork((previous) => ({ ...previous, error: 'Network statistics are unavailable.' })),
- ),
- ...(coolingVisible.current ? [readCooling()] : []),
- api
- .read('release')
- .then(setRelease)
- .catch(() => setRelease({ error: 'Release information is unavailable.' })),
- api
- .read('release-history')
- .then((value) => setReleaseHistory(parseReleaseHistory(value)))
- .catch(() =>
- setReleaseHistory({
- history: [],
- error: 'Release history and support policy are unavailable.',
- }),
- ),
- api
- .read('leaderboard')
- .then((data) => {
- setLeaders(parseLeaderboard(data));
- setLeaderError('');
- })
- .catch(() => setLeaderError('Rankings could not refresh.')),
- ]);
- }, [readCooling]);
+ await Promise.allSettled([api?.read('state').then(observeState), refreshVisible()]);
+ }, [refreshVisible, observeState]);
useEffect(() => {
if (!api) {
setStatus({
@@ -105,7 +164,7 @@ export function useBackend(route: Route = 'home', machine: MachineSelection = nu
return;
}
api.status().then(setStatus);
- const offState = api.onState(setState);
+ const offState = api.onState(observeState);
const offStatus = api.onStatus(setStatus);
return () => {
offState();
@@ -115,11 +174,14 @@ export function useBackend(route: Route = 'home', machine: MachineSelection = nu
useEffect(() => {
if (status.state !== 'ready') return;
void refresh();
- const timer = setInterval(() => {
- if (!document.hidden) void refresh();
- }, 30_000);
- return () => clearInterval(timer);
}, [status.state, refresh]);
+ useEffect(() => {
+ if (status.state === 'ready') void refreshVisible(false);
+ }, [route, refreshVisible]);
+ useEffect(() => {
+ if (status.state !== 'ready' || document.hidden || !state?.resource_revision) return;
+ void refreshVisible();
+ }, [state?.resource_revision, state?.account_revision]);
const coolingShown = showsCooling(route, machine);
useEffect(() => {
coolingVisible.current = coolingShown;
@@ -134,25 +196,16 @@ export function useBackend(route: Route = 'home', machine: MachineSelection = nu
setBusy(true);
setError('');
try {
- const operation = await api.act(action);
if (wait) {
- const deadline = Date.now() + 40 * 60_000;
- while (Date.now() < deadline) {
- const latest = await api.read('state');
- setState(latest);
- const current = latest.operations.find((item) => item.id === operation.id);
- if (current && current.state !== 'running') {
- if (current.state !== 'succeeded') throw new Error(current.message);
- await refresh();
- return true;
- }
- await new Promise((resolve) => setTimeout(resolve, 750));
- }
- throw new Error(
- 'The operation is taking longer than expected. Check its status before retrying.',
- );
+ await submitAction(api, action, {
+ timeoutMs: 40 * 60_000,
+ timeout:
+ 'The operation is taking longer than expected. Check its status before retrying.',
+ });
+ } else {
+ await api.act(action);
}
- await refresh();
+ await refreshVisible();
return true;
} catch (error) {
setError(error instanceof Error ? error.message : 'The action failed');
@@ -161,7 +214,7 @@ export function useBackend(route: Route = 'home', machine: MachineSelection = nu
setBusy(false);
}
},
- [refresh],
+ [refreshVisible],
);
return {
status,
diff --git a/desktop-app/src/shared/autopilot.ts b/desktop-app/src/shared/autopilot.ts
index 787a66422e..7b6ffc6ab5 100644
--- a/desktop-app/src/shared/autopilot.ts
+++ b/desktop-app/src/shared/autopilot.ts
@@ -1,10 +1,11 @@
// Mirrors `darkbloom start --autopilot --model … [--local-endpoint]` followed by
-// `darkbloom autopilot pin …`. `models` are the startup models: the runtime downloads and
-// verifies them, and once cached they join Autopilot's approved inventory. `pinned` must be a
+// `darkbloom autopilot pin …`. `downloads` are explicitly chosen downloads, completed before
+// the CLI verifies cached inventory and starts `models`. `pinned` must be a
// subset of `models`; a pinned model is protected from automatic unloading.
export interface AutopilotAction {
action: 'autopilot';
models: string[];
+ downloads?: string[];
pinned: string[];
endpoint?: boolean;
}
@@ -14,8 +15,8 @@ export interface AutopilotAction {
// in the pool (`AutopilotStatus.selected`).
// - `autopilot_pause` / `autopilot_resume` → `autopilot pause|resume`.
// - `autopilot_disable` → `autopilot disable`; loaded models stay as they are.
-// - `autopilot_models` → `autopilot models`: re-inventories the downloaded models into the pool
-// through the runtime's safe drain and restart. Downloading alone never adds to the pool.
+// - `autopilot_models` → noninteractive `start --autopilot --model `:
+// re-inventories cached models through the same safe drain/restart used by `autopilot models`.
export type AutopilotPolicyAction =
| { action: 'autopilot_pin' | 'autopilot_unpin'; models: string[] }
| { action: 'autopilot_pause' | 'autopilot_resume' | 'autopilot_disable' | 'autopilot_models' };
@@ -25,6 +26,7 @@ export type AutopilotPolicyAction =
// can't run Autopilot. `selected` is the pool and `phase` the live daemon phase, absent while
// the daemon isn't reporting.
export interface AutopilotStatus {
+ configured?: boolean;
enabled: boolean;
paused: boolean;
selected: string[];
diff --git a/desktop-app/src/shared/contracts.ts b/desktop-app/src/shared/contracts.ts
index c0db587cb7..d2d2a5c7af 100644
--- a/desktop-app/src/shared/contracts.ts
+++ b/desktop-app/src/shared/contracts.ts
@@ -30,16 +30,16 @@ export interface NativeModel {
id: string;
display_name: string;
size_gb: number;
- memory_gb?: number;
+ memory_gb?: number | null;
downloaded: boolean;
serving: boolean;
loaded: boolean;
eligible: boolean;
- reason?: string;
- description?: string;
- context_length?: number;
- family?: string;
- quantization?: string;
+ reason?: string | null;
+ description?: string | null;
+ context_length?: number | null;
+ family?: string | null;
+ quantization?: string | null;
}
export interface Machine {
id: string;
@@ -79,15 +79,46 @@ export interface Snapshot {
installation_id: string;
linked: boolean;
account_revision?: string;
+ resource_revision?: string;
+ capabilities?: string[];
+ account?: {
+ signed_in: boolean;
+ email?: string | null;
+ expires_at?: number;
+ legacy_data?: boolean;
+ };
state: 'stopped' | 'starting' | 'running' | 'draining' | 'stale';
readiness: string;
+ /** Coordinator-reported connection status, distinct from its diagnostic event reason. */
+ provider_status?: string | null;
machine: Machine;
models: NativeModel[];
operations: Operation[];
- memory: { total_gb: number; active_gb?: number; cache_gb?: number; free_for_load_gb?: number };
+ memory: {
+ total_gb: number;
+ active_gb?: number;
+ cache_gb?: number;
+ free_for_load_gb?: number;
+ pin_budget_gb?: number;
+ max_model_slots?: number;
+ };
activity: {
requests?: string;
tokens?: string;
+ /** All prompt tokens, including cached input; output already includes reasoning. */
+ prompt_tokens?: string | null;
+ usage_gaps?: string | null;
+ processed_tokens?: string | null;
+ processed_input_tokens?: string | null;
+ processed_output_tokens?: string | null;
+ cached_input_tokens?: string | null;
+ reasoning_tokens?: string | null;
+ counted_requests?: string | null;
+ pending_usage_requests?: string | null;
+ usage_source?: 'local' | 'settled-history';
+ usage_observed_at?: number;
+ /** Settled earnings for this provider session only, when the server supplies them. */
+ earnings_micro_usd?: string | null;
started_at?: number;
samples: ActivitySample[];
sampled_at?: number;
@@ -123,9 +154,14 @@ export interface CloudData {
observed_at: number;
lifetime_micro_usd?: string;
week_micro_usd?: string;
+ /** False when the returned records cover only part of the requested week. */
+ earnings_complete?: boolean;
+ earnings_since?: number;
+ settled_records?: string;
balance_micro_usd?: string;
machines: Machine[];
local_earnings_micro_usd?: string;
+ minimum_provider_version?: string;
// This Mac's settled earnings including base rewards: all time, and the rolling past 24 hours.
local_lifetime_micro_usd?: string;
local_day_micro_usd?: string;
@@ -134,12 +170,14 @@ export interface CloudData {
// Request metadata only: history never carries prompt or response content.
export interface RequestRecord {
id: string;
- started_at: number;
+ started_at?: number;
+ settled_at?: number;
+ completed_at?: number;
model: string;
input_tokens: number;
output_tokens: number;
- duration_ms: number;
- outcome: 'completed' | 'cancelled' | 'failed';
+ duration_ms?: number;
+ outcome: 'completed' | 'cancelled' | 'failed' | 'settled';
// Omitted until the request settles.
earnings_micro_usd?: string;
}
@@ -149,6 +187,11 @@ export interface RequestHistory {
records: RequestRecord[];
}
export interface NetworkData {
+ model_earnings?: {
+ window: '7d';
+ as_of: string;
+ models: { id: string; earnings_micro_usd: string }[];
+ } | null;
total_tokens?: string;
total_requests?: string;
// Prompt plus completion tokens in the past 24 hours; omitted by runtimes that do not relay it.
@@ -159,9 +202,14 @@ export interface NetworkData {
}
export interface CoolingData {
supported: boolean;
+ enabled?: boolean | null;
+ observed_at?: number;
mode: string;
- temperature?: number;
+ temperature?: number | null;
fans: { name: string; rpm: number; max_rpm: number }[];
+ control_available?: boolean;
+ speed?: number;
+ threshold?: number;
error?: string;
}
export interface ReleaseData {
@@ -185,7 +233,17 @@ export interface Leader {
}
export type Action =
| { action: 'start' | 'switch'; models: string[]; local?: boolean; endpoint?: boolean }
- | { action: 'stop' | 'restart' | 'update' | 'diagnose' | 'link' | 'unlink' }
+ | {
+ action:
+ | 'stop'
+ | 'restart'
+ | 'update'
+ | 'diagnose'
+ | 'link'
+ | 'unlink'
+ | 'account-signin'
+ | 'account-signout';
+ }
| { action: 'download' | 'remove'; model: string }
| { action: 'cancel'; operation: string }
| {
diff --git a/desktop-app/tests/accountSignInProgress.test.tsx b/desktop-app/tests/accountSignInProgress.test.tsx
new file mode 100644
index 0000000000..19eea1f05f
--- /dev/null
+++ b/desktop-app/tests/accountSignInProgress.test.tsx
@@ -0,0 +1,161 @@
+// @vitest-environment jsdom
+import { afterEach, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import '@testing-library/jest-dom/vitest';
+import { OperationFeed } from '../src/renderer/components/UI';
+import { AccountControl } from '../src/renderer/components/AccountControl';
+import { backendWith, operation, snapshot } from './onboardingFixtures';
+
+const bridge = vi.hoisted(() => ({ copy: vi.fn(), openExternal: vi.fn() }));
+vi.mock('../src/renderer/useBackend', () => ({ api: bridge }));
+afterEach(() => {
+ cleanup();
+ vi.resetAllMocks();
+ localStorage.clear();
+});
+const pending = { ...operation('running', 'Working…', 'account-signin'), cancellable: true };
+const link = {
+ code: 'ABCD-EFGH',
+ url: 'https://console.darkbloom.dev/link',
+ expires_at: 1_790_001_000,
+ state: 'waiting',
+};
+const login = (overrides: Parameters[0] = {}) =>
+ backendWith(
+ snapshot({ capabilities: ['account-signin'], operations: [pending], link, ...overrides }),
+ );
+
+it('opens immediately, waits for a fresh code, and opens the browser only on an explicit click', async () => {
+ const backend = login({ operations: [operation('failed', 'Old failure', 'account-signin')] });
+ let finish!: (value: boolean) => void;
+ vi.mocked(backend.act).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { rerender } = render( );
+ fireEvent.click(screen.getByRole('button', { name: 'Sign in' }));
+ expect(screen.getByRole('dialog', { name: 'Sign in to Darkbloom' })).toBeVisible();
+ expect(screen.getByText('Getting a connection code…')).toBeVisible();
+ expect(screen.getByRole('button', { name: 'Continue in browser' })).toBeDisabled();
+ expect(screen.queryByText(link.code)).not.toBeInTheDocument();
+ expect(bridge.openExternal).not.toHaveBeenCalled();
+ rerender( );
+ expect(screen.getByLabelText('Connection code ABCD-EFGH')).toBeVisible();
+ expect(bridge.openExternal).not.toHaveBeenCalled();
+ expect(screen.getByText('Enter this code in your browser.')).toBeVisible();
+ expect(
+ within(screen.getByRole('dialog')).queryByText('Waiting for approval'),
+ ).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Continue in browser' }));
+ expect(bridge.openExternal).toHaveBeenCalledExactlyOnceWith('link');
+ expect(await screen.findByText('Approve the connection in your browser.')).toBeVisible();
+ finish(true);
+ await waitFor(() =>
+ expect(backend.act).toHaveBeenCalledExactlyOnceWith({ action: 'account-signin' }),
+ );
+});
+
+it('reopens pending sign-in without a duplicate request and restores keyboard focus', async () => {
+ const backend = login();
+ backend.busy = true;
+ render(
+ <>
+
+
+ >,
+ );
+ const button = screen.getByRole('button', { name: 'Continue sign-in' });
+ button.focus();
+ fireEvent.click(button);
+ expect(screen.getAllByLabelText('Connection code ABCD-EFGH')).toHaveLength(1);
+ fireEvent.click(screen.getByRole('button', { name: 'Copy code' }));
+ expect(bridge.copy).toHaveBeenCalledWith(link.code);
+ await screen.findByRole('button', { name: 'Copied' });
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ expect(button).toHaveFocus();
+ fireEvent.click(button);
+ expect(screen.getByLabelText('Connection code ABCD-EFGH')).toBeVisible();
+ expect(backend.act).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(backend.act).toHaveBeenCalledWith({ action: 'cancel', operation: pending.id });
+});
+
+it('removes expired codes, retains failure details, and starts a fresh attempt on retry', async () => {
+ const { rerender } = render( );
+ fireEvent.click(screen.getByRole('button', { name: 'Continue sign-in' }));
+ const failed = login({
+ operations: [{ ...pending, state: 'failed', message: 'Device code expired' }],
+ });
+ rerender( );
+ expect(screen.queryByText(link.code)).not.toBeInTheDocument();
+ expect(screen.getByText('Could not complete sign-in.')).toBeVisible();
+ expect(screen.getByText('Device code expired')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
+ await waitFor(() => expect(failed.act).toHaveBeenCalledWith({ action: 'account-signin' }));
+ expect(screen.getByText('Getting a connection code…')).toBeVisible();
+});
+
+it('shows a recoverable error if the login request cannot start', async () => {
+ const backend = login({ operations: [], link: undefined });
+ vi.mocked(backend.act).mockResolvedValue(false);
+ backend.error = 'Coordinator unavailable';
+ render( );
+ fireEvent.click(screen.getByRole('button', { name: 'Sign in' }));
+ expect(await screen.findByText('Could not complete sign-in.')).toBeVisible();
+ expect(screen.getByRole('alert')).toHaveTextContent('Coordinator unavailable');
+ expect(screen.getByRole('button', { name: 'Try again' })).toBeEnabled();
+});
+
+it('confirms approval in the dialog and switches the footer to Account', () => {
+ const { rerender } = render( );
+ fireEvent.click(screen.getByRole('button', { name: 'Continue sign-in' }));
+ rerender(
+ ,
+ );
+ expect(screen.getByText('You’re signed in.')).toBeVisible();
+ expect(screen.queryByText(link.code)).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Account' })).toBeVisible();
+ fireEvent.click(screen.getByRole('button', { name: 'Done' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Account' }));
+ expect(screen.getByRole('dialog', { name: 'Your account' })).toBeVisible();
+ expect(screen.getByRole('button', { name: 'Sign out' })).toBeEnabled();
+});
+
+it('keeps clipboard and browser failures actionable inside the dialog', async () => {
+ bridge.copy.mockRejectedValue(new Error('Clipboard unavailable'));
+ bridge.openExternal.mockRejectedValue(new Error('Browser unavailable'));
+ render( );
+ fireEvent.click(screen.getByRole('button', { name: 'Continue sign-in' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Copy code' }));
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not copy the connection code.');
+ fireEvent.click(screen.getByRole('button', { name: 'Continue in browser' }));
+ await waitFor(() =>
+ expect(screen.getByRole('alert')).toHaveTextContent('Could not open sign-in. Try again.'),
+ );
+});
+
+it('shows the signed-in email in the footer and hides it immediately after sign-out', () => {
+ const email = 'a.long.account.email.address@example.com';
+ const { rerender } = render(
+ ,
+ );
+ const control = screen.getByRole('button', { name: `Account ${email}` });
+ expect(within(control).getByText(email)).toHaveAttribute('title', email);
+ expect(within(control).getByText('Signed in')).toBeVisible();
+ fireEvent.click(control);
+ expect(within(screen.getByRole('dialog')).getByText(email)).toBeVisible();
+ fireEvent.click(screen.getByRole('button', { name: 'Done' }));
+ rerender(
+ ,
+ );
+ expect(screen.getByRole('button', { name: 'Sign in' })).toBeVisible();
+ expect(screen.queryByText(email)).not.toBeInTheDocument();
+});
diff --git a/desktop-app/tests/app.test.tsx b/desktop-app/tests/app.test.tsx
index 874462681b..6a74f3ed99 100644
--- a/desktop-app/tests/app.test.tsx
+++ b/desktop-app/tests/app.test.tsx
@@ -14,6 +14,10 @@ describe('desktop operator journeys', () => {
render( );
await screen.findByRole('heading', { name: 'Your contribution' });
expect(screen.getByText('Development preview')).toBeVisible();
+ fireEvent.click(await screen.findByRole('button', { name: /Auto fan on.*Open Cooling/ }));
+ expect(await screen.findByRole('heading', { name: 'Cooling' })).toBeVisible();
+ fireEvent.click(screen.getByRole('button', { name: 'Home' }));
+ await screen.findByRole('heading', { name: 'Your contribution' });
expect(screen.getByRole('link', { name: 'Darkbloom on X' })).toHaveAttribute(
'href',
'https://x.com/darkbloomai',
@@ -106,17 +110,18 @@ describe('desktop operator journeys', () => {
fireEvent.click(screen.getByRole('button', { name: 'Manage models' }));
expect(screen.getByRole('region', { name: 'Autopilot' })).toBeVisible();
expect(screen.queryByRole('button', { name: 'Apply selection' })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Browse models' }));
fireEvent.change(screen.getByRole('textbox', { name: 'Search models' }), {
target: { value: 'Qwen 3.6' },
});
expect(screen.queryByRole('heading', { name: 'GPT-OSS 20B' })).not.toBeInTheDocument();
const row = screen.getByRole('heading', { name: 'Qwen 3.6 35B A3B' }).closest('article')!;
expect(within(row).getByText('Not downloaded')).toBeVisible();
- fireEvent.click(within(row).getByRole('button', { name: /Download/ }));
+ fireEvent.click(within(row).getByRole('button', { name: 'Download' }));
+ await within(row).findByRole('progressbar', { name: 'Download progress' });
expect(
- await within(row).findByRole('progressbar', { name: 'Download progress' }),
+ await within(row).findByText('Available to Autopilot', {}, { timeout: 10_000 }),
).toBeVisible();
- expect(await within(row).findByText('In pool', {}, { timeout: 10_000 })).toBeVisible();
});
it('does not overwrite a concurrent CLI settings change with a stale draft', async () => {
render( );
diff --git a/desktop-app/tests/chipLayout.test.ts b/desktop-app/tests/chipLayout.test.ts
index 454ce1ae7f..91e64716da 100644
--- a/desktop-app/tests/chipLayout.test.ts
+++ b/desktop-app/tests/chipLayout.test.ts
@@ -21,7 +21,10 @@ describe.each(CHIPS)('%s layout', (chip) => {
expect(counted('gpu')).toBe(anatomy.gpuCores);
expect(counted('performance')).toBe(anatomy.performanceCores);
expect(counted('efficiency')).toBe(anatomy.efficiencyCores);
- expect(counted('neural')).toBe(anatomy.neuralCores);
+ expect(counted('neural')).toBe(0);
+ expect(layout.blocks.every((block) => ['cpu', 'gpu', 'interface'].includes(block.kind))).toBe(
+ true,
+ );
expect(layout.dies).toHaveLength(anatomy.dies);
expect(layout.memory).toHaveLength(anatomy.memoryPackages);
@@ -61,7 +64,6 @@ describe.each(CHIPS)('%s layout', (chip) => {
contains(layout.dies[layout.memory[trace.package].die], { ...trace.to, w: 0, h: 0 }),
).toBe(true);
}
- expect(contains(layout.substrate, { ...layout.io.path[0], w: 0, h: 0 })).toBe(true);
});
it('is deterministic', () => {
@@ -80,6 +82,5 @@ describe('package arrangement', () => {
const ultra = chipLayout(chipAnatomy('Apple M2 Ultra', 192), SIZES[0]);
expect(ultra.dies.map((die) => die.orientation)).toEqual(['cw', 'ccw']);
expect(ultra.bridge).not.toBeNull();
- expect(ultra.io.side).toBe('left');
});
});
diff --git a/desktop-app/tests/chipMeasured.test.ts b/desktop-app/tests/chipMeasured.test.ts
new file mode 100644
index 0000000000..c9f85b605c
--- /dev/null
+++ b/desktop-app/tests/chipMeasured.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+import { measuredFrame } from '../src/renderer/features/home/chip/workload/measured';
+import { memoryMap } from '../src/renderer/features/home/chip/memoryMap';
+import { createHardwareDrive } from '../src/renderer/features/home/chip/hardware/drive';
+import { IDLE_INPUTS } from '../src/renderer/features/home/chip/workload/types';
+import {
+ gpuLevel,
+ cpuLevel,
+ tracePulses,
+} from '../src/renderer/features/home/chip/render/activity';
+import { chipLayout } from '../src/renderer/features/home/chip/layout';
+import { chipAnatomy } from '../src/renderer/features/home/chip/anatomy';
+
+const memory = memoryMap(64, [{ id: 'a', name: 'A', gb: 10 }], 14);
+const reading = {
+ fresh: true,
+ sample: null,
+ inputs: { ...IDLE_INPUTS, mode: 'live' as const, running: 8, waiting: 2, tokensPerSecond: 300 },
+};
+describe('live chip frames', () => {
+ it('shows real counts and allocation without inventing prompt phases or token motion', () => {
+ const frame = measuredFrame(reading, memory, 14);
+ expect(frame).toMatchObject({
+ running: 8,
+ waiting: 2,
+ tokensPerSecond: 300,
+ resident: 1,
+ prefill: 0,
+ decode: 0,
+ memoryRead: 0,
+ kvWrite: 0,
+ steps: 0,
+ });
+ expect(frame.kvFill).toBeCloseTo((14 / 64 - 10 / 64) / (0.9 - 10 / 64));
+ expect(measuredFrame(reading, memory, null).kvFill).toBe(0);
+ });
+ it('withholds stale counts and leaves unmeasured processors and traffic dark', () => {
+ const workload = measuredFrame({ ...reading, fresh: false }, memory, 14);
+ const lit = createHardwareDrive().step(1, workload, null);
+ const frame = { ...lit, motion: true, pointer: null };
+ const layout = chipLayout(chipAnatomy('Apple M3 Max', 64), { width: 900, height: 440 });
+ expect(workload).toMatchObject({ running: 0, waiting: 0, tokensPerSecond: 0 });
+ expect(
+ gpuLevel(
+ layout.tiles.find((tile) => tile.kind === 'gpu')!,
+ frame,
+ ),
+ ).toEqual({ prefill: 0, decode: 0 });
+ expect(
+ cpuLevel(
+ layout.tiles.find((tile) => tile.kind === 'performance')!,
+ frame,
+ ),
+ ).toBe(0);
+ expect(tracePulses(layout.traces[0], frame)).toEqual([]);
+ });
+});
diff --git a/desktop-app/tests/chipStage.test.tsx b/desktop-app/tests/chipStage.test.tsx
index 659379ad42..a39b9cafdc 100644
--- a/desktop-app/tests/chipStage.test.tsx
+++ b/desktop-app/tests/chipStage.test.tsx
@@ -32,12 +32,13 @@ describe('ChipStage', () => {
expect(within(stage).getByRole('heading', { name: state.machine.chip })).toBeVisible();
expect(within(stage).getByText(`${state.machine.memory_gb} GB unified memory`)).toBeVisible();
const loaded = state.models.filter((model) => model.loaded)[0];
- expect(within(stage).getByText(new RegExp(loaded.display_name))).toBeVisible();
+ expect(within(stage).getByText(loaded.display_name, { selector: 'span' })).toBeVisible();
expect(within(stage).getByText('Simulated activity')).toBeVisible();
const legend = within(stage).getByRole('list', { name: 'What lights up' });
- for (const phase of ['Prefill', 'Decode', 'KV cache', 'Neural Engine'])
+ for (const phase of ['Prefill', 'Decode', 'KV cache'])
expect(within(legend).getByText(phase)).toBeVisible();
- expect(within(legend).getByText('Idle')).toBeVisible();
+ expect(within(legend).queryByText('Neural Engine')).not.toBeInTheDocument();
+ expect(within(legend).queryByText('Memory traffic')).not.toBeInTheDocument();
});
it('switches between the two variants through the URL in preview', async () => {
@@ -77,8 +78,10 @@ describe('ChipStage', () => {
const { rerender } = render( );
const stage = stageFor(state);
expect(within(stage).queryByRole('group', { name: 'Chip style' })).not.toBeInTheDocument();
- expect(within(stage).getByText('Simulated activity')).toBeVisible();
- expect(within(stage).getAllByText('—')).toHaveLength(3);
+ expect(within(stage).getByText('Waiting for live activity')).toBeVisible();
+ expect(within(stage).queryByText('tokens per second')).not.toBeInTheDocument();
+ expect(within(stage).queryByText('In progress')).not.toBeInTheDocument();
+ expect(within(stage).queryByText('Waiting')).not.toBeInTheDocument();
rerender( );
expect(within(stage).getByText('Provider stopped')).toBeVisible();
expect(stage).toHaveAttribute('data-powered', 'false');
@@ -93,7 +96,7 @@ describe('ChipStage', () => {
};
render( );
const stage = stageFor(state);
- expect(within(stage).getByText('Simulated activity')).toBeVisible();
+ expect(within(stage).getByText('Live from this Mac')).toBeVisible();
expect(within(stage).getByText('In progress').nextSibling).toHaveTextContent('3');
expect(within(stage).getByText('Waiting').nextSibling).toHaveTextContent('2');
});
@@ -107,21 +110,21 @@ describe('ChipStage', () => {
expect(row('GPU busy')).toHaveTextContent('99%');
expect(row('GPU busy')).toHaveTextContent('Darkbloom 96%');
expect(row('GPU clock')).toHaveTextContent('1,578 MHz');
- expect(row('Memory traffic')).toHaveTextContent(/\d+ GB\/s.*Estimated/);
+ expect(within(stage).queryByText('Memory traffic')).not.toBeInTheDocument();
expect(
- within(stage).getByText('macOS reports GPU busy for the whole GPU, not per core.'),
+ within(stage).getByTitle('macOS reports GPU busy for the whole GPU, not per core.'),
).toBeVisible();
- expect(within(stage).getByText('Idle: Darkbloom runs on the GPU')).toBeVisible();
});
- it('falls back to the simulation when the hardware stream is stale', async () => {
+ it('withholds hardware readings when the stream is stale', async () => {
const state = await previewState();
const source = hardwareSource(10);
+ state.activity.sampled_at = 1;
render( );
const stage = stageFor(state);
await vi.waitFor(() => expect(source.read).toHaveBeenCalled());
expect(await within(stage).findByText('GPU busy')).toBeVisible();
- expect(within(stage).getByText('Simulated activity')).toBeVisible();
+ expect(within(stage).getByText('Waiting for live activity')).toBeVisible();
expect(within(stage).getByText('GPU busy').nextSibling).toHaveTextContent('—');
expect(within(stage).queryByText('Live from this Mac')).not.toBeInTheDocument();
});
diff --git a/desktop-app/tests/chipStageText.test.ts b/desktop-app/tests/chipStageText.test.ts
index 3e11ee8ac2..1f0fe54be9 100644
--- a/desktop-app/tests/chipStageText.test.ts
+++ b/desktop-app/tests/chipStageText.test.ts
@@ -57,7 +57,7 @@ describe('stage text', () => {
it('prints live snapshot numbers only while they are current', () => {
expect(
stageText({ ...base, preview: false, provider: 'draining', reading: reading(true) }),
- ).toMatchObject({ mode: 'Simulated activity', tokensPerSecond: 333, running: 7, waiting: 2 });
+ ).toMatchObject({ mode: 'Live from this Mac', tokensPerSecond: 333, running: 7, waiting: 2 });
const waiting = stageText({
...base,
preview: false,
@@ -65,16 +65,16 @@ describe('stage text', () => {
reading: reading(false),
});
expect(waiting).toMatchObject({
- mode: 'Simulated activity',
+ mode: 'Waiting for live activity',
current: false,
tokensPerSecond: null,
running: null,
waiting: null,
});
- expect(waiting.summary).toContain('Waiting for current activity.');
+ expect(waiting.summary).not.toContain('Waiting for current activity.');
expect(
stageText({ ...base, preview: false, provider: 'stale', reading: reading(false) }),
- ).toMatchObject({ mode: 'Simulated activity', running: null });
+ ).toMatchObject({ mode: 'Waiting for live activity', running: null });
});
it('says the chip is live from this Mac while fresh measurements drive it', () => {
diff --git a/desktop-app/tests/chipTargets.test.ts b/desktop-app/tests/chipTargets.test.ts
index ee84de69d6..9d05da90c7 100644
--- a/desktop-app/tests/chipTargets.test.ts
+++ b/desktop-app/tests/chipTargets.test.ts
@@ -10,12 +10,7 @@ import {
sessionPeakPower,
} from '../src/renderer/features/home/chip/hardware/targets';
import { chipLayout } from '../src/renderer/features/home/chip/layout';
-import {
- cpuLevel,
- gpuLevel,
- gpuShare,
- neuralLevel,
-} from '../src/renderer/features/home/chip/render/activity';
+import { cpuLevel, gpuLevel, gpuShare } from '../src/renderer/features/home/chip/render/activity';
import type { RenderFrame } from '../src/renderer/features/home/chip/render/types';
import { anatomyFromTopology } from '../src/renderer/features/home/chip/topologyAnatomy';
import { createWorkloadEngine } from '../src/renderer/features/home/chip/workload/engine';
@@ -166,15 +161,23 @@ describe('hardware phase', () => {
});
describe('hardware drive', () => {
- it('overlays eased measurements on the simulation while fresh', () => {
+ it('uses measured light without manufacturing live phases or traffic', () => {
const drive = createHardwareDrive(),
targets = targetsAt(DECODE),
{ lit } = run(drive, targets, 3);
expect(lit.hardware?.weight).toBeGreaterThan(0.99);
expect(lit.workload.power).toBeCloseTo(1);
- expect(lit.workload.memoryRead).toBeCloseTo(targets.traffic!, 2);
- expect(lit.workload.decode).toBeCloseTo(0.99 * 0.97, 1);
- expect(lit.workload.phase).toBe('decode');
+ expect(lit.workload.memoryRead).toBe(0);
+ expect(lit.workload.decode).toBe(0);
+ expect(lit.workload.phase).toBe('ready');
+ });
+
+ it('does not animate unmeasured bandwidth as live traffic', () => {
+ const drive = createHardwareDrive();
+ const targets = { ...targetsAt(DECODE), traffic: null };
+ const { lit } = run(drive, targets, 4);
+ expect(lit.workload.memoryRead).toBeLessThan(0.001);
+ expect(lit.workload.kvWrite).toBeLessThan(0.001);
});
it('eases between 1 Hz samples instead of jumping', () => {
@@ -186,7 +189,7 @@ describe('hardware drive', () => {
expect(traffic).toBeGreaterThan(targetsAt(IDLE).traffic! + 0.2);
});
- it('falls back to the simulation once the stream goes stale', () => {
+ it('turns measured lights off as soon as the stream goes stale', () => {
const drive = createHardwareDrive();
run(drive, targetsAt(DECODE), 3);
const { lit, simulated } = run(drive, null, 4);
@@ -204,7 +207,7 @@ describe('measured light', () => {
};
it('gives every GPU core the same intensity, tinted by Darkbloom’s share', () => {
- const frame = frameAt(DECODE),
+ const frame = { ...frameAt(DECODE), motion: true },
levels = layout.tiles
.filter((tile) => tile.kind === 'gpu' && !tile.filler)
.map((tile) => {
@@ -217,11 +220,10 @@ describe('measured light', () => {
expect(gpuShare(frameAt(DECODE, false))).toBeCloseTo(0, 2);
});
- it('lights CPU cores individually and keeps the Neural Engine dark', () => {
+ it('lights CPU cores individually', () => {
const frame = frameAt(DECODE),
measured = sample(DECODE).cpu.load;
for (const tile of layout.tiles.filter((tile) => tile.kind === 'performance'))
expect(cpuLevel(tile, frame)).toBeCloseTo(measured[tile.cpu!], 2);
- expect(neuralLevel(frame)).toBe(0);
});
});
diff --git a/desktop-app/tests/contributionMetrics.test.tsx b/desktop-app/tests/contributionMetrics.test.tsx
new file mode 100644
index 0000000000..3a373dd71f
--- /dev/null
+++ b/desktop-app/tests/contributionMetrics.test.tsx
@@ -0,0 +1,69 @@
+// @vitest-environment jsdom
+import { afterEach, expect, it, vi } from 'vitest';
+import { cleanup, render, screen } from '@testing-library/react';
+import '@testing-library/jest-dom/vitest';
+import { ContributionMetrics } from '../src/renderer/features/home/ContributionMetrics';
+import { contribution } from '../src/renderer/features/home/contribution';
+
+afterEach(cleanup);
+it('counts input plus output once and displays cached and reasoning subsets', () => {
+ const activity = {
+ samples: [],
+ tokens: '30',
+ prompt_tokens: '120',
+ cached_input_tokens: '80',
+ reasoning_tokens: '20',
+ };
+ expect(contribution(activity)).toMatchObject({
+ tokens: '150',
+ input: '120',
+ output: '30',
+ cached: '80',
+ reasoning: '20',
+ label: 'Tokens processed this session',
+ });
+ render( );
+ expect(screen.getByText('150')).toBeVisible();
+ expect(screen.getByLabelText('Token breakdown')).toHaveTextContent(
+ 'Input 120Cached 80Output 30Reasoning 20',
+ );
+});
+it('keeps the requested label and unknown totals blank instead of showing output as the total', () => {
+ render(
+ ,
+ );
+ expect(screen.getByText('Tokens processed this session')).toBeVisible();
+ expect(screen.getByTitle('Waiting for complete input and output usage')).toHaveTextContent('—');
+ expect(screen.queryByText(/≥/)).not.toBeInTheDocument();
+ expect(screen.getByTitle('Session earnings unavailable')).toHaveTextContent('—');
+});
+it('uses verified history without combining it with newer output-only totals', () => {
+ expect(
+ contribution({
+ samples: [],
+ tokens: '45',
+ requests: '3',
+ processed_tokens: '150',
+ processed_input_tokens: '120',
+ processed_output_tokens: '30',
+ pending_usage_requests: '1',
+ usage_source: 'settled-history',
+ earnings_micro_usd: '1000',
+ }),
+ ).toMatchObject({ tokens: '150', pending: '1', earnings: '$0.0010' });
+});
+it('distinguishes complete zero, incomplete usage and invalid counters with exact large integers', () => {
+ expect(
+ contribution({ samples: [], tokens: '0', prompt_tokens: '0', earnings_micro_usd: '0' }),
+ ).toMatchObject({ tokens: '0', earnings: '$0.0000' });
+ expect(
+ contribution({ samples: [], tokens: '30', prompt_tokens: '120', usage_gaps: '1' }).tokens,
+ ).toBe('—');
+ expect(contribution({ samples: [], tokens: 'invalid', prompt_tokens: '120' }).tokens).toBe('—');
+ expect(
+ contribution({ samples: [], tokens: '30', prompt_tokens: '9007199254740993' }).tokens,
+ ).toBe('9,007,199,254,741,023');
+});
diff --git a/desktop-app/tests/coolingRefresh.test.tsx b/desktop-app/tests/coolingRefresh.test.tsx
index ea9e96038f..16fb42f655 100644
--- a/desktop-app/tests/coolingRefresh.test.tsx
+++ b/desktop-app/tests/coolingRefresh.test.tsx
@@ -4,7 +4,7 @@ import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
import type { Resource, Route } from '../src/shared/contracts';
// Cooling status is read by spawning `darkbloom fan status --json` in the
-// native backend, so it is fetched only while Cooling or This Mac's Overview is shown.
+// native backend, so it is fetched only while Home, Cooling or This Mac's Overview is shown.
let useBackend: typeof import('../src/renderer/useBackend').useBackend;
let showsCooling: typeof import('../src/renderer/useBackend').showsCooling;
let previewAPI: typeof import('../src/renderer/preview').previewAPI;
@@ -26,28 +26,29 @@ async function mount(route: Route, machine: string | null = null) {
const hook = renderHook(({ route, machine }: View) => useBackend(route, machine), {
initialProps: { route, machine },
});
- await waitFor(() => expect(read).toHaveBeenCalledWith('leaderboard'));
+ await waitFor(() => expect(read).toHaveBeenCalledWith('state'));
return { read, ...hook };
}
-it('shows cooling only on Cooling and on This Mac’s Overview', () => {
+it('shows cooling on Home, Cooling and This Mac’s Overview', () => {
+ expect(showsCooling('home')).toBe(true);
expect(showsCooling('cooling')).toBe(true);
expect(showsCooling('cooling', 'remote-studio')).toBe(true);
expect(showsCooling('machines')).toBe(true);
expect(showsCooling('machines', 'remote-studio')).toBe(false);
- for (const route of ['home', 'models', 'analysis', 'settings', 'studio'] as const)
+ for (const route of ['models', 'analysis', 'settings', 'studio'] as const)
expect(showsCooling(route)).toBe(false);
});
it('does not read cooling while another screen is shown', async () => {
- const { read, result } = await mount('home');
+ const { read, result } = await mount('models');
await act(() => result.current.refresh());
expect(reads(read, 'state')).toBeGreaterThanOrEqual(2);
expect(reads(read, 'cooling')).toBe(0);
});
it('reads cooling on entering the cooling screen and on each refresh there', async () => {
- const { read, result, rerender } = await mount('home');
+ const { read, result, rerender } = await mount('models');
rerender({ route: 'cooling', machine: null });
await waitFor(() => expect(reads(read, 'cooling')).toBe(1));
await waitFor(() => expect(result.current.cooling?.supported).toBe(true));
@@ -69,3 +70,16 @@ it('reads cooling on This Mac’s Overview but not on a remote Mac’s', async (
rerender({ route: 'machines', machine: null });
await waitFor(() => expect(reads(read, 'cooling')).toBe(3));
});
+
+it('loads rankings and releases only when their pages are opened', async () => {
+ const { read, rerender } = await mount('home');
+ expect(reads(read, 'leaderboard')).toBe(0);
+ expect(reads(read, 'release')).toBe(0);
+ expect(reads(read, 'release-history')).toBe(0);
+ rerender({ route: 'leaderboard', machine: null });
+ await waitFor(() => expect(reads(read, 'leaderboard')).toBe(1));
+ expect(reads(read, 'release')).toBe(0);
+ rerender({ route: 'updates', machine: null });
+ await waitFor(() => expect(reads(read, 'release')).toBe(1));
+ expect(reads(read, 'release-history')).toBe(1);
+});
diff --git a/desktop-app/tests/fanStatus.test.tsx b/desktop-app/tests/fanStatus.test.tsx
new file mode 100644
index 0000000000..39a31b1226
--- /dev/null
+++ b/desktop-app/tests/fanStatus.test.tsx
@@ -0,0 +1,45 @@
+// @vitest-environment jsdom
+import { afterEach, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import '@testing-library/jest-dom/vitest';
+import { FanStatus } from '../src/renderer/features/home/chip/FanStatus';
+import type { CoolingData } from '../src/shared/contracts';
+
+afterEach(cleanup);
+const status: CoolingData = {
+ supported: true,
+ enabled: false,
+ mode: 'automatic',
+ temperature: 60,
+ fans: [],
+};
+
+it('keeps enabled cooling blue at any temperature, including below its trigger', () => {
+ const open = vi.fn();
+ const { rerender } = render(
+ ,
+ );
+ const button = screen.getByRole('button', { name: /Auto fan on/ });
+ expect(button).toHaveAttribute('data-enabled', 'true');
+ expect(button.style.color).toBe('');
+ fireEvent.click(button);
+ expect(open).toHaveBeenCalledOnce();
+ rerender( );
+ expect(button).toHaveTextContent('45°C');
+ expect(button.style.color).toBe('');
+});
+
+it('progressively reddens above 60 when the fan option is off and withholds stale readings', () => {
+ const { rerender } = render( {}} />);
+ const button = screen.getByRole('button', { name: /Auto fan off/ });
+ expect(button.style.color).toBe('');
+ rerender( {}} />);
+ const warm = button.style.color;
+ expect(warm).not.toBe('');
+ rerender( {}} />);
+ expect(button.style.color).not.toBe(warm);
+ rerender( {}} />);
+ expect(button).toHaveTextContent('Fan status unavailable');
+ expect(button).not.toHaveTextContent('°C');
+ expect(button).toHaveAttribute('data-enabled', 'false');
+});
diff --git a/desktop-app/tests/fleetEarnings.test.tsx b/desktop-app/tests/fleetEarnings.test.tsx
new file mode 100644
index 0000000000..455d6675c5
--- /dev/null
+++ b/desktop-app/tests/fleetEarnings.test.tsx
@@ -0,0 +1,70 @@
+// @vitest-environment jsdom
+import { afterEach, expect, it, vi } from 'vitest';
+import { cleanup, render, screen } from '@testing-library/react';
+import '@testing-library/jest-dom/vitest';
+import { FleetEarnings } from '../src/renderer/features/home/FleetEarnings';
+import { parseInsights } from '../src/renderer/features/insights/types';
+import { previewInsights } from '../src/renderer/previewInsights';
+import { backendWith } from './onboardingFixtures';
+import { poolSnapshot } from './modelsFixtures';
+import { ModelEarningsOrder } from '../src/renderer/features/models/ModelEarnings';
+import { modelEarnings } from '../src/renderer/features/models/earnings';
+
+const mocks = vi.hoisted(() => ({ data: null as any }));
+vi.mock('../src/renderer/features/insights/useInsights', () => ({
+ useInsights: () => ({ data: mocks.data, error: null }),
+}));
+afterEach(cleanup);
+it('shows account lifetime and summed recent history without projecting a truncated week', () => {
+ mocks.data = parseInsights({
+ ...previewInsights('7d'),
+ history_complete: false,
+ lifetime: {
+ count: '1234',
+ total_micro_usd: '12345678',
+ prompt_tokens: null,
+ completion_tokens: null,
+ },
+ });
+ const backend = backendWith(poolSnapshot());
+ backend.cloud = {
+ linked: true,
+ observed_at: 1,
+ machines: [],
+ lifetime_micro_usd: '12345678',
+ week_micro_usd: '1200000',
+ earnings_complete: false,
+ earnings_since: 1791052800,
+ settled_records: '1234',
+ };
+ render( );
+ expect(screen.getByText('$12.35')).toBeVisible();
+ expect(screen.getByText('$1.20')).toBeVisible();
+ expect(screen.getByText('Recent earnings')).toBeVisible();
+ expect(screen.getByText('1,234')).toBeVisible();
+ expect(screen.queryByText('Annualized pace')).not.toBeInTheDocument();
+ expect(screen.queryByText('Past 7 days')).not.toBeInTheDocument();
+ expect(screen.getByText('Daily earnings · 7 days')).toBeVisible();
+});
+it('keeps the week and annualized pace for complete history', () => {
+ mocks.data = parseInsights(previewInsights('7d'));
+ const backend = backendWith(poolSnapshot());
+ backend.cloud = {
+ linked: true,
+ observed_at: 1,
+ machines: [],
+ lifetime_micro_usd: '12345678',
+ week_micro_usd: '7000000',
+ earnings_complete: true,
+ };
+ render( );
+ expect(screen.getByText('Past 7 days')).toBeVisible();
+ expect(screen.getByText('Annualized pace')).toBeVisible();
+ expect(screen.getByText('$365')).toBeVisible();
+});
+it('does not call a ranking from bounded history a full thirty-day ranking', () => {
+ const data = parseInsights({ ...previewInsights('30d'), history_complete: false });
+ render( );
+ expect(screen.getByText('Most earned · Recent')).toBeVisible();
+ expect(screen.queryByText('Most earned · 30d')).not.toBeInTheDocument();
+});
diff --git a/desktop-app/tests/insights.test.tsx b/desktop-app/tests/insights.test.tsx
index 9d002c6f54..fe4272469d 100644
--- a/desktop-app/tests/insights.test.tsx
+++ b/desktop-app/tests/insights.test.tsx
@@ -47,15 +47,15 @@ it('does not animate or claim stale native model counts', () => {
},
} as unknown as Snapshot;
const { rerender, container } = render( );
- expect(screen.getByText('5 running')).toBeInTheDocument();
+ expect(screen.getByText('5 processing')).toBeInTheDocument();
expect(container.querySelectorAll('[data-active="true"]')).toHaveLength(5);
fireEvent.click(screen.getByRole('button', { name: 'Pause activity animation' }));
expect(container.querySelector('[data-animate="false"]')).toBeInTheDocument();
rerender( );
- expect(screen.queryByText('5 running')).not.toBeInTheDocument();
+ expect(screen.queryByText('5 processing')).not.toBeInTheDocument();
expect(container.querySelectorAll('[data-active="true"]')).toHaveLength(0);
rerender( );
- expect(screen.queryByText('5 running')).not.toBeInTheDocument();
+ expect(screen.queryByText('5 processing')).not.toBeInTheDocument();
expect(container.querySelectorAll('[data-active="true"]')).toHaveLength(0);
rerender(
{
}}
/>,
);
- expect(screen.queryByText('5 running')).not.toBeInTheDocument();
+ expect(screen.queryByText('5 processing')).not.toBeInTheDocument();
expect(container.querySelectorAll('[data-active="true"]')).toHaveLength(0);
});
it('celebrates a new milestone once and handles exact boundaries', () => {
diff --git a/desktop-app/tests/macStats.test.tsx b/desktop-app/tests/macStats.test.tsx
new file mode 100644
index 0000000000..2d77971d99
--- /dev/null
+++ b/desktop-app/tests/macStats.test.tsx
@@ -0,0 +1,107 @@
+// @vitest-environment jsdom
+import { afterEach, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
+import '@testing-library/jest-dom/vitest';
+import { ChipReadouts } from '../src/renderer/features/home/chip/ChipReadouts';
+import { EarningsTimeline } from '../src/renderer/features/insights/EarningsTimeline';
+import { parseInsights } from '../src/renderer/features/insights/types';
+import { previewInsights } from '../src/renderer/previewInsights';
+import {
+ parseRequestHistory,
+ tokensPerSecond,
+} from '../src/renderer/features/stats/activity/requests';
+import { RequestTable } from '../src/renderer/features/stats/activity/RequestTable';
+import { recordedTraffic } from '../src/renderer/features/stats/data';
+import { tokenBars } from '../src/renderer/features/stats/tokenSeries';
+import { MacPerformance } from '../src/renderer/features/stats/Performance';
+import { backendWith } from './onboardingFixtures';
+import { poolSnapshot } from './modelsFixtures';
+
+const mocks = vi.hoisted(() => ({ history: undefined as any }));
+vi.mock('../src/renderer/features/stats/activity/useRequestHistory', () => ({
+ useRequestHistory: () => ({ history: mocks.history }),
+}));
+afterEach(cleanup);
+const history = () =>
+ parseRequestHistory({
+ observed_at: 100,
+ records: [
+ {
+ id: 'ledger-1',
+ settled_at: 99,
+ model: 'actual-model',
+ input_tokens: 12000,
+ output_tokens: 1000,
+ outcome: 'settled',
+ earnings_micro_usd: '123',
+ },
+ ],
+ });
+it('hides missing live activity while preserving measured zeroes', () => {
+ const props = { mode: 'Live from this Mac', live: true, phase: null, hardware: null };
+ const view = render(
+ ,
+ );
+ for (const label of ['tokens per second', 'In progress', 'Waiting'])
+ expect(screen.queryByText(label)).not.toBeInTheDocument();
+ view.rerender( );
+ for (const label of ['tokens per second', 'In progress', 'Waiting'])
+ expect(screen.getByText(label)).toBeVisible();
+});
+it('shows seven calendar days and identifies unavailable history without zero earnings', () => {
+ const fixture = previewInsights('7d');
+ const data = parseInsights({
+ ...fixture,
+ days: fixture.days.map((day, i) => ({ ...day, available: i >= 5, complete: i === 5 })),
+ });
+ render( );
+ const bars = within(screen.getByRole('group', { name: 'Daily earnings in UTC' })).getAllByRole(
+ 'button',
+ );
+ expect(bars).toHaveLength(7);
+ expect(bars[0]).toHaveAccessibleName(/History unavailable/);
+ fireEvent.click(bars[0]);
+ expect(screen.getByText('History unavailable')).toBeVisible();
+ expect(screen.queryByText(/inference$/)).not.toBeInTheDocument();
+});
+it('uses settlement time and omits unreported duration and speed columns', () => {
+ const data = history();
+ expect(tokensPerSecond(data.records[0])).toBeUndefined();
+ render( );
+ expect(screen.getByRole('columnheader', { name: 'Settled at' })).toBeVisible();
+ expect(screen.queryByRole('columnheader', { name: 'Duration' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('columnheader', { name: 'Tokens/s' })).not.toBeInTheDocument();
+ expect(screen.getByText('12,000')).toBeVisible();
+ expect(screen.getByText('Settled')).toBeVisible();
+});
+it('fills this Mac Stats with verified input, output, session earnings and model history', () => {
+ mocks.history = history();
+ const state = poolSnapshot();
+ state.activity = {
+ ...state.activity,
+ requests: '4',
+ processed_input_tokens: '12000',
+ processed_output_tokens: '1000',
+ processed_tokens: '13000',
+ earnings_micro_usd: '123',
+ samples: [],
+ };
+ render( );
+ expect(screen.getByText('13,000')).toBeVisible();
+ expect(screen.getByText('Input tokens')).toBeVisible();
+ expect(screen.getByText('actual-model')).toBeVisible();
+ expect(screen.queryByText('Success rate')).not.toBeInTheDocument();
+ expect(screen.queryByText('Waiting for activity')).not.toBeInTheDocument();
+ expect(
+ screen.queryByText(/Per-model traffic history is not yet available/),
+ ).not.toBeInTheDocument();
+});
+
+it('builds traffic from settlement metadata including input without inventing cached tokens', () => {
+ const records = history().records;
+ const points = recordedTraffic([...records, { ...records[0], id: 'later', settled_at: 4000 }]);
+ expect(points.map((point) => point.requests)).toEqual([1, 0, 1]);
+ expect(points.reduce((sum, point) => sum + point.input!, 0)).toBe(24000);
+ expect(tokenBars(points).reduce((sum, bar) => sum + bar.total, 0)).toBe(26000);
+ expect(points.every((point) => point.cached === undefined)).toBe(true);
+});
diff --git a/desktop-app/tests/machines.test.tsx b/desktop-app/tests/machines.test.tsx
index 374233e669..1602039843 100644
--- a/desktop-app/tests/machines.test.tsx
+++ b/desktop-app/tests/machines.test.tsx
@@ -3,6 +3,8 @@ import { useState } from 'react';
import { afterEach, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import '@testing-library/jest-dom/vitest';
+import { OperationFeed } from '../src/renderer/components/UI';
+import { AccountControl } from '../src/renderer/components/AccountControl';
import { Machines } from '../src/renderer/features/Machines';
import type { BackendState } from '../src/renderer/useBackend';
import type { Route } from '../src/shared/contracts';
@@ -55,7 +57,12 @@ it('opens This Mac by default without a fleet overview', async () => {
it('keeps a selected remote Mac view-only and refreshes its observed values', async () => {
const backend = await previewBackend();
const navigate = vi.fn();
- const { rerender } = render( );
+ const { rerender } = render(
+ <>
+
+
+ >,
+ );
fireEvent.click(screen.getByRole('button', { name: 'Select Mac Studio, View only' }));
expect(screen.getByText(/^View only\. Controls for this Mac/)).toBeVisible();
expect(screen.queryByRole('navigation', { name: 'Machine sections' })).not.toBeInTheDocument();
@@ -75,7 +82,7 @@ it('keeps a selected remote Mac view-only and refreshes its observed values', as
};
rerender( );
expect(screen.getByText('$9.00')).toBeVisible();
- expect(screen.getAllByText('offline').length).toBeGreaterThan(0);
+ expect(screen.getAllByText('Offline').length).toBeGreaterThan(0);
rerender(
{
+it('keeps pending account approval visible while browsing a remote Mac', async () => {
+ const backend = await previewBackend();
+ backend.state!.operations = [
+ {
+ id: 'login',
+ action: 'account-signin',
+ state: 'running',
+ started_at: 1,
+ message: 'Working…',
+ cancellable: true,
+ },
+ ];
+ backend.state!.link = {
+ code: 'ABCD-EFGH',
+ url: 'https://console.darkbloom.dev/link',
+ expires_at: 1_790_001_000,
+ state: 'waiting',
+ };
+ backend.state!.capabilities = ['account-signin'];
+ render(
+ <>
+
+
+ >,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Select Mac Studio, View only' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Continue sign-in' }));
+ expect(screen.getByRole('dialog', { name: 'Sign in to Darkbloom' })).toBeVisible();
+ expect(screen.getByLabelText('Connection code ABCD-EFGH')).toBeVisible();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(backend.act).toHaveBeenCalledWith({ action: 'cancel', operation: 'login' });
+});
+
+it('keeps local controls in the workspace and cancellation in the global notification', async () => {
const backend = await previewBackend();
const navigate = vi.fn();
backend.state!.operations = [
@@ -119,7 +159,12 @@ it('keeps the local machine controls and supported operation cancellation in the
cancellable: true,
},
];
- render( );
+ render(
+ <>
+
+
+ >,
+ );
expect(screen.getByRole('button', { name: 'Stop provider' })).toBeVisible();
const tabs = screen.getByRole('navigation', { name: 'Machine sections' });
expect(
diff --git a/desktop-app/tests/memoryAllocation.test.ts b/desktop-app/tests/memoryAllocation.test.ts
new file mode 100644
index 0000000000..bd5d1ead91
--- /dev/null
+++ b/desktop-app/tests/memoryAllocation.test.ts
@@ -0,0 +1,28 @@
+import { expect, it } from 'vitest';
+import { memoryMap } from '../src/renderer/features/home/chip/memoryMap';
+import { modelColor } from '../src/renderer/features/home/chip/memoryStyle';
+import { otherMemory, providerMemory } from '../src/renderer/features/home/chip/memoryUsage';
+import { hardwareTargets } from '../src/renderer/features/home/chip/hardware/targets';
+import { anatomyFromTopology } from '../src/renderer/features/home/chip/topologyAnatomy';
+import { previewHardwareSample, previewTopology } from '../src/renderer/previewHardware';
+import type { Snapshot } from '../src/shared/contracts';
+
+it('uses provider allocator memory, rather than whole-GPU memory, for other-app attribution', () => {
+ const state = { memory: { active_gb: 52, cache_gb: 1 } } as Snapshot;
+ expect(providerMemory(state)).toBe(53);
+ const sample = previewHardwareSample(16, true);
+ sample.memory.used_gb = 60;
+ sample.gpu.memory_in_use_gb = 16;
+ const anatomy = anatomyFromTopology(previewTopology, '', 0);
+ expect(hardwareTargets(sample, anatomy, 62, 53).other).toBeCloseTo(7 / 64);
+ expect(hardwareTargets(sample, anatomy, 62).other).toBeNull();
+ expect(otherMemory(60, 53)).toBe(7);
+ expect(otherMemory(60, null)).toBeNull();
+});
+it('bounds estimated model colors by measured Darkbloom allocation', () => {
+ const models = [0, 1, 2].map((i) => ({ id: String(i), name: String(i), gb: 30 }));
+ const map = memoryMap(128, models, 52);
+ const weights = map.segments.filter((s) => s.kind === 'weights');
+ expect(weights.reduce((sum, s) => sum + s.to - s.from, 0)).toBeCloseTo(52 / 128);
+ expect(new Set(models.map((_, i) => modelColor(i).join(','))).size).toBe(3);
+});
diff --git a/desktop-app/tests/modelEarnings.test.ts b/desktop-app/tests/modelEarnings.test.ts
new file mode 100644
index 0000000000..2fb8ec9525
--- /dev/null
+++ b/desktop-app/tests/modelEarnings.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+import { rankModels, modelEarnings } from '../src/renderer/features/models/earnings';
+import { parseInsights } from '../src/renderer/features/insights/types';
+import { previewInsights } from '../src/renderer/previewInsights';
+import { poolModels } from './modelsFixtures';
+
+describe('models ranked by settled earnings', () => {
+ it('sorts descending with exact counters and preserves ties without mutating selection order', () => {
+ const earnings = new Map([
+ ['gpt-oss-20b', 9007199254740992n],
+ ['gemma-4-26b', 9007199254740993n],
+ ['qwen-3.5-9b', 0n],
+ ]);
+ expect(rankModels(poolModels, earnings).map((model) => model.id)).toEqual([
+ 'gemma-4-26b',
+ 'gpt-oss-20b',
+ 'qwen-3.5-9b',
+ 'qwen-3.6-35b',
+ 'kimi-k2.6',
+ ]);
+ expect(poolModels[0].id).toBe('gpt-oss-20b');
+ });
+ it('keeps catalog order when earnings have never been supplied', () => {
+ expect(modelEarnings(null)).toBeNull();
+ expect(rankModels(poolModels, null)).toBe(poolModels);
+ });
+ it('uses only model-attributed settled earnings', () => {
+ const insights = parseInsights(previewInsights('30d'));
+ const row = insights.models[0];
+ insights.models.push({ ...row, id: '', work_micro_usd: 999999999n });
+ const earnings = modelEarnings(insights)!;
+ expect(earnings.get(row.id)).toBe(row.work_micro_usd + row.base_reward_micro_usd);
+ expect(earnings.has('')).toBe(false);
+ });
+});
diff --git a/desktop-app/tests/modelsAutopilot.test.tsx b/desktop-app/tests/modelsAutopilot.test.tsx
index 3ec0d0eda8..0fa343e79d 100644
--- a/desktop-app/tests/modelsAutopilot.test.tsx
+++ b/desktop-app/tests/modelsAutopilot.test.tsx
@@ -24,6 +24,8 @@ function renderModels(state = poolSnapshot()) {
current = state;
const backend = backendWith(state);
render( );
+ fireEvent.click(screen.getByRole('button', { name: 'Browse models' }));
+ fireEvent.click(screen.getByRole('button', { name: /Show \d+ more models/ }));
return backend;
}
const row = (name: string) => screen.getByRole('heading', { name }).closest('article')!;
@@ -31,26 +33,21 @@ const card = () => screen.getByRole('region', { name: 'Autopilot' });
const sent = () => api.act.mock.calls.map(([action]) => action);
describe('Autopilot on', () => {
- it('explains Autopilot and shows what is loaded, pinned and free to load', () => {
+ it('shows a compact live status and direct controls without serving selection', () => {
renderModels();
expect(within(card()).getByText('On')).toBeVisible();
- expect(card()).toHaveTextContent(
- 'You choose which models live on this Mac. Autopilot decides which ones to load into memory as demand changes.',
- );
- expect(card()).toHaveTextContent('Loaded nowGPT-OSS 20B, Gemma 4 26B');
- expect(card()).toHaveTextContent('Pinned · always onGemma 4 26B');
- expect(card()).toHaveTextContent('Free to load20.0 GB of 64.0 GB');
- expect(card()).toHaveTextContent('1 pinned · 21.4 GB of 64 GB memory');
+ expect(card()).toHaveTextContent('3 available · 2 in memory');
+ expect(screen.getByRole('button', { name: 'Keep GPT-OSS 20B in memory' })).toBeVisible();
expect(screen.queryByRole('button', { name: /Apply selection/ })).not.toBeInTheDocument();
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
});
it('lists the catalog as the pool, with each model’s state and facts', () => {
renderModels();
- expect(row('GPT-OSS 20B')).toHaveTextContent('Loaded now · Autopilot');
+ expect(row('GPT-OSS 20B')).toHaveTextContent('In memory');
expect(row('GPT-OSS 20B')).toHaveTextContent('12.1 GB on disk · needs 16.4 GB memory');
- expect(row('Gemma 4 26B')).toHaveTextContent('Pinned · always on');
- expect(row('Qwen 3.5 9B')).toHaveTextContent('In pool');
+ expect(row('Gemma 4 26B')).toHaveTextContent('In memory · kept');
+ expect(row('Qwen 3.5 9B')).toHaveTextContent('Available to Autopilot');
expect(row('Qwen 3.6 35B A3B')).toHaveTextContent('Not downloaded');
expect(row('Qwen 3.6 35B A3B')).toHaveTextContent('21.3 GB download');
expect(row('Kimi K2.6')).toHaveTextContent('Not available');
@@ -61,13 +58,13 @@ describe('Autopilot on', () => {
it('filters by pool state and searches', () => {
renderModels();
const headings = () => screen.getAllByRole('heading', { level: 3 }).map((h) => h.textContent);
- fireEvent.click(screen.getByRole('button', { name: 'Pinned' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Kept in memory' }));
expect(headings()).toEqual(['Autopilot', 'Gemma 4 26B']);
- fireEvent.click(screen.getByRole('button', { name: 'In pool' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Your models' }));
expect(headings()).toEqual(['Autopilot', 'GPT-OSS 20B', 'Gemma 4 26B', 'Qwen 3.5 9B']);
fireEvent.click(screen.getByRole('button', { name: 'Not downloaded' }));
expect(headings()).toEqual(['Autopilot', 'Qwen 3.6 35B A3B']);
- fireEvent.click(screen.getByRole('button', { name: 'All' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Browse models' }));
fireEvent.change(screen.getByRole('textbox', { name: 'Search models' }), {
target: { value: 'qwen' },
});
@@ -77,7 +74,7 @@ describe('Autopilot on', () => {
it('downloads a model, then adds it to the pool', async () => {
renderModels();
await act(async () =>
- fireEvent.click(within(row('Qwen 3.6 35B A3B')).getByRole('button', { name: /Download/ })),
+ fireEvent.click(within(row('Qwen 3.6 35B A3B')).getByRole('button', { name: 'Download' })),
);
expect(sent()).toEqual([
{ action: 'download', model: 'qwen-3.6-35b' },
@@ -88,7 +85,9 @@ describe('Autopilot on', () => {
it('pins a model that isn’t downloaded by downloading it into the pool first', async () => {
renderModels();
await act(async () =>
- fireEvent.click(screen.getByRole('button', { name: 'Pin Qwen 3.6 35B A3B' })),
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Download & keep Qwen 3.6 35B A3B in memory' }),
+ ),
);
expect(sent()).toEqual([
{ action: 'download', model: 'qwen-3.6-35b' },
@@ -99,8 +98,10 @@ describe('Autopilot on', () => {
it('pins a pool model directly and unpins a pinned one', async () => {
renderModels();
- await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Pin Qwen 3.5 9B' })));
- const unpin = screen.getByRole('button', { name: 'Unpin Gemma 4 26B' });
+ await act(async () =>
+ fireEvent.click(screen.getByRole('button', { name: 'Keep Qwen 3.5 9B in memory' })),
+ );
+ const unpin = screen.getByRole('button', { name: 'Stop keeping Gemma 4 26B in memory' });
expect(unpin).toHaveAttribute('aria-pressed', 'true');
await act(async () => fireEvent.click(unpin));
expect(sent()).toEqual([
@@ -111,31 +112,27 @@ describe('Autopilot on', () => {
it('adds a downloaded model outside the pool', async () => {
renderModels(poolSnapshot({ selected: ['gpt-oss-20b', 'gemma-4-26b'] }));
- expect(row('Qwen 3.5 9B')).toHaveTextContent('On this Mac · not in pool');
+ expect(row('Qwen 3.5 9B')).toHaveTextContent('Downloaded · not in Autopilot');
await act(async () =>
fireEvent.click(within(row('Qwen 3.5 9B')).getByRole('button', { name: /Add to pool/ })),
);
expect(sent()).toEqual([{ action: 'autopilot_models' }]);
});
- it('blocks removing a pinned model, and explains that a loaded model is unloaded first', async () => {
+ it('protects resident and pinned models from removal', () => {
renderModels();
expect(screen.getByRole('button', { name: 'Remove Gemma 4 26B' })).toBeDisabled();
- expect(row('Gemma 4 26B')).toHaveTextContent('Unpin it to remove it from this Mac.');
- fireEvent.click(screen.getByRole('button', { name: 'Remove GPT-OSS 20B' }));
- expect(screen.getByRole('dialog')).toHaveTextContent(
- 'This deletes GPT-OSS 20B from this Mac and takes it out of the Autopilot pool. Autopilot unloads it first.',
- );
- await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Remove model' })));
- expect(sent()).toEqual([{ action: 'remove', model: 'gpt-oss-20b' }]);
+ expect(screen.getByRole('button', { name: 'Remove GPT-OSS 20B' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Remove Qwen 3.5 9B' })).toBeEnabled();
+ expect(sent()).toEqual([]);
});
it('refuses a pin that would need more memory than this Mac has', () => {
renderModels(poolSnapshot({}, { memory: { total_gb: 32, free_for_load_gb: 4 } }));
- const pin = screen.getByRole('button', { name: 'Pin GPT-OSS 20B' });
+ const pin = screen.getByRole('button', { name: 'Keep GPT-OSS 20B in memory' });
expect(pin).toBeDisabled();
expect(pin).toHaveAttribute('title', 'Pinning this needs more memory than this Mac has.');
- expect(screen.getByRole('button', { name: 'Pin Qwen 3.5 9B' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Keep Qwen 3.5 9B in memory' })).toBeEnabled();
});
it('shows download progress reported by the runtime', () => {
@@ -162,13 +159,15 @@ describe('Autopilot on', () => {
expect(row('Qwen 3.6 35B A3B')).toHaveTextContent('40%');
});
- it('starts serving the pool when this Mac is stopped', () => {
- const backend = renderModels(poolSnapshot({ phase: undefined }, { state: 'stopped' }));
+ it('starts with the saved startup models instead of loading the whole pool', async () => {
+ renderModels(poolSnapshot({ phase: undefined }, { state: 'stopped' }));
expect(within(card()).getByText('Ready')).toBeVisible();
- fireEvent.click(screen.getByRole('button', { name: /Start serving/ }));
- expect(backend.act).toHaveBeenCalledWith({
- action: 'start',
- models: ['gpt-oss-20b', 'gemma-4-26b', 'qwen-3.5-9b'],
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: /Start serving/ })));
+ expect(api.act).toHaveBeenCalledWith({
+ action: 'autopilot',
+ models: ['gpt-oss-20b', 'gemma-4-26b'],
+ pinned: [],
+ endpoint: false,
});
});
@@ -177,24 +176,62 @@ describe('Autopilot on', () => {
new Error("Error invoking remote method 'darkbloom:act': Error: Unknown action"),
);
renderModels();
- await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Pin Qwen 3.5 9B' })));
+ await act(async () =>
+ fireEvent.click(screen.getByRole('button', { name: 'Keep Qwen 3.5 9B in memory' })),
+ );
expect(screen.getByRole('alert')).toHaveTextContent(
'This version of Darkbloom doesn’t support that Autopilot change.',
);
- expect(screen.getByRole('button', { name: 'Pin Qwen 3.5 9B' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Keep Qwen 3.5 9B in memory' })).toBeEnabled();
+ });
+
+ it('links first when a new user enables Autopilot from Models', async () => {
+ renderModels(
+ poolSnapshot(
+ { enabled: false, configured: false, selected: [], pinned: [], phase: undefined },
+ { linked: false },
+ ),
+ );
+ await act(async () =>
+ fireEvent.click(screen.getByRole('button', { name: 'Turn on Autopilot' })),
+ );
+ expect(sent().map((action) => action.action)).toEqual(['link', 'autopilot']);
+ });
+
+ it('never starts serving after account linking fails', async () => {
+ api.act.mockResolvedValueOnce({
+ ...succeeded('link'),
+ state: 'failed',
+ message: 'Link expired',
+ });
+ renderModels(
+ poolSnapshot(
+ { enabled: false, configured: false, selected: [], pinned: [], phase: undefined },
+ { linked: false },
+ ),
+ );
+ await act(async () =>
+ fireEvent.click(screen.getByRole('button', { name: 'Turn on Autopilot' })),
+ );
+ expect(sent().map((action) => action.action)).toEqual(['link']);
+ expect(screen.getByRole('alert')).toHaveTextContent('Link expired');
});
});
describe('Autopilot phases', () => {
it('says plainly that shadow mode leaves models as they are', () => {
renderModels(poolSnapshot({ phase: 'shadow' }));
- expect(within(card()).getByText('Learning')).toBeVisible();
- expect(card()).toHaveTextContent('Autopilot is learning; models stay as they are for now.');
+ expect(within(card()).getByText('Observing demand')).toBeVisible();
+ expect(card()).toHaveTextContent(
+ 'Autopilot is observing demand; models stay as they are for now.',
+ );
});
it('offers to refresh the pool when the runtime is waiting for it', async () => {
renderModels(poolSnapshot({ phase: 'waiting_inventory' }));
- await act(async () => fireEvent.click(screen.getByRole('button', { name: /Refresh pool/ })));
+ await act(async () =>
+ fireEvent.click(screen.getByRole('button', { name: /Update available models/ })),
+ );
expect(sent()).toEqual([{ action: 'autopilot_models' }]);
});
@@ -213,13 +250,13 @@ describe('Autopilot phases', () => {
it('turns off after confirming that manual selection takes over', async () => {
renderModels();
- fireEvent.click(screen.getByRole('button', { name: /Turn off/ }));
+ fireEvent.click(screen.getByRole('button', { name: /Switch to manual/ }));
expect(screen.getByRole('dialog')).toHaveTextContent(
'Models stay loaded as they are and manual selection takes over',
);
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(api.act).not.toHaveBeenCalled();
- fireEvent.click(screen.getByRole('button', { name: /Turn off/ }));
+ fireEvent.click(screen.getByRole('button', { name: /Switch to manual/ }));
await act(async () =>
fireEvent.click(screen.getByRole('button', { name: 'Turn off Autopilot' })),
);
diff --git a/desktop-app/tests/modelsManual.test.tsx b/desktop-app/tests/modelsManual.test.tsx
index 5be6f5bf71..4120999c96 100644
--- a/desktop-app/tests/modelsManual.test.tsx
+++ b/desktop-app/tests/modelsManual.test.tsx
@@ -23,6 +23,7 @@ function renderModels(state = poolSnapshot({ enabled: false, phase: 'off' })) {
it('keeps the manual workflow while Autopilot is off', () => {
const backend = renderModels();
expect(screen.getByText('Native load allowance')).toBeVisible();
+ fireEvent.click(screen.getByRole('button', { name: /Show \d+ more models/ }));
expect(screen.getByRole('checkbox', { name: 'Select Qwen 3.6 35B A3B' })).toBeDisabled();
fireEvent.click(screen.getByRole('checkbox', { name: 'Select Qwen 3.5 9B' }));
fireEvent.click(screen.getByRole('button', { name: /Apply selection/ }));
@@ -36,8 +37,7 @@ it('offers to turn Autopilot on with the models serving now', async () => {
api.act.mockImplementation(async (action: Action) => succeeded(action.action));
renderModels();
const offer = screen.getByRole('region', { name: 'Autopilot' });
- expect(offer).toHaveTextContent('downloaded models form Autopilot’s pool');
- expect(offer).toHaveTextContent('pin the ones that must always stay loaded');
+ expect(offer).toHaveTextContent('Choose downloads. Autopilot manages what’s loaded.');
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Turn on Autopilot' })));
expect(api.act).toHaveBeenCalledExactlyOnceWith({
action: 'autopilot',
diff --git a/desktop-app/tests/modelsPool.test.ts b/desktop-app/tests/modelsPool.test.ts
index 94f1b2c736..1349b5b2b8 100644
--- a/desktop-app/tests/modelsPool.test.ts
+++ b/desktop-app/tests/modelsPool.test.ts
@@ -46,7 +46,7 @@ describe('pool state', () => {
it('groups states into filters', () => {
expect(inFilter('outside', 'all')).toBe(true);
expect(inFilter('loaded', 'pool')).toBe(true);
- expect(inFilter('outside', 'pool')).toBe(false);
+ expect(inFilter('outside', 'pool')).toBe(true);
expect(inFilter('pinned', 'pinned')).toBe(true);
expect(inFilter('loaded', 'pinned')).toBe(false);
expect(inFilter('downloading', 'available')).toBe(true);
@@ -74,7 +74,7 @@ describe('phase copy', () => {
/stay as they are|reconciling/,
);
expect(phaseCopy({ ...activeAutopilot, phase: 'shadow' }, true).detail).toMatch(
- /^Autopilot is learning; models stay as they are for now\./,
+ /^Autopilot is observing demand; models stay as they are for now\./,
);
});
@@ -89,7 +89,7 @@ describe('phase copy', () => {
it('distinguishes a runtime that hasn’t reported yet from a stopped Mac', () => {
const unreported = { ...activeAutopilot, phase: undefined };
- expect(phaseCopy(unreported, true).label).toBe('Starting');
+ expect(phaseCopy(unreported, true).label).toBe('Checking status');
expect(phaseCopy(unreported, false).label).toBe('Ready');
});
});
diff --git a/desktop-app/tests/modelsRanking.test.tsx b/desktop-app/tests/modelsRanking.test.tsx
new file mode 100644
index 0000000000..6a8a5b61e4
--- /dev/null
+++ b/desktop-app/tests/modelsRanking.test.tsx
@@ -0,0 +1,49 @@
+// @vitest-environment jsdom
+import { afterEach, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import '@testing-library/jest-dom/vitest';
+import { Models } from '../src/renderer/features/models/Models';
+import { parseInsights } from '../src/renderer/features/insights/types';
+import { previewInsights } from '../src/renderer/previewInsights';
+import { backendWith } from './onboardingFixtures';
+import { poolSnapshot } from './modelsFixtures';
+
+const mocks = vi.hoisted(() => ({ data: null as any }));
+vi.mock('../src/renderer/features/insights/useInsights', () => ({
+ useInsights: () => ({ data: mocks.data, error: null }),
+}));
+vi.mock('../src/renderer/useBackend', () => ({ isPreview: false, api: undefined }));
+afterEach(cleanup);
+
+for (const enabled of [false, true]) {
+ it(`orders ${enabled ? 'Autopilot' : 'manual'} rows by earnings while preserving filters and selections`, () => {
+ const state = poolSnapshot({ enabled });
+ const insights = parseInsights(previewInsights('30d'));
+ const template = insights.models[0];
+ insights.models = [
+ { ...template, id: 'gpt-oss-20b', work_micro_usd: 1_000_000n, base_reward_micro_usd: 0n },
+ { ...template, id: 'gemma-4-26b', work_micro_usd: 4_000_000n, base_reward_micro_usd: 0n },
+ { ...template, id: 'qwen-3.5-9b', work_micro_usd: 2_000_000n, base_reward_micro_usd: 0n },
+ ];
+ mocks.data = insights;
+ const backend = backendWith(state);
+ render( );
+ expect(
+ screen
+ .getAllByRole('heading', { level: 3 })
+ .filter((heading) => heading.closest('.model-row'))
+ .map((heading) => heading.textContent),
+ ).toEqual(['Gemma 4 26B', 'Qwen 3.5 9B', 'GPT-OSS 20B']);
+ expect(screen.getByText('Most earned · 30d')).toBeVisible();
+ fireEvent.click(screen.getByRole('button', { name: enabled ? 'Your models' : 'Serving' }));
+ expect(screen.queryByRole('heading', { name: 'Qwen 3.6 35B A3B' })).not.toBeInTheDocument();
+ if (!enabled) {
+ expect(screen.getByRole('checkbox', { name: 'Select Gemma 4 26B' })).toBeChecked();
+ fireEvent.click(screen.getByRole('button', { name: /Apply selection/ }));
+ expect(backend.act).toHaveBeenCalledWith({
+ action: 'switch',
+ models: ['gpt-oss-20b', 'gemma-4-26b'],
+ });
+ }
+ });
+}
diff --git a/desktop-app/tests/modelsRecommendations.test.tsx b/desktop-app/tests/modelsRecommendations.test.tsx
new file mode 100644
index 0000000000..ae085781a5
--- /dev/null
+++ b/desktop-app/tests/modelsRecommendations.test.tsx
@@ -0,0 +1,188 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
+import '@testing-library/jest-dom/vitest';
+import type { NetworkData } from '../src/shared/contracts';
+import {
+ networkEarnings,
+ recommendedModels,
+ recommendedStart,
+} from '../src/renderer/features/models/recommendations';
+import { RecommendedModels } from '../src/renderer/features/models/RecommendedModels';
+import { Models } from '../src/renderer/features/models/Models';
+import { backendWith } from './onboardingFixtures';
+import { poolModels, poolSnapshot } from './modelsFixtures';
+import { pinnedMemory } from '../src/renderer/models/selection';
+
+vi.mock('../src/renderer/useBackend', () => ({ isPreview: false, api: undefined }));
+afterEach(cleanup);
+const network: NetworkData = {
+ model_earnings: {
+ window: '7d',
+ as_of: new Date().toISOString(),
+ models: [
+ { id: 'kimi-k2.6', earnings_micro_usd: '9007199254740999' },
+ { id: 'qwen-3.6-35b', earnings_micro_usd: '4000000' },
+ { id: 'qwen-3.5-9b', earnings_micro_usd: '3000000' },
+ { id: 'gpt-oss-20b', earnings_micro_usd: '2000000' },
+ { id: 'gemma-4-26b', earnings_micro_usd: '1000000' },
+ ],
+ },
+};
+
+describe('network recommendations', () => {
+ it('browses native catalog models whose memory has not been measured yet', () => {
+ // Swift serializes absent measurements as JSON null, including undownloaded models.
+ const models = poolModels.map((model) =>
+ model.downloaded ? model : { ...model, memory_gb: null },
+ );
+ const snapshot = poolSnapshot({}, { models });
+ render( );
+ fireEvent.click(screen.getByRole('button', { name: 'Browse models' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Show 2 more models' }));
+ const row = screen.getByRole('heading', { name: 'Qwen 3.6 35B A3B' }).closest('article')!;
+ expect(row).toHaveTextContent('21.3 GB download');
+ expect(row).not.toHaveTextContent('needs');
+ expect(within(row).getByRole('button', { name: 'Download' })).toBeEnabled();
+ expect(pinnedMemory(snapshot, ['qwen-3.6-35b'])).toMatchObject({
+ needed: 21.3,
+ measured: false,
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Not downloaded' }));
+ expect(screen.getByRole('heading', { name: 'Qwen 3.6 35B A3B' })).toBeVisible();
+ });
+ it('chooses three compatible models using network earnings independently of downloads', () => {
+ const selected = recommendedModels(poolModels, networkEarnings(network));
+ expect(selected.map((m) => m.id)).toEqual(['qwen-3.6-35b', 'qwen-3.5-9b', 'gpt-oss-20b']);
+ expect(recommendedStart(poolSnapshot(), selected)).toEqual({
+ action: 'autopilot',
+ models: ['qwen-3.6-35b'],
+ pinned: [],
+ downloads: ['qwen-3.6-35b'],
+ endpoint: false,
+ });
+ });
+ it('preserves integer precision and rejects missing or invalid ranking data', () => {
+ expect(networkEarnings(network)?.get('kimi-k2.6')).toBe(9007199254740999n);
+ expect(recommendedModels(poolModels, networkEarnings(undefined))).toEqual([]);
+ expect(networkEarnings({ ...network, error: 'Unavailable' })).toBeNull();
+ expect(
+ networkEarnings({
+ ...network,
+ model_earnings: {
+ ...network.model_earnings!,
+ as_of: new Date(Date.now() - 6 * 60_000).toISOString(),
+ },
+ }),
+ ).toBeNull();
+ expect(
+ networkEarnings({
+ ...network,
+ model_earnings: {
+ ...network.model_earnings!,
+ models: [{ id: 'a', earnings_micro_usd: '-1' }],
+ },
+ }),
+ ).toBeNull();
+ expect(
+ networkEarnings({
+ ...network,
+ model_earnings: {
+ ...network.model_earnings!,
+ models: [
+ { id: 'a', earnings_micro_usd: '1' },
+ { id: 'a', earnings_micro_usd: '2' },
+ ],
+ },
+ }),
+ ).toBeNull();
+ });
+ it('preselects all three downloads and lets people remove one before starting', () => {
+ const selected = recommendedModels(poolModels, networkEarnings(network));
+ const onStart = vi.fn();
+ render(
+ ,
+ );
+ expect(screen.getAllByRole('checkbox')).toHaveLength(3);
+ for (const checkbox of screen.getAllByRole('checkbox')) expect(checkbox).toBeChecked();
+ fireEvent.click(screen.getByRole('checkbox', { name: 'Choose Qwen 3.6 35B A3B' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Start Autopilot' }));
+ expect(onStart).toHaveBeenCalledWith({
+ action: 'autopilot',
+ models: ['qwen-3.5-9b'],
+ pinned: [],
+ downloads: [],
+ endpoint: false,
+ });
+ });
+ it('opens Your models by default and sorts Browse using network earnings', () => {
+ render( );
+ expect(screen.getByRole('button', { name: 'Your models' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ const rows = () =>
+ screen
+ .getAllByRole('heading', { level: 3 })
+ .filter((h) => h.closest('article'))
+ .map((h) => h.textContent);
+ expect(rows()).toEqual(['GPT-OSS 20B', 'Gemma 4 26B', 'Qwen 3.5 9B']);
+ fireEvent.click(screen.getByRole('button', { name: 'Browse models' }));
+ expect(rows()).toEqual(['Kimi K2.6', 'Qwen 3.6 35B A3B', 'Qwen 3.5 9B']);
+ const expand = screen.getByRole('button', { name: 'Show 2 more models' });
+ expect(expand).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.click(expand);
+ expect(rows()).toEqual([
+ 'Kimi K2.6',
+ 'Qwen 3.6 35B A3B',
+ 'Qwen 3.5 9B',
+ 'GPT-OSS 20B',
+ 'Gemma 4 26B',
+ ]);
+ fireEvent.click(screen.getByRole('button', { name: 'Show fewer models' }));
+ expect(rows()).toHaveLength(3);
+ fireEvent.click(screen.getByRole('button', { name: 'Show 2 more models' }));
+ fireEvent.change(screen.getByRole('textbox', { name: 'Search models' }), {
+ target: { value: 'gpt' },
+ });
+ expect(rows()).toEqual(['GPT-OSS 20B']);
+ expect(screen.queryByRole('button', { name: /Show .* models/ })).not.toBeInTheDocument();
+ fireEvent.change(screen.getByRole('textbox', { name: 'Search models' }), {
+ target: { value: '' },
+ });
+ expect(rows()).toHaveLength(3);
+ expect(screen.getByText('Network earnings · 7 days')).toBeVisible();
+ });
+ it('shows a cold pin as waiting instead of claiming it is resident', () => {
+ render( );
+ const row = screen.getByRole('heading', { name: 'Qwen 3.5 9B' }).closest('article')!;
+ expect(row).toHaveTextContent('Kept · waiting to load');
+ expect(
+ within(row).getByRole('button', { name: 'Stop keeping Qwen 3.5 9B in memory' }),
+ ).toHaveAttribute('aria-pressed', 'true');
+ });
+ it('first use shows Autopilot setup and does not silently invent missing recommendations', () => {
+ render(
+ ,
+ );
+ expect(screen.getByText(/Network recommendations are unavailable/)).toBeVisible();
+ expect(screen.queryByRole('button', { name: 'Apply selection' })).not.toBeInTheDocument();
+ });
+});
diff --git a/desktop-app/tests/networkMilestone.test.tsx b/desktop-app/tests/networkMilestone.test.tsx
index 0cb0ec0a43..2d172d9e56 100644
--- a/desktop-app/tests/networkMilestone.test.tsx
+++ b/desktop-app/tests/networkMilestone.test.tsx
@@ -50,11 +50,11 @@ it('shows live production totals, the day’s tokens and the next proposed miles
render( );
const region = strip();
expect(within(region).getByText('659.1B')).toBeVisible();
- expect(within(region).getByText('tokens processed by the network')).toBeVisible();
+ expect(within(region).getByText('Network tokens')).toBeVisible();
expect(within(region).getByText('+14.6B')).toBeVisible();
expect(within(region).getByText('1,137')).toBeVisible();
expect(within(region).getByText('Next milestone 1T')).toBeVisible();
- expect(within(region).getByText('Proposed')).toBeVisible();
+ expect(within(region).getByTitle('Proposed network milestone')).toBeVisible();
expect(within(region).getByText('Live')).toBeVisible();
expect(within(region).getByRole('progressbar')).toHaveAttribute('aria-valuenow', '66');
expect(within(region).getByRole('progressbar')).toHaveAttribute(
@@ -77,7 +77,7 @@ it('keeps the last known totals while reconnecting', () => {
error: 'Network statistics are unavailable.',
};
render( );
- expect(within(strip()).getByText('Last known, reconnecting')).toBeVisible();
+ expect(within(strip()).getByText('Reconnecting')).toBeVisible();
expect(within(strip()).getByText('659.1B')).toBeVisible();
expect(cellsOn()).toBe(16);
});
@@ -85,12 +85,10 @@ it('keeps the last known totals while reconnecting', () => {
it('says when statistics are unavailable or still connecting, without inventing numbers', () => {
const { rerender } = render( );
expect(within(strip()).getByText('Connecting')).toBeVisible();
- expect(within(strip()).getByText('Connecting to public network statistics')).toBeVisible();
+ expect(within(strip()).getByText('Network tokens')).toBeVisible();
rerender( );
expect(within(strip()).getByText('Unavailable')).toBeVisible();
- expect(
- within(strip()).getByText('Statistics unavailable. Retrying automatically.'),
- ).toBeVisible();
+ expect(within(strip()).getByText('Network tokens')).toBeVisible();
expect(screen.queryByText('Macs connected')).not.toBeInTheDocument();
expect(within(strip()).getByText('Next milestone')).toBeVisible();
expect(within(strip()).getByRole('progressbar')).not.toHaveAttribute('aria-valuenow');
@@ -105,7 +103,7 @@ it('leads Home with the network milestone and drops the duplicated collective bl
openMachine={vi.fn()}
/>,
);
- const session = screen.getByText('Tokens shared this session');
+ const session = screen.getByText('Tokens processed this session');
expect(strip().compareDocumentPosition(session) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(screen.getByRole('heading', { name: 'Your contribution' })).toBeVisible();
expect(screen.queryByText('Macs powering the network')).not.toBeInTheDocument();
diff --git a/desktop-app/tests/onboarding.test.tsx b/desktop-app/tests/onboarding.test.tsx
index e40090414a..841ef7c95c 100644
--- a/desktop-app/tests/onboarding.test.tsx
+++ b/desktop-app/tests/onboarding.test.tsx
@@ -62,7 +62,7 @@ it('states what Autopilot will do from reported facts, with the terms beside the
expect(summary).toHaveTextContent('MacBook Pro');
expect(summary).toHaveTextContent('Apple M4 Max · 64 GB');
expect(summary).toHaveTextContent('Starts with GPT-OSS 20B, already on this Mac.');
- expect(summary).toHaveTextContent('Updates on · managed by the native runtime.');
+ expect(summary).toHaveTextContent('Automatic updates on.');
expect(summary).toHaveTextContent('Stop any time from the app or the menu bar.');
expect(screen.getByText('Your Darkbloom account is linked.')).toBeVisible();
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
diff --git a/desktop-app/tests/onboardingAdvanced.test.tsx b/desktop-app/tests/onboardingAdvanced.test.tsx
index 300a403bd6..a596bed134 100644
--- a/desktop-app/tests/onboardingAdvanced.test.tsx
+++ b/desktop-app/tests/onboardingAdvanced.test.tsx
@@ -55,7 +55,7 @@ it('pins models to keep them always on and sends the pins with Autopilot', async
expect(pin(/Kimi K3/).closest('label')).toHaveTextContent('Needs 512 GB of unified memory.');
fireEvent.click(pin(/Qwen 3.5 9B/));
fireEvent.click(pin(/GPT-OSS 20B/));
- expect(within(panel).getByText('2 pinned · at least 16.4 GB of 64 GB memory')).toBeVisible();
+ expect(within(panel).getByText('2 pinned · at least 22.5 GB of 64 GB memory')).toBeVisible();
expect(screen.getByRole('region', { name: 'What happens next' })).toHaveTextContent(
'Keeps pinned models loaded and manages the rest as demand changes.',
);
@@ -65,6 +65,7 @@ it('pins models to keep them always on and sends the pins with Autopilot', async
action: 'autopilot',
models: ['qwen-3.5-9b', 'gpt-oss-20b'],
pinned: ['gpt-oss-20b', 'qwen-3.5-9b'],
+ downloads: ['qwen-3.5-9b'],
endpoint: true,
});
});
diff --git a/desktop-app/tests/onboardingStartPlan.test.ts b/desktop-app/tests/onboardingStartPlan.test.ts
index 2768393a3c..906e8ab0ec 100644
--- a/desktop-app/tests/onboardingStartPlan.test.ts
+++ b/desktop-app/tests/onboardingStartPlan.test.ts
@@ -39,6 +39,7 @@ describe('start action', () => {
action: 'autopilot',
models: ['qwen-3.5-9b', 'gpt-oss-20b'],
pinned: ['gpt-oss-20b', 'qwen-3.5-9b'],
+ downloads: ['qwen-3.5-9b'],
endpoint: true,
});
});
diff --git a/desktop-app/tests/onboardingWaitlist.test.tsx b/desktop-app/tests/onboardingWaitlist.test.tsx
index 9fa8bb9154..524b34f61f 100644
--- a/desktop-app/tests/onboardingWaitlist.test.tsx
+++ b/desktop-app/tests/onboardingWaitlist.test.tsx
@@ -123,7 +123,7 @@ describe('waitlist contract', () => {
'ada@example.com',
['memory'],
);
- await vi.advanceTimersByTimeAsync(1500);
+ await vi.advanceTimersByTimeAsync(10_000);
await expect(signup).resolves.toBeUndefined();
expect(read).toHaveBeenCalledTimes(2);
});
diff --git a/desktop-app/tests/operationNotifications.test.tsx b/desktop-app/tests/operationNotifications.test.tsx
new file mode 100644
index 0000000000..2ab863f25e
--- /dev/null
+++ b/desktop-app/tests/operationNotifications.test.tsx
@@ -0,0 +1,124 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import '@testing-library/jest-dom/vitest';
+import { afterEach, expect, it, vi } from 'vitest';
+import { OperationFeed } from '../src/renderer/components/operations/OperationFeed';
+import App from '../src/renderer/App';
+import { backendWith, operation, snapshot } from './onboardingFixtures';
+
+const runtime = vi.hoisted(() => ({ backend: undefined as unknown }));
+vi.mock('../src/renderer/useBackend', () => ({
+ api: undefined,
+ isPreview: true,
+ useBackend: () => runtime.backend,
+}));
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ localStorage.clear();
+});
+const backend = (state: Parameters[0] = 'succeeded', message = 'Saved.') =>
+ backendWith(snapshot({ operations: [operation(state, message, 'settings')] }));
+
+it('expires a success after ten seconds without restarting on repeated snapshots', () => {
+ vi.useFakeTimers();
+ const { rerender } = render( );
+ expect(screen.getByRole('status')).toHaveTextContent('Settings · Complete');
+ act(() => {
+ vi.advanceTimersByTime(6000);
+ });
+ rerender( );
+ act(() => {
+ vi.advanceTimersByTime(3999);
+ });
+ expect(screen.getByRole('status')).toBeVisible();
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(screen.queryByRole('status')).not.toBeInTheDocument();
+});
+
+it('starts the countdown on completion, and cancels it when a new operation replaces it', () => {
+ vi.useFakeTimers();
+ const running = backend('running');
+ const { rerender } = render( );
+ act(() => {
+ vi.advanceTimersByTime(60_000);
+ });
+ expect(screen.getByRole('status')).toBeVisible();
+ rerender( );
+ act(() => {
+ vi.advanceTimersByTime(9000);
+ });
+ const next = backend();
+ next.state!.operations[0].id = 'second-operation';
+ rerender( );
+ act(() => {
+ vi.advanceTimersByTime(9999);
+ });
+ expect(screen.getByRole('status')).toBeVisible();
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(screen.queryByRole('status')).not.toBeInTheDocument();
+});
+
+it('keeps a failure until Close and remembers dismissal across remounts', () => {
+ vi.useFakeTimers();
+ const failure = backend('failed', 'Permission denied');
+ const { unmount } = render( );
+ act(() => {
+ vi.advanceTimersByTime(120_000);
+ });
+ expect(screen.getByRole('alert')).toHaveTextContent('Settings · Failed');
+ fireEvent.click(screen.getByRole('button', { name: 'Close notification' }));
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ unmount();
+ render( );
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+});
+
+it('does not revive an old completed operation when the app reopens', () => {
+ vi.useFakeTimers();
+ const previous = backend();
+ previous.state!.operations[0].finished_at = (Date.now() - 11_000) / 1000;
+ render( );
+ expect(screen.queryByRole('status')).not.toBeInTheDocument();
+});
+
+it('shows immediate action errors at the bottom and closes matching failed operation feedback once', () => {
+ vi.useFakeTimers();
+ const failure = backend('failed', 'Permission denied');
+ failure.error = 'Permission denied';
+ const { rerender } = render( );
+ expect(screen.getAllByRole('alert')).toHaveLength(1);
+ expect(screen.getByLabelText('Operation notification').parentElement).toBe(document.body);
+ act(() => {
+ vi.advanceTimersByTime(120_000);
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Close notification' }));
+ expect(failure.setError).toHaveBeenCalledWith('');
+ rerender( );
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+});
+
+it('uses one global bottom notification on every page and preserves its deadline through navigation', () => {
+ vi.useFakeTimers();
+ runtime.backend = backend();
+ render( );
+ const toast = screen.getByLabelText('Operation notification');
+ expect(toast.parentElement).toBe(document.body);
+ act(() => {
+ vi.advanceTimersByTime(6000);
+ });
+ for (const page of ['My Macs', 'Leaderboard', 'Updates', 'Home']) {
+ fireEvent.click(screen.getByRole('button', { name: page }));
+ expect(screen.getAllByLabelText('Operation notification')).toHaveLength(1);
+ expect(screen.getByLabelText('Operation notification')).toBe(toast);
+ expect(document.querySelector('.operation-inline')).not.toBeInTheDocument();
+ }
+ act(() => {
+ vi.advanceTimersByTime(4000);
+ });
+ expect(screen.queryByLabelText('Operation notification')).not.toBeInTheDocument();
+});
diff --git a/desktop-app/tests/operationStream.test.ts b/desktop-app/tests/operationStream.test.ts
new file mode 100644
index 0000000000..4958385c05
--- /dev/null
+++ b/desktop-app/tests/operationStream.test.ts
@@ -0,0 +1,60 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import type { DesktopAPI, Operation, Snapshot } from '../src/shared/contracts';
+import { submitAction } from '../src/renderer/actions';
+
+afterEach(() => vi.useRealTimers());
+const running: Operation = {
+ id: 'operation',
+ action: 'download',
+ state: 'running',
+ started_at: 1,
+ message: 'Working',
+ cancellable: true,
+};
+
+it('receives terminal progress from the state stream without polling', async () => {
+ let observe!: (snapshot: Snapshot) => void;
+ const off = vi.fn();
+ const read = vi.fn();
+ const api = {
+ onState: vi.fn((callback) => {
+ observe = callback;
+ return off;
+ }),
+ act: vi.fn().mockResolvedValue(running),
+ read,
+ } as unknown as DesktopAPI;
+ const work = submitAction(
+ api,
+ { action: 'download', model: 'model' },
+ { timeoutMs: 60_000, timeout: 'Timed out' },
+ );
+ await Promise.resolve();
+ observe({ operations: [{ ...running, state: 'succeeded' }] } as Snapshot);
+ await work;
+ expect(read).not.toHaveBeenCalled();
+ expect(off).toHaveBeenCalledOnce();
+});
+
+it('falls back after stream silence and removes the subscriber on failure', async () => {
+ vi.useFakeTimers();
+ const off = vi.fn();
+ const read = vi.fn().mockResolvedValue({
+ operations: [{ ...running, state: 'failed', message: 'Download refused' }],
+ });
+ const api = {
+ onState: () => off,
+ act: vi.fn().mockResolvedValue(running),
+ read,
+ } as unknown as DesktopAPI;
+ const work = submitAction(
+ api,
+ { action: 'download', model: 'model' },
+ { timeoutMs: 60_000, timeout: 'Timed out' },
+ );
+ const failure = expect(work).rejects.toThrow('Download refused');
+ await vi.advanceTimersByTimeAsync(10_000);
+ await failure;
+ expect(read).toHaveBeenCalledOnce();
+ expect(off).toHaveBeenCalledOnce();
+});
diff --git a/desktop-app/tests/overview.test.tsx b/desktop-app/tests/overview.test.tsx
index 213a9978ea..2db0c5fee9 100644
--- a/desktop-app/tests/overview.test.tsx
+++ b/desktop-app/tests/overview.test.tsx
@@ -24,17 +24,15 @@ const health = () => screen.getByRole('region', { name: 'Health' });
it('shows This Mac’s memory, fans, readiness and earnings', async () => {
render( );
- expect(within(health()).getByRole('status')).toHaveTextContent(
- 'Connected and ready for requests',
- );
+ expect(within(health()).getByRole('status')).toHaveTextContent('Ready to serve');
for (const text of [
- 'Serving GPT-OSS 20B and Gemma 4 26B',
+ '2 models loaded',
'19.8 GB of 64.0 GB',
'16.4 GB active',
'3.4 GB cache',
'34.0 GB free to load',
'Spinning · 2,495 RPM',
- 'Left fan 2,480 · Right fan 2,510 RPM · macOS managed',
+ 'Left fan 2,480 · Right fan 2,510 RPM · macOS control',
'52°C GPU',
])
expect(health()).toHaveTextContent(text);
@@ -85,7 +83,7 @@ it('distinguishes unread, fanless, unavailable and provider-cooled fans', async
navigate={vi.fn()}
/>,
);
- expect(health()).toHaveTextContent('Spinning · 4,100 RPM82% of max · Provider cooling');
+ expect(health()).toHaveTextContent('Spinning · 4,100 RPM82% of max · Darkbloom control');
expect(within(health()).getByRole('img', { name: 'Fan spinning at 4,100 RPM' })).toHaveAttribute(
'data-animate',
'true',
@@ -103,7 +101,7 @@ it('lists next steps with working actions for a stopped, unlinked Mac', async ()
};
const navigate = vi.fn();
const { rerender } = render( );
- expect(within(health()).getByRole('status')).toHaveTextContent('Ready when you are');
+ expect(within(health()).getByRole('status')).toHaveTextContent('Stopped');
expect(health()).toHaveTextContent('Not serving requests');
const steps = within(health()).getByRole('list');
expect(
@@ -153,8 +151,8 @@ it('explains a disconnected runtime and repairs it through the native installer'
navigate={vi.fn()}
/>,
);
- expect(within(health()).getByRole('status')).toHaveTextContent(message);
- expect(health()).toHaveTextContent('Status unknown while disconnected');
+ expect(within(health()).getByRole('status')).toHaveTextContent('Connection unavailable');
+ expect(health()).toHaveTextContent('Serving status unavailable');
fireEvent.click(within(health()).getByRole('button', { name: 'Repair runtime' }));
expect(install).toHaveBeenCalled();
});
@@ -169,9 +167,7 @@ it('shows unreported per-Mac earnings as unknown, never as zero', async () => {
const { rerender } = render( );
const earnings = () => screen.getByRole('region', { name: 'This Mac’s earnings' });
expect(within(earnings()).getAllByText('—')).toHaveLength(2);
- expect(earnings()).toHaveTextContent(
- 'Per-Mac totals appear here once your Darkbloom runtime reports them.',
- );
+ expect(earnings()).toHaveTextContent('Some earnings totals are not available yet.');
rerender(
{
);
expect(bars).toHaveLength(24);
expect(bars[21]).toHaveAccessibleName(/1,500 tokens · 2 requests · observed 1 of 60 min$/);
- expect(bars[22]).toHaveAccessibleName(/No observations$/);
+ expect(bars[22]).toHaveAccessibleName(/No data$/);
expect(bars[23]).toHaveAccessibleName(/now: 1,000 tokens · 1 request · observed 1 of 5 min$/);
expect(bars[23]).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByText('2.5K tokens · 3 requests')).toBeVisible();
diff --git a/desktop-app/tests/productStatus.test.ts b/desktop-app/tests/productStatus.test.ts
new file mode 100644
index 0000000000..7acc06bec3
--- /dev/null
+++ b/desktop-app/tests/productStatus.test.ts
@@ -0,0 +1,36 @@
+import { expect, it } from 'vitest';
+import { machineStatus, modelActivity } from '../src/renderer/presentation/status';
+import { operationLabel } from '../src/renderer/components/operations/labels';
+import { coolingStatus } from '../src/renderer/features/cooling/status';
+
+it('distinguishes online Macs and idle models from requests being processed', () => {
+ expect(machineStatus('running')).toBe('Online');
+ expect(machineStatus('untrusted')).toBe('Verification needed');
+ expect(machineStatus('unknown_from_new_runtime')).toBe('Status unavailable');
+ expect(modelActivity('idle', 0)).toBe('Ready');
+ expect(modelActivity('running', 0)).toBe('Ready');
+ expect(modelActivity('running', 3)).toBe('3 processing');
+ expect(modelActivity('crashed', 3)).toBe('Needs restart');
+ expect(modelActivity('idle_shutdown', 0)).toBe('Unloaded');
+});
+
+it('presents operations as user actions and keeps completion distinct from failure', () => {
+ expect(operationLabel({ action: 'autopilot_pin', state: 'running' })).toBe(
+ 'Keeping models in memory',
+ );
+ expect(operationLabel({ action: 'autopilot_models', state: 'succeeded' })).toBe(
+ 'Model refresh · Complete',
+ );
+ expect(operationLabel({ action: 'account-signin', state: 'failed' })).toBe('Sign-in · Failed');
+ expect(operationLabel({ action: 'cooling', state: 'cancelled' })).toBe(
+ 'Fan settings · Cancelled',
+ );
+});
+
+it('shows enabled fan policy independently from its current firmware control mode', () => {
+ const cooling = { supported: true, mode: 'automatic' as const, enabled: true, fans: [] };
+ expect(coolingStatus(cooling)).toBe('Auto fan on');
+ expect(coolingStatus({ ...cooling, enabled: false })).toBe('Auto fan off');
+ expect(coolingStatus({ ...cooling, observed_at: 1 })).toBe('Fan status unavailable');
+ expect(coolingStatus({ ...cooling, error: 'SMC diagnostic' })).toBe('Fan status unavailable');
+});
diff --git a/desktop-app/tests/readiness.test.ts b/desktop-app/tests/readiness.test.ts
index 5a541777a3..acfda35b82 100644
--- a/desktop-app/tests/readiness.test.ts
+++ b/desktop-app/tests/readiness.test.ts
@@ -13,7 +13,8 @@ const ids = (readiness: ReturnType) => readiness.steps.map((step)
it('is ready with no steps while linked models serve', async () => {
expect(assess(await state())).toEqual({
tone: 'ready',
- summary: 'Serving GPT-OSS 20B and Gemma 4 26B',
+ status: 'Ready to serve',
+ summary: '2 models loaded',
steps: [],
});
});
@@ -140,7 +141,7 @@ it('puts a running operation first and holds provider steps during lifecycle cha
const starting = assess({ ...snapshot, state: 'stopped', operations: [operation('start')] });
expect(starting.tone).toBe('pending');
expect(starting.steps).toEqual([
- expect.objectContaining({ id: 'operation', title: 'Start in progress', actions: [] }),
+ expect.objectContaining({ id: 'operation', title: 'Starting provider', actions: [] }),
]);
const downloading = assess({
...snapshot,
@@ -162,3 +163,32 @@ it('requires an update the routing floor rejects and offers it only when compati
const unavailable = assess(snapshot, connected, { required: true, available: false });
expect(unavailable.steps[0]).toMatchObject({ id: 'update', actions: [] });
});
+
+it('uses current facts instead of authorization event text or processing counts', async () => {
+ const snapshot = {
+ ...(await state()),
+ readiness: 'Provider authorization updated',
+ provider_status: 'online',
+ };
+ const ready = assess(snapshot);
+ expect(ready.status).toBe('Ready to serve');
+ expect(ready.summary).toBe('2 models loaded');
+ const unloaded = snapshot.models.map((model) => ({ ...model, loaded: false }));
+ expect(assess({ ...snapshot, models: unloaded }).status).toBe('Loading models');
+ expect(assess({ ...snapshot, provider_status: 'untrusted' })).toMatchObject({
+ tone: 'blocked',
+ status: 'Verification needed',
+ });
+ expect(assess({ ...snapshot, provider_status: 'offline' })).toMatchObject({
+ tone: 'pending',
+ status: 'Connecting to the network',
+ });
+ expect(assess({ ...snapshot, state: 'stale' }).status).toBe('Status unavailable');
+ expect(assess({ ...snapshot, state: 'stopped' }).status).toBe('Stopped');
+ expect(
+ assess({
+ ...snapshot,
+ models: snapshot.models.map((model, i) => ({ ...model, loaded: i === 0 })),
+ }).summary,
+ ).toBe('1 model loaded');
+});
diff --git a/desktop-app/tests/remoteOverview.test.tsx b/desktop-app/tests/remoteOverview.test.tsx
index beb1aa55bf..d5720f34e4 100644
--- a/desktop-app/tests/remoteOverview.test.tsx
+++ b/desktop-app/tests/remoteOverview.test.tsx
@@ -22,7 +22,7 @@ it('shows the remote Mac’s earnings, 24-hour traffic, hourly chart and models'
expect(screen.getByRole('status')).toHaveTextContent(/^Online$/);
expect(screen.getByRole('status').parentElement).toHaveTextContent('Last observed just now');
expect(screen.getByText('Online since').nextElementSibling).toHaveTextContent(
- /^\d{1,2}:\d{2}\s?[AP]M1[23]h \d+m$/,
+ /\d{1,2}:\d{2}\s?[AP]M1[23]h \d+m$/,
);
const earnings = screen.getByRole('region', { name: 'Mac Studio’s earnings' });
for (const amount of ['$186.40', '$4.12', '$7.00']) expect(earnings).toHaveTextContent(amount);
@@ -43,7 +43,7 @@ it('shows the remote Mac’s earnings, 24-hour traffic, hourly chart and models'
'button',
);
expect(bars).toHaveLength(24);
- expect(bars[9]).toHaveAccessibleName(/No observations$/);
+ expect(bars[9]).toHaveAccessibleName(/No data$/);
expect(bars[23]).toHaveAccessibleName(/now: [\d,]+ tokens$/);
expect(screen.getByText('Last paid work').nextElementSibling).toHaveTextContent('2m ago');
expect(screen.getByText('Gemma 4 26B')).toBeVisible();
@@ -81,7 +81,7 @@ it('shows a dash for every figure the account projection does not report yet', a
for (const label of ['Provider version', 'Last paid work', 'Online since'])
expect(screen.getByText(label).nextElementSibling).toHaveTextContent('—');
expect(screen.queryByRole('group', { name: 'Tokens shared per hour' })).not.toBeInTheDocument();
- expect(screen.getByText('No serving models reported')).toBeVisible();
+ expect(screen.getByText('No models reported')).toBeVisible();
expect(container).not.toHaveTextContent('$0.00');
});
@@ -95,7 +95,7 @@ it('flags a silent or offline Mac and a provider below the minimum version', asy
/>,
);
const status = screen.getByRole('status');
- expect(status).toHaveTextContent('Not reportinglast reported online');
+ expect(status).toHaveTextContent('Not reportinglast reported Online');
expect(status.parentElement).toHaveTextContent('Last observed 3h ago');
expect(status.querySelector('i')).toHaveAttribute('data-presence', 'stale');
expect(screen.getByText('Online since').nextElementSibling).toHaveTextContent('—');
diff --git a/desktop-app/tests/requestActivity.test.tsx b/desktop-app/tests/requestActivity.test.tsx
index 54be420e79..e057c6206a 100644
--- a/desktop-app/tests/requestActivity.test.tsx
+++ b/desktop-app/tests/requestActivity.test.tsx
@@ -103,7 +103,9 @@ it('keeps the last observation when a refresh fails', async () => {
vi.spyOn(previewAPI, 'read').mockRejectedValue(new Error('offline'));
fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
expect(
- await screen.findByText('Couldn’t refresh request history. Showing the last observation.'),
+ await screen.findByText(
+ 'Couldn’t refresh request history. Showing previously loaded requests.',
+ ),
).toBeVisible();
expect(rows()).toHaveLength(25);
});
diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md
index aee0b3e5f2..62c97b40e1 100644
--- a/docs/architecture/storage.md
+++ b/docs/architecture/storage.md
@@ -1,6 +1,6 @@
# Storage
-> Last updated: 2026-10-02
+> Last updated: 2026-10-06
What the coordinator persists, through which interface, in which backend, and
how the schema reaches a fresh database; then what a provider keeps on its own
@@ -43,6 +43,13 @@ The additive `app_attest_build_qualifications` table stores immutable signed-art
## Context
+`NetworkModelEarningsReader` (`coordinator/store/network_model_earnings.go`,
+`NetworkModelEarnings`) groups positive settled inference payouts across accounts
+by model for the public stats projection. It excludes base rewards and empty model
+IDs, validates the bounded half-open window and has a five-second SQL deadline.
+It adds no schema or writer changes. `store.As` discovers the capability through
+decorators; a query failure is unavailable, never a successful zero ranking.
+
The desktop earnings reader (`ProviderInsightsReader` in
`coordinator/store/provider_insights.go`) groups the account's settled earnings
by UTC day, model and historical provider ID. `store.As` discovers it through
@@ -415,3 +422,15 @@ An unchanged decision can age outside the admin endpoint's recent-events window
while the current tick summary remains fresh. Proposals are not dispatched
commands, residency changes or live capacity evidence; see the
[API contract](../reference/api-contracts.md#experimental-model-autopilot).
+
+## Desktop account grants
+
+The existing `device_codes` and `provider_tokens` tables also store desktop
+account grants. A purpose prefix binds the opaque grant to dashboard consent;
+`ConsumeDeviceCode` atomically moves an approved, unexpired grant to `consumed`.
+The token's distinct prefix, label, and creation time enforce read-only scope and
+30-day expiry before cached data is returned. Provider tokens retain their
+existing behavior; no table or column migration is introduced
+(`coordinator/store/memory.go`, `ConsumeDeviceCode`;
+`coordinator/store/postgres.go`, `ConsumeDeviceCode`;
+`coordinator/api/desktop_account_auth.go`, `desktopAccountToken`).
diff --git a/docs/assets/desktop-api-architecture.html b/docs/assets/desktop-api-architecture.html
new file mode 100644
index 0000000000..75846486a0
--- /dev/null
+++ b/docs/assets/desktop-api-architecture.html
@@ -0,0 +1,96 @@
+
+
+
+
+
+Darkbloom · API architecture, before & after
+
+
+
+
+ darkbloom/ architecture
DESKTOP APP · PR 1318 · OCT 05, 2026
+Architecture review
The same darkbloom CLI.A thinner Electron app. The existing darkbloom executable owns authentication, API requests, native operations and shared caches. Electron renders the UI and connects to its desktop serve API.
Print / save PDF ↗
+Reuse account APIs Swift account session → existing /me endpoints
Reuse the darkbloom CLI Same executable · existing desktop serve API
Keep Electron thin UI + IPC · backend observations drive every page
+All flows This Mac Account Public network
Select a flow or click a diagram card to inspect it.
+
+
+
01 · Renderer
Home My Macs Models Stats Earnings All pages wait for the local runtime snapshot.
+
02 · Fetch & refresh
useBackend + page-specific hooks Global reads every 30s · separate insights/history refreshes State also arrives every 2s; actions poll it every 750ms.
+
03 · Native gateway
Electron IPC → Swift desktop API /control/v1/* mixes local controls with coordinator requests. Device-link token authenticates account reads.
+
04 · Data sources
+This Mac Runtime + hardware daemon-state.jsonhardware / eventsfan statusReal local readings. Legacy input counts backfilled from settlements.
+Coordinator Desktop projections /provider/desktop/desktop/insights404 → fallback /account-earningsLatest 1,000 rows + lifetime totals. /providers/attestationPublic roster used to identify this Mac.
+Coordinator Public reads /stats/leaderboard/releases/latest/releases/desktophistory: 404 Refreshed on every page. /models/catalogAwaited inside local state generation every 2 min.
+
+
+
01 · Renderer
Home My Macs Models Stats Earnings Pages subscribe to shared stores through fixed IPC.
+
02 · Thin Electron bridge
Renderer → Electron IPC → darkbloom desktop serve Electron main forwards fixed requests and native events. The renderer receives data; Swift owns credentials and coordinator calls.
+
03 · Same darkbloom CLI executable · desktop serve
+CLI · runtime State + operations Live state, usage journal, hardware stream & native actions. One operation manager. Provider device link stays separate.
+CLI · account Session + earnings Browser device-code consent, native storage & 30-day expiry. Shared account-scoped fleet, summary and earnings caches.
+CLI · public data Catalog + network Shared caches, backoff & selective refresh. Catalog fetches never block local state snapshots.
+
+
04 · Data sources
+This Mac Native measurements daemon state + usage journalhardware monitorfan helperInput/output tokens, models & request activity stay local.
+Existing APIs Account + settlements /v1/me/providers/v1/me/summary/v1/provider/account-earnings Existing earnings API: complete 7/30-day aggregates.
+Existing APIs Network + catalog /v1/stats/v1/leaderboard/v1/releases/latest/v1/models/catalogKeep current endpoints; request and cache independently.
+
+
+Read the architecture Lines show which layer consumes which source. Green is this Mac, terracotta is your account, and blue is public network data. Click a card for the implementation detail.
+Account login · Swift owns the dashboard session Reuse browser email sign-in and the existing device-code flow with purpose=desktop_account. Swift polls, stores a separate read-only session and owns all account reads. Deploy the prepared coordinator and console changes to enable this flow.
Device link · the provider retains its identity The serving provider retains its device credential. Account sign-out does not unlink or stop this Mac. desktop serve and the serving provider can be separate processes of the same darkbloom executable, reusing ProviderCore and the existing CLI commands.
+What stays, what changes Coordinator paths are fully qualified below. Diagram cards abbreviate some paths.
Current endpoint / resource Decision After
+/v1/provider/desktopPR-added · live check: 404 Replace Use existing /v1/me/providers and /v1/me/summary through account login. Keep a thin desktop adapter for display fields.
+/v1/provider/desktop/insightsPR-added · live check: 404 Merge into earnings Extend the existing earnings endpoint with grouped day/model/machine totals. Home, Models, Stats and Earnings share those results.
+/v1/provider/account-earningsLive check: 200 · latest 1,000 rows Keep + extend Complete 7/30-day aggregates through the existing window parameter. Legacy records retain explicit coverage. The existing record limit cannot recover missing historical days.
+/v1/providers/attestationUsed for dashboard identity matching Remove dashboard polling Signed-in sessions match this Mac against the owned fleet. Legacy settlement backfill caches the public roster for five minutes.
+/v1/me/providers/v1/me/summaryExisting console endpoints · device token gets 403 Reuse with user login Owned fleet, live/stored machine state, account totals and balances. No new fleet endpoint required.
+/v1/stats/v1/leaderboardKeep · fetch selectively Cache network data on Home/Leaderboard. Fetch rankings on Leaderboard; do not refresh them after unrelated native actions.
+/v1/releases/latest/v1/releases/desktopLatest: 200 · PR-added history: 404 Consolidate release reads Share one latest-release read; show only its available notes. Preserve signed runtime update verification.
+/v1/models/catalog/v1/models/catalog/manifest/{id}Keep · decouple Refresh catalog in the background; fetch manifests on download. Catalog requests cannot block local state snapshots.
+/control/v1/state/control/v1/eventsKeep · stream first One shared state subscription. Snapshot reads for startup/resync and fallback; operation completion comes from the stream.
+POST /control/v1/actionsKeep one action interface One operation manager; supported-action capabilities in state. Keep the backend’s native mutation and lifecycle safeguards.
+/control/v1/hardware/control/v1/hardware/events/control/v1/cooling/control/v1/endpoint-keyKeep local Read hardware/cooling while displayed. Reveal the inference key only on explicit request. No coordinator measurement API.
+/control/v1/cloud/control/v1/insights-week/control/v1/insights-monthConsolidate in Swift Keep native account resources backed by the Swift account session. Preserve fixed week/month IPC resources, mapped to the existing ledger window parameter and shared native caches.
+/control/v1/request-historyLocal history + settlement join Read exact request metadata from the native journal, then attach settled earnings by a stable request/job identifier. Existing runtimes retain a clearly scoped legacy fallback.
+/control/v1/network/control/v1/leaderboard/control/v1/release/control/v1/release-historyKeep Swift adapters Swift owns the coordinator requests and caches. Electron subscribes or requests them only when needed. Catalog and account fetching run independently of live snapshots.
+
+01 / NEW SWIFT CAPABILITY Account session Implemented separate read-only sessions through browser approval. Credentials stay in Swift; sign-out keeps serving intact. Coordinator and console deployment are still needed.
02 / EXISTING API EXTENSION Complete earnings windows 48,800 lifetime records versus 1,000 returned in the audit. Summing the returned rows is not a complete seven-day total. Preserve integer precision and mark coverage.
03 / LOCAL RUNTIME FIELDS Exact activity and capabilities Publish input/output tokens, optional cache/reasoning counts and supported actions through native state. Prepared usage changes require a signed provider release to run in the serving provider.
+Supporting flows retained outside the dashboard diagram POST /v1/device/code + POST /v1/device/token: existing Mac-linking flow; browser approval uses the account login.POST /v1/enroll: conditional installation/enrollment.Provider WebSocket: registration, serving, heartbeats and coordinator commands. Model manifests + artifact URLs: native model downloads and verification. /health + attestation checks: explicit native diagnostics.Electron update feed + signed runtime downloads: distinct product update flows.
+
+
+
+
+
diff --git a/docs/assets/desktop-autopilot-browse.png b/docs/assets/desktop-autopilot-browse.png
new file mode 100644
index 0000000000..7a4353f1ed
Binary files /dev/null and b/docs/assets/desktop-autopilot-browse.png differ
diff --git a/docs/consumer/billing.md b/docs/consumer/billing.md
index 947f6f56ee..efe282d2dc 100644
--- a/docs/consumer/billing.md
+++ b/docs/consumer/billing.md
@@ -1,6 +1,6 @@
# Billing: fund an account and keep spend under control
-> Last updated: 2026-10-02
+> Last updated: 2026-10-05
How to add credit, read your balance and usage, cap what a key can spend,
redeem an invite code, and act on a `402`. Why the coordinator behaves this
@@ -277,3 +277,12 @@ as a new withdrawal.
The bank panel and self-service migration state are implemented by
`console-ui/src/components/payouts/StripePayoutsCard.tsx` and
`coordinator/api/global_payouts_status.go` (`maybeGlobalStatus`).
+
+## View earnings from the desktop app
+
+Choose **Sign in** in the desktop app and authorize the displayed code in the
+browser. Account views use a separate read-only session. Signing out leaves
+provider linkage and serving intact. Sign in again when the session expires.
+See the [desktop account contract](../reference/api-contracts.md#desktop-account-sessions)
+for accepted reads and the [desktop CLI reference](../provider/cli-reference.md)
+for terminal access.
diff --git a/docs/consumer/models.md b/docs/consumer/models.md
index 60685ad303..31d7a16ba8 100644
--- a/docs/consumer/models.md
+++ b/docs/consumer/models.md
@@ -1,11 +1,17 @@
# Models reference
-> Last updated: 2026-09-30
+> Last updated: 2026-10-06
Reference for `GET /v1/models` and `GET /v1/models/{id}`: every field of a `ModelEntry`, how the `model` you send is resolved, and the capability flags the API exposes and enforces. For SDK users and integrators. The catalog itself is database-driven — builds, capabilities and prices live in the coordinator's registry and price tables, and public names are aliases maintained by operators (`coordinator/api/model_alias_handlers.go`, [`../architecture/model-registry.md`](../architecture/model-registry.md)) — so there is no static list to reproduce here; `GET /v1/models` is the list.
## `GET /v1/models`
+Public `/v1/stats` includes optional seven-day settled model payout aggregates,
+used by desktop download recommendations. These network totals are separate from
+catalog consumer prices and account-specific earnings; see the
+[public stats contract](../reference/api-contracts.md#public-stats-and-health-6)
+(`coordinator/api/network_model_earnings.go`, `networkModelEarnings`).
+
MiMo image/video requests also require temporary preparation memory beyond the
loaded weights and text KV budget. A request that cannot reserve that memory
can fail over or return 429 while text remains serviceable. The provider's
diff --git a/docs/developer/build.md b/docs/developer/build.md
index f86eb30de6..7d6d0d69a4 100644
--- a/docs/developer/build.md
+++ b/docs/developer/build.md
@@ -1,6 +1,6 @@
# Build
-> Last updated: 2026-10-01
+> Last updated: 2026-10-05
The provider test runner isolates daemon-state and loaded-model snapshots in a
temporary directory for each run. Unit-test providers must not overwrite the
@@ -939,3 +939,11 @@ Exercise the API, funding and settlement contracts with
Set `DATABASE_URL` to a disposable local PostgreSQL database to run transaction,
concurrency and rollback coverage. Never point tests at production. Console
migration coverage runs with `npm test` in `console-ui`.
+
+## Desktop architecture checks
+
+`make desktop-api-test` exercises the real Swift control API against isolated
+local fixtures. It checks that release reads share the existing latest-release
+API, earnings use the existing ledger window parameter, and a credential change
+rejects an in-flight private response (`scripts/test-desktop-api.py`).
+The fixture never starts a serving provider or changes its credentials.
diff --git a/docs/developer/desktop-app.md b/docs/developer/desktop-app.md
index e91ef6cf70..a47e2eb8ed 100644
--- a/docs/developer/desktop-app.md
+++ b/docs/developer/desktop-app.md
@@ -1,6 +1,6 @@
# Build and validate the macOS desktop app
-> Last updated: 2026-10-03
+> Last updated: 2026-10-07
Build the Electron frontend and its Swift CLI/backend API in this repository.
This guide covers development and review artifacts; production distribution also
@@ -125,7 +125,7 @@ projection supplies them. The
app stores the selected machine ID so new remote observations are shown instead
of retaining the originally clicked snapshot, and Models, Cooling, Stats,
Settings and Studio always apply to This Mac. Cancellable native operations
-appear inline for This Mac; Settings retains Availability and Memory controls,
+appear in the shared bottom popup; Settings retains Availability and Memory controls,
and model metadata uses expandable details.
This Mac's Overview starts with a health bar: memory from native state, fan
@@ -153,6 +153,46 @@ Regions sharing a map cell light it together in one of four shades scaled by Mac
count; hovering a cell or choosing a region shows its count.
+The Home chip header links to Cooling through `FanStatus`. The enabled helper
+stays blue regardless of its current SMC mode. With the option off, temperatures
+above 60°C become progressively red up to 90°C; missing or stale observations
+stay neutral. Home reads the existing cached cooling resource while visible
+(`showsCooling`, `DesktopBackend.projectCooling`).
+
+Overview readiness uses `assessReadiness` to show current state, including the
+coordinator’s `provider_status`, rather than the raw `readiness` event message.
+A ready Mac shows "Ready to serve" with its loaded-model count. Shared product
+labels in `desktop-app/src/renderer/presentation/status.ts` (`machineStatus`,
+`modelActivity`) distinguish online Macs and idle models from processing requests.
+`operationLabel` names actions in progress and completed outcomes. `App` mounts
+one `OperationFeed` outside page content; its body portal stays at the bottom
+on Home, My Macs (including remote Macs and all tabs), Leaderboard and Updates.
+Successful operations disappear after ten seconds, using their native completion
+time when available; navigation and state refresh do not reset the countdown.
+Failures and immediate `backend.error` messages remain until Close. Dismissal
+persists across remounts, and expanded details retain native diagnostic messages. Cooling labels use the
+enabled fan policy independently of its current firmware mode (`coolingStatus`).
+
+The account footer displays `state.account.email` with Signed in. Swift obtains
+identity from the existing `/v1/provider/account-earnings` response's optional
+`email`, persists it with the coordinator-scoped dashboard credential, and shares
+the same cached ledger request with stats and earnings (`DesktopAccountIdentity`).
+State polling hydrates older credentials even when the provider is stopped;
+missing identity leaves Account as the label. Sign-out removes the identity,
+and replies from another coordinator/session cannot update it. Coordinators must
+include the authenticated owner's email in that response for the address to appear.
+
+Account control replaces the machine-name card at the bottom of the sidebar.
+Sign in immediately opens a modal (`AccountControl`, `useAccountSignIn`,
+`components/account/AccountSignInProgress.tsx`) using `link.code` from the native
+snapshot. Electron's Swift account action sets `automaticallyOpenBrowser=false`;
+only Continue in browser calls the existing external-link bridge. The dialog leads
+with a short code instruction and a full-width action; waiting status appears
+after the browser opens. The CLI keeps automatic
+browser opening. Copy, cancel, retry and approval states stay in the modal.
+Closing it preserves pending approval; Continue sign-in reopens the same attempt
+across pages. Account sign-in is excluded from the generic `OperationFeed`.
+
Home scrolls. It opens with the network milestone strip: tokens processed, the
last 24 hours when the runtime relays `last_24h_tokens`, Macs connected, and a
segmented bar toward the next proposed milestone (1, 2.5 and 5 of each power of
@@ -262,13 +302,16 @@ one gets its reasons and a waitlist; an unconfirmed one can check again or conti
- **Waitlist.** `{ action: 'waitlist', email, reasons }` takes the failed check
IDs as reasons and counts only once its operation succeeds.
- **Autopilot.** "Start serving with Autopilot" sends
- `{ action: 'autopilot', models, pinned, endpoint: true }`
+ `{ action: 'autopilot', models, pinned, downloads, endpoint: true }`
(`desktop-app/src/shared/autopilot.ts`). It mirrors
`darkbloom start --autopilot --model … --local-endpoint` followed by
`darkbloom autopilot pin …`.
- - `models` is the startup selection. It is the pins or, with no pins, one
- starting model: an eligible model already on disk, else the smallest eligible
- download.
+ - With network earnings available, choose from the top three compatible earners
+ over seven days; all three are checked initially. `downloads` contains only
+ chosen models missing from disk. Swift completes downloads before enrollment.
+ - `models` is the startup selection: the pins or one chosen model. Other cached
+ network models are verified and enrolled without pinning or loading all three
+ together. Without ranking data, the existing single-model start remains available.
- `pinned` is a subset of `models`, matching the CLI rule that pins must be
selected models.
- It is a separate action, not a `start` flag, because `DesktopAction`
@@ -276,8 +319,8 @@ one gets its reasons and a waitlist; an unconfirmed one can check again or conti
success.
- A runtime that supports the action reports `Snapshot.autopilot`
(configured enrollment plus the live phase from `autopilot status --json`).
- - Pins need provider-side residency enforcement while Autopilot holds
- ownership.
+ - Pins use the existing CLI's unload protection while Autopilot holds ownership;
+ pinning a cold model does not itself load it.
- **Account linking.** An unlinked Mac runs the existing `link` action first and
starts serving as soon as the account is linked. A failed or cancelled link
returns to the start button.
@@ -304,25 +347,36 @@ Preview links (`?preview` plus):
This Mac > Models follows `Snapshot.autopilot`
(`desktop-app/src/renderer/features/models/`). The user decides which models
are downloaded; Autopilot decides which of them are loaded in memory.
+Both model modes show the first three ranked matches, with a Show more models
+bar to reveal the remainder. Changing the filter or search restores the compact
+view; expansion preserves the existing earnings order.
+
+
+
+The local review screenshot shows an older coordinator without network earnings;
+recommendations remain unavailable until that response field is deployed.
-- **Autopilot on** (`enabled: true`). The catalog is the pool. Each row shows
- its size, its memory need and one state: Not downloaded, Downloading, On this
- Mac · not in pool, In pool, Loaded now · Autopilot, Pinned · always on, or Not
- available with the reason. There is no Apply selection.
+- **Autopilot on** (`enabled: true`). Your models opens first and ranks downloads
+ by personal earnings. Browse models ranks the catalog by seven-day network
+ earnings from `network`. Recommendations select eligible positive earners,
+ at most three (`recommendations.ts`, `recommendedModels`). The status bar shows
+ the daemon's actual phase and resident count. Descriptions and phase explanations
+ stay collapsed. There is no Apply selection.
- Downloading alone never adds a model to the pool. Download sends `download`,
then `autopilot_models` to re-inventory the pool.
- - Pin downloads the model into the pool first when needed.
- - A pin is refused when the pinned models' memory would exceed the Mac's
- memory.
- - Remove is disabled while a model is pinned. Removing a loaded model unloads
- it first.
- - The card above the list shows what is loaded, what is pinned, the runtime's
- free-to-load allowance and the phase. Only `active` and `transitioning`
- change what is loaded; `shadow`, `waiting`, `waiting_inventory` and `paused`
- say that models stay as they are.
+ - Keep in memory is a direct row toggle. Catalog rows also offer Download & keep
+ in memory. A cold pin says Kept · waiting to load; only observed residents
+ say In memory · kept (`PoolRow`).
+ - Pin capacity uses native `pin_budget_gb` (the shared startup load allowance)
+ and `max_model_slots`. Swift rechecks downloaded estimates before pinning.
+ - Remove is disabled for pinned, resident or advertised models. After removing
+ a cached pool model, refresh available models.
- Pause and Turn off ask for confirmation first. Models stay loaded as they
are, and after Turn off, manual selection takes over.
-- **Autopilot off** (`enabled: false`). The manual workflow (checkboxes, Apply
+- **First use** (`configured: false`). Show Autopilot setup with editable
+ recommendations. Missing earnings stay unavailable; prices and demand counts
+ are never substituted for settled payouts.
+- **Autopilot explicitly off** (`enabled: false`, `configured: true`). The manual workflow (checkboxes, Apply
selection) plus a card that sends `{ action: 'autopilot', models, pinned: [],
endpoint }` with the models serving now.
- **No `Snapshot.autopilot`.** The manual workflow with a note that Autopilot
@@ -339,7 +393,7 @@ The policy actions (`AutopilotPolicyAction` in
| `{ action: 'autopilot_pause' }` | `darkbloom autopilot pause` |
| `{ action: 'autopilot_resume' }` | `darkbloom autopilot resume` |
| `{ action: 'autopilot_disable' }` | `darkbloom autopilot disable` |
-| `{ action: 'autopilot_models' }` | `darkbloom autopilot models` |
+| `{ action: 'autopilot_models' }` | Noninteractive `darkbloom start --autopilot --model `; same verified inventory and safe restart as `autopilot models` |
A runtime that rejects one of these by name gets an error asking for a newer
runtime or manual selection. A download operation that reports `model` and
@@ -351,7 +405,7 @@ Preview links (`?preview` plus):
| Query | Shows |
|---|---|
| none (`&autopilot=on`) | Autopilot on: two models loaded, one pinned, one in the pool and not loaded, and several not downloaded |
-| `&autopilot=shadow` | Shadow mode: Autopilot is learning and changes nothing |
+| `&autopilot=shadow` | Shadow mode: Autopilot is observing demand and changes nothing |
| `&autopilot=off` | Manual selection with the turn-on card |
| `&autopilot=unsupported` | Runtime without Autopilot: manual selection with the note |
diff --git a/docs/developer/test.md b/docs/developer/test.md
index f7cc31a181..a8a7a51cd7 100644
--- a/docs/developer/test.md
+++ b/docs/developer/test.md
@@ -1,6 +1,6 @@
# Test
-> Last updated: 2026-10-02
+> Last updated: 2026-10-05
Desktop activity and earnings tests are described in the
[desktop verification guide](desktop-app.md#verify). `make desktop-api-test`
@@ -2949,3 +2949,11 @@ Exercise the API, funding and settlement contracts with
Set `DATABASE_URL` to a disposable local PostgreSQL database to run transaction,
concurrency and rollback coverage. Never point tests at production. Console
migration coverage runs with `npm test` in `console-ui`.
+
+## Desktop architecture checks
+
+`make desktop-api-test` exercises the real Swift control API against isolated
+local fixtures. It checks that release reads share the existing latest-release
+API, earnings use the existing ledger window parameter, and a credential change
+rejects an in-flight private response (`scripts/test-desktop-api.py`).
+The fixture never starts a serving provider or changes its credentials.
diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md
index 4a9c07c7a8..206e628183 100644
--- a/docs/provider/cli-reference.md
+++ b/docs/provider/cli-reference.md
@@ -1,6 +1,6 @@
# Provider CLI reference
-> Last updated: 2026-10-02
+> Last updated: 2026-10-06
Reference for the `darkbloom` command-line tool: every subcommand and flag, the
files and identifiers it creates, the `provider.toml` keys it reads with their
@@ -27,6 +27,13 @@ keeps the provider independent of its window lifetime. Internal
(each accepting `--config`) retain the native provider owner and termination handler. Cooling uses
`desktop configure-cooling --enabled --speed --temperature `
to request macOS administrator authorization for the existing signed helper.
+`darkbloom desktop login [--config ]` signs into the account
+workspace through browser approval; `darkbloom desktop logout [--config ]`
+signs out without changing provider linkage or serving state. Both use the same
+CLI and native account store as Electron (`Desktop.Login`, `Desktop.Logout`).
+It prefers a scoped account session and supports existing coordinator device-code
+grants when the desktop scope is not reported. Dashboard credentials stay separate
+from the running provider (`DeviceLoginScope`, `DesktopAccountCredential`).
See [desktop control](../reference/desktop-control.md) for the exact routes,
credentials, outcomes, and limits (`Desktop`, `DesktopBackend`).
diff --git a/docs/reference/api-contracts.md b/docs/reference/api-contracts.md
index 599aa14e83..5907a24f8a 100644
--- a/docs/reference/api-contracts.md
+++ b/docs/reference/api-contracts.md
@@ -1,6 +1,6 @@
# HTTP API contracts
-> Last updated: 2026-10-02
+> Last updated: 2026-10-07
The complete public HTTP surface of the coordinator, derived from the 120 `HandleFunc` registrations in `routes()` (`coordinator/api/server.go`), including the `/v1/` catch-all. Every route is listed once below with its handler symbol, authentication requirement, and rate-limit bucket; the second half of the page gives the wire shapes, headers, error table, SSE framing, limits, timeouts, and version-gate semantics that those routes share. For *why* the pipeline is built this way see [`../architecture/components/consumer.md`](../architecture/components/consumer.md); for the crypto model behind sealed transport see [`../architecture/security/encryption.md`](../architecture/security/encryption.md).
@@ -277,11 +277,39 @@ as inference budgets.
Lifecycle semantics: [`../consumer/authentication.md`](../consumer/authentication.md).
-### Device-code flow (3)
+### Desktop account sessions
+
+`POST /v1/device/code` accepts optional `{"purpose":"desktop_account"}`;
+normal provider login remains the default. The response echoes the purpose and
+uses `/link?purpose=desktop_account`. Approval must send the matching purpose:
+provider consent cannot authorize dashboard access. The server encodes purpose
+in the opaque device code; no schema migration is required (`handleDeviceCode`,
+`handleDeviceApprove` in `coordinator/api/device_auth.go`).
+
+A desktop grant exchanges once for a `darkbloom-at-` read-only token at
+`POST /v1/device/token`, with `expires_in=2592000`. Concurrent exchanges consume
+the approved grant atomically; only one token is returned. Tokens are stored as
+hashes in the existing token store and expire 30 days after issuance. Only
+`GET /v1/me/providers`, `GET /v1/me/summary`, and
+`GET /v1/provider/account-earnings` accept this scope. Inference, payments,
+provider registration, device approval, and account mutations reject it.
+`DELETE /v1/device/token` revokes only this dashboard session and returns `204`;
+invalid/revoked/expired credentials return `401` (`desktopAccountToken`,
+`requireAccountRead`, `revokeDesktopAccountToken` in
+`coordinator/api/desktop_account_auth.go`). Existing Privy and provider-token
+access retains its prior scope.
+
+`GET /v1/provider/account-earnings?window=7d|30d` returns the existing exact
+insights shape, aggregated over the full calendar window rather than the recent
+row limit. Invalid windows return `400`. Omitting `window` preserves the existing
+ledger response and `limit` behavior (`handleAccountEarnings`, `handleDesktopInsights`).
+
+### Device-code flow (4)
| Method | Path | Handler | Auth | Limiter | Notes |
|---|---|---|---|---|---|
| POST | `/v1/device/code` | `handleDeviceCode` (`coordinator/api/device_auth.go`) | `—` | — | 200 `{device_code, user_code, verification_uri, expires_in, interval}` |
+| DELETE | `/v1/device/token` | `revokeDesktopAccountToken` (`coordinator/api/desktop_account_auth.go`) | desktop account | — | 204; dashboard session only |
| POST | `/v1/device/token` | `handleDeviceToken` (`coordinator/api/device_auth.go`) | `—` | — | Body `{"device_code"}` (400 `invalid_request` if missing). 200 `{status: "authorization_pending"}` until approved; 200 `{status: "authorized", token, account_id}` once approved; 404 `invalid_grant`; 410 `expired_token` |
| POST | `/v1/device/approve` | `handleDeviceApprove` (`coordinator/api/device_auth.go`) | `privy` | `fin` | Body `{"user_code"}`. 404 `invalid_code`, 409 `already_used`, 410 `expired_code` |
@@ -356,6 +384,17 @@ Ledger semantics, reservations and payouts: [`../architecture/billing.md`](../ar
| GET | `/health` | `handleHealth` (`coordinator/api/consumer.go`) | `—` | `HealthResponse` `{status: "ok", draining, providers, version, build_commit, build_date}` |
A successful empty analytics window returns 200 with empty arrays or zero totals.
+`/v1/stats` also includes `model_earnings`, an optional public aggregate for
+desktop download recommendations (`coordinator/api/network_model_earnings.go`,
+`networkModelEarnings`). It is `null` when aggregation is unavailable. On success
+it contains `window: "7d"`, UTC `since` and `as_of` timestamps and `models` rows
+`{id, earnings_micro_usd}` sorted by descending payout, then ID. Money is a decimal
+string, preserving integers beyond JavaScript's safe range. The half-open rolling
+window excludes base rewards, unknown-model and nonpositive payouts; account and
+provider identities never enter the response. A successful empty window has
+`models: []`. This optional aggregate shares the existing stats refresh/cache and
+does not change core stats availability.
+
Core stats query failures retain the unexpired success or return 503; request
geography never blocks core stats. Geography refreshes on its own
`statsRefreshInterval` loop, using `statsGeographyCacheKey`. Core snapshots
@@ -1046,3 +1085,13 @@ Checkout amounts require at most two decimal places and the supported integer
cent range (`coordinator/api/stripe_checkout_webhook.go`, `checkoutUSDCents`).
Current and legacy Checkout signatures share exact local-session validation and
atomic, non-withdrawable credit (`handleStripeWebhook`, `CompleteStripeCheckout`).
+
+### Desktop account email
+
+`GET /v1/provider/account-earnings` without a `window` parameter optionally
+includes `email` for the authenticated account owner. This adds identity to the
+existing account read, without another endpoint. Query parameters cannot select
+another account's address. The field is omitted for identities without an email;
+older coordinators and credentials remain compatible. Desktop Swift stores the
+verified address alongside its account credential and exposes only the address
+and signed-in status to Electron.
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index f88f1df225..48b7ee81f7 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -1,6 +1,6 @@
# Configuration reference
-> Last updated: 2026-10-01
+> Last updated: 2026-10-05
Every environment variable read by the coordinator, the provider CLI
(`darkbloom`), console-ui and admin-ui: accepted values, the compiled default,
@@ -17,7 +17,7 @@ Autopilot `selected_models` is the cached planning inventory; `backend.enabled_m
| Setting | Default | Consumer and effect |
|---|---|---|
-| `DARKBLOOM_DESKTOP_DIR` | `~/.darkbloom/desktop` | `DesktopStorage.directory` in `provider-swift/Sources/darkbloom/Desktop/DesktopStorage.swift`; owner-only API discovery and operation journal; useful for isolated tests |
+| `DARKBLOOM_DESKTOP_DIR` | `~/.darkbloom/desktop` | `DesktopStorage.directory` in `provider-swift/Sources/darkbloom/Desktop/DesktopStorage.swift`; owner-only API discovery, operation journal, and coordinator-scoped dashboard credentials; useful for isolated tests |
| `DARKBLOOM_CLI_PATH` | `~/.darkbloom/bin/darkbloom` | `Backend.binary` in `desktop-app/src/main/backend.ts`; development-only CLI override, ignored by packaged apps |
| `DARKBLOOM_DESKTOP_ATTACH_ONLY` | unset | `Backend.connect` in `desktop-app/src/main/backend.ts`; when `1` in development, attach to an already-running isolated API without creating a LaunchAgent; ignored in packaged apps |
| `DARKBLOOM_DEV_URL` | Packaged `darkbloom://app/index.html` | `desktop-app/src/main/index.ts`; development-only renderer URL, ignored by packaged apps |
diff --git a/docs/reference/desktop-control.md b/docs/reference/desktop-control.md
index 9985e81a73..e64d531416 100644
--- a/docs/reference/desktop-control.md
+++ b/docs/reference/desktop-control.md
@@ -1,12 +1,15 @@
# Desktop control API
-> Last updated: 2026-10-02
+> Last updated: 2026-10-07
The Electron app controls the Swift CLI/backend through its authenticated local
API. The backend owns provider operations, configuration, model state, credentials,
and coordinator requests. This contract is implemented by
`provider-swift/Sources/darkbloom/Desktop/` (`Desktop`, `DesktopHTTP`, `DesktopBackend`).
+The [interactive before-and-after architecture diagram](../assets/desktop-api-architecture.html)
+shows the local, account, and public-network data flows.
+
## Transport and discovery
`darkbloom desktop ensure` installs/starts the user LaunchAgent
@@ -61,13 +64,14 @@ credential (`desktop-app/src/main/backend.ts`, `Backend`; `DesktopHTTP.authorize
| `GET /control/v1/state` | Protocol/version, local machine, provider state, models, memory, settings revision, operations, linking state, and observed activity | `DesktopBackend.state` |
| `GET /control/v1/events` | Full `state` snapshots as SSE every two seconds; connection renews after 30 snapshots; maximum eight streams | `DesktopHTTP.respond`, `DesktopStreamLimiter` |
| `POST /control/v1/actions` | Validated operation; JSON body limited to 16 KiB; returns `202` and its operation ID | `DesktopAction.validate`, `DesktopBackend.submit` |
+| `GET /control/v1/request-history` | Exact metadata from the current native usage journal, with settled money joined only by job ID; verified ledger fallback on older runtimes | `DesktopBackend.requestHistory`, `localRequestHistory` |
| `GET /control/v1/cloud` | Account and owned fleet projection through the coordinator; separates This Mac using native identity | `DesktopBackend.resource` |
-| `GET /control/v1/insights-week`, `GET /control/v1/insights-month` | Settled earnings, lifetime output tokens, and 7/30-calendar-day analytics through the provider-token-authenticated coordinator endpoint | `DesktopBackend.resource` |
-| `GET /control/v1/network` | Normalized public totals and approximate `provider_regions` from `/v1/stats` | `DesktopBackend.resource` |
-| `GET /control/v1/release-history` | Public release notes and routing floor from `/v1/releases/desktop` | `DesktopBackend.resource` |
+| `GET /control/v1/insights-week`, `GET /control/v1/insights-month` | Settled earnings, lifetime output tokens, and 7/30-calendar-day analytics through the account-session-authenticated ledger API | `DesktopBackend.resource` |
+| `GET /control/v1/network` | Public totals, approximate `provider_regions`, and optional seven-day `model_earnings` from `/v1/stats` | `DesktopBackend.resource` |
+| `GET /control/v1/release-history` | Latest release notes from `/v1/releases/latest`; no separate desktop release request | `DesktopBackend.resource` |
| `GET /control/v1/leaderboard` | Public earnings ranking over 24 hours (`metric=earnings&window=24h`); response includes `metric`, `window`, and `entries`; money and token counts remain decimal strings | `DesktopBackend.resource` |
| `GET /control/v1/release` | Latest registered runtime version and changelog | `DesktopBackend.resource` |
-| `GET /control/v1/cooling` | Native fan diagnostics and helper state; concurrent and repeat reads within 10 s share one `fan status` run; a finished `cooling` action clears it | `DesktopBackend.cooling` |
+| `GET /control/v1/cooling` | Native fan diagnostics and helper state, including `enabled` and `observed_at`; concurrent and repeat reads within 10 s share one `fan status` run; a finished `cooling` action clears it | `DesktopBackend.cooling`, `projectCooling` |
| `GET /control/v1/endpoint-key` | Existing local inference credential for explicit reveal | `DesktopBackend.resource` |
| `GET /control/v1/hardware` | Chip topology and the latest whole-machine load sample (see [Hardware load](#hardware-load)); waits up to 1.5 s for a first sample | `DesktopHardware.resource` |
| `GET /control/v1/hardware/events` | One full `hardware` sample per SSE frame at 1 Hz; connection renews after 120 frames; shares the eight-stream limit with `/events` | `DesktopHardware.events`, `DesktopStreamLimiter` |
@@ -89,6 +93,14 @@ Snapshots replace client state rather than applying deltas. Reconnection always
obtains a full snapshot. Normal snapshots omit credentials. Missing/stale native
observations are not evidence of zero memory usage or zero historical activity.
+The existing state snapshot adds `provider_status`, the fresh daemon trust status
+from the coordinator (`DesktopBackend.state`). It is `null` when the daemon is
+stale or only the local endpoint is active. `readiness` retains the diagnostic
+event reason for compatibility; Electron derives the primary readiness label
+from lifecycle, loaded selected models, update requirements and `provider_status`
+(`assessReadiness`). `untrusted` requires verification; `offline` waits for the
+network. A ready Mac shows a loaded-model count, distinct from processing counts.
+
### Live model activity and account insights
`DaemonState.Capacity.modelActivity` and `activityObservedAt` are additive local
@@ -102,13 +114,16 @@ observation time; refreshing the control API cannot make old capacity fresh.
Missing fields on older runtimes remain unknown, rather than becoming zero.
`account_revision` is an opaque process-local session marker that changes when
-the linked credential changes. It contains no token or token hash. The renderer
+the dashboard credential or coordinator changes. It contains no token or token hash. The renderer
uses it to discard old account analytics; `DesktopBackend.resource` also rejects
an in-flight private response if the credential changed while awaiting it.
The insights resources map to
-`GET /v1/provider/desktop/insights?window=7d|30d`. The Swift backend supplies the
-provider token; Electron receives no credential or configurable request URL.
+`GET /v1/provider/account-earnings?window=7d|30d`. Swift owns the separate
+dashboard account session; Electron receives no credential or configurable request URL.
+Before the first dashboard sign-in, existing linked-provider earnings remain
+available as a migration fallback. Signing out disables that fallback for account views.
+Local session settlement backfill remains separate (`DesktopAccountCredential`, `accountReadToken`, `usageCredentialToken`).
All money and token counters in the insights response cross the boundary as decimal strings. The renderer
uses `BigInt` for totals, shares, averages, milestones, and CSV serialization;
only normalized chart geometry and abbreviated labels use floating point.
@@ -184,10 +199,15 @@ that cleanup completes, then the operation becomes `cancelled`.
| Action | Additional fields | Behavior |
|---|---|---|
| `start` | `models`; optional `local`, `endpoint` | Existing start path; local-only mode uses the same canonical provider LaunchAgent |
+| `autopilot` | `models`, `pinned`; optional `downloads`, `endpoint` | Complete selected native downloads, then verified `start --autopilot --model …`; pin only after successful start. Fail before enrollment when a download fails |
+| `autopilot_pin`, `autopilot_unpin` | `models` | Existing CLI pin/unpin; pin budget is rechecked against downloaded estimates and configured slots |
+| `autopilot_pause`, `autopilot_resume`, `autopilot_disable` | — | Existing CLI policy commands |
+| `autopilot_models` | — | Explicit saved startup selection through `start --autopilot`; same inventory verification and drain/restart as the CLI wizard, preserving live endpoint options |
| `switch` | `models` | Existing validated live model-switch path |
| `stop`, `restart` | — | Existing native drain; local-only owner uses its registered native termination handler |
| `download`, `remove` | `model` | Native model management; removal refuses models reported serving/resident |
| `settings` | `revision`, `name`, `idle_minutes`, `auto_update`; optional `schedule`, `startup_preload` | Expected-revision check and mutation under the existing configuration lock |
+| `account-signin`, `account-signout` | — | Separate dashboard session; browser approval, owner-only storage, cache clearing; provider credentials remain independent |
| `link`, `unlink` | — | Native provider account linking/logout; UI does not retain the token |
| `update` | — | Existing verified native updater and lifecycle exclusion |
| `diagnose` | — | Existing `doctor` checks; result output is bounded |
@@ -200,26 +220,77 @@ or parsing terminal output to determine state. Settings reuse `withMutableConfig
Process output is bounded diagnostic detail; the native exit status determines
operation success (`DesktopWorker`, `DesktopBackend.execute`).
-## Coordinator projection
-
-`GET /v1/provider/desktop` accepts only an active provider device token linked
-to an account, and returns only that account's fleet status and earnings.
-Privy JWTs, the admin key, consumer API keys and revoked tokens are rejected
-(`requireDesktopProviderToken`). Revocation is checked on every request, before
-the cached result is served. Requests count against the account's shared
-per-account rate limiter (the same bucket as inference, reported under the
-`desktop` tier); excess requests get `429` with `Retry-After` (`rateLimitDesktop`).
-The projection is cached for 20 seconds per account. The optional
-`X-Darkbloom-Device-Identity` header never keys that cache: each request matches
-it against the cached fleet's keys to set `is_this_mac`, and it is not
-authentication (`coordinator/api/desktop_handlers.go`, `handleDesktopAccount`,
-`forIdentity`).
-
-Account monetary totals are decimal integer strings in micro-USD. Per-machine
-`earnings_micro_usd` is observed organic usage earnings over the last seven days,
-excluding base rewards; it is omitted when attribution is unavailable. The
-projection omits raw device keys, attestation evidence, and hardware control
-endpoints. Remote machines are read-only in the app.
+Local review builds using `DARKBLOOM_DESKTOP_ATTACH_ONLY=1` run operation children
+through the verified installed Darkbloom CLI, preserving the signed serving
+installation (`Desktop.Serve.run`, `DesktopFanRuntime.resolve`). Normal builds
+invoke their own shared CLI executable.
+
+`Snapshot.autopilot` contains `configured` (consent recorded), `enabled`, `paused`,
+`selected` and `pinned`. Its `phase` is populated only by a fresh live daemon;
+enrollment alone never implies active control (`DesktopBackend.autopilotSnapshot`).
+`memory.pin_budget_gb` and `memory.max_model_slots` expose the shared startup
+allowance and current/configured slot limit (`DesktopBackend.state`). Pins protect
+from unloading while Autopilot controls residency; a cold pin is not reported as
+loaded. Operations optionally report the current download `model` and `progress`
+in `[0,1]` (`DesktopBackend.runAutopilot`, `downloadProgress`).
+
+## Account session and refresh
+
+`DesktopBackend.accountCloud` combines `/v1/me/providers`, `/v1/me/summary`,
+and windowed `/v1/provider/account-earnings` reads. The owned fleet's SE identity
+identifies This Mac; remote models come from loaded `running`/`idle` slots when
+capacity exists. Missing per-machine money stays unknown. The renderer receives
+only the UI projection (`DesktopAccountCloud.swift`, `projectAccountCloud`).
+
+The account footer displays `state.account.email` with Signed in. Swift obtains
+identity from the existing `/v1/provider/account-earnings` response's optional
+`email`, persists it with the coordinator-scoped dashboard credential, and shares
+the same cached ledger request with stats and earnings (`DesktopAccountIdentity`).
+State polling hydrates older credentials even when the provider is stopped;
+missing identity leaves Account as the label. Sign-out removes the identity,
+and replies from another coordinator/session cannot update it. Coordinators must
+include the authenticated owner's email in that response for the address to appear.
+
+`account-signin` and `darkbloom desktop login` reuse the browser device-code flow
+with `purpose=desktop_account`. The bottom-left account button opens a modal with
+the snapshot's `link.code`, copy, explicit Continue in browser and cancellation controls
+(`AccountControl`, `AccountSignInProgress`). Electron sets
+`automaticallyOpenBrowser=false` in the shared login client; `darkbloom login` and
+`darkbloom desktop login` retain the default automatic launch. Closing the dialog
+preserves pending approval and Continue sign-in reopens it. Completion, failure or
+cancellation hides the code; failure supports retry. No additional endpoint is needed.
+The browser uses its Privy session to approve
+read-only access on coordinators that acknowledge that scope. Older coordinators
+that omit the purpose use their existing provider device-code grant; the browser
+shows the standard device-link approval. Swift accepts only the matching token
+prefix for the negotiated grant and never downgrades an acknowledged scoped grant
+(`ProviderCore/Auth/DeviceLoginScope.swift`, `DeviceLoginScope`). This legacy token
+has provider privileges on the server, but the dashboard uses it only for account
+reads and stores it separately from the serving credential. Local dashboard use
+expires after 30 days in both cases, in an owner-only, coordinator-scoped file
+under `DARKBLOOM_DESKTOP_DIR`.
+The renderer never receives it. Expiry or revocation requires sign-in again.
+`account-signout` and `darkbloom desktop logout` clear the local credential and
+account caches and attempt bounded server revocation for scoped sessions; offline
+sign-out can leave them valid until expiry. Legacy coordinators have no account
+revocation endpoint or server expiry, so legacy sign-out removes only local access.
+Neither command changes the provider's
+`AuthTokenStore` credential (`DesktopAccountCredential.swift`, `DesktopAccountCommands.swift`).
+
+`DesktopResourceCache.swift` (`cachedResource`) coalesces reads and caches account
+and public data for 30 seconds, releases for one hour. Failed reads back off
+from 30 seconds to four minutes; credential changes discard old in-flight results. The local state stream
+includes `resource_revision` on the native 30-second clock. Mounted views use it
+as their refresh signal; unrelated pages make no resource reads (`pageResources`).
+The catalog refresh runs independently of local snapshots. Legacy global identity
+roster reads are cached for five minutes; authenticated account sessions use the
+owned fleet instead (`refreshUsageHistoryIfNeeded`). Operation waiters consume
+state events, falling back to a state read after ten seconds of stream silence
+(`desktop-app/src/renderer/actions.ts`, `submitAction`).
+
+The earlier `/v1/provider/desktop`, `/v1/provider/desktop/insights`, and
+`/v1/releases/desktop` routes remain compatibility surfaces. The app no longer
+requests them (`DesktopBackend.readRemoteResource`).
## Lifetime and updates
@@ -230,7 +301,7 @@ made in macOS Login Items. The app starts hidden when macOS reports
`shouldStartHidden`). Explicitly quitting Electron does not stop the provider or
CLI API process. Stop/restart
buttons call the backend. The API process checks for native updates every four
-hours when the saved automatic-update setting is enabled
+hours when automatic updates are enabled and the serving provider is stopped
(`DesktopBackend.automaticUpdates`). The existing native updater owns verification,
draining, installation and quarantine. Electron's updater owns only the GUI.
Its feed exists only when `DARKBLOOM_DESKTOP_UPDATE_URL` is set at build time;
diff --git a/provider-swift/Sources/ProviderCore/Auth/DeviceAuth.swift b/provider-swift/Sources/ProviderCore/Auth/DeviceAuth.swift
index ebc4106fef..f8faeb4081 100644
--- a/provider-swift/Sources/ProviderCore/Auth/DeviceAuth.swift
+++ b/provider-swift/Sources/ProviderCore/Auth/DeviceAuth.swift
@@ -82,26 +82,6 @@ public enum AuthTokenStore: Sendable {
// MARK: - Device Code Flow
-/// Response from POST /v1/device/code
-private struct DeviceCodeResponse: Decodable, Sendable {
- let device_code: String
- let user_code: String
- let verification_uri: String
- let expires_in: Int
- let interval: Int
-}
-
-/// Response from POST /v1/device/token
-private struct DeviceTokenResponse: Decodable, Sendable {
- let status: String?
- let token: String?
- let error: TokenError?
-
- struct TokenError: Decodable, Sendable {
- let message: String?
- }
-}
-
public enum DeviceAuthError: Error, CustomStringConvertible, Sendable {
case alreadyLoggedIn(tokenPrefix: String)
case coordinatorUnreachable(String)
@@ -152,116 +132,20 @@ public func coordinatorHTTPBase(_ wsURL: String) -> String {
/// Called once when the device code is received. The caller should print
/// these to the terminal. Parameters: (userCode, verificationURI, expiresInSeconds).
/// - onPollTick: Optional callback on each poll iteration (e.g., to print a dot).
+/// - automaticallyOpenBrowser: Open verification immediately by default. Desktop UI
+/// disables this so the user can read the code before choosing Open sign-in.
/// - Returns: The auth token string on success.
/// - Throws: `DeviceAuthError` on failure.
@discardableResult
public func performDeviceCodeLogin(
coordinatorURL: String,
onDisplayCode: @Sendable (String, String, Int) -> Void,
- onPollTick: (@Sendable () -> Void)? = nil
+ onPollTick: (@Sendable () -> Void)? = nil,
+ purpose: String? = nil,
+ allowLegacyAccountFlow: Bool = false,
+ automaticallyOpenBrowser: Bool = true
) async throws -> String {
- // Check if already logged in.
- if let existingToken = AuthTokenStore.load() {
- let prefix = String(existingToken.prefix(min(20, existingToken.count)))
- throw DeviceAuthError.alreadyLoggedIn(tokenPrefix: prefix)
- }
-
- let baseURL = coordinatorHTTPBase(coordinatorURL)
-
- // Step 1: Request a device code.
- let codeURL = URL(string: "\(baseURL)/v1/device/code")!
- var codeRequest = URLRequest(url: codeURL)
- codeRequest.httpMethod = "POST"
- codeRequest.timeoutInterval = 10
-
- let codeData: Data
- let codeResponse: URLResponse
- do {
- (codeData, codeResponse) = try await URLSession.shared.data(for: codeRequest)
- } catch {
- throw DeviceAuthError.coordinatorUnreachable(error.localizedDescription)
- }
-
- guard let httpResponse = codeResponse as? HTTPURLResponse else {
- throw DeviceAuthError.invalidResponse("non-HTTP response")
- }
- guard httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 else {
- let body = String(data: codeData, encoding: .utf8) ?? ""
- throw DeviceAuthError.deviceCodeRequestFailed(body)
- }
-
- let dc: DeviceCodeResponse
- do {
- dc = try JSONDecoder().decode(DeviceCodeResponse.self, from: codeData)
- } catch {
- throw DeviceAuthError.invalidResponse("could not decode device code response: \(error)")
- }
-
- // Display the code to the user.
- onDisplayCode(dc.user_code, dc.verification_uri, dc.expires_in)
-
- // Try to open the browser automatically.
- let openProcess = Process()
- openProcess.executableURL = URL(fileURLWithPath: "/usr/bin/open")
- openProcess.arguments = [dc.verification_uri]
- openProcess.standardOutput = FileHandle.nullDevice
- openProcess.standardError = FileHandle.nullDevice
- _ = try? openProcess.run()
-
- // Step 2: Poll for authorization.
- let tokenURL = URL(string: "\(baseURL)/v1/device/token")!
- let pollInterval = max(dc.interval, 1) // At least 1 second
- let deadline = Date().addingTimeInterval(TimeInterval(dc.expires_in))
-
- while Date() < deadline {
- try await Task.sleep(nanoseconds: UInt64(pollInterval) * 1_000_000_000)
-
- var tokenRequest = URLRequest(url: tokenURL)
- tokenRequest.httpMethod = "POST"
- tokenRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
- tokenRequest.timeoutInterval = 10
-
- let body = try JSONSerialization.data(
- withJSONObject: ["device_code": dc.device_code]
- )
- tokenRequest.httpBody = body
-
- let tokenData: Data
- do {
- (tokenData, _) = try await URLSession.shared.data(for: tokenRequest)
- } catch {
- // Network error -- retry on next tick.
- onPollTick?()
- continue
- }
-
- let tokenResp: DeviceTokenResponse
- do {
- tokenResp = try JSONDecoder().decode(DeviceTokenResponse.self, from: tokenData)
- } catch {
- // Malformed response -- retry.
- onPollTick?()
- continue
- }
-
- switch tokenResp.status ?? "" {
- case "authorization_pending":
- onPollTick?()
- continue
-
- case "authorized":
- guard let token = tokenResp.token, !token.isEmpty else {
- throw DeviceAuthError.invalidResponse("authorized but no token in response")
- }
- try AuthTokenStore.save(token)
- return token
-
- default:
- // expired or error
- let message = tokenResp.error?.message ?? "Device code expired or invalid"
- throw DeviceAuthError.authorizationFailed(message)
- }
- }
-
- throw DeviceAuthError.deviceCodeExpired
+ try await DeviceLoginClient().login(coordinatorURL: coordinatorURL, onDisplayCode: onDisplayCode,
+ onPollTick: onPollTick, purpose: purpose, allowLegacyAccountFlow: allowLegacyAccountFlow,
+ automaticallyOpenBrowser: automaticallyOpenBrowser)
}
diff --git a/provider-swift/Sources/ProviderCore/Auth/DeviceCodeLogin.swift b/provider-swift/Sources/ProviderCore/Auth/DeviceCodeLogin.swift
new file mode 100644
index 0000000000..bae464e36a
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Auth/DeviceCodeLogin.swift
@@ -0,0 +1,137 @@
+import Foundation
+
+struct DeviceLoginClient {
+ let session: URLSession
+ let openBrowser: @Sendable (String) -> Void
+ let saveProviderToken: @Sendable (String) throws -> Void
+
+ init(session: URLSession = .shared,
+ openBrowser: @escaping @Sendable (String) -> Void = Self.openSystemBrowser,
+ saveProviderToken: @escaping @Sendable (String) throws -> Void = AuthTokenStore.save) {
+ self.session = session
+ self.openBrowser = openBrowser
+ self.saveProviderToken = saveProviderToken
+ }
+
+ static func openSystemBrowser(_ url: String) {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/open")
+ process.arguments = [url]
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ _ = try? process.run()
+ }
+
+ func login(coordinatorURL: String,
+ onDisplayCode: @Sendable (String, String, Int) -> Void,
+ onPollTick: (@Sendable () -> Void)? = nil,
+ purpose: String? = nil,
+ allowLegacyAccountFlow: Bool = false,
+ automaticallyOpenBrowser: Bool = true) async throws -> String {
+ // Check if already logged in.
+ if purpose == nil, let existingToken = AuthTokenStore.load() {
+ let prefix = String(existingToken.prefix(min(20, existingToken.count)))
+ throw DeviceAuthError.alreadyLoggedIn(tokenPrefix: prefix)
+ }
+
+ let baseURL = coordinatorHTTPBase(coordinatorURL)
+
+ // Step 1: Request a device code.
+ let codeURL = URL(string: "\(baseURL)/v1/device/code")!
+ var codeRequest = URLRequest(url: codeURL)
+ codeRequest.httpMethod = "POST"
+ codeRequest.timeoutInterval = 10
+ if let purpose {
+ guard purpose == "desktop_account" else { throw DeviceAuthError.invalidResponse("unsupported authorization purpose") }
+ codeRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ codeRequest.httpBody = try JSONSerialization.data(withJSONObject: ["purpose": purpose])
+ }
+
+ let codeData: Data
+ let codeResponse: URLResponse
+ do {
+ (codeData, codeResponse) = try await session.data(for: codeRequest)
+ } catch {
+ throw DeviceAuthError.coordinatorUnreachable(error.localizedDescription)
+ }
+
+ guard let httpResponse = codeResponse as? HTTPURLResponse else {
+ throw DeviceAuthError.invalidResponse("non-HTTP response")
+ }
+ guard httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 else {
+ let body = String(data: codeData, encoding: .utf8) ?? ""
+ throw DeviceAuthError.deviceCodeRequestFailed(body)
+ }
+
+ let dc: DeviceCodeResponse
+ do {
+ dc = try JSONDecoder().decode(DeviceCodeResponse.self, from: codeData)
+ } catch {
+ throw DeviceAuthError.invalidResponse("could not decode device code response: \(error)")
+ }
+
+ let scope = try DeviceLoginScope.negotiate(purpose: purpose, response: dc, allowLegacyAccountFlow: allowLegacyAccountFlow)
+ // Display the code to the user.
+ onDisplayCode(dc.user_code, dc.verification_uri, dc.expires_in)
+
+ if automaticallyOpenBrowser { openBrowser(dc.verification_uri) }
+
+ // Step 2: Poll for authorization.
+ let tokenURL = URL(string: "\(baseURL)/v1/device/token")!
+ let pollInterval = max(dc.interval, 1) // At least 1 second
+ let deadline = Date().addingTimeInterval(TimeInterval(dc.expires_in))
+
+ while Date() < deadline {
+ try await Task.sleep(nanoseconds: UInt64(pollInterval) * 1_000_000_000)
+
+ var tokenRequest = URLRequest(url: tokenURL)
+ tokenRequest.httpMethod = "POST"
+ tokenRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ tokenRequest.timeoutInterval = 10
+
+ let body = try JSONSerialization.data(
+ withJSONObject: ["device_code": dc.device_code]
+ )
+ tokenRequest.httpBody = body
+
+ let tokenData: Data
+ do {
+ (tokenData, _) = try await session.data(for: tokenRequest)
+ } catch {
+ // Network error -- retry on next tick.
+ onPollTick?()
+ continue
+ }
+
+ let tokenResp: DeviceTokenResponse
+ do {
+ tokenResp = try JSONDecoder().decode(DeviceTokenResponse.self, from: tokenData)
+ } catch {
+ // Malformed response -- retry.
+ onPollTick?()
+ continue
+ }
+
+ switch tokenResp.status ?? "" {
+ case "authorization_pending":
+ onPollTick?()
+ continue
+
+ case "authorized":
+ guard let token = tokenResp.token, !token.isEmpty else {
+ throw DeviceAuthError.invalidResponse("authorized but no token in response")
+ }
+ try scope.validate(token: token, purpose: tokenResp.purpose)
+ if scope == .provider { try saveProviderToken(token) }
+ return token
+
+ default:
+ // expired or error
+ let message = tokenResp.error?.message ?? "Device code expired or invalid"
+ throw DeviceAuthError.authorizationFailed(message)
+ }
+ }
+
+ throw DeviceAuthError.deviceCodeExpired
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Auth/DeviceLoginScope.swift b/provider-swift/Sources/ProviderCore/Auth/DeviceLoginScope.swift
new file mode 100644
index 0000000000..16cef40f5d
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Auth/DeviceLoginScope.swift
@@ -0,0 +1,57 @@
+import Foundation
+
+/// Response from POST /v1/device/code
+struct DeviceCodeResponse: Decodable, Sendable {
+ let device_code: String
+ let user_code: String
+ let verification_uri: String
+ let expires_in: Int
+ let interval: Int
+ let purpose: String?
+}
+
+/// Response from POST /v1/device/token
+struct DeviceTokenResponse: Decodable, Sendable {
+ let status: String?
+ let token: String?
+ let purpose: String?
+ let error: TokenError?
+
+ struct TokenError: Decodable, Sendable {
+ let message: String?
+ }
+}
+
+// Scope is negotiated before opening the browser; an account login never replaces the
+// provider's AuthTokenStore, even on coordinators that only implement provider device grants.
+enum DeviceLoginScope {
+ case provider, desktopAccount, legacyAccount
+
+ static func negotiate(purpose: String?, response: DeviceCodeResponse,
+ allowLegacyAccountFlow: Bool) throws -> Self {
+ guard purpose != nil else { return .provider }
+ if response.purpose == "desktop_account", response.device_code.hasPrefix("desktop-account-") {
+ return .desktopAccount
+ }
+ if allowLegacyAccountFlow, [nil, "provider"].contains(response.purpose),
+ !response.device_code.hasPrefix("desktop-account-") {
+ return .legacyAccount
+ }
+ throw DeviceAuthError.authorizationFailed("This coordinator does not support desktop account sign-in yet.")
+ }
+
+ func validate(token: String, purpose: String?) throws {
+ switch self {
+ case .provider: break
+ case .desktopAccount:
+ guard purpose == "desktop_account", token.hasPrefix("darkbloom-at-") else {
+ throw DeviceAuthError.invalidResponse("wrong account token scope")
+ }
+ case .legacyAccount:
+ guard [nil, "provider"].contains(purpose), token.hasPrefix("eigeninference-pt-") else {
+ throw DeviceAuthError.invalidResponse("wrong legacy account token scope")
+ }
+ }
+ }
+}
+
diff --git a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClientState.swift b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClientState.swift
index 37a064ac51..f7ebf474a0 100644
--- a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClientState.swift
+++ b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClientState.swift
@@ -12,6 +12,9 @@ import os
public final class AtomicProviderStats: Sendable {
private let _requestsServed = ManagedAtomic(0)
private let _tokensGenerated = ManagedAtomic(0)
+ private let _promptTokensProcessed = ManagedAtomic(0)
+ private let _cachedInputTokens = ManagedAtomic(0)
+ private let _reasoningTokens = ManagedAtomic(0)
private let _cancellationsReceived = ManagedAtomic(0)
private let _cancellationsBeforeOutput = ManagedAtomic(0)
private let _cancellationsPartialComplete = ManagedAtomic(0)
@@ -117,6 +120,18 @@ public final class AtomicProviderStats: Sendable {
_requestsServed.add(1)
}
+ /// Includes cached prompt tokens; output usage already contains reasoning.
+ public var promptTokensProcessed: UInt64 { _promptTokensProcessed.load() }
+
+ public func addPromptTokensProcessed(_ count: UInt64) {
+ _promptTokensProcessed.add(count)
+ }
+
+ public var cachedInputTokens: UInt64 { _cachedInputTokens.load() }
+ public var reasoningTokens: UInt64 { _reasoningTokens.load() }
+ public func addCachedInputTokens(_ count: UInt64) { _cachedInputTokens.add(count) }
+ public func addReasoningTokens(_ count: UInt64) { _reasoningTokens.add(count) }
+
public func addTokensGenerated(_ count: UInt64) {
_tokensGenerated.add(count)
}
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift
index ed587b3bae..c24ec0173b 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift
@@ -1422,6 +1422,7 @@ extension ProviderLoop {
// Update stats
providerStats.incrementRequestsServed()
providerStats.addTokensGenerated(UInt64(max(completionTokens, 0)))
+ providerStats.addPromptTokensProcessed(UInt64(max(promptTokens, 0)))
// Commit the TTFT sample (routing v2): completed real requests
// only — a cancelled stream's first-token timing is still real,
@@ -1459,6 +1460,14 @@ extension ProviderLoop {
prefillTokensSaved: cacheResult.map { UInt64(max(0, $0.prefillTokensSaved)) },
cacheStageMs: cacheResult?.stageMs
)
+ let localCachedTokens = min(usageInfo.promptTokens, usageInfo.cachedTokens ?? UInt64(max(0, v2UsageSignal.prefixCacheHitTokens ?? 0)))
+ providerStats.addCachedInputTokens(localCachedTokens)
+ providerStats.addReasoningTokens(min(usageInfo.reasoningTokens, usageInfo.completionTokens))
+ await me.recordLocalUsage(ProviderUsageRecord(
+ id: requestId, sessionStartedAt: me.startedAtEpoch, model: modelId,
+ inputTokens: usageInfo.promptTokens, outputTokens: usageInfo.completionTokens,
+ cachedInputTokens: localCachedTokens, reasoningTokens: usageInfo.reasoningTokens,
+ exact: !usageRecovered))
finalizeProfile(framesEmitted, bytesEmitted, usageRecovered, seSignDuration)
lookupReceiptFinalizer.sendTerminal(
.inferenceComplete(
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift
index fa1f9ff7cd..a9bd892fcf 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift
@@ -61,7 +61,10 @@ extension ProviderLoop {
stats: DaemonState.Stats(
requestsServed: stats.requestsServed,
tokensGenerated: stats.tokensGenerated,
- usageGaps: stats.usageGaps
+ usageGaps: stats.usageGaps,
+ promptTokensProcessed: self.stats.promptTokensProcessed,
+ cachedInputTokens: self.stats.cachedInputTokens,
+ reasoningTokens: self.stats.reasoningTokens
),
capacity: cap.map {
DaemonState.Capacity(
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+UsageHistory.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+UsageHistory.swift
new file mode 100644
index 0000000000..99f603b0b1
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+UsageHistory.swift
@@ -0,0 +1,5 @@
+extension ProviderLoop {
+ func recordLocalUsage(_ record: ProviderUsageRecord) {
+ usageHistory.enqueue(record)
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift
index 46e34526f5..f3725fc067 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift
@@ -217,6 +217,7 @@ public actor ProviderLoop {
internal let signer: (any AttestationSigner)?
internal let attestationBuilder: AttestationBuilder?
internal let stats: AtomicProviderStats
+ internal let usageHistory = ProviderUsageHistory()
internal let state: ProviderState
internal let cancellationRegistry: InferenceCancellationRegistry
internal let kvBudget: GlobalKVCacheBudget
diff --git a/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift b/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift
index 0863499d16..05e0ddc50b 100644
--- a/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift
+++ b/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift
@@ -114,10 +114,17 @@ public struct DaemonState: Codable, Sendable, Equatable {
public var requestsServed: UInt64
public var tokensGenerated: UInt64
public var usageGaps: UInt64
- public init(requestsServed: UInt64 = 0, tokensGenerated: UInt64 = 0, usageGaps: UInt64 = 0) {
+ /// Nil on older runtimes; all prompt tokens including prefix-cache hits.
+ public var promptTokensProcessed: UInt64?
+ public var cachedInputTokens: UInt64?
+ public var reasoningTokens: UInt64?
+ public init(requestsServed: UInt64 = 0, tokensGenerated: UInt64 = 0, usageGaps: UInt64 = 0, promptTokensProcessed: UInt64? = nil, cachedInputTokens: UInt64? = nil, reasoningTokens: UInt64? = nil) {
self.requestsServed = requestsServed
self.tokensGenerated = tokensGenerated
self.usageGaps = usageGaps
+ self.promptTokensProcessed = promptTokensProcessed
+ self.cachedInputTokens = cachedInputTokens
+ self.reasoningTokens = reasoningTokens
}
}
diff --git a/provider-swift/Sources/ProviderCore/Service/ProviderUsageHistory.swift b/provider-swift/Sources/ProviderCore/Service/ProviderUsageHistory.swift
new file mode 100644
index 0000000000..a252dcc9d3
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Service/ProviderUsageHistory.swift
@@ -0,0 +1,77 @@
+import Foundation
+#if canImport(Darwin)
+import Darwin
+#else
+import Glibc
+#endif
+
+/// Usage metadata only: never prompts, output text, credentials, or request bodies.
+public struct ProviderUsageRecord: Codable, Sendable, Equatable {
+ public let id: String
+ public let sessionStartedAt: Double
+ public let completedAt: Double
+ public let model: String
+ public let inputTokens: UInt64
+ public let outputTokens: UInt64
+ public let cachedInputTokens: UInt64?
+ public let reasoningTokens: UInt64?
+ public let exact: Bool
+
+ public init(id: String, sessionStartedAt: Double, completedAt: Double = Date().timeIntervalSince1970,
+ model: String, inputTokens: UInt64, outputTokens: UInt64,
+ cachedInputTokens: UInt64?, reasoningTokens: UInt64?, exact: Bool) {
+ self.id = id; self.sessionStartedAt = sessionStartedAt; self.completedAt = completedAt
+ self.model = model; self.inputTokens = inputTokens; self.outputTokens = outputTokens
+ self.cachedInputTokens = cachedInputTokens.map { min($0, inputTokens) }
+ self.reasoningTokens = reasoningTokens.map { min($0, outputTokens) }; self.exact = exact
+ }
+}
+
+/// A bounded, owner-only journal shared by the provider and desktop reader.
+/// Atomic replacement keeps readers from observing half of a terminal record.
+public final class ProviderUsageHistory: @unchecked Sendable {
+ public static var defaultURL: URL {
+ FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".darkbloom/usage-history.json")
+ }
+ private let queue = DispatchQueue(label: "dev.darkbloom.usage-history")
+ private let lock = NSLock()
+ private let url: URL
+ private var records: [ProviderUsageRecord]
+ public init(url: URL = defaultURL) {
+ self.url = url; records = Self.read(url: url)
+ }
+ public static func read(url: URL = defaultURL) -> [ProviderUsageRecord] {
+ guard let attrs = try? FileManager.default.attributesOfItem(atPath: url.path),
+ attrs[.type] as? FileAttributeType == .typeRegular,
+ (attrs[.ownerAccountID] as? NSNumber)?.uint32Value == getuid(),
+ let data = try? Data(contentsOf: url), data.count <= 4_000_000 else { return [] }
+ return (try? JSONDecoder().decode([ProviderUsageRecord].self, from: data)) ?? []
+ }
+ /// Terminal responses never wait on journal disk I/O.
+ public func enqueue(_ record: ProviderUsageRecord) {
+ queue.async { [self] in
+ do { try self.record(record) }
+ catch { ProviderLogger(subsystem: "dev.darkbloom.provider", category: "usage").warning("Local usage history could not be saved") }
+ }
+ }
+ @discardableResult public func record(_ record: ProviderUsageRecord) throws -> Bool {
+ lock.lock(); defer { lock.unlock() }
+ guard !records.contains(where: { $0.id == record.id && $0.sessionStartedAt == record.sessionStartedAt }) else { return false }
+ let next = Array((records + [record]).suffix(4096))
+ let fm = FileManager.default
+ let directory = url.deletingLastPathComponent()
+ try fm.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
+ let attrs = try fm.attributesOfItem(atPath: directory.path)
+ guard attrs[.type] as? FileAttributeType == .typeDirectory,
+ (attrs[.ownerAccountID] as? NSNumber)?.uint32Value == getuid() else { throw CocoaError(.fileWriteNoPermission) }
+ let temporary = directory.appendingPathComponent(".usage-\(UUID().uuidString)")
+ let fd = open(temporary.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)
+ guard fd >= 0 else { throw CocoaError(.fileWriteNoPermission) }
+ let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
+ defer { try? fm.removeItem(at: temporary) }
+ try handle.write(contentsOf: JSONEncoder().encode(next)); try handle.synchronize(); try handle.close()
+ guard rename(temporary.path, url.path) == 0 else { throw CocoaError(.fileWriteUnknown) }
+ records = next
+ return true
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopAccountActions.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountActions.swift
new file mode 100644
index 0000000000..56faa2eb61
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountActions.swift
@@ -0,0 +1,28 @@
+import Foundation
+import ProviderCore
+
+extension DesktopBackend {
+ func executeAccountAction(_ request: DesktopAction) async throws {
+ if request.action == "account-signin" {
+ let config = try configuration().config
+ let base = coordinatorHTTPBase(config.coordinator.url)
+ let token = try await performDeviceCodeLogin(coordinatorURL: base, onDisplayCode: { [weak self] code, url, seconds in
+ Task { await self?.setLink(request.id, .dict(["url": .string(url), "code": .string(code), "expires_at": .number(Date().timeIntervalSince1970 + Double(seconds)), "state": .string("waiting")])) }
+ }, purpose: "desktop_account", allowLegacyAccountFlow: true, automaticallyOpenBrowser: false)
+ try Task.checkCancellation()
+ try DesktopAccountCredential.save(token: token, base: base)
+ clearAccountResources()
+ link = .null
+ complete(request.id, code: 0, message: "Signed in.")
+ } else {
+ let base = coordinatorHTTPBase(try configuration().config.coordinator.url)
+ let credential = DesktopAccountCredential.load(base: base)
+ try DesktopAccountCredential.remove(base: base)
+ clearAccountResources()
+ // Local sign-out succeeds offline; server-side revocation is attempted with a bounded request.
+ if let credential { try? await Self.revokeAccount(base: base, token: credential.token) }
+ complete(request.id, code: 0, message: "Signed out.")
+
+ }
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopAccountCloud.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountCloud.swift
new file mode 100644
index 0000000000..dc2e27a923
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountCloud.swift
@@ -0,0 +1,66 @@
+import Foundation
+import ProviderCore
+
+extension DesktopBackend {
+ static func usageDate(_ value: String) -> Date? {
+ let iso = ISO8601DateFormatter(); iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ return iso.date(from: value) ?? ISO8601DateFormatter().date(from: value)
+ }
+ func accountCloud(base: String, token: String) async throws -> JSONValue {
+ async let fleetRead = cachedResource("owned-providers", base: base, token: token)
+ async let summaryRead = cachedResource("summary", base: base, token: token)
+ async let insightsRead = cachedResource("insights-week", base: base, token: token)
+ let (fleet, summary) = try await (fleetRead, summaryRead)
+ let insights = try? await insightsRead
+ guard accountCredentialToken() == token else { throw URLError(.userAuthenticationRequired) }
+ return Self.projectAccountCloud(fleet: fleet, summary: summary, identity: DaemonStateFile.read()?.attestationPublicKey, insights: insights)
+ }
+
+ static func projectAccountCloud(fleet: JSONValue, summary: JSONValue, identity: String?, insights: JSONValue? = nil) -> JSONValue {
+ let providers = fleet.field("providers").values
+ let local = identity.flatMap { key in providers.first { $0.field("se_public_key").text == key } }
+ func money(_ id: String?) -> JSONValue {
+ guard let id, let slice = insights?.field("machines").values.first(where: { $0.field("id").text == id }),
+ let work = usageInteger(slice.field("work_micro_usd")), let reward = usageInteger(slice.field("base_reward_micro_usd")) else { return .null }
+ return .string(String(work + reward))
+ }
+ let machines = providers.filter { provider in
+ guard let identity, !identity.isEmpty else { return true }
+ return provider.field("se_public_key").text != identity
+ }.map { provider -> JSONValue in
+ let hardware = provider.field("hardware")
+ let slots = provider.field("backend_capacity").field("slots").values
+ let loaded = slots.filter { ["running", "idle"].contains($0.field("state").text ?? "") }.compactMap { $0.field("model").text }
+ let models = slots.isEmpty ? provider.field("warm_models").values : loaded.map(DV.string)
+ let timestamp = provider.field("last_heartbeat").text ?? provider.field("last_seen").text
+ return .dict([
+ "id": provider.field("id"), "name": hardware.field("machine_model").text.map(DV.string) ?? .string("Mac"),
+ "chip": hardware.field("chip_name"), "memory_gb": hardware.field("memory_gb"),
+ "status": provider.field("status"), "version": provider.field("version"),
+ "earnings_micro_usd": money(provider.field("id").text),
+ "observed_at": .number(timestamp.flatMap(Self.usageDate)?.timeIntervalSince1970), "models": .array(models),
+ ])
+ }
+ return .dict([
+ "linked": .bool(true), "account_id": summary.field("account_id"),
+ "observed_at": .number(Date().timeIntervalSince1970), "machines": .array(machines),
+ "lifetime_micro_usd": integerText(summary.field("lifetime_micro_usd")),
+ "week_micro_usd": integerText(summary.field("last_7d_micro_usd")),
+ "balance_micro_usd": integerText(summary.field("withdrawable_balance_micro_usd")),
+ "earnings_complete": .bool(true), "local_provider_id": local?.field("id") ?? .null,
+ "minimum_provider_version": fleet.field("min_provider_version"),
+ "local_earnings_micro_usd": money(insights?.field("machines").values.contains(where: { $0.field("id").text == "this-mac" }) == true ? "this-mac" : local?.field("id").text),
+ ])
+ }
+
+ static func localizeInsights(_ value: JSONValue, providerID: String?) -> JSONValue {
+ guard let providerID, case .object(let pairs) = value else { return value }
+ var fields = Dictionary(uniqueKeysWithValues: pairs)
+ fields["machines"] = .array(value.field("machines").values.map { machine in
+ guard machine.field("id").text == providerID, case .object(let pairs) = machine else { return machine }
+ var fields = Dictionary(uniqueKeysWithValues: pairs); fields["id"] = .string("this-mac")
+ return .dict(fields)
+ })
+ return .dict(fields)
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopAccountCommands.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountCommands.swift
new file mode 100644
index 0000000000..ea0f00284f
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountCommands.swift
@@ -0,0 +1,29 @@
+import ArgumentParser
+import Foundation
+import ProviderCore
+
+extension Desktop {
+ struct Login: AsyncParsableCommand {
+ static let configuration = CommandConfiguration(abstract: "Sign in to the read-only desktop account dashboard.")
+ @OptionGroup var configOptions: ConfigOptions
+ mutating func run() async throws {
+ let base = coordinatorHTTPBase(try loadRuntimeConfiguration(configPath: configOptions.config).config.coordinator.url)
+ let token = try await performDeviceCodeLogin(coordinatorURL: base, onDisplayCode: { code, url, _ in
+ print("Open \(url) and authorize desktop access with code \(code).")
+ }, purpose: "desktop_account", allowLegacyAccountFlow: true)
+ try DesktopAccountCredential.save(token: token, base: base)
+ print("Signed in to the desktop dashboard.")
+ }
+ }
+ struct Logout: AsyncParsableCommand {
+ static let configuration = CommandConfiguration(abstract: "Sign out of the desktop dashboard.")
+ @OptionGroup var configOptions: ConfigOptions
+ mutating func run() async throws {
+ let base = coordinatorHTTPBase(try loadRuntimeConfiguration(configPath: configOptions.config).config.coordinator.url)
+ let credential = DesktopAccountCredential.load(base: base)
+ try DesktopAccountCredential.remove(base: base)
+ if let credential { try? await DesktopBackend.revokeAccount(base: base, token: credential.token) }
+ print("Signed out of the desktop dashboard.")
+ }
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopAccountCredential.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountCredential.swift
new file mode 100644
index 0000000000..df30e2c06e
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountCredential.swift
@@ -0,0 +1,76 @@
+import Crypto
+import Foundation
+import ProviderCore
+
+/// Native-only account credential, separate from AuthTokenStore and scoped to its coordinator.
+struct DesktopAccountCredential: Codable, Sendable {
+ let token: String
+ let base: String
+ let expiresAt: Date
+ var email: String? = nil
+
+ static func supports(token: String) -> Bool {
+ token.hasPrefix("darkbloom-at-") || token.hasPrefix("eigeninference-pt-")
+ }
+ static func filename(base: String) -> String {
+ let hash = SHA256.hash(data: Data(base.utf8)).map { String(format: "%02x", $0) }.joined()
+ return "account-\(hash).json"
+ }
+ static func legacyAllowed(base: String) -> Bool {
+ !(DesktopStorage.read(Bool.self, name: "disabled-" + filename(base: base)) ?? false)
+ }
+ static func load(base: String) -> Self? {
+ guard let value = DesktopStorage.read(Self.self, name: filename(base: base)),
+ value.base == base, Self.supports(token: value.token), value.expiresAt > Date()
+ else { return nil }
+ return value
+ }
+ static func save(token: String, base: String) throws {
+ guard supports(token: token) else { throw URLError(.userAuthenticationRequired) }
+ try DesktopStorage.write(true, name: "disabled-" + filename(base: base))
+ // Cap local dashboard use at 30 days. Scoped sessions also expire on the server;
+ // older coordinator provider grants have no server-side account-session expiry.
+ try DesktopStorage.write(Self(token: token, base: base, expiresAt: Date().addingTimeInterval(30 * 86400 - 60)), name: filename(base: base))
+ }
+ static func remove(base: String) throws {
+ try DesktopStorage.write(true, name: "disabled-" + filename(base: base))
+ let url = DesktopStorage.directory.appendingPathComponent(filename(base: base))
+ if FileManager.default.fileExists(atPath: url.path) { try FileManager.default.removeItem(at: url) }
+ }
+}
+
+extension DesktopBackend {
+ func accountCredentialToken() -> String? {
+ guard let config = try? configuration().config else { return nil }
+ return DesktopAccountCredential.load(base: coordinatorHTTPBase(config.coordinator.url))?.token
+ }
+ func accountReadToken() -> String? {
+ if let token = accountCredentialToken() { return token }
+ guard let config = try? configuration().config,
+ DesktopAccountCredential.legacyAllowed(base: coordinatorHTTPBase(config.coordinator.url)) else { return nil }
+ return AuthTokenStore.load()
+ }
+ func usageCredentialToken() -> String? { accountCredentialToken() ?? AuthTokenStore.load() }
+ func accountStatus() -> JSONValue {
+ guard let config = try? configuration().config,
+ let credential = DesktopAccountCredential.load(base: coordinatorHTTPBase(config.coordinator.url))
+ else { return .dict(["signed_in": .bool(false), "legacy_data": .bool(accountReadToken() != nil)]) }
+ return .dict(["signed_in": .bool(true), "email": credential.email.map(JSONValue.string) ?? .null,
+ "expires_at": .number(credential.expiresAt.timeIntervalSince1970)])
+ }
+ func clearAccountResources() {
+ resourceGeneration += 1
+ accountIdentityRead?.cancel(); accountIdentityRead = nil; accountIdentityReadAt = .distantPast
+ catalogTask?.cancel(); catalogTask = nil; catalogAt = .distantPast
+ accountEarningsTask?.task.cancel(); accountEarningsTask = nil; accountEarningsCache = nil
+ for task in resourceTasks.values { task.cancel() }; resourceTasks = [:]; resourceCache = [:]; resourceFailures = [:]
+ usageRead?.cancel(); usageRead = nil; usageReadAt = .distantPast; usageArchive = DesktopUsageArchive()
+ }
+ static func revokeAccount(base: String, token: String) async throws {
+ guard token.hasPrefix("darkbloom-at-") else { return }
+ guard let url = URL(string: "\(base)/v1/device/token") else { throw URLError(.badURL) }
+ var request = URLRequest(url: url); request.httpMethod = "DELETE"; request.timeoutInterval = 5
+ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ _ = try await URLSession.shared.data(for: request)
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopAccountEarnings.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountEarnings.swift
new file mode 100644
index 0000000000..f965025255
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountEarnings.swift
@@ -0,0 +1,129 @@
+import Foundation
+import ProviderCore
+
+/// Read-only aggregation of the existing account earnings response.
+/// Lifetime money comes from its summary; breakdowns only sum returned records.
+struct DesktopAccountEarnings {
+ struct Row {
+ let id: String
+ let at: Date
+ let key: String
+ let model: String
+ let money: UInt64
+ let input: UInt64
+ let output: UInt64
+ }
+ struct Amounts {
+ var work: UInt64 = 0, reward: UInt64 = 0, jobs: UInt64 = 0, input: UInt64 = 0, output: UInt64 = 0
+ mutating func add(_ row: Row) {
+ if row.model == "base_reward" { reward += row.money }
+ else { work += row.money; jobs += 1; input += row.input; output += row.output }
+ }
+ var json: [String: JSONValue] {
+ ["work_micro_usd": .string(String(work)), "base_reward_micro_usd": .string(String(reward)),
+ "jobs": .string(String(jobs)), "prompt_tokens": .string(String(input)), "completion_tokens": .string(String(output))]
+ }
+ }
+ let account: String
+ let lifetime: UInt64
+ let count: UInt64
+ let balance: JSONValue
+ let rows: [Row]
+ let localKeys: Set
+ let now: Date
+
+ init(_ value: JSONValue, localKeys: Set, now: Date = Date()) throws {
+ guard let account = value.field("account_id").text,
+ let lifetime = DesktopBackend.usageInteger(value.field("total_micro_usd")),
+ let count = DesktopBackend.usageInteger(value.field("count")) else { throw URLError(.cannotParseResponse) }
+ let iso = ISO8601DateFormatter(); iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ let plain = ISO8601DateFormatter()
+ var unique: [String: Row] = [:]
+ for item in value.field("earnings").values {
+ guard let id = DesktopBackend.integerText(item.field("id")).text,
+ let time = item.field("created_at").text, let at = iso.date(from: time) ?? plain.date(from: time),
+ let key = item.field("provider_key").text, let model = item.field("model").text,
+ let money = DesktopBackend.usageInteger(item.field("amount_micro_usd")),
+ let input = DesktopBackend.usageInteger(item.field("prompt_tokens")),
+ let output = DesktopBackend.usageInteger(item.field("completion_tokens")) else { throw URLError(.cannotParseResponse) }
+ unique[id] = Row(id: id, at: at, key: key, model: model, money: money, input: input, output: output)
+ }
+ self.account = account; self.lifetime = lifetime; self.count = count
+ self.balance = DesktopBackend.integerText(value.field("available_balance_micro_usd"))
+ self.rows = unique.values.sorted { $0.at < $1.at }; self.localKeys = localKeys; self.now = now
+ }
+
+ var calendar: Calendar {
+ var value = Calendar(identifier: .gregorian); value.timeZone = TimeZone(secondsFromGMT: 0)!; return value
+ }
+ func start(_ window: String) -> Date {
+ calendar.date(byAdding: .day, value: -(window == "30d" ? 29 : 6), to: calendar.startOfDay(for: now))!
+ }
+ var fullHistory: Bool {
+ let totals = sum(rows)
+ return totals.jobs == count && totals.work + totals.reward == lifetime
+ }
+ func complete(_ window: String) -> Bool {
+ fullHistory || rows.first.map { $0.at <= start(window) } == true
+ }
+ func selected(_ window: String) -> [Row] { rows.filter { $0.at >= start(window) && $0.at <= now } }
+ func sum(_ rows: [Row]) -> Amounts { rows.reduce(Amounts()) { totals, row in var totals = totals; totals.add(row); return totals } }
+
+ func cloud() -> JSONValue {
+ let recent = selected("7d")
+ let local = recent.filter { localKeys.contains($0.key) }
+ let localDay = local.filter { $0.at >= now.addingTimeInterval(-86400) }
+ return .dict([
+ "linked": .bool(true), "account_id": .string(account), "observed_at": .number(now.timeIntervalSince1970),
+ "lifetime_micro_usd": .string(String(lifetime)), "week_micro_usd": .string(String(sum(recent).work + sum(recent).reward)),
+ "balance_micro_usd": balance, "machines": .array([]),
+ "local_earnings_micro_usd": localKeys.isEmpty ? .null : .string(String(sum(local).work + sum(local).reward)),
+ "local_lifetime_micro_usd": .null,
+ "local_day_micro_usd": !localKeys.isEmpty && (fullHistory || rows.first.map { $0.at <= now.addingTimeInterval(-86400) } == true)
+ ? .string(String(sum(localDay).work + sum(localDay).reward)) : .null,
+ "earnings_complete": .bool(complete("7d")),
+ "earnings_since": .number((complete("7d") ? start("7d") : rows.first?.at ?? now).timeIntervalSince1970),
+ "settled_records": .string(String(count)),
+ ])
+ }
+
+ func insights(_ window: String) -> JSONValue {
+ let selected = selected(window), totals = sum(selected), all = sum(rows)
+ var days: [String: Amounts] = [:], models: [String: Amounts] = [:], machines: [String: Amounts] = [:]
+ let iso = ISO8601DateFormatter()
+ for row in selected {
+ let day = String(iso.string(from: row.at).prefix(10))
+ days[day, default: Amounts()].add(row)
+ models[row.model, default: Amounts()].add(row)
+ machines[localKeys.contains(row.key) ? "this-mac" : "", default: Amounts()].add(row)
+ }
+ let since = complete(window) ? start(window) : max(start(window), rows.first?.at ?? now)
+ var date = start(window)
+ while date <= now {
+ days[String(iso.string(from: date).prefix(10)), default: Amounts()] = days[String(iso.string(from: date).prefix(10))] ?? Amounts()
+ date = calendar.date(byAdding: .day, value: 1, to: date)!
+ }
+ func slices(_ values: [String: Amounts]) -> JSONValue {
+ .array(values.keys.sorted().map { id in var fields = values[id]!.json; fields["id"] = .string(id); return .dict(fields) })
+ }
+ let daily = days.keys.sorted().map { id -> JSONValue in
+ var fields = days[id]!.json
+ fields["id"] = .string(id)
+ let day = iso.date(from: "\(id)T00:00:00Z")!
+ let covered = complete(window) || day >= calendar.startOfDay(for: since)
+ fields["available"] = .bool(covered)
+ fields["complete"] = .bool(covered && day >= since && day < calendar.startOfDay(for: now))
+ return .dict(fields)
+ }
+ return .dict([
+ "account_id": .string(account), "window": .string(window), "since": .string(iso.string(from: since)),
+ "as_of": .string(iso.string(from: now)), "history_complete": .bool(complete(window)),
+ "lifetime": .dict([
+ "count": .string(String(count)), "total_micro_usd": .string(String(lifetime)),
+ "prompt_tokens": fullHistory ? .string(String(all.input)) : .null,
+ "completion_tokens": fullHistory ? .string(String(all.output)) : .null,
+ ]),
+ "totals": .dict(totals.json), "days": .array(daily), "models": slices(models), "machines": slices(machines),
+ ])
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopAccountEarningsCache.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountEarningsCache.swift
new file mode 100644
index 0000000000..5f1f4742c6
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountEarningsCache.swift
@@ -0,0 +1,25 @@
+import Crypto
+import Foundation
+import ProviderCore
+
+extension DesktopBackend {
+ /// Session usage, fleet totals and charts share the same existing ledger read.
+ func accountEarnings(base: String, token: String) async throws -> JSONValue {
+ let key = SHA256.hash(data: Data("\(base)\n\(token)".utf8)).map { String(format: "%02x", $0) }.joined()
+ if let cached = accountEarningsCache, cached.key == key, Date().timeIntervalSince(cached.at) < 30 { return cached.value }
+ let generation = resourceGeneration
+ if let pending = accountEarningsTask, pending.key == key {
+ let value = try await pending.task.value
+ guard generation == resourceGeneration, usageCredentialToken() == token else { throw URLError(.userAuthenticationRequired) }
+ return value
+ }
+ let task = Task { try await Self.readUsageJSON(base: base, path: "/v1/provider/account-earnings", token: token) }
+ accountEarningsTask = (key, task)
+ defer { if generation == resourceGeneration, accountEarningsTask?.key == key { accountEarningsTask = nil } }
+ let value = try await task.value
+ guard generation == resourceGeneration, usageCredentialToken() == token else { throw URLError(.userAuthenticationRequired) }
+ recordAccountIdentity(value, base: base, token: token)
+ accountEarningsCache = (key, Date(), value)
+ return value
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopAccountIdentity.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountIdentity.swift
new file mode 100644
index 0000000000..60f4dee52e
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountIdentity.swift
@@ -0,0 +1,36 @@
+import Foundation
+import ProviderCore
+
+extension DesktopAccountCredential {
+ /// Only attach identity returned for this exact coordinator and account session.
+ func withIdentity(_ value: JSONValue, base: String, token: String) -> Self {
+ guard self.base == base, self.token == token,
+ let email = value.field("email").text?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !email.isEmpty else { return self }
+ var updated = self
+ updated.email = email
+ return updated
+ }
+}
+
+extension DesktopBackend {
+ func recordAccountIdentity(_ value: JSONValue, base: String, token: String) {
+ guard let credential = DesktopAccountCredential.load(base: base) else { return }
+ let updated = credential.withIdentity(value, base: base, token: token)
+ guard updated.email != credential.email else { return }
+ try? DesktopStorage.write(updated, name: DesktopAccountCredential.filename(base: base))
+ }
+
+ /// Hydrate older logins and stopped Macs without introducing another coordinator API.
+ /// This joins the same cached/in-flight ledger read used by earnings and session stats.
+ func refreshAccountIdentityIfNeeded(base: String, now: Date) {
+ guard let credential = DesktopAccountCredential.load(base: base), credential.email == nil,
+ accountIdentityRead == nil, now.timeIntervalSince(accountIdentityReadAt) >= 30 else { return }
+ accountIdentityReadAt = now
+ let generation = resourceGeneration
+ accountIdentityRead = Task {
+ defer { if generation == resourceGeneration { accountIdentityRead = nil } }
+ _ = try? await accountEarnings(base: base, token: credential.token)
+ }
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopAutomaticUpdates.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopAutomaticUpdates.swift
index 6fc6f51b79..2ef0987b64 100644
--- a/provider-swift/Sources/darkbloom/Desktop/DesktopAutomaticUpdates.swift
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAutomaticUpdates.swift
@@ -8,7 +8,7 @@ extension DesktopBackend {
do { try await Task.sleep(for: .seconds(4 * 60 * 60)) } catch { return }
do {
let config = try configuration().config
- guard config.provider.autoUpdate else { continue }
+ guard config.provider.autoUpdate, DaemonStateFile.read()?.processIdentity?.isCurrent() != true else { continue }
let updater = SelfUpdater(coordinatorBaseURL: config.coordinator.url)
switch await updater.checkForUpdate() {
case .updateAvailable, .restartRequired:
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopAutopilot.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopAutopilot.swift
new file mode 100644
index 0000000000..91d8260268
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAutopilot.swift
@@ -0,0 +1,98 @@
+import ArgumentParser
+import Foundation
+import ProviderCore
+
+extension DesktopBackend {
+ func runAutopilot(_ request: DesktopAction, arguments: [String], worker: DesktopWorker,
+ beforeStart: @Sendable () async throws -> Void = {}) async throws -> (Int32, String) {
+ for model in request.downloads ?? [] {
+ try Task.checkCancellation()
+ setDownloadModel(request.id, model: model)
+ let (code, output) = try await worker.run(
+ ["models", "download", model] + (configPath.map { ["--config", $0] } ?? []),
+ progress: { [weak self] output in Task { await self?.setProgress(request.id, output: output, downloadModel: model) } })
+ guard code == 0 else { throw ValidationError("Download failed for \(model): \(output)") }
+ }
+ try Task.checkCancellation()
+ setDownloadModel(request.id, model: nil)
+ try validateAutopilotPins(request.pinned ?? [])
+ try await beforeStart()
+ try Task.checkCancellation()
+ var result = try await worker.run(arguments,
+ progress: { [weak self] output in Task { await self?.setProgress(request.id, output: output) } })
+ if result.0 == 0, let pinned = request.pinned, !pinned.isEmpty {
+ try Task.checkCancellation()
+ result = try await worker.run(Self.autopilotPinArguments(pinned, configPath: configPath))
+ }
+ return result
+ }
+
+ static func autopilotArguments(for request: DesktopAction, config: [String]) -> [String]? {
+ switch request.action {
+ case "autopilot":
+ return ["start", "--autopilot"] + (request.models ?? []).flatMap { ["--model", $0] }
+ + (request.endpoint == true ? ["--local-endpoint"] : []) + config
+ case "autopilot_pin", "autopilot_unpin":
+ return ["autopilot", request.action == "autopilot_pin" ? "pin" : "unpin"]
+ + (request.models ?? []) + config
+ case "autopilot_pause", "autopilot_resume", "autopilot_disable", "autopilot_models":
+ return ["autopilot", String(request.action.dropFirst("autopilot_".count))] + config
+ default: return nil
+ }
+ }
+
+ static func autopilotPinArguments(_ models: [String], configPath: String?) -> [String] {
+ ["autopilot", "pin"] + models + (configPath.map { ["--config", $0] } ?? [])
+ }
+
+ /// The CLI inventory wizard is interactive. Desktop uses its existing explicit
+ /// startup selection path, which verifies cached inventory before safely draining.
+ static func autopilotRefreshArguments(settings: ModelAutopilotSettings,
+ startupModels: [String], endpoint: LocalEndpoint.Info?, configPath: String?) throws -> [String] {
+ guard settings.hasConsent else { throw ValidationError("Turn on Autopilot first") }
+ let models = startupModels.isEmpty ? Array(settings.selectedModels.prefix(1)) : startupModels
+ guard !models.isEmpty else { throw ValidationError("Choose a startup model first") }
+ try models.forEach(DesktopAction.validateModel)
+ var arguments = ["start", "--autopilot"] + models.flatMap { ["--model", $0] }
+ if let endpoint {
+ arguments += ["--local-endpoint", "--port", String(endpoint.port), "--bind", endpoint.host]
+ if endpoint.apiKey.isEmpty { arguments += ["--no-auth"] }
+ }
+ return arguments + (configPath.map { ["--config", $0] } ?? [])
+ }
+
+ func validateAutopilotPins(_ requested: [String]) throws {
+ guard !requested.isEmpty else { return }
+ let loaded = try configuration()
+ let pins = Set(loaded.config.backend.modelAutopilot.pinnedModels + requested)
+ guard pins.count <= loaded.config.backend.maxModelSlots else {
+ throw ValidationError("These pins exceed this Mac’s model slot limit")
+ }
+ guard let hardware = loaded.hardware else { throw ValidationError("Cannot check this Mac’s memory") }
+ ModelScanner.configureCacheDirectory(try ConfigManager.modelCacheDirectory(in: loaded.config, relativeTo: loaded.configPath))
+ let local = ModelScanner.scanAllModels(hardwareInfo: hardware)
+ let chosen = local.filter { pins.contains($0.id) }
+ guard Set(chosen.map(\.id)) == pins else { throw ValidationError("Download every pinned model first") }
+ guard chosen.reduce(0, { $0 + $1.estimatedMemoryGb }) <= Start.pickerLoadBudgetGiB(memoryGb: Double(hardware.memoryGb)) else {
+ throw ValidationError("These pins exceed this Mac’s model memory allowance")
+ }
+ }
+
+ static func autopilotSnapshot(_ settings: ModelAutopilotSettings, daemon: DaemonState?, fresh: Bool) -> JSONValue {
+ .dict([
+ "enabled": .bool(settings.hasConsent), "paused": .bool(settings.paused),
+ "configured": .bool(settings.consentRecorded),
+ "selected": .array(settings.selectedModels.map(DV.string)),
+ "pinned": .array(settings.pinnedModels.map(DV.string)),
+ "phase": fresh ? daemon?.autopilotPhase.map(DV.string) ?? .null : .null,
+ ])
+ }
+
+ static func downloadProgress(_ output: String) -> Double? {
+ guard let pattern = try? NSRegularExpression(pattern: #"(\d+(?:\.\d+)?)%"#),
+ let match = pattern.matches(in: output, range: NSRange(output.startIndex..., in: output)).last,
+ let range = Range(match.range(at: 1), in: output), let percent = Double(output[range]),
+ (0...100).contains(percent) else { return nil }
+ return percent / 100
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopBackend.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopBackend.swift
index 0283a5e015..5644646c4d 100644
--- a/provider-swift/Sources/darkbloom/Desktop/DesktopBackend.swift
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopBackend.swift
@@ -20,12 +20,24 @@ actor DesktopBackend {
var catalog: [CatalogModel] = []
var catalogError: String?
var catalogAt = Date.distantPast
+ var catalogTask: Task?
+ var resourceGeneration = 0
+ var resourceFailures: [String: (attempts: Int, retryAt: Date)] = [:]
+ var resourceCache: [String: DesktopResourceCache] = [:]
+ var resourceTasks: [String: Task] = [:]
var localAt = Date.distantPast
var localModels: [ModelInfo] = []
var link: JSONValue = .null
var samples: [JSONValue] = []
var sampleSession: Double?
+ var accountEarningsCache: (key: String, at: Date, value: JSONValue)?
+ var accountEarningsTask: (key: String, task: Task)?
+ var usageArchive = DesktopUsageArchive()
+ var usageReadAt = Date.distantPast
+ var usageRead: Task?
var accountSession = DesktopAccountSession()
+ var accountIdentityRead: Task?
+ var accountIdentityReadAt = Date.distantPast
/// Shared `fan status` read; `coolingReadAt` is nil while it is in flight.
var coolingRead: Task?
var coolingReadAt: Date?
@@ -66,7 +78,7 @@ actor DesktopBackend {
}
let operation = DesktopOperation(
id: request.id, action: request.action, started_at: Date().timeIntervalSince1970,
- cancellable: ["download", "diagnose", "link"].contains(request.action))
+ cancellable: ["download", "diagnose", "link", "account-signin", "autopilot"].contains(request.action))
requests[request.id] = request
operations.insert(operation, at: 0)
operations = Array(operations.prefix(32))
@@ -101,6 +113,8 @@ actor DesktopBackend {
complete(
request.id, code: 0,
message: "Settings saved. Restart the provider to apply runtime changes.")
+ } else if ["account-signin", "account-signout"].contains(request.action) {
+ try await executeAccountAction(request)
} else if request.action == "link" {
guard AuthTokenStore.load() == nil else {
throw ValidationError("This Mac is already linked")
@@ -128,12 +142,17 @@ actor DesktopBackend {
try Task.checkCancellation()
let worker = DesktopWorker(executable: executable)
workers[request.id] = worker
+ if request.action == "download" {
+ setDownloadModel(request.id, model: request.model)
+ }
let before = Self.currentExecutableStamp()
- let (code, output) = try await worker.run(
- arguments,
- progress: { [weak self] output in
- Task { await self?.setProgress(request.id, output: output) }
- })
+ let (code, output) = request.action == "autopilot"
+ ? try await runAutopilot(request, arguments: arguments, worker: worker, beforeStart: { [configPath] in
+ if DesktopLocalLifecycle.isActive { try await DesktopLocalLifecycle.stop(configPath: configPath) }
+ })
+ : try await worker.run(arguments, progress: { [weak self] output in
+ Task { await self?.setProgress(request.id, output: output) }
+ })
complete(request.id, code: code, message: output)
if request.action == "update", code == 0,
Self.shouldRestartForReplacedExecutable(
@@ -144,12 +163,18 @@ actor DesktopBackend {
}
}
} catch {
- if request.action == "link" { link = .null }
+ if ["link", "account-signin"].contains(request.action) { link = .null }
complete(request.id, code: 1, message: String(describing: error))
}
}
func arguments(for request: DesktopAction) throws -> [String] {
+ if request.action == "autopilot_pin" { try validateAutopilotPins(request.models ?? []) }
+ if request.action == "autopilot_models" {
+ let config = try configuration().config
+ return try Self.autopilotRefreshArguments(settings: config.backend.modelAutopilot,
+ startupModels: config.backend.enabledModels, endpoint: LocalEndpoint.readLiveInfo(), configPath: configPath)
+ }
if request.action == "remove" {
let state = DaemonStateFile.read()
guard !(state?.warmModels.contains(request.model!) ?? false),
@@ -168,6 +193,7 @@ actor DesktopBackend {
) throws -> [String] {
let config = configPath.map { ["--config", $0] } ?? []
let models = (request.models ?? []).flatMap { ["--model", $0] }
+ if let arguments = autopilotArguments(for: request, config: config) { return arguments }
switch request.action {
case "start":
guard request.local != true else { return ["desktop", "start-local"] + models + config }
@@ -190,19 +216,27 @@ actor DesktopBackend {
}
}
- private func setLink(_ id: String, _ value: JSONValue) {
+ func setLink(_ id: String, _ value: JSONValue) {
guard !cancellationRequested.contains(id),
operations.contains(where: { $0.id == id && $0.state == "running" })
else { return }
link = value
}
- private func setProgress(_ id: String, output: String) {
+ func setProgress(_ id: String, output: String, downloadModel: String? = nil) {
guard let index = operations.firstIndex(where: { $0.id == id }),
operations[index].state == "running"
else { return }
+ if let downloadModel, operations[index].model != downloadModel { return }
operations[index].message = String(output.suffix(8000))
+ operations[index].progress = Self.downloadProgress(output)
+ }
+ func setDownloadModel(_ id: String, model: String?) {
+ guard let index = operations.firstIndex(where: { $0.id == id }) else { return }
+ operations[index].model = model
+ operations[index].progress = nil
+ operations[index].message = model.map { "Downloading \($0)…" } ?? "Starting Autopilot…"
}
- private func complete(_ id: String, code: Int32, message: String) {
+ func complete(_ id: String, code: Int32, message: String) {
guard let index = operations.firstIndex(where: { $0.id == id }),
operations[index].state == "running"
else { return }
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopCommand.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopCommand.swift
index 113da6b403..33242e7b93 100644
--- a/provider-swift/Sources/darkbloom/Desktop/DesktopCommand.swift
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopCommand.swift
@@ -10,7 +10,7 @@ struct Desktop: AsyncParsableCommand {
abstract: "Serve the authenticated desktop control API.",
subcommands: [
Serve.self, Ensure.self, StartLocal.self, ConfigureCooling.self, StopLocal.self,
- RestartLocal.self,
+ RestartLocal.self, Login.self, Logout.self,
])
struct Serve: AsyncParsableCommand {
@@ -37,7 +37,11 @@ struct Desktop: AsyncParsableCommand {
}
let token = Data(bytes).base64EncodedString()
let instance = UUID().uuidString
- let backend = DesktopBackend(configPath: configOptions.config)
+ // Local review builds attach to an existing installation; serving operations
+ // must keep using its verified CLI rather than installing this ad-hoc build.
+ let worker = ProcessInfo.processInfo.environment["DARKBLOOM_DESKTOP_ATTACH_ONLY"] == "1"
+ ? try DesktopFanRuntime.resolve() : nil
+ let backend = DesktopBackend(configPath: configOptions.config, executable: worker)
let app = Application(
responder: DesktopHTTP(backend: backend, token: token),
configuration: .init(address: .hostname("127.0.0.1", port: 0)),
@@ -94,23 +98,15 @@ struct Desktop: AsyncParsableCommand {
@Option var speed: Int = 70
@Option var temperature: Int = 50
mutating func run() async throws {
- guard (30...100).contains(speed), (40...90).contains(temperature) else {
+ guard (60...90).contains(speed), (40...90).contains(temperature) else {
throw ValidationError("Invalid fan policy")
}
- let executable = try FanServiceManager().currentExecutableURL()
- // Verify the existing provisioned CLI/helper before asking macOS for administrator authorization.
- _ = try FanServiceManager().bundledHelperURL()
+ let executable = try DesktopFanRuntime.resolve()
let command =
"/usr/bin/env SUDO_UID=\(getuid()) SUDO_GID=\(getgid()) \(Self.quote(executable.path)) fan \(enabled ? "enable --speed \(speed) --temperature \(temperature)" : "disable")"
let script = "do shell script \(Self.appleString(command)) with administrator privileges"
- let process = Process()
- process.executableURL = URL(fileURLWithPath: "/usr/bin/osascript")
- process.arguments = ["-e", script]
- try process.run()
- process.waitUntilExit()
- guard process.terminationStatus == 0 else {
- throw ValidationError("Cooling authorization cancelled or failed")
- }
+ let output = try await DesktopCoolingAuthorization.perform(script: script)
+ if !output.isEmpty { print(output.trimmingCharacters(in: .whitespacesAndNewlines)) }
}
static func quote(_ value: String) -> String {
"'" + value.replacingOccurrences(of: "'", with: "'\\''") + "'"
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopConfiguration.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopConfiguration.swift
index d9b2362998..59c1769ecd 100644
--- a/provider-swift/Sources/darkbloom/Desktop/DesktopConfiguration.swift
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopConfiguration.swift
@@ -20,6 +20,8 @@ extension DesktopBackend {
configPath: previous.configPath, configFileExists: exists,
config: config, hardware: previous.hardware, hardwareError: previous.hardwareError)
if config.coordinator.url != previous.config.coordinator.url {
+ catalogTask?.cancel(); catalogTask = nil
+ clearAccountResources()
catalog = []
catalogAt = .distantPast
}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopCooling.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopCooling.swift
index f78dac2793..43dd6f86dd 100644
--- a/provider-swift/Sources/darkbloom/Desktop/DesktopCooling.swift
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopCooling.swift
@@ -24,8 +24,9 @@ extension DesktopBackend {
}
static func readCooling(executable: URL?) async -> JSONValue {
+ let signed = executable ?? (try? DesktopFanRuntime.resolve())
guard
- let (code, output) = try? await DesktopWorker(executable: executable).run(
+ let (code, output) = try? await DesktopWorker(executable: signed ?? executable).run(
["fan", "status", "--json"], timeout: 15),
code == 0, let data = output.data(using: .utf8),
let status = try? JSONDecoder().decode(JSONValue.self, from: data)
@@ -35,6 +36,10 @@ extension DesktopBackend {
"error": .string("Cooling status unavailable"),
])
}
+ return Self.projectCooling(status, controlAvailable: signed != nil)
+ }
+
+ static func projectCooling(_ status: JSONValue, controlAvailable: Bool) -> JSONValue {
let diagnostic = status.field("diagnostic")
let temperatures = diagnostic.field("gpuTemperatures").values.compactMap {
$0.field("celsius").number
@@ -45,9 +50,22 @@ extension DesktopBackend {
"rpm": fan.field("actualRPM"), "max_rpm": fan.field("maximumRPM"),
])
}
+ // Automatic describes the current SMC mode, including an enabled helper below its
+ // trigger. The opt-in is on while the installed helper is loaded and reporting status.
+ let enabled: JSONValue
+ if status.field("helperError").text != nil { enabled = .null }
+ else if status.field("loaded").flag == false { enabled = .bool(false) }
+ else if status.field("loaded").flag == true, status.field("helper").field("mode").text != nil { enabled = .bool(true) }
+ else { enabled = .null }
return .dict([
"supported": diagnostic.field("supported"),
- "mode": status.field("helper").field("mode").text.map(DV.string) ?? .string("automatic"),
+ "control_available": .bool(controlAvailable),
+ "enabled": enabled, "observed_at": .number(Date().timeIntervalSince1970),
+ "speed": status.field("helper").field("speedPercent"),
+ "threshold": status.field("helper").field("triggerTemperatureC"),
+ "mode": status.field("helper").field("mode").text.map(DV.string)
+ ?? .string(status.field("helperError").text == nil ? "automatic" : "unavailable"),
+ "error": status.field("helperError"),
"temperature": .number(temperatures.max()), "fans": .array(fans),
])
}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopCoolingAuthorization.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopCoolingAuthorization.swift
new file mode 100644
index 0000000000..250681ac93
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopCoolingAuthorization.swift
@@ -0,0 +1,42 @@
+import Foundation
+
+/// Retry only firmware restoration failures through the verified CLI; its
+/// ownership checks and automatic-control recovery remain authoritative.
+enum DesktopCoolingAuthorization {
+ enum Decision: Equatable { case retry, cancelled, failed }
+ static func decision(_ output: String) -> Decision {
+ if output.contains("(-128)") { return .cancelled }
+ if output.contains("fan ownership recovery failed"),
+ output.contains("SMC firmware rejected") || output.contains("Ftst remained") {
+ return .retry
+ }
+ return .failed
+ }
+ static func perform(
+ script: String,
+ run: @Sendable (String) async throws -> (Int32, String) = { script in
+ try await DesktopWorker(executable: URL(fileURLWithPath: "/usr/bin/osascript"))
+ .run(["-e", script], timeout: 120)
+ },
+ pause: @Sendable () async throws -> Void = {
+ try await Task.sleep(for: .milliseconds(700))
+ }
+ ) async throws -> String {
+ for attempt in 0..<3 {
+ let (status, output) = try await run(script)
+ if status == 0 { return output }
+ let result = decision(output)
+ if result == .retry && attempt < 2 { try await pause(); continue }
+ throw Failure(cancelled: result == .cancelled, output: output)
+ }
+ preconditionFailure("Bounded cooling retry must return or throw")
+ }
+ struct Failure: Error, CustomStringConvertible {
+ let cancelled: Bool
+ let output: String
+ var description: String {
+ cancelled ? "Cooling authorization cancelled" :
+ "Cooling change failed: \(output.trimmingCharacters(in: .whitespacesAndNewlines))"
+ }
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopFanRuntime.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopFanRuntime.swift
new file mode 100644
index 0000000000..4141bb583a
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopFanRuntime.swift
@@ -0,0 +1,30 @@
+import Foundation
+
+/// Fan XPC authenticates signed providers. The desktop preview must use the
+/// installed signed runtime for status and root-helper operations.
+enum DesktopFanRuntime {
+ static func resolve() throws -> URL {
+ let manager = FanServiceManager()
+ let current = try manager.currentExecutableURL()
+ let installed = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".darkbloom/Darkbloom.app/Contents/MacOS/darkbloom")
+ return try select([current, installed]) { executable in
+ let directory = executable.deletingLastPathComponent()
+ guard directory.lastPathComponent == "MacOS" else { return false }
+ let contents = directory.deletingLastPathComponent()
+ let app = contents.deletingLastPathComponent()
+ guard app.pathExtension == "app" else { return false }
+ try manager.verifyRegularExecutable(executable)
+ try manager.verifyBundledApp(app: app, executable: executable,
+ helper: contents.appendingPathComponent("Helpers/darkbloom-fan-helper"))
+ return true
+ }
+ }
+
+ static func select(_ candidates: [URL], verify: (URL) throws -> Bool) throws -> URL {
+ for candidate in candidates {
+ if (try? verify(candidate)) == true { return candidate }
+ }
+ throw FanServiceManagerError.helperNotBundled(["a verified signed Darkbloom.app installation"])
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopHTTP.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopHTTP.swift
index c8175a9a30..93c681a5d4 100644
--- a/provider-swift/Sources/darkbloom/Desktop/DesktopHTTP.swift
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopHTTP.swift
@@ -98,7 +98,9 @@ struct DesktopHTTP: HTTPResponder {
case let error as HTTPError: return (error.status, error.body ?? error.status.reasonPhrase)
case let error as any HTTPResponseError: return (error.status, error.status.reasonPhrase)
case let error as ValidationError: return (.badRequest, error.message)
- case is URLError: return (.badGateway, "Coordinator request failed")
+ case let error as URLError:
+ if error.code == .userAuthenticationRequired { return (.unauthorized, "Account changed or expired. Sign in to continue.") }
+ return (.badGateway, "Coordinator request failed")
default: return (.internalServerError, "Internal error")
}
}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopRequestHistory.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopRequestHistory.swift
new file mode 100644
index 0000000000..e1d0903c22
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopRequestHistory.swift
@@ -0,0 +1,57 @@
+import Foundation
+import Hummingbird
+import ProviderCore
+
+extension DesktopBackend {
+ static func localRequestHistory(_ records: [ProviderUsageRecord], settlements: [DesktopUsageArchive.Settlement]) throws -> JSONValue {
+ guard records.allSatisfy({ $0.inputTokens <= 9_007_199_254_740_991 && $0.outputTokens <= 9_007_199_254_740_991 }) else { throw URLError(.cannotParseResponse) }
+ let money = Dictionary(settlements.compactMap { row in row.jobID.map { ($0, row) } }, uniquingKeysWith: { _, last in last })
+ let sorted = records.sorted { $0.completedAt > $1.completedAt }
+ return .dict([
+ "observed_at": .number(Date().timeIntervalSince1970), "since": .number(sorted.last?.completedAt),
+ "records": .array(sorted.map { record in .dict([
+ "id": .string(record.id), "completed_at": .number(record.completedAt),
+ "model": .string(record.model), "input_tokens": .int(Int64(clamping: record.inputTokens)),
+ "output_tokens": .int(Int64(clamping: record.outputTokens)), "outcome": .string("completed"),
+ "earnings_micro_usd": money[record.id].map { .string(String($0.earnings)) } ?? .null,
+ ]) })
+ ])
+ }
+ func requestHistory() async throws -> JSONValue {
+ if let daemon = DaemonStateFile.read(), daemon.processIdentity?.isCurrent() == true {
+ let local = ProviderUsageHistory.read().filter { $0.sessionStartedAt == daemon.startedAt && $0.exact }
+ if !local.isEmpty {
+ refreshUsageHistoryIfNeeded(daemon: daemon, now: Date())
+ return try Self.localRequestHistory(local, settlements: usageArchive.settlements)
+ }
+ }
+ guard let token = usageCredentialToken() else { throw HTTPError(.unauthorized, message: "Link your account to view history") }
+ if let daemon = DaemonStateFile.read() {
+ refreshUsageHistoryIfNeeded(daemon: daemon, now: Date())
+ if let usageRead { await usageRead.value }
+ }
+ let base = coordinatorHTTPBase(try configuration().config.coordinator.url)
+ let scope = usageArchive.scope
+ let ledger = try await accountEarnings(base: base, token: token)
+ guard scope == usageArchive.scope else { throw HTTPError(.unauthorized, message: "Mac identity changed; refresh to continue") }
+ return try DesktopAccountEarnings(ledger, localKeys: Set(usageArchive.providerKeys.keys)).requestHistory()
+ }
+}
+
+extension DesktopAccountEarnings {
+ func requestHistory() throws -> JSONValue {
+ guard !localKeys.isEmpty else { throw HTTPError(.serviceUnavailable, message: "This Mac's identity is not verified yet") }
+ let local = rows.filter { localKeys.contains($0.key) && $0.model != "base_reward" }
+ guard local.allSatisfy({ $0.input <= 9_007_199_254_740_991 && $0.output <= 9_007_199_254_740_991 }) else { throw URLError(.cannotParseResponse) }
+ return .dict([
+ "observed_at": .number(now.timeIntervalSince1970),
+ "since": local.first.map { .number($0.at.timeIntervalSince1970) } ?? .null,
+ "records": .array(local.reversed().map { row in .dict([
+ "id": .string(row.id), "settled_at": .number(row.at.timeIntervalSince1970),
+ "model": .string(row.model), "input_tokens": .int(Int64(row.input)),
+ "output_tokens": .int(Int64(row.output)), "outcome": .string("settled"),
+ "earnings_micro_usd": .string(String(row.money)),
+ ]) })
+ ])
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopResourceCache.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopResourceCache.swift
new file mode 100644
index 0000000000..ceafdbecca
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopResourceCache.swift
@@ -0,0 +1,61 @@
+import Crypto
+import Foundation
+import ProviderCore
+
+struct DesktopResourceCache: Sendable {
+ let value: JSONValue
+ let at: Date
+}
+
+extension DesktopBackend {
+ /// One native cache/in-flight request per coordinator, credential and resource.
+ func cachedResource(_ name: String, base: String, token: String?, ttl: Double = 30) async throws -> JSONValue {
+ let hash = SHA256.hash(data: Data("\(base)\n\(token ?? "")\n\(name)".utf8)).map { String(format: "%02x", $0) }.joined()
+ if let cached = resourceCache[hash], Date().timeIntervalSince(cached.at) < ttl { return cached.value }
+ let generation = resourceGeneration
+ if let failure = resourceFailures[hash], failure.retryAt > Date() { throw URLError(.cannotConnectToHost) }
+ if let task = resourceTasks[hash] {
+ let value = try await task.value
+ guard generation == resourceGeneration else { throw URLError(.cancelled) }
+ if let token, accountReadToken() != token { throw URLError(.userAuthenticationRequired) }
+ return value
+ }
+ let task = Task { try await self.readRemoteResource(name, base: base, token: token) }
+ resourceTasks[hash] = task
+ defer { if generation == resourceGeneration { resourceTasks[hash] = nil } }
+ let value: JSONValue
+ do { value = try await task.value } catch {
+ if (error as? URLError)?.code == .userAuthenticationRequired, let token,
+ token.hasPrefix("darkbloom-at-"), accountCredentialToken() == token {
+ try? DesktopAccountCredential.remove(base: base)
+ clearAccountResources()
+ }
+ if error is URLError, generation == resourceGeneration {
+ let attempts = min((resourceFailures[hash]?.attempts ?? 0) + 1, 4)
+ resourceFailures[hash] = (attempts, Date().addingTimeInterval(min(300, 30 * pow(2, Double(attempts - 1)))))
+ }
+ throw error
+ }
+ if let token, accountReadToken() != token { throw URLError(.userAuthenticationRequired) }
+ guard generation == resourceGeneration else { throw URLError(.cancelled) }
+ // Bound retained caches even if accounts or coordinator URLs change repeatedly.
+ if resourceCache.count > 32 { resourceCache = [:] }
+ resourceFailures[hash] = nil
+ resourceCache[hash] = DesktopResourceCache(value: value, at: Date())
+ return value
+ }
+
+ func refreshCatalogIfNeeded(coordinator: String, now: Date) {
+ guard catalogTask == nil, now.timeIntervalSince(catalogAt) > 120 else { return }
+ catalogAt = now
+ let generation = resourceGeneration
+ catalogTask = Task {
+ defer { if generation == resourceGeneration { catalogTask = nil } }
+ do {
+ let models = try await ModelCatalogClient(coordinatorURL: coordinator).fetchCatalog(typeFilter: nil)
+ guard generation == resourceGeneration, (try? configuration().config.coordinator.url) == coordinator else { return }
+ catalog = models; catalogError = nil
+ } catch { if generation == resourceGeneration { catalogError = "Model catalog unavailable. Downloaded models remain available." } }
+ }
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopResources.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopResources.swift
index a7c5ea78f9..d8776f6215 100644
--- a/provider-swift/Sources/darkbloom/Desktop/DesktopResources.swift
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopResources.swift
@@ -17,67 +17,49 @@ extension DesktopBackend {
guard let endpoint = LocalEndpoint.readLiveInfo() else { return .null }
return .dict(["key": .string(endpoint.apiKey)])
}
+ if name == "request-history" { return try await requestHistory() }
if name == "cooling" { return await cooling() }
- let paths = [
- "cloud": "/v1/provider/desktop", "network": "/v1/stats", "leaderboard": "/v1/leaderboard",
- "release": "/v1/releases/latest", "release-history": "/v1/releases/desktop",
- "insights-week": "/v1/provider/desktop/insights",
- "insights-month": "/v1/provider/desktop/insights",
- ]
- guard let path = paths[name] else { throw HTTPError(.notFound, message: "Unknown resource") }
- let config = try configuration().config
- let privateResource = name == "cloud" || name.hasPrefix("insights-")
- let accountToken = privateResource ? AuthTokenStore.load() : nil
- if name.hasPrefix("insights-"), accountToken == nil {
- throw HTTPError(.unauthorized, message: "Link your account to view earnings")
- }
- if name == "cloud", accountToken == nil {
- return .dict([
- "linked": .bool(false), "observed_at": .number(Date().timeIntervalSince1970),
- "machines": .array([]),
- ])
- }
- let base = config.coordinator.url.replacingOccurrences(of: "wss://", with: "https://")
- .replacingOccurrences(of: "ws://", with: "http://")
- guard var components = URLComponents(string: base) else { throw URLError(.badURL) }
- components.path = path
- components.query = nil
- components.fragment = nil
- if name == "leaderboard" {
- components.queryItems = [
- URLQueryItem(name: "metric", value: "earnings"),
- URLQueryItem(name: "window", value: "24h"),
- ]
- }
- if name.hasPrefix("insights-") {
- components.queryItems = [URLQueryItem(name: "window", value: name == "insights-week" ? "7d" : "30d")]
+ let base = coordinatorHTTPBase(try configuration().config.coordinator.url)
+ let token = (name == "cloud" || name.hasPrefix("insights-")) ? accountReadToken() : nil
+ if name == "cloud", token == nil {
+ return .dict(["linked": .bool(false), "observed_at": .number(Date().timeIntervalSince1970), "machines": .array([])])
}
- guard let url = components.url else { throw URLError(.badURL) }
- var request = URLRequest(url: url)
- request.timeoutInterval = 15
- if privateResource, let token = accountToken {
- request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ if name.hasPrefix("insights-"), token == nil {
+ throw HTTPError(.unauthorized, message: "Sign in to view account earnings")
}
- if name == "cloud", let identity = DaemonStateFile.read()?.attestationPublicKey {
- request.setValue(identity, forHTTPHeaderField: "X-Darkbloom-Device-Identity")
- }
- let (data, response) = try await URLSession.shared.data(for: request)
- if privateResource, AuthTokenStore.load() != accountToken {
- throw HTTPError(.unauthorized, message: "Account changed; refresh to continue")
+ return try await cachedResource(name, base: base, token: token, ttl: name.hasPrefix("release") ? 3600 : 30)
+ }
+
+ func readRemoteResource(_ name: String, base: String, token: String?) async throws -> JSONValue {
+ if name == "cloud", let token {
+ if token.hasPrefix("darkbloom-at-") { return try await accountCloud(base: base, token: token) }
+ return try DesktopAccountEarnings(try await accountEarnings(base: base, token: token), localKeys: Set(usageArchive.providerKeys.keys)).cloud()
}
- guard let http = response as? HTTPURLResponse, http.statusCode == 200, data.count <= 4_000_000
- else {
- throw URLError(.badServerResponse)
+ if name.hasPrefix("insights-"), let token {
+ let window = name == "insights-week" ? "7d" : "30d"
+ if !token.hasPrefix("darkbloom-at-") {
+ return try DesktopAccountEarnings(try await accountEarnings(base: base, token: token), localKeys: Set(usageArchive.providerKeys.keys)).insights(window)
+ }
+ let value = try await Self.readUsageJSON(base: base, path: "/v1/provider/account-earnings", token: token, query: [URLQueryItem(name: "window", value: window)])
+ if value.field("window").text == window { return Self.localizeInsights(value, providerID: usageArchive.localProviderID) }
+ // Older coordinators ignore window: preserve truthful partial-history coverage.
+ return try DesktopAccountEarnings(try await accountEarnings(base: base, token: token), localKeys: Set(usageArchive.providerKeys.keys)).insights(window)
}
- guard let value = try? JSONDecoder().decode(JSONValue.self, from: data) else {
- throw URLError(.cannotParseResponse)
+ let paths = ["network": "/v1/stats", "leaderboard": "/v1/leaderboard", "release": "/v1/releases/latest", "release-history": "/v1/releases/latest", "owned-providers": "/v1/me/providers", "summary": "/v1/me/summary", "legacy-roster": "/v1/providers/attestation"]
+ guard let path = paths[name] else { throw HTTPError(.notFound, message: "Unknown resource") }
+ if name == "release-history" {
+ let latest = try await cachedResource("release", base: base, token: nil, ttl: 3600)
+ return .dict(["history": .array([.dict(["version": latest.field("version"), "published_at": latest.field("published_at"), "notes": latest.field("notes"), "active": .bool(true)])])])
}
+ let query = name == "leaderboard" ? [URLQueryItem(name: "metric", value: "earnings"), URLQueryItem(name: "window", value: "24h")] : []
+ let value = try await Self.readUsageJSON(base: base, path: path, token: token, query: query)
if name == "network" {
return .dict([
"total_tokens": Self.integerText(value.field("total_tokens")),
"total_requests": Self.integerText(value.field("total_requests")),
"total_macs": value.field("active_providers"),
"provider_regions": value.field("provider_regions"),
+ "model_earnings": value.field("model_earnings"),
])
}
if name == "leaderboard" {
@@ -99,15 +81,6 @@ extension DesktopBackend {
"notes": value.field("changelog"),
])
}
- if name == "cloud", case .object(let pairs) = value {
- let machines = value.field("machines").values
- var fields = Dictionary(uniqueKeysWithValues: pairs)
- fields["machines"] = .array(machines.filter { $0.field("is_this_mac").flag != true })
- fields["local_earnings_micro_usd"] =
- machines.first { $0.field("is_this_mac").flag == true }?.field("earnings_micro_usd")
- ?? .null
- return .dict(fields)
- }
return value
}
}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopSnapshot.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopSnapshot.swift
index 7901b83776..16840f3352 100644
--- a/provider-swift/Sources/darkbloom/Desktop/DesktopSnapshot.swift
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopSnapshot.swift
@@ -5,20 +5,14 @@ extension DesktopBackend {
func state() async throws -> JSONValue {
let loaded = try configuration()
let now = Date()
+ refreshAccountIdentityIfNeeded(base: coordinatorHTTPBase(loaded.config.coordinator.url), now: now)
if now.timeIntervalSince(localAt) > 30 {
ModelScanner.configureCacheDirectory(
try ConfigManager.modelCacheDirectory(in: loaded.config, relativeTo: loaded.configPath))
localModels = loaded.hardware.map { ModelScanner.scanAllModels(hardwareInfo: $0) } ?? []
localAt = now
}
- if now.timeIntervalSince(catalogAt) > 120 {
- catalogAt = now
- do {
- catalog = try await ModelCatalogClient(coordinatorURL: loaded.config.coordinator.url)
- .fetchCatalog(typeFilter: nil)
- catalogError = nil
- } catch { catalogError = "Model catalog unavailable. Downloaded models remain available." }
- }
+ refreshCatalogIfNeeded(coordinator: loaded.config.coordinator.url, now: now)
let daemon = DaemonStateFile.read()
let current = daemon?.processIdentity?.isCurrent() == true
let fresh = current && daemon?.isStale(now: now.timeIntervalSince1970) == false
@@ -36,6 +30,7 @@ extension DesktopBackend {
let supported = Set(EngineV2SupportedModels.partition(localModels).supported.map(\.id))
let capabilities = Set(
(daemon?.runtimeCapabilities ?? []).map { ProviderRuntimeCapability(rawValue: $0) })
+ let totalMemory = Double(loaded.hardware?.memoryGb ?? 0)
let modelIDs = Set(catalog.map(\.id)).union(localModels.map(\.id)).sorted()
let models = modelIDs.map { id -> JSONValue in
let entry = catalog.first { $0.id == id }
@@ -43,14 +38,20 @@ extension DesktopBackend {
let runtimeOK =
!fresh || daemon?.runtimeCapabilities == nil
|| ModelRuntimeRequirements.isEligible(modelID: id, available: capabilities)
- let reason: String? =
+ let catalogReason: String? = entry.flatMap { entry in
+ if Double(entry.minRamGb ?? 0) > totalMemory { return "Needs \(entry.minRamGb ?? 0) GB of unified memory" }
+ if !Start.modelFitsBudget(sizeGb: local?.estimatedMemoryGb ?? entry.sizeGb, memoryGb: totalMemory) { return "Does not fit this Mac’s model load allowance" }
+ if fresh && daemon?.runtimeCapabilities != nil && !ModelRuntimeRequirements.isEligible(modelID: id, catalogRequirements: entry.requiredProviderCapabilities, available: capabilities) { return "Requires runtime capabilities this Mac does not report" }
+ return nil
+ }
+ let reason: String? = catalogReason ?? (
local == nil
? nil
: (!supported.contains(id)
? "Unsupported by this runtime"
: (local?.templateRenderOK == false
? "Chat template validation failed"
- : (!runtimeOK ? "Runtime capability check required before serving" : nil)))
+ : (!runtimeOK ? "Runtime capability check required before serving" : nil))))
return .dict([
"id": .string(id), "display_name": .string(entry?.displayName ?? id),
"size_gb": .number(entry?.sizeGb ?? local.map { Double($0.sizeBytes) / 1_073_741_824 }),
@@ -78,7 +79,21 @@ extension DesktopBackend {
]))
samples = Array(samples.suffix(1440))
}
+ let promptTokens = fresh ? daemon?.stats.promptTokensProcessed : nil
+ let promptCount: JSONValue = promptTokens.map { JSONValue.string(String($0)) } ?? .null
+ var activity: [String: JSONValue] = [
+ "models": Self.modelActivity(daemon?.capacity, fresh: fresh, now: now.timeIntervalSince1970),
+ "sampled_at": .number(fresh ? daemon?.capacity?.activityObservedAt : nil),
+ "requests": fresh ? .string(String(requestCount)) : .null,
+ "tokens": fresh ? .string(String(tokens)) : .null,
+ "prompt_tokens": promptCount,
+ "usage_gaps": fresh ? .string(String(daemon?.stats.usageGaps ?? 0)) : .null,
+ "started_at": .number(fresh ? daemon?.startedAt : nil), "samples": .array(samples),
+ ]
+ activity.merge(sessionUsage(daemon: daemon, fresh: fresh, now: now)) { _, usage in usage }
let total = Double(loaded.hardware?.memoryGb ?? 0)
+ let maxModelSlots = (fresh ? daemon?.autopilot.map { Double($0.maxModelSlots) } : nil)
+ ?? Double(loaded.config.backend.maxModelSlots)
let machine: JSONValue = .dict([
"id": .string("this-mac"), "name": .string(loaded.config.provider.name),
"chip": .string(loaded.hardware?.chipName ?? "Unknown hardware"), "memory_gb": .number(total),
@@ -86,13 +101,20 @@ extension DesktopBackend {
"models": .array(selected.map(DV.string)),
"observed_at": .number(fresh ? daemon?.writtenAt : nil),
])
+ let connectionStatus: String? = fresh && !localOnly ? daemon?.trust?.status : nil
+ let providerStatus: JSONValue = connectionStatus.map(JSONValue.string) ?? .null
return .dict([
"protocol": .int(1), "version": .string(ProviderCore.version),
"installation_id": .string(instance),
"observed_at": .number(now.timeIntervalSince1970),
+ "resource_revision": .string(String(Int(now.timeIntervalSince1970 / 30))),
"linked": .bool(AuthTokenStore.load() != nil),
- "account_revision": .string(accountSession.observe(AuthTokenStore.load())),
+ "account_revision": .string(accountSession.observe("\(loaded.config.coordinator.url)\n\(accountReadToken() ?? "")")),
+ "account": accountStatus(),
+ "capabilities": .array(["account-signin", "account-signout", "request-history", "autopilot"].map(DV.string)),
+ "autopilot": Self.autopilotSnapshot(loaded.config.backend.modelAutopilot, daemon: daemon, fresh: fresh),
"state": .string(phase),
+ "provider_status": providerStatus,
"readiness": .string(
fresh
? daemon?.trust?.reason ?? "Provider connected"
@@ -102,17 +124,13 @@ extension DesktopBackend {
"machine": machine, "models": .array(models), "operations": try .encoded(operations),
"memory": .dict([
"total_gb": .number(total),
+ "pin_budget_gb": .number(Start.pickerLoadBudgetGiB(memoryGb: total)),
+ "max_model_slots": .number(maxModelSlots),
"active_gb": .number(fresh ? daemon?.capacity?.gpuMemoryActiveGb : nil),
"cache_gb": .number(fresh ? daemon?.capacity?.gpuMemoryCacheGb : nil),
"free_for_load_gb": .number(fresh ? daemon?.capacity?.freeForLoadGb : nil),
]),
- "activity": .dict([
- "models": Self.modelActivity(daemon?.capacity, fresh: fresh, now: now.timeIntervalSince1970),
- "sampled_at": .number(fresh ? daemon?.capacity?.activityObservedAt : nil),
- "requests": fresh ? .string(String(requestCount)) : .null,
- "tokens": fresh ? .string(String(tokens)) : .null,
- "started_at": .number(fresh ? daemon?.startedAt : nil), "samples": .array(samples),
- ]),
+ "activity": .dict(activity),
"settings": .dict([
"revision": .string(DesktopStorage.revision(loaded.configPath)),
"name": .string(loaded.config.provider.name),
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopTypes.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopTypes.swift
index d3f1ceb0a9..10f219c55e 100644
--- a/provider-swift/Sources/darkbloom/Desktop/DesktopTypes.swift
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopTypes.swift
@@ -43,6 +43,8 @@ struct DesktopAction: Codable, Sendable, Equatable {
let id: String
let action: String
var models: [String]?
+ var pinned: [String]?
+ var downloads: [String]?
var model: String?
var operation: String?
var local: Bool?
@@ -61,14 +63,28 @@ struct DesktopAction: Codable, Sendable, Equatable {
guard UUID(uuidString: id) != nil else { throw ValidationError("Invalid request ID") }
let known = [
"start", "switch", "stop", "restart", "download", "remove", "settings", "link", "unlink",
- "update", "diagnose", "cancel", "cooling",
+ "update", "diagnose", "cancel", "cooling", "account-signin", "account-signout",
+ "autopilot", "autopilot_pin", "autopilot_unpin", "autopilot_pause", "autopilot_resume",
+ "autopilot_disable", "autopilot_models",
]
guard known.contains(action) else { throw ValidationError("Unknown action") }
- if ["start", "switch"].contains(action) {
+ if ["start", "switch", "autopilot", "autopilot_pin", "autopilot_unpin"].contains(action) {
guard let models, !models.isEmpty, models.count <= 32, Set(models).count == models.count
else { throw ValidationError("Choose at least one model") }
try models.forEach(Self.validateModel)
}
+ if action == "autopilot" {
+ guard local != true, let pinned, Set(pinned).isSubset(of: Set(models ?? [])),
+ Set(pinned).count == pinned.count
+ else { throw ValidationError("Autopilot pins must be startup models") }
+ try pinned.forEach(Self.validateModel)
+ if let downloads {
+ guard downloads.count <= 256, Set(downloads).count == downloads.count else {
+ throw ValidationError("Invalid Autopilot downloads")
+ }
+ try downloads.forEach(Self.validateModel)
+ }
+ }
if ["download", "remove"].contains(action) { try Self.validateModel(model ?? "") }
if action == "settings" {
guard let name, !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
@@ -83,7 +99,7 @@ struct DesktopAction: Codable, Sendable, Equatable {
try schedule.validate()
}
if action == "cooling" {
- guard enabled != nil, (30...100).contains(speed ?? 70), (40...90).contains(temperature ?? 50)
+ guard enabled != nil, (60...90).contains(speed ?? 70), (40...90).contains(temperature ?? 50)
else { throw ValidationError("Invalid cooling policy") }
}
}
@@ -108,4 +124,6 @@ struct DesktopOperation: Codable, Sendable {
var finished_at: Double?
var message = "Working…"
var cancellable: Bool
+ var model: String?
+ var progress: Double?
}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopUsageArchive.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopUsageArchive.swift
new file mode 100644
index 0000000000..3590bb7371
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopUsageArchive.swift
@@ -0,0 +1,66 @@
+import Foundation
+import ProviderCore
+
+/// Persisted settlement metadata is scoped to the exact Mac, coordinator and account.
+struct DesktopUsageArchive: Codable, Sendable {
+ struct Settlement: Codable, Sendable, Equatable {
+ let id: String
+ var jobID: String? = nil
+ let providerKey: String
+ let completedAt: Double
+ let input: UInt64
+ let output: UInt64
+ let earnings: UInt64
+ }
+ struct Totals: Codable, Sendable {
+ var input: UInt64 = 0
+ var output: UInt64 = 0
+ var earnings: UInt64 = 0
+ var requests: UInt64 = 0
+ }
+ var totalsByKey: [String: Totals] = [:]
+ var scope = ""
+ var localProviderID: String?
+ var providerKeys: [String: Double] = [:]
+ var settlements: [Settlement] = []
+ var observedAt: Double?
+
+ mutating func merge(_ records: [Settlement], providerID: String, identities: [String: String], sessionStartedAt: Double) {
+ localProviderID = providerID
+ for record in records where identities[record.id] == providerID {
+ providerKeys[record.providerKey] = sessionStartedAt
+ }
+ var known = Dictionary(settlements.map { ($0.id, $0) }, uniquingKeysWith: { _, latest in latest })
+ for record in records where providerKeys[record.providerKey] != nil {
+ let previous = known[record.id]
+ var totals = totalsByKey[record.providerKey] ?? Totals()
+ totals.input = totals.input - (previous?.input ?? 0) + record.input
+ totals.output = totals.output - (previous?.output ?? 0) + record.output
+ totals.earnings = totals.earnings - (previous?.earnings ?? 0) + record.earnings
+ if previous == nil { totals.requests += 1 }
+ totalsByKey[record.providerKey] = totals
+ known[record.id] = record
+ }
+ settlements = Array(known.values.sorted { $0.completedAt > $1.completedAt }.prefix(4096))
+ }
+
+ func totals(since: Double, requests: UInt64) -> JSONValue {
+ guard observedAt != nil else { return .null }
+ let rows = totalsByKey.filter { providerKeys[$0.key] == since }.map(\.value)
+ let input = rows.reduce(UInt64(0)) { $0 + $1.input }
+ let output = rows.reduce(UInt64(0)) { $0 + $1.output }
+ let earned = rows.reduce(UInt64(0)) { $0 + $1.earnings }
+ let counted = rows.reduce(UInt64(0)) { $0 + $1.requests }
+ guard counted > 0 || requests == 0 else { return .null }
+ return .dict([
+ "processed_tokens": .string(String(input + output)),
+ "processed_input_tokens": .string(String(input)),
+ "processed_output_tokens": .string(String(output)),
+ "counted_requests": .string(String(counted)),
+ "pending_usage_requests": .string(String(requests > counted ? requests - counted : 0)),
+ "earnings_micro_usd": .string(String(earned)),
+ "usage_source": .string("settled-history"),
+ "usage_observed_at": .number(observedAt),
+ ])
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopUsageHistory.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopUsageHistory.swift
new file mode 100644
index 0000000000..4a0b2d3703
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopUsageHistory.swift
@@ -0,0 +1,108 @@
+import Crypto
+import Foundation
+import ProviderCore
+
+extension DesktopBackend {
+ /// Called by state polling, with one network refresh shared across readers.
+ func refreshUsageHistoryIfNeeded(daemon: DaemonState, now: Date) {
+ guard let token = usageCredentialToken(), let identity = daemon.attestationPublicKey else {
+ usageArchive = DesktopUsageArchive()
+ return
+ }
+ let configuredBase = coordinatorHTTPBase((try? configuration().config.coordinator.url) ?? "")
+ let base = coordinatorHTTPBase(daemon.coordinatorUrl ?? configuredBase)
+ // A daemon from another coordinator must never receive this account session.
+ guard base == configuredBase else { return }
+ let scope = SHA256.hash(data: Data("\(base)\n\(identity)\n\(token)".utf8)).map { String(format: "%02x", $0) }.joined()
+ if usageArchive.scope != scope {
+ let saved = DesktopStorage.read(DesktopUsageArchive.self, name: "usage-history.json")
+ let legacyBase = daemon.coordinatorUrl ?? (try? configuration().config.coordinator.url) ?? ""
+ let legacyScope = SHA256.hash(data: Data("\(legacyBase)\n\(identity)\n\(token)".utf8)).map { String(format: "%02x", $0) }.joined()
+ if let saved, saved.scope == scope || saved.scope == legacyScope {
+ usageArchive = saved
+ usageArchive.scope = scope
+ } else { usageArchive = DesktopUsageArchive(scope: scope) }
+ usageReadAt = .distantPast
+ }
+ guard usageRead == nil, now.timeIntervalSince(usageReadAt) >= 30 else { return }
+ usageReadAt = now
+ let generation = resourceGeneration
+ usageRead = Task {
+ defer { if generation == resourceGeneration { usageRead = nil } }
+ do {
+ async let roster = cachedResource(token.hasPrefix("darkbloom-at-") ? "owned-providers" : "legacy-roster", base: base, token: token.hasPrefix("darkbloom-at-") ? token : nil, ttl: 300)
+ async let ledger = accountEarnings(base: base, token: token)
+ let (providers, history) = try await (roster, ledger)
+ guard generation == resourceGeneration, usageCredentialToken() == token, usageArchive.scope == scope,
+ DaemonStateFile.read()?.startedAt == daemon.startedAt,
+ let provider = providers.field("providers").values.first(where: { $0.field("se_public_key").text == identity }),
+ let providerID = provider.field("id").text ?? provider.field("provider_id").text else { return }
+ let (records, identities) = Self.parseUsageSettlements(history)
+ if !history.field("earnings").values.isEmpty && records.isEmpty { throw URLError(.cannotParseResponse) }
+ usageArchive.merge(records, providerID: providerID, identities: identities, sessionStartedAt: daemon.startedAt)
+ usageArchive.observedAt = Date().timeIntervalSince1970
+ try DesktopStorage.write(usageArchive, name: "usage-history.json")
+ } catch {
+ // Keep the last verified records; absent usage never becomes zero.
+ }
+ }
+ }
+
+ static func usageInteger(_ value: JSONValue) -> UInt64? {
+ switch value {
+ case .int(let v): return v >= 0 ? UInt64(v) : nil
+ case .string(let v): return UInt64(v)
+ default: return nil
+ }
+ }
+
+ static func readUsageJSON(base: String, path: String, token: String?, query: [URLQueryItem] = []) async throws -> JSONValue {
+ guard var url = URLComponents(string: base.replacingOccurrences(of: "wss://", with: "https://").replacingOccurrences(of: "ws://", with: "http://")) else { throw URLError(.badURL) }
+ url.path = path; url.query = nil; url.fragment = nil
+ url.queryItems = !query.isEmpty ? query : (path == "/v1/provider/account-earnings" ? [URLQueryItem(name: "limit", value: "1000")] : nil)
+ guard let endpoint = url.url else { throw URLError(.badURL) }
+ var request = URLRequest(url: endpoint); request.timeoutInterval = 15
+ if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
+ let (data, response) = try await URLSession.shared.data(for: request)
+ if let status = (response as? HTTPURLResponse)?.statusCode, [401, 403].contains(status), token?.hasPrefix("darkbloom-at-") == true { throw URLError(.userAuthenticationRequired) }
+ guard (response as? HTTPURLResponse)?.statusCode == 200, data.count <= 4_000_000 else { throw URLError(.badServerResponse) }
+ return try JSONDecoder().decode(JSONValue.self, from: data)
+ }
+
+ func sessionUsage(daemon: DaemonState?, fresh: Bool, now: Date) -> [String: JSONValue] {
+ guard fresh, let daemon else { return [:] }
+ refreshUsageHistoryIfNeeded(daemon: daemon, now: now)
+ var fields: [String: JSONValue] = [:]
+ if case .object(let pairs) = usageArchive.totals(since: daemon.startedAt, requests: daemon.stats.requestsServed) {
+ fields = Dictionary(uniqueKeysWithValues: pairs)
+ }
+ if let input = daemon.stats.promptTokensProcessed, daemon.stats.usageGaps == 0 {
+ let output = daemon.stats.tokensGenerated
+ fields["processed_tokens"] = .string(String(input + output))
+ fields["processed_input_tokens"] = .string(String(input))
+ fields["processed_output_tokens"] = .string(String(output))
+ fields["cached_input_tokens"] = daemon.stats.cachedInputTokens.map { .string(String($0)) } ?? .null
+ fields["reasoning_tokens"] = daemon.stats.reasoningTokens.map { .string(String($0)) } ?? .null
+ fields["usage_source"] = .string("local")
+ fields["counted_requests"] = .string(String(daemon.stats.requestsServed))
+ fields["pending_usage_requests"] = .string("0")
+ } else if daemon.stats.promptTokensProcessed != nil {
+ let records = ProviderUsageHistory.read().filter { $0.sessionStartedAt == daemon.startedAt && $0.exact }
+ let input = records.reduce(UInt64(0)) { $0 + $1.inputTokens }
+ let output = records.reduce(UInt64(0)) { $0 + $1.outputTokens }
+ fields["processed_tokens"] = .string(String(input + output))
+ fields["processed_input_tokens"] = .string(String(input))
+ fields["processed_output_tokens"] = .string(String(output))
+ fields["counted_requests"] = .string(String(records.count))
+ fields["pending_usage_requests"] = .string(String(max(daemon.stats.requestsServed, UInt64(records.count)) - UInt64(records.count)))
+ fields["usage_source"] = .string("local")
+ } else if daemon.stats.requestsServed == 0 {
+ fields["processed_tokens"] = .string("0")
+ fields["processed_input_tokens"] = .string("0")
+ fields["processed_output_tokens"] = .string("0")
+ fields["counted_requests"] = .string("0")
+ fields["pending_usage_requests"] = .string("0")
+ }
+ return fields
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopUsageSettlement.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopUsageSettlement.swift
new file mode 100644
index 0000000000..14b555e997
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/Desktop/DesktopUsageSettlement.swift
@@ -0,0 +1,26 @@
+import Foundation
+import ProviderCore
+
+extension DesktopBackend {
+ static func parseUsageSettlements(_ history: JSONValue) -> ([DesktopUsageArchive.Settlement], [String: String]) {
+ let iso = ISO8601DateFormatter(); iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ let plain = ISO8601DateFormatter()
+ var identities: [String: String] = [:]
+ let records = history.field("earnings").values.compactMap { row -> DesktopUsageArchive.Settlement? in
+ guard let id = Self.integerText(row.field("id")).text,
+ let key = row.field("provider_key").text,
+ let providerID = row.field("provider_id").text,
+ let timestamp = row.field("created_at").text,
+ let time = iso.date(from: timestamp) ?? plain.date(from: timestamp),
+ let input = Self.usageInteger(row.field("prompt_tokens")),
+ let output = Self.usageInteger(row.field("completion_tokens")),
+ let earned = Self.usageInteger(row.field("amount_micro_usd")) else { return nil }
+ identities[id] = providerID
+ var record = DesktopUsageArchive.Settlement(id: id, providerKey: key, completedAt: time.timeIntervalSince1970,
+ input: input, output: output, earnings: earned)
+ record.jobID = row.field("job_id").text
+ return record
+ }
+ return (records, identities)
+ }
+}
diff --git a/provider-swift/Tests/DarkbloomCLITests/DesktopAccountCloudTests.swift b/provider-swift/Tests/DarkbloomCLITests/DesktopAccountCloudTests.swift
new file mode 100644
index 0000000000..369c0867fb
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/DesktopAccountCloudTests.swift
@@ -0,0 +1,58 @@
+import Foundation
+import ProviderCore
+import Testing
+@testable import darkbloom
+
+struct DesktopAccountCloudTests {
+ @Test func dashboardCredentialAcceptsScopedAndExistingDeviceTokensOnly() {
+ #expect(DesktopAccountCredential.supports(token: "darkbloom-at-test"))
+ #expect(DesktopAccountCredential.supports(token: "eigeninference-pt-test"))
+ #expect(!DesktopAccountCredential.supports(token: "consumer-api-key"))
+ }
+ @Test func identifiesThisMacByIdentityAndUsesAuthoritativeLoadedSlots() throws {
+ let fleet = try JSONDecoder().decode(JSONValue.self, from: Data("""
+ {"providers":[
+ {"id":"local-id","se_public_key":"local-se"},
+ {"id":"remote-id","se_public_key":"other-se","hardware":{"machine_model":"Mac Studio","chip_name":"Apple M3 Ultra","memory_gb":192},"status":"online","warm_models":["stale-model"],"backend_capacity":{"slots":[{"model":"idle-model","state":"idle"},{"model":"running-model","state":"running"},{"model":"crashed-model","state":"crashed"}]},"last_heartbeat":"2026-10-05T14:00:00.123Z"}
+ ]}
+ """.utf8))
+ let summary: JSONValue = .dict(["account_id": .string("owner"), "lifetime_micro_usd": .int(9007199254740993), "last_7d_micro_usd": .int(100), "withdrawable_balance_micro_usd": .int(200)])
+ let projected = DesktopBackend.projectAccountCloud(fleet: fleet, summary: summary, identity: "local-se")
+ #expect(projected.field("lifetime_micro_usd").text == "9007199254740993")
+ #expect(projected.field("local_provider_id").text == "local-id")
+ let machines = projected.field("machines").values
+ #expect(machines.count == 1)
+ #expect(machines.first?.field("models").values.compactMap(\.text) == ["idle-model", "running-model"])
+ #expect(machines.first?.field("se_public_key") == .null)
+ #expect(machines.first?.field("observed_at").number != nil)
+ #expect(machines.first?.field("earnings_micro_usd") == .null)
+ }
+
+ @Test func unknownLocalIdentityDoesNotHideAnOwnedMacOrInventZeroMoney() {
+ let fleet: JSONValue = .dict(["providers": .array([.dict(["id": .string("remote"), "hardware": .dict([:]), "status": .string("offline")])])])
+ let result = DesktopBackend.projectAccountCloud(fleet: fleet, summary: .dict([:]), identity: nil)
+ #expect(result.field("machines").values.count == 1)
+ #expect(result.field("lifetime_micro_usd") == .null)
+ #expect(result.field("local_provider_id") == .null)
+ }
+
+ @Test func localizesOnlyTheVerifiedMachineInInsights() {
+ let source: JSONValue = .dict(["machines": .array([.dict(["id": .string("local"), "jobs": .string("2")]), .dict(["id": .string("other"), "jobs": .string("5")])])])
+ let result = DesktopBackend.localizeInsights(source, providerID: "local")
+ #expect(result.field("machines").values.map { $0.field("id").text } == ["this-mac", "other"])
+ #expect(DesktopBackend.localizeInsights(source, providerID: nil) == source)
+ }
+ @Test func localHistoryJoinsSettledMoneyByJobIDOnly() throws {
+ let local = ProviderUsageRecord(id: "request", sessionStartedAt: 10, completedAt: 20, model: "model", inputTokens: 100, outputTokens: 20, cachedInputTokens: nil, reasoningTokens: nil, exact: true)
+ var settlement = DesktopUsageArchive.Settlement(id: "ledger-row", providerKey: "key", completedAt: 30, input: 100, output: 20, earnings: 40)
+ settlement.jobID = "request"
+ let joined = try DesktopBackend.localRequestHistory([local], settlements: [settlement]).field("records").values[0]
+ #expect(joined.field("earnings_micro_usd").text == "40")
+ #expect(joined.field("completed_at").number == 20)
+ #expect(joined.field("input_tokens").number == 100)
+ settlement.jobID = "another-request"
+ let pending = try DesktopBackend.localRequestHistory([local], settlements: [settlement]).field("records").values[0]
+ #expect(pending.field("earnings_micro_usd") == .null)
+ }
+
+}
diff --git a/provider-swift/Tests/DarkbloomCLITests/DesktopAccountEarningsTests.swift b/provider-swift/Tests/DarkbloomCLITests/DesktopAccountEarningsTests.swift
new file mode 100644
index 0000000000..97c234b2f3
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/DesktopAccountEarningsTests.swift
@@ -0,0 +1,59 @@
+import Foundation
+import ProviderCore
+import Testing
+@testable import darkbloom
+
+struct DesktopAccountEarningsTests {
+ let now = ISO8601DateFormatter().date(from: "2026-10-04T18:00:00Z")!
+ func row(_ id: Int64, key: String, model: String = "test", amount: Int64, at: String, input: Int64 = 120, output: Int64 = 30) -> JSONValue {
+ .dict(["id": .int(id), "provider_key": .string(key), "model": .string(model),
+ "amount_micro_usd": .int(amount), "prompt_tokens": .int(input), "completion_tokens": .int(output), "created_at": .string(at)])
+ }
+ func ledger(_ rows: [JSONValue], lifetime: Int64, count: Int64) -> JSONValue {
+ .dict(["account_id": .string("test-account"), "total_micro_usd": .int(lifetime), "count": .int(count),
+ "available_balance_micro_usd": .int(7000), "earnings": .array(rows)])
+ }
+ @Test func combinesMacsOnceAndSeparatesRewardsWithoutChangingLifetimeSummary() throws {
+ let own = row(1, key: "own", amount: 1000, at: "2026-10-04T10:00:00Z")
+ let other = row(2, key: "other", amount: 2000, at: "2026-10-03T10:00:00Z")
+ let reward = row(3, key: "own", model: "base_reward", amount: 5000, at: "2026-10-04T12:00:00Z", input: 0, output: 0)
+ let earnings = try DesktopAccountEarnings(ledger([own, other, reward, own], lifetime: 8000, count: 2), localKeys: ["own"], now: now)
+ let cloud = earnings.cloud(), insights = earnings.insights("7d")
+ #expect(cloud.field("lifetime_micro_usd").text == "8000")
+ #expect(cloud.field("week_micro_usd").text == "8000")
+ #expect(cloud.field("local_earnings_micro_usd").text == "6000")
+ #expect(cloud.field("earnings_complete").flag == true)
+ #expect(insights.field("totals").field("work_micro_usd").text == "3000")
+ #expect(insights.field("totals").field("base_reward_micro_usd").text == "5000")
+ #expect(insights.field("totals").field("jobs").text == "2")
+ #expect(insights.field("totals").field("prompt_tokens").text == "240")
+ #expect(insights.field("days").values.count == 7)
+ }
+ @Test func truncatedRecentRecordsDoNotPretendToCoverSevenDaysOrLifetimeTokens() throws {
+ let earnings = try DesktopAccountEarnings(ledger([row(1, key: "own", amount: 1000, at: "2026-10-04T10:00:00Z")], lifetime: 900000, count: 5000), localKeys: [], now: now)
+ let cloud = earnings.cloud(), insights = earnings.insights("7d")
+ #expect(cloud.field("lifetime_micro_usd").text == "900000")
+ #expect(cloud.field("week_micro_usd").text == "1000")
+ #expect(cloud.field("earnings_complete").flag == false)
+ #expect(cloud.field("local_earnings_micro_usd") == .null)
+ #expect(cloud.field("local_day_micro_usd") == .null)
+ #expect(insights.field("history_complete").flag == false)
+ #expect(insights.field("lifetime").field("completion_tokens") == .null)
+ #expect(insights.field("days").values.count == 7)
+ #expect(insights.field("days").values.filter { $0.field("available").flag == false }.count == 6)
+ #expect(insights.field("days").values.last?.field("complete").flag == false)
+ }
+ @Test func olderPageBoundaryProvesWeekCoverageButNotMonthCoverage() throws {
+ let earnings = try DesktopAccountEarnings(ledger([
+ row(1, key: "own", amount: 9999, at: "2026-09-27T10:00:00Z"),
+ row(2, key: "own", amount: 1000, at: "2026-10-04T10:00:00Z")], lifetime: 900000, count: 5000), localKeys: ["own"], now: now)
+ #expect(earnings.cloud().field("earnings_complete").flag == true)
+ #expect(earnings.cloud().field("week_micro_usd").text == "1000")
+ #expect(earnings.insights("30d").field("history_complete").flag == false)
+ }
+ @Test func rejectsMalformedRowsInsteadOfInventingZeroEarnings() throws {
+ #expect(throws: (any Error).self) {
+ try DesktopAccountEarnings(ledger([.dict(["id": .int(1)])], lifetime: 1000, count: 1), localKeys: [], now: now)
+ }
+ }
+}
diff --git a/provider-swift/Tests/DarkbloomCLITests/DesktopAccountIdentityTests.swift b/provider-swift/Tests/DarkbloomCLITests/DesktopAccountIdentityTests.swift
new file mode 100644
index 0000000000..3fec6eba76
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/DesktopAccountIdentityTests.swift
@@ -0,0 +1,39 @@
+import Foundation
+import ProviderCore
+import Testing
+@testable import darkbloom
+
+struct DesktopAccountIdentityTests {
+ private let base = "https://coordinator.test"
+ private var credential: DesktopAccountCredential {
+ DesktopAccountCredential(token: "darkbloom-at-test", base: base, expiresAt: Date(timeIntervalSince1970: 2_000_000_000))
+ }
+
+ @Test func identityIsBoundToCoordinatorAndAccountCredential() {
+ let payload: JSONValue = .dict(["email": .string(" owner@example.com ")])
+ let original = credential
+ let updated = original.withIdentity(payload, base: base, token: original.token)
+ #expect(updated.email == "owner@example.com")
+ #expect(updated.token == original.token)
+ #expect(updated.expiresAt == original.expiresAt)
+ #expect(original.withIdentity(payload, base: "https://other.test", token: original.token).email == nil)
+ #expect(original.withIdentity(payload, base: base, token: "another-account-token").email == nil)
+ }
+
+ @Test func identitySurvivesRestartAndOlderCredentialFilesStillDecode() throws {
+ let original = credential
+ let legacy = try JSONSerialization.data(withJSONObject: ["token": original.token, "base": base, "expiresAt": original.expiresAt.timeIntervalSinceReferenceDate])
+ #expect(try JSONDecoder().decode(DesktopAccountCredential.self, from: legacy).email == nil)
+ let updated = original.withIdentity(.dict(["email": .string("owner@example.com")]), base: base, token: original.token)
+ let saved = try JSONEncoder().encode(updated)
+ #expect(try JSONDecoder().decode(DesktopAccountCredential.self, from: saved).email == "owner@example.com")
+ }
+
+ @Test func missingIdentityDoesNotInventEmailOrEraseLastVerifiedIdentity() {
+ let original = credential
+ #expect(original.withIdentity(.dict([:]), base: base, token: original.token).email == nil)
+ let identified = original.withIdentity(.dict(["email": .string("owner@example.com")]), base: base, token: original.token)
+ #expect(identified.withIdentity(.dict(["email": .null]), base: base, token: identified.token).email == "owner@example.com")
+ #expect(identified.withIdentity(.dict(["email": .string(" ")]), base: base, token: identified.token).email == "owner@example.com")
+ }
+}
diff --git a/provider-swift/Tests/DarkbloomCLITests/DesktopActionArgumentsTests.swift b/provider-swift/Tests/DarkbloomCLITests/DesktopActionArgumentsTests.swift
index 6eea160c6f..c17a6152c1 100644
--- a/provider-swift/Tests/DarkbloomCLITests/DesktopActionArgumentsTests.swift
+++ b/provider-swift/Tests/DarkbloomCLITests/DesktopActionArgumentsTests.swift
@@ -1,5 +1,6 @@
import ArgumentParser
import Foundation
+import ProviderCore
import Testing
@testable import darkbloom
@@ -48,6 +49,13 @@ struct DesktopActionArgumentsTests {
Case(action: action("unlink"), localActive: local, forwardsConfig: false),
Case(action: action("download") { $0.model = model }, localActive: local, forwardsConfig: true),
Case(action: action("remove") { $0.model = model }, localActive: local, forwardsConfig: true),
+ Case(action: action("autopilot") { $0.models = [model]; $0.pinned = [] }, localActive: local, forwardsConfig: true),
+ Case(action: action("autopilot_pin") { $0.models = [model] }, localActive: local, forwardsConfig: true),
+ Case(action: action("autopilot_unpin") { $0.models = [model] }, localActive: local, forwardsConfig: true),
+ Case(action: action("autopilot_pause"), localActive: local, forwardsConfig: true),
+ Case(action: action("autopilot_resume"), localActive: local, forwardsConfig: true),
+ Case(action: action("autopilot_disable"), localActive: local, forwardsConfig: true),
+ Case(action: action("autopilot_models"), localActive: local, forwardsConfig: true),
Case(
action: action("cooling") {
$0.enabled = true
@@ -86,4 +94,49 @@ struct DesktopActionArgumentsTests {
func localLifecycleCommandsAcceptConfig(command: String) throws {
_ = try Darkbloom.parseAsRoot(["desktop", command, "--config", Self.config])
}
+
+ @Test func refusesPinsOutsideStartupSelection() throws {
+ let request = Self.action("autopilot") { $0.models = [Self.model]; $0.pinned = ["another-model"] }
+ #expect(throws: (any Error).self) { try request.validate() }
+ }
+
+ @Test func pinFollowupUsesTheSameCLIAndConfig() throws {
+ let argv = DesktopBackend.autopilotPinArguments([Self.model], configPath: Self.config)
+ _ = try Darkbloom.parseAsRoot(argv)
+ #expect(argv == ["autopilot", "pin", Self.model, "--config", Self.config])
+ }
+
+ @Test func refreshRetainsStartupAndEndpointWithoutAnInteractiveWizard() throws {
+ let settings = ModelAutopilotSettings(enabled: true, consentRecorded: true,
+ selectedModels: [Self.model, "another-model"], revision: "test")
+ let endpoint = LocalEndpoint.Info(host: "0.0.0.0", port: 7777, apiKey: "", version: "test", pid: 1, updatedAt: "test")
+ let argv = try DesktopBackend.autopilotRefreshArguments(settings: settings,
+ startupModels: [Self.model], endpoint: endpoint, configPath: Self.config)
+ _ = try Darkbloom.parseAsRoot(argv)
+ #expect(argv == ["start", "--autopilot", "--model", Self.model, "--local-endpoint", "--port", "7777", "--bind", "0.0.0.0", "--no-auth", "--config", Self.config])
+ let fallback = try DesktopBackend.autopilotRefreshArguments(settings: settings,
+ startupModels: [], endpoint: nil, configPath: nil)
+ #expect(fallback == ["start", "--autopilot", "--model", Self.model])
+ #expect(throws: (any Error).self) {
+ try DesktopBackend.autopilotRefreshArguments(settings: ModelAutopilotSettings(),
+ startupModels: [Self.model], endpoint: nil, configPath: nil)
+ }
+ }
+
+ @Test func configuredEnrollmentDoesNotInventALivePhase() {
+ let settings = ModelAutopilotSettings(enabled: true, consentRecorded: true,
+ selectedModels: [Self.model], revision: "test")
+ let snapshot = DesktopBackend.autopilotSnapshot(settings, daemon: nil, fresh: false)
+ #expect(snapshot.field("configured").flag == true)
+ #expect(snapshot.field("enabled").flag == true)
+ #expect(snapshot.field("phase") == .null)
+ #expect(DesktopBackend.autopilotSnapshot(ModelAutopilotSettings(), daemon: nil, fresh: false).field("configured").flag == false)
+ }
+
+ @Test func progressUsesTheLatestValidDownloadPercentage() {
+ #expect(DesktopBackend.downloadProgress("10%\nmodel 40.5%") == 0.405)
+ #expect(DesktopBackend.downloadProgress("Downloaded 100%") == 1)
+ #expect(DesktopBackend.downloadProgress("Loading weights" ) == nil)
+ #expect(DesktopBackend.downloadProgress("Impossible 200%") == nil)
+ }
}
diff --git a/provider-swift/Tests/DarkbloomCLITests/DesktopAutopilotTests.swift b/provider-swift/Tests/DarkbloomCLITests/DesktopAutopilotTests.swift
new file mode 100644
index 0000000000..30890d3473
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/DesktopAutopilotTests.swift
@@ -0,0 +1,44 @@
+import Foundation
+import Testing
+@testable import darkbloom
+
+struct DesktopAutopilotTests {
+ /// A process fixture records argv; no provider, model, account or launchd action runs.
+ private func fixture() throws -> URL {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("desktop-autopilot-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let executable = directory.appendingPathComponent("cli")
+ try """
+ #!/bin/sh
+ printf '%s\\n' "$*" >> "${0}.calls"
+ if [ "$3" = "broken" ]; then exit 7; fi
+ printf '100%%\\n'
+ """.write(to: executable, atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: executable.path)
+ return executable
+ }
+
+ @Test func allDownloadsCompleteBeforeOneEnrollment() async throws {
+ let executable = try fixture()
+ defer { try? FileManager.default.removeItem(at: executable.deletingLastPathComponent()) }
+ let request = DesktopAction(id: UUID().uuidString, action: "autopilot", models: ["a"], pinned: [], downloads: ["a", "b", "c"])
+ let backend = DesktopBackend(configPath: "/tmp/autopilot-test.toml")
+ let argv = try DesktopBackend.arguments(for: request, configPath: "/tmp/autopilot-test.toml", localActive: false)
+ let result = try await backend.runAutopilot(request, arguments: argv, worker: DesktopWorker(executable: executable))
+ #expect(result.0 == 0)
+ let calls = try String(contentsOfFile: executable.path + ".calls", encoding: .utf8).split(separator: "\n")
+ #expect(calls == ["models download a --config /tmp/autopilot-test.toml", "models download b --config /tmp/autopilot-test.toml", "models download c --config /tmp/autopilot-test.toml", "start --autopilot --model a --config /tmp/autopilot-test.toml"])
+ }
+
+ @Test func downloadFailureNeverStartsOrEnrollsTheProvider() async throws {
+ let executable = try fixture()
+ defer { try? FileManager.default.removeItem(at: executable.deletingLastPathComponent()) }
+ let request = DesktopAction(id: UUID().uuidString, action: "autopilot", models: ["a"], pinned: [], downloads: ["a", "broken", "c"])
+ let backend = DesktopBackend(configPath: nil)
+ await #expect(throws: (any Error).self) {
+ try await backend.runAutopilot(request, arguments: ["start", "--autopilot", "--model", "a"], worker: DesktopWorker(executable: executable))
+ }
+ let calls = try String(contentsOfFile: executable.path + ".calls", encoding: .utf8).split(separator: "\n")
+ #expect(calls == ["models download a", "models download broken"])
+ }
+}
diff --git a/provider-swift/Tests/DarkbloomCLITests/DesktopCoolingAuthorizationTests.swift b/provider-swift/Tests/DarkbloomCLITests/DesktopCoolingAuthorizationTests.swift
new file mode 100644
index 0000000000..f0c4487de1
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/DesktopCoolingAuthorizationTests.swift
@@ -0,0 +1,49 @@
+import Foundation
+import Testing
+@testable import darkbloom
+
+struct DesktopCoolingAuthorizationTests {
+ let firmware = "execution error: fan ownership recovery failed: restoreMode fan 0: SMC firmware rejected writeBytes for F0Md (0x82); clearFtst global: Ftst remained 1 (1)"
+ @Test func retriesTransientFirmwareRestorationButPreservesTheCommand() async throws {
+ let runner = Runner([(1, firmware), (0, "Fan enabled")])
+ let value = try await DesktopCoolingAuthorization.perform(script: "verified-command",
+ run: { await runner.run($0) }, pause: {})
+ #expect(value == "Fan enabled")
+ #expect(await runner.scripts == ["verified-command", "verified-command"])
+ }
+ @Test func permanentFirmwareFailureRemainsVisibleAfterThreeAttempts() async throws {
+ let runner = Runner(Array(repeating: (1, firmware), count: 3))
+ do {
+ _ = try await DesktopCoolingAuthorization.perform(script: "verified-command",
+ run: { await runner.run($0) }, pause: {})
+ Issue.record("Persistent restoration failure must not succeed")
+ } catch let error as DesktopCoolingAuthorization.Failure {
+ #expect(!error.cancelled)
+ #expect(error.description.contains("F0Md (0x82)"))
+ #expect(!error.description.contains("authorization cancelled"))
+ }
+ #expect(await runner.scripts.count == 3)
+ }
+ @Test func authorizationCancellationAndOtherFailuresAreNotRetried() async throws {
+ for message in ["User canceled. (-128)", "signed helper missing", "foreign manual control"] {
+ let runner = Runner([(1, message)])
+ do {
+ _ = try await DesktopCoolingAuthorization.perform(script: "verified-command",
+ run: { await runner.run($0) }, pause: {})
+ Issue.record("Failed command must remain failed")
+ } catch let error as DesktopCoolingAuthorization.Failure {
+ #expect(error.cancelled == message.contains("(-128)"))
+ }
+ #expect(await runner.scripts.count == 1)
+ }
+ }
+}
+private actor Runner {
+ var results: [(Int32, String)]
+ var scripts: [String] = []
+ init(_ results: [(Int32, String)]) { self.results = results }
+ func run(_ script: String) -> (Int32, String) {
+ scripts.append(script)
+ return results.removeFirst()
+ }
+}
diff --git a/provider-swift/Tests/DarkbloomCLITests/DesktopCoolingCacheTests.swift b/provider-swift/Tests/DarkbloomCLITests/DesktopCoolingCacheTests.swift
index fe8a065260..fcb76e36ba 100644
--- a/provider-swift/Tests/DarkbloomCLITests/DesktopCoolingCacheTests.swift
+++ b/provider-swift/Tests/DarkbloomCLITests/DesktopCoolingCacheTests.swift
@@ -6,6 +6,16 @@ import Testing
/// The cooling resource runs a real child process; rapid and concurrent reads
/// must share one run instead of each spawning `fan status`.
struct DesktopCoolingCacheTests {
+ @Test func enabledHelperIsDistinctFromItsCurrentFanMode() {
+ for mode in ["automatic", "manual"] {
+ let status: DV = .dict(["loaded": .bool(true), "helper": .dict(["mode": .string(mode)]), "diagnostic": .dict(["supported": .bool(true)])])
+ #expect(DesktopBackend.projectCooling(status, controlAvailable: true).field("enabled").flag == true)
+ }
+ let disabled: DV = .dict(["loaded": .bool(false), "helper": .null])
+ #expect(DesktopBackend.projectCooling(disabled, controlAvailable: true).field("enabled").flag == false)
+ let failed: DV = .dict(["loaded": .bool(true), "helperError": .string("Unavailable")])
+ #expect(DesktopBackend.projectCooling(failed, controlAvailable: true).field("enabled") == .null)
+ }
/// A stand-in CLI that counts its runs and prints a `fan status --json` body.
static func fakeCLI() throws -> (directory: URL, script: URL, counter: URL) {
let directory = FileManager.default.temporaryDirectory
diff --git a/provider-swift/Tests/DarkbloomCLITests/DesktopMacStatsTests.swift b/provider-swift/Tests/DarkbloomCLITests/DesktopMacStatsTests.swift
new file mode 100644
index 0000000000..289f2c4b76
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/DesktopMacStatsTests.swift
@@ -0,0 +1,40 @@
+import Foundation
+import ProviderCore
+import Testing
+@testable import darkbloom
+
+struct DesktopMacStatsTests {
+ @Test func settledHistoryOnlyContainsVerifiedMacAndDoesNotInventTiming() throws {
+ let fixtures = DesktopAccountEarningsTests()
+ let ledger = fixtures.ledger([
+ fixtures.row(1, key: "mine", amount: 100, at: "2026-10-04T10:00:00Z"),
+ fixtures.row(2, key: "another-mac", amount: 10000, at: "2026-10-04T11:00:00Z"),
+ fixtures.row(3, key: "mine", model: "base_reward", amount: 500, at: "2026-10-04T12:00:00Z")
+ ], lifetime: 10600, count: 2)
+ let data = try DesktopAccountEarnings(ledger, localKeys: ["mine"], now: fixtures.now).requestHistory()
+ let records = data.field("records").values
+ #expect(records.count == 1)
+ #expect(records.first?.field("id").text == "1")
+ #expect(records.first?.field("outcome").text == "settled")
+ #expect(records.first?.field("input_tokens") == .int(120))
+ #expect(records.first?.field("earnings_micro_usd").text == "100")
+ #expect(records.first?.field("started_at") == .null)
+ #expect(records.first?.field("duration_ms") == .null)
+ #expect(throws: (any Error).self) {
+ try DesktopAccountEarnings(ledger, localKeys: [], now: fixtures.now).requestHistory()
+ }
+ }
+ @Test func fanResolutionUsesOnlyVerifiedCandidatesAndHandlesRejectedSignature() throws {
+ let preview = URL(fileURLWithPath: "/preview/unsigned"), installed = URL(fileURLWithPath: "/signed/Darkbloom.app/Contents/MacOS/darkbloom")
+ var seen: [URL] = []
+ let selected = try DesktopFanRuntime.select([preview, installed]) { candidate in
+ seen.append(candidate)
+ if candidate == preview { throw URLError(.noPermissionsToReadFile) }
+ return candidate == installed
+ }
+ #expect(selected == installed)
+ #expect(seen == [preview, installed])
+ #expect(throws: (any Error).self) { try DesktopFanRuntime.select([preview, installed]) { _ in false } }
+ #expect(try DesktopFanRuntime.select([installed, preview]) { $0 == installed } == installed)
+ }
+}
diff --git a/provider-swift/Tests/DarkbloomCLITests/DesktopUsageHistoryTests.swift b/provider-swift/Tests/DarkbloomCLITests/DesktopUsageHistoryTests.swift
new file mode 100644
index 0000000000..8df2a55212
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/DesktopUsageHistoryTests.swift
@@ -0,0 +1,63 @@
+import Foundation
+import ProviderCore
+import Testing
+@testable import darkbloom
+
+struct DesktopUsageHistoryTests {
+ @Test func historyDeduplicatesAndScopesBothMacAndSession() throws {
+ var history = DesktopUsageArchive()
+ let own = DesktopUsageArchive.Settlement(id: "one", providerKey: "own-key", completedAt: 120, input: 120, output: 30, earnings: 1000)
+ let other = DesktopUsageArchive.Settlement(id: "other", providerKey: "other-key", completedAt: 120, input: 9000, output: 500, earnings: 5000)
+ history.merge([own, other], providerID: "this-mac", identities: ["one": "this-mac", "other": "other-mac"], sessionStartedAt: 100)
+ history.merge([own, other], providerID: "this-mac", identities: ["one": "this-mac", "other": "other-mac"], sessionStartedAt: 100)
+ history.observedAt = 130
+ let value = history.totals(since: 100, requests: 2)
+ #expect(value.field("processed_tokens").text == "150")
+ #expect(value.field("processed_input_tokens").text == "120")
+ #expect(value.field("processed_output_tokens").text == "30")
+ #expect(value.field("earnings_micro_usd").text == "1000")
+ #expect(value.field("pending_usage_requests").text == "1")
+ #expect(history.settlements.count == 1)
+ #expect(history.totals(since: 200, requests: 0).field("processed_tokens").text == "0")
+ let restored = try JSONDecoder().decode(DesktopUsageArchive.self, from: JSONEncoder().encode(history))
+ #expect(restored.totals(since: 100, requests: 2) == value)
+ }
+ @Test func trimmingOldRowsPreservesAccumulatedSessionTotals() {
+ var history = DesktopUsageArchive()
+ let records = (0..<4200).map { index in
+ DesktopUsageArchive.Settlement(id: String(index), providerKey: "own-key", completedAt: Double(index), input: 10, output: 5, earnings: 1)
+ }
+ history.merge(records, providerID: "this-mac", identities: Dictionary(uniqueKeysWithValues: records.map { ($0.id, "this-mac") }), sessionStartedAt: 100)
+ history.observedAt = 5000
+ history.merge(Array(records.suffix(1000)), providerID: "this-mac", identities: [:], sessionStartedAt: 100)
+ #expect(history.settlements.count == 4096)
+ #expect(history.totals(since: 100, requests: 4200).field("processed_tokens").text == "63000")
+ #expect(history.totals(since: 100, requests: 4200).field("pending_usage_requests").text == "0")
+ }
+ @Test func aLaterSettlementOfThePreviousSessionStaysOutOfTheNewSession() {
+ var history = DesktopUsageArchive()
+ let old = DesktopUsageArchive.Settlement(id: "old", providerKey: "old-key", completedAt: 300, input: 120, output: 30, earnings: 1)
+ let new = DesktopUsageArchive.Settlement(id: "new", providerKey: "new-key", completedAt: 250, input: 10, output: 5, earnings: 1)
+ history.merge([old], providerID: "previous", identities: ["old": "previous"], sessionStartedAt: 100)
+ history.merge([old, new], providerID: "current", identities: ["old": "previous", "new": "current"], sessionStartedAt: 200)
+ history.observedAt = 400
+ #expect(history.totals(since: 200, requests: 1).field("processed_tokens").text == "15")
+ }
+ @Test func settlementParserAcceptsTheProductionIntegerIDAndExactUsage() throws {
+ let json = try JSONDecoder().decode(JSONValue.self, from: Data(#"{"earnings":[{"id":221610837,"provider_id":"this-mac","provider_key":"key","prompt_tokens":120,"completion_tokens":30,"amount_micro_usd":1000,"created_at":"2026-10-04T17:20:00.367667Z"}]}"#.utf8))
+ let (records, identities) = DesktopBackend.parseUsageSettlements(json)
+ #expect(records.count == 1)
+ #expect(records.first?.id == "221610837")
+ #expect(records.first?.input == 120)
+ #expect(records.first?.output == 30)
+ #expect(identities["221610837"] == "this-mac")
+ }
+ @Test func absentHistoryIsUnknownAndIntegerUsageIsStrict() {
+ #expect(DesktopUsageArchive().totals(since: 100, requests: 2) == .null)
+ var observed = DesktopUsageArchive(); observed.observedAt = 130
+ #expect(observed.totals(since: 100, requests: 2) == .null)
+ #expect(DesktopBackend.usageInteger(.int(-1)) == nil)
+ #expect(DesktopBackend.usageInteger(.double(1.5)) == nil)
+ #expect(DesktopBackend.usageInteger(.string("9007199254740993")) == 9_007_199_254_740_993)
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/Auth/DeviceCodeLoginTests.swift b/provider-swift/Tests/ProviderCoreTests/Auth/DeviceCodeLoginTests.swift
new file mode 100644
index 0000000000..51c5eb6afa
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/Auth/DeviceCodeLoginTests.swift
@@ -0,0 +1,88 @@
+import Foundation
+import Testing
+@testable import ProviderCore
+
+// Each URL selects its response, so concurrent tests need no global mutable fixture.
+private final class DeviceLoginProtocol: URLProtocol, @unchecked Sendable {
+ override class func canInit(with request: URLRequest) -> Bool { request.url?.host == "device-login.test" }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func stopLoading() {}
+ override func startLoading() {
+ let path = request.url!.path
+ let scoped = path.hasPrefix("/scoped") || path.hasPrefix("/wrong")
+ let body: String
+ if path.hasSuffix("/code") {
+ body = """
+ {"device_code":"\(scoped ? "desktop-account-code" : "legacy-code")","user_code":"TEST-CODE","verification_uri":"https://device-login.test/link","expires_in":15,"interval":1\(scoped ? ",\"purpose\":\"desktop_account\"" : "")}
+ """
+ } else {
+ let valid = !path.hasPrefix("/wrong")
+ body = """
+ {"status":"authorized","token":"\(scoped && valid ? "darkbloom-at-test" : "eigeninference-pt-test")"\(scoped ? ",\"purpose\":\"desktop_account\"" : "")}
+ """
+ }
+ client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type": "application/json"])!, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: Data(body.utf8))
+ client?.urlProtocolDidFinishLoading(self)
+ }
+}
+
+private final class LoginCalls: @unchecked Sendable {
+ private let lock = NSLock()
+ private var urls: [String] = []
+ func opened(_ url: String) { lock.withLock { urls.append(url) } }
+ var count: Int { lock.withLock { urls.count } }
+}
+
+struct DeviceCodeLoginTests {
+ private func client(_ calls: LoginCalls) -> DeviceLoginClient {
+ let config = URLSessionConfiguration.ephemeral
+ config.protocolClasses = [DeviceLoginProtocol.self]
+ return DeviceLoginClient(session: URLSession(configuration: config), openBrowser: calls.opened,
+ saveProviderToken: { _ in throw DeviceAuthError.invalidResponse("Account login attempted to replace provider credentials") })
+ }
+
+ @Test func olderCoordinatorUsesExistingDeviceEndpointsWithoutChangingProviderCredentials() async throws {
+ let calls = LoginCalls()
+ let token = try await client(calls).login(coordinatorURL: "https://device-login.test/legacy",
+ onDisplayCode: { code, _, _ in #expect(code == "TEST-CODE") }, purpose: "desktop_account", allowLegacyAccountFlow: true)
+ #expect(token == "eigeninference-pt-test")
+ #expect(calls.count == 1)
+ }
+
+ @Test func desktopDisplaysCodeAndPollsWithoutLaunchingBrowser() async throws {
+ let calls = LoginCalls()
+ let token = try await client(calls).login(coordinatorURL: "https://device-login.test/scoped",
+ onDisplayCode: { code, url, _ in
+ #expect(code == "TEST-CODE")
+ #expect(url == "https://device-login.test/link")
+ }, purpose: "desktop_account", allowLegacyAccountFlow: true, automaticallyOpenBrowser: false)
+ #expect(token == "darkbloom-at-test")
+ #expect(calls.count == 0)
+ }
+
+ @Test func scopedCoordinatorStillUsesTheScopedAccountSession() async throws {
+ let calls = LoginCalls()
+ let token = try await client(calls).login(coordinatorURL: "https://device-login.test/scoped",
+ onDisplayCode: { _, _, _ in }, purpose: "desktop_account", allowLegacyAccountFlow: true)
+ #expect(token == "darkbloom-at-test")
+ #expect(calls.count == 1)
+ }
+
+ @Test func scopeMismatchNeverDowngradesAnAcknowledgedAccountGrant() async {
+ let calls = LoginCalls()
+ await #expect(throws: DeviceAuthError.self) {
+ try await client(calls).login(coordinatorURL: "https://device-login.test/wrong",
+ onDisplayCode: { _, _, _ in }, purpose: "desktop_account", allowLegacyAccountFlow: true)
+ }
+ }
+
+ @Test func legacyCompatibilityMustBeExplicitlyEnabled() async {
+ let calls = LoginCalls()
+ await #expect(throws: DeviceAuthError.self) {
+ try await client(calls).login(coordinatorURL: "https://device-login.test/legacy",
+ onDisplayCode: { _, _, _ in }, purpose: "desktop_account")
+ }
+ #expect(calls.count == 0)
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/Coordinator/DesktopSessionUsageTests.swift b/provider-swift/Tests/ProviderCoreTests/Coordinator/DesktopSessionUsageTests.swift
new file mode 100644
index 0000000000..26eda8fb64
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/Coordinator/DesktopSessionUsageTests.swift
@@ -0,0 +1,67 @@
+import Foundation
+import Testing
+@testable import ProviderCore
+
+@Test func desktopSessionUsageAccumulatesConcurrentPromptsWithoutChangingWireStats() async throws {
+ let stats = AtomicProviderStats()
+ await withTaskGroup(of: Void.self) { group in
+ for _ in 0..<100 {
+ group.addTask {
+ stats.addPromptTokensProcessed(120)
+ stats.addTokensGenerated(30)
+ }
+ }
+ }
+ #expect(stats.promptTokensProcessed == 12_000)
+ #expect(stats.snapshot().tokensGenerated == 3_000)
+ let wire = try JSONSerialization.jsonObject(with: JSONEncoder().encode(stats.snapshot())) as! [String: Any]
+ #expect(wire["promptTokensProcessed"] == nil)
+}
+
+@Test func desktopSessionUsageDecodesOldDaemonAsUnknownInput() throws {
+ let old = Data(#"{"requestsServed":12,"tokensGenerated":5641,"usageGaps":0}"#.utf8)
+ let stats = try JSONDecoder().decode(DaemonState.Stats.self, from: old)
+ #expect(stats.tokensGenerated == 5641)
+ #expect(stats.promptTokensProcessed == nil)
+ let encoded = try JSONSerialization.jsonObject(with: JSONEncoder().encode(stats)) as! [String: Any]
+ #expect(encoded["promptTokensProcessed"] == nil)
+}
+
+@Test func desktopSessionUsageRoundTripsExplicitZeroAndLargeCounts() throws {
+ for input: UInt64 in [0, 9_007_199_254_740_993] {
+ let stats = DaemonState.Stats(requestsServed: 1, tokensGenerated: 30, promptTokensProcessed: input)
+ let decoded = try JSONDecoder().decode(DaemonState.Stats.self, from: JSONEncoder().encode(stats))
+ #expect(decoded.promptTokensProcessed == input)
+ }
+}
+
+@Test func desktopSessionUsageJournalDeduplicatesAndSurvivesReopen() throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let url = directory.appendingPathComponent("usage.json")
+ let history = ProviderUsageHistory(url: url)
+ let record = ProviderUsageRecord(id: "one", sessionStartedAt: 100, completedAt: 110, model: "test",
+ inputTokens: 120, outputTokens: 30, cachedInputTokens: 80, reasoningTokens: 20, exact: true)
+ #expect(try history.record(record))
+ #expect(try !history.record(record))
+ let restored = ProviderUsageHistory(url: url)
+ #expect(try !restored.record(record))
+ #expect(ProviderUsageHistory.read(url: url) == [record])
+ let permissions = try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? NSNumber
+ #expect(permissions?.intValue == 0o600)
+ let otherSession = ProviderUsageRecord(id: "one", sessionStartedAt: 200, model: "test",
+ inputTokens: 10, outputTokens: 5, cachedInputTokens: 999, reasoningTokens: 999, exact: false)
+ #expect(otherSession.cachedInputTokens == 10)
+ #expect(otherSession.reasoningTokens == 5)
+ #expect(try restored.record(otherSession))
+ #expect(ProviderUsageHistory.read(url: url).count == 2)
+}
+
+@Test func desktopSessionUsageSubsetsDoNotIncreaseTheTotal() {
+ let stats = AtomicProviderStats()
+ stats.addPromptTokensProcessed(120); stats.addTokensGenerated(30)
+ stats.addCachedInputTokens(80); stats.addReasoningTokens(20)
+ #expect(stats.promptTokensProcessed + stats.tokensGenerated == 150)
+ #expect(stats.cachedInputTokens == 80)
+ #expect(stats.reasoningTokens == 20)
+}
diff --git a/scripts/test-desktop-api.py b/scripts/test-desktop-api.py
index e123ed24bd..51b801a49f 100644
--- a/scripts/test-desktop-api.py
+++ b/scripts/test-desktop-api.py
@@ -35,12 +35,14 @@ def do_POST(self):
pass
def do_GET(self):
- if self.path == "/v1/releases/desktop":
+ self.server.reads.append(self.path)
+ assert self.path not in ("/v1/releases/desktop", "/v1/provider/desktop"), "obsolete dashboard request"
+ if self.path == "/v1/releases/latest":
assert self.headers.get("Authorization") is None
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
- self.wfile.write(b'{"minimum_provider_version":"0.9.15","history":[{"version":"0.9.16","active":true,"notes":"Faster recovery","published_at":"2026-10-02T00:00:00Z"}]}')
+ self.wfile.write(b'{"version":"0.9.16","active":true,"changelog":"Faster recovery","created_at":"2026-10-02T00:00:00Z"}')
return
if self.path in ("/v1/stats", "/v1/leaderboard?metric=earnings&window=24h"):
assert self.headers.get("Authorization") is None
@@ -54,14 +56,18 @@ def do_GET(self):
self.end_headers()
self.wfile.write(json.dumps(payload).encode())
return
- if self.path.startswith("/v1/provider/desktop/insights?window="):
- assert self.headers.get("Authorization") == "Bearer fixture-provider-token"
+ if self.path == "/v1/provider/account-earnings?limit=1000":
+ authorization = self.headers.get("Authorization")
+ account_authorization = "Bearer darkbloom-at-" + "a" * 64
+ assert authorization in ("Bearer fixture-provider-token", "Bearer fixture-provider-token-2", account_authorization)
if self.server.hold_insights:
self.server.insights_started.set()
self.server.insights_release.wait(10)
- window = self.path.split("window=")[1]
- assert window in ("7d", "30d")
- body = json.dumps({"window": window, "lifetime": {"completion_tokens": "9007199254740993"}}).encode()
+ payload = {"account_id":"fixture", "total_micro_usd":0, "count":1, "available_balance_micro_usd":0,
+ "earnings":[{"id":1,"provider_key":"fixture-key","provider_id":"fixture-mac","model":"fixture-model","amount_micro_usd":0,"prompt_tokens":0,"completion_tokens":9007199254740993,"created_at":"2026-10-05T00:00:00Z"}]}
+ if authorization == account_authorization:
+ payload["email"] = "fixture@example.com"
+ body = json.dumps(payload).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
@@ -72,6 +78,12 @@ def do_GET(self):
self.end_headers()
self.wfile.write(b'{"models":[]}')
+ def do_DELETE(self):
+ assert self.path == "/v1/device/token"
+ assert self.headers.get("Authorization", "").startswith("Bearer darkbloom-at-")
+ self.send_response(204)
+ self.end_headers()
+
def log_message(self, *_):
pass
@@ -116,6 +128,7 @@ def main():
parser.add_argument("--hold", action="store_true", help="Keep the isolated API available for a manual Electron bridge check")
args = parser.parse_args()
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Catalog)
+ server.reads = []
server.link_started = threading.Event()
server.link_release = threading.Event()
server.hold_insights = False
@@ -174,8 +187,10 @@ def request(path="state", body=None, auth=True, origin=None):
assert code == 200 and snapshot["machine"]["name"] == "Desktop fixture", snapshot
assert snapshot["state"] == "stopped" and not snapshot["linked"]
code, release_history = request("release-history")
- assert code == 200 and release_history["minimum_provider_version"] == "0.9.15", release_history
+ assert code == 200 and "minimum_provider_version" not in release_history, release_history
assert release_history["history"][0]["notes"] == "Faster recovery", release_history
+ assert request("release")[1]["version"] == "0.9.16"
+ assert server.reads.count("/v1/releases/latest") == 1, server.reads
code, network = request("network")
assert code == 200 and network["total_tokens"] == "9007199254740993", network
assert network["provider_regions"][0]["region"] == "Tokyo", network
@@ -194,6 +209,7 @@ def request(path="state", body=None, auth=True, origin=None):
code, insights = request(resource)
assert code == 200 and insights["window"] == window, insights
assert insights["lifetime"]["completion_tokens"] == "9007199254740993"
+ (root / "auth").write_text("fixture-provider-token-2")
server.hold_insights = True
inflight_result = []
inflight = threading.Thread(target=lambda: inflight_result.append(request("insights-week")))
@@ -206,6 +222,33 @@ def request(path="state", body=None, auth=True, origin=None):
server.hold_insights = False
assert request()[1]["account_revision"] != linked_snapshot["account_revision"]
assert request("insights-week")[0] == 401
+ # Native dashboard sign-out must leave provider linkage intact.
+ (root / "auth").write_text("fixture-provider-token")
+ base = f"http://127.0.0.1:{server.server_port}"
+ account_file = root / "desktop" / ("account-" + hashlib.sha256(base.encode()).hexdigest() + ".json")
+ account_file.write_text(json.dumps({"base":base,"token":"darkbloom-at-" + "a" * 64,"expiresAt":time.time()+86400-978307200}))
+ account_file.chmod(0o600)
+ assert request()[1]["account"]["signed_in"] is True
+ for _ in range(40):
+ snapshot = request()[1]
+ if snapshot["account"].get("email") == "fixture@example.com": break
+ time.sleep(.1)
+ assert snapshot["account"].get("email") == "fixture@example.com", snapshot["account"]
+ assert json.loads(account_file.read_text())["email"] == "fixture@example.com"
+ assert "darkbloom-at-" not in json.dumps(snapshot), "account token leaked to renderer"
+ code, signout = request("actions", {"id":str(uuid.uuid4()),"action":"account-signout"})
+ assert code == 202, signout
+ for _ in range(40):
+ snapshot = request()[1]
+ if snapshot["operations"][0]["state"] != "running": break
+ time.sleep(.1)
+ assert snapshot["operations"][0]["state"] == "succeeded", snapshot
+ assert snapshot["linked"] and not snapshot["account"]["signed_in"], snapshot
+ assert not snapshot["account"].get("email"), "signed-out identity remained visible"
+ assert (root / "auth").read_text() == "fixture-provider-token"
+ assert not account_file.exists()
+ assert request("insights-week")[0] == 401
+ (root / "auth").unlink()
code, rejected = request("actions", {"id": str(uuid.uuid4()), "action": "start", "models": ["--force"]})
assert code == 400 and rejected["error"] == "Invalid model ID", rejected
code, malformed = request("actions", {"action": "start"})