From cb104f9df34f6bb11f694829226d32e1607fa4a0 Mon Sep 17 00:00:00 2001 From: kydo-researcher Date: Mon, 5 Oct 2026 14:04:52 -0400 Subject: [PATCH 1/2] feat(desktop): integrate live usage, earnings and shared Swift account backend Simplify Home and live chip activity, preserve exact session usage, rank models by earnings, improve Mac Stats and cooling recovery, and reuse existing coordinator APIs through scoped native caches and read-only dashboard sessions. Include native, UI, API and store regression tests and canonical documentation. --- CHANGELOG.md | 8 + console-ui/__tests__/pages.test.tsx | 12 +- console-ui/src/app/link/DeviceLinkForm.tsx | 23 ++- console-ui/src/app/link/page.tsx | 12 +- coordinator/api/billing_handlers.go | 4 + coordinator/api/desktop_account_auth.go | 97 +++++++++ coordinator/api/desktop_account_auth_test.go | 135 +++++++++++++ coordinator/api/desktop_handlers.go | 3 +- coordinator/api/device_auth.go | 35 +++- coordinator/api/provider.go | 6 +- coordinator/api/server.go | 13 +- .../store/device_code_consumption_test.go | 75 +++++++ coordinator/store/interface_domains.go | 3 + coordinator/store/memory.go | 11 ++ coordinator/store/postgres.go | 13 ++ desktop-app/src/renderer/App.tsx | 18 +- desktop-app/src/renderer/actions.ts | 56 ++++-- .../renderer/components/AccountControl.tsx | 32 +++ desktop-app/src/renderer/components/UI.tsx | 17 +- .../components/onboarding/ScanFooter.tsx | 4 +- .../components/onboarding/ScanStep.tsx | 7 +- .../components/onboarding/StartServing.tsx | 9 +- .../src/renderer/data/pageResources.ts | 18 ++ desktop-app/src/renderer/features/Cooling.tsx | 2 +- .../src/renderer/features/Earnings.tsx | 34 ++-- desktop-app/src/renderer/features/Home.tsx | 41 ++-- .../src/renderer/features/Machines.tsx | 2 +- desktop-app/src/renderer/features/Stats.tsx | 6 +- .../features/cooling/CoolingControls.tsx | 10 +- .../features/home/ContributionMetrics.tsx | 54 +++++ .../renderer/features/home/FleetEarnings.tsx | 42 ++-- .../src/renderer/features/home/FleetMacs.tsx | 6 +- .../renderer/features/home/FleetSummary.tsx | 7 +- .../features/home/NetworkMilestone.tsx | 15 +- .../features/home/chip/ChipReadouts.tsx | 52 +++-- .../renderer/features/home/chip/ChipStage.tsx | 72 ++++--- .../features/home/chip/ChipStatus.tsx | 8 + .../features/home/chip/HardwareReadouts.tsx | 18 +- .../features/home/chip/MemoryLegend.tsx | 79 ++++++++ .../features/home/chip/PhaseLegend.tsx | 50 +---- .../home/chip/blueprint/paintActivity.ts | 44 +---- .../home/chip/blueprint/paintStatic.ts | 44 +---- .../features/home/chip/chip.module.css | 165 +++++----------- .../renderer/features/home/chip/dieLayout.ts | 26 +-- .../features/home/chip/hardware/drive.ts | 22 ++- .../features/home/chip/hardware/targets.ts | 8 +- .../home/chip/hardwareReadouts.module.css | 44 +++++ .../home/chip/hooks/useChipWorkload.ts | 38 ++-- .../home/chip/hooks/useHardwareFeed.ts | 10 +- .../src/renderer/features/home/chip/layout.ts | 36 +--- .../home/chip/memoryLegend.module.css | 104 ++++++++++ .../renderer/features/home/chip/memoryMap.ts | 11 +- .../features/home/chip/memoryStyle.ts | 26 +++ .../features/home/chip/memoryUsage.ts | 17 ++ .../features/home/chip/photoreal/dieParts.ts | 23 --- .../features/home/chip/photoreal/emissive.ts | 33 +--- .../features/home/chip/photoreal/layoutFit.ts | 1 - .../home/chip/photoreal/memoryLight.ts | 14 +- .../home/chip/photoreal/paintLight.ts | 38 +--- .../home/chip/photoreal/paintSilicon.ts | 11 +- .../home/chip/photoreal/paintSubstrate.ts | 31 +-- .../home/chip/photoreal/substrateLayout.ts | 12 -- .../features/home/chip/render/activity.ts | 56 +++--- .../features/home/chip/render/types.ts | 4 +- .../renderer/features/home/chip/stageText.ts | 18 +- .../features/home/chip/workload/measured.ts | 38 ++++ .../renderer/features/home/contribution.ts | 31 +++ .../renderer/features/home/fleet.module.css | 7 +- .../renderer/features/home/home.module.css | 40 +++- .../features/home/milestone.module.css | 4 - .../features/insights/EarningsBreakdown.tsx | 1 + .../features/insights/EarningsTimeline.tsx | 49 +++-- .../features/insights/insights.module.css | 5 + .../src/renderer/features/insights/types.ts | 25 ++- .../renderer/features/insights/useInsights.ts | 8 +- .../features/models/AutopilotModels.tsx | 13 +- .../renderer/features/models/ManualModels.tsx | 14 +- .../features/models/ModelEarnings.tsx | 45 +++++ .../src/renderer/features/models/Models.tsx | 27 ++- .../src/renderer/features/models/PoolRow.tsx | 5 + .../src/renderer/features/models/earnings.ts | 22 +++ .../src/renderer/features/stats/ModelWork.tsx | 62 ++++++ .../renderer/features/stats/Performance.tsx | 170 ++++++---------- .../features/stats/PreviewPerformance.tsx | 130 ++++++++++++ .../src/renderer/features/stats/TokenBars.tsx | 4 +- .../stats/activity/RequestActivity.tsx | 14 +- .../features/stats/activity/RequestTable.tsx | 38 ++-- .../features/stats/activity/requests.ts | 24 ++- .../stats/activity/useRequestHistory.ts | 32 ++- .../src/renderer/features/stats/data.ts | 26 ++- .../src/renderer/features/updates/version.ts | 7 +- desktop-app/src/renderer/styles/layout.css | 24 ++- desktop-app/src/renderer/styles/models.css | 14 ++ desktop-app/src/renderer/useBackend.ts | 187 +++++++++++------- desktop-app/src/shared/contracts.ts | 45 ++++- desktop-app/tests/app.test.tsx | 4 +- desktop-app/tests/chipLayout.test.ts | 7 +- desktop-app/tests/chipMeasured.test.ts | 57 ++++++ desktop-app/tests/chipStage.test.tsx | 25 +-- desktop-app/tests/chipStageText.test.ts | 8 +- desktop-app/tests/chipTargets.test.ts | 30 +-- .../tests/contributionMetrics.test.tsx | 69 +++++++ desktop-app/tests/coolingRefresh.test.tsx | 15 +- desktop-app/tests/fleetEarnings.test.tsx | 70 +++++++ desktop-app/tests/macStats.test.tsx | 107 ++++++++++ desktop-app/tests/memoryAllocation.test.ts | 28 +++ desktop-app/tests/modelEarnings.test.ts | 35 ++++ desktop-app/tests/modelsRanking.test.tsx | 49 +++++ desktop-app/tests/networkMilestone.test.tsx | 14 +- desktop-app/tests/onboardingWaitlist.test.tsx | 2 +- desktop-app/tests/operationStream.test.ts | 60 ++++++ desktop-app/tests/remoteOverview.test.tsx | 2 +- docs/architecture/storage.md | 14 +- docs/assets/desktop-api-architecture.html | 96 +++++++++ docs/consumer/billing.md | 11 +- docs/developer/build.md | 10 +- docs/developer/test.md | 10 +- docs/provider/cli-reference.md | 6 +- docs/reference/api-contracts.md | 32 ++- docs/reference/configuration.md | 4 +- docs/reference/desktop-control.md | 75 ++++--- .../ProviderCore/Auth/DeviceAuth.swift | 19 +- .../Coordinator/CoordinatorClientState.swift | 15 ++ .../ProviderLoop+InferenceHandler.swift | 9 + .../ProviderCore/ProviderLoop+Trust.swift | 5 +- .../ProviderLoop+UsageHistory.swift | 5 + .../Sources/ProviderCore/ProviderLoop.swift | 1 + .../Service/DaemonStateFile.swift | 9 +- .../Service/ProviderUsageHistory.swift | 77 ++++++++ .../Desktop/DesktopAccountActions.swift | 28 +++ .../Desktop/DesktopAccountCloud.swift | 66 +++++++ .../Desktop/DesktopAccountCommands.swift | 29 +++ .../Desktop/DesktopAccountCredential.swift | 67 +++++++ .../Desktop/DesktopAccountEarnings.swift | 129 ++++++++++++ .../Desktop/DesktopAccountEarningsCache.swift | 24 +++ .../Desktop/DesktopAutomaticUpdates.swift | 2 +- .../darkbloom/Desktop/DesktopBackend.swift | 20 +- .../darkbloom/Desktop/DesktopCommand.swift | 18 +- .../Desktop/DesktopConfiguration.swift | 2 + .../darkbloom/Desktop/DesktopCooling.swift | 10 +- .../Desktop/DesktopCoolingAuthorization.swift | 42 ++++ .../darkbloom/Desktop/DesktopFanRuntime.swift | 30 +++ .../darkbloom/Desktop/DesktopHTTP.swift | 4 +- .../Desktop/DesktopRequestHistory.swift | 57 ++++++ .../Desktop/DesktopResourceCache.swift | 61 ++++++ .../darkbloom/Desktop/DesktopResources.swift | 88 +++------ .../darkbloom/Desktop/DesktopSnapshot.swift | 34 ++-- .../darkbloom/Desktop/DesktopTypes.swift | 4 +- .../Desktop/DesktopUsageArchive.swift | 66 +++++++ .../Desktop/DesktopUsageHistory.swift | 108 ++++++++++ .../Desktop/DesktopUsageSettlement.swift | 26 +++ .../DesktopAccountCloudTests.swift | 53 +++++ .../DesktopAccountEarningsTests.swift | 59 ++++++ .../DesktopCoolingAuthorizationTests.swift | 49 +++++ .../DesktopMacStatsTests.swift | 40 ++++ .../DesktopUsageHistoryTests.swift | 63 ++++++ .../DesktopSessionUsageTests.swift | 67 +++++++ scripts/test-desktop-api.py | 46 ++++- 158 files changed, 4165 insertions(+), 1163 deletions(-) create mode 100644 coordinator/api/desktop_account_auth.go create mode 100644 coordinator/api/desktop_account_auth_test.go create mode 100644 coordinator/store/device_code_consumption_test.go create mode 100644 desktop-app/src/renderer/components/AccountControl.tsx create mode 100644 desktop-app/src/renderer/data/pageResources.ts create mode 100644 desktop-app/src/renderer/features/home/ContributionMetrics.tsx create mode 100644 desktop-app/src/renderer/features/home/chip/ChipStatus.tsx create mode 100644 desktop-app/src/renderer/features/home/chip/MemoryLegend.tsx create mode 100644 desktop-app/src/renderer/features/home/chip/hardwareReadouts.module.css create mode 100644 desktop-app/src/renderer/features/home/chip/memoryLegend.module.css create mode 100644 desktop-app/src/renderer/features/home/chip/memoryStyle.ts create mode 100644 desktop-app/src/renderer/features/home/chip/memoryUsage.ts create mode 100644 desktop-app/src/renderer/features/home/chip/workload/measured.ts create mode 100644 desktop-app/src/renderer/features/home/contribution.ts create mode 100644 desktop-app/src/renderer/features/models/ModelEarnings.tsx create mode 100644 desktop-app/src/renderer/features/models/earnings.ts create mode 100644 desktop-app/src/renderer/features/stats/ModelWork.tsx create mode 100644 desktop-app/src/renderer/features/stats/PreviewPerformance.tsx create mode 100644 desktop-app/tests/chipMeasured.test.ts create mode 100644 desktop-app/tests/contributionMetrics.test.tsx create mode 100644 desktop-app/tests/fleetEarnings.test.tsx create mode 100644 desktop-app/tests/macStats.test.tsx create mode 100644 desktop-app/tests/memoryAllocation.test.ts create mode 100644 desktop-app/tests/modelEarnings.test.ts create mode 100644 desktop-app/tests/modelsRanking.test.tsx create mode 100644 desktop-app/tests/operationStream.test.ts create mode 100644 docs/assets/desktop-api-architecture.html create mode 100644 provider-swift/Sources/ProviderCore/ProviderLoop+UsageHistory.swift create mode 100644 provider-swift/Sources/ProviderCore/Service/ProviderUsageHistory.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopAccountActions.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopAccountCloud.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopAccountCommands.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopAccountCredential.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopAccountEarnings.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopAccountEarningsCache.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopCoolingAuthorization.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopFanRuntime.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopRequestHistory.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopResourceCache.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopUsageArchive.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopUsageHistory.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopUsageSettlement.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DesktopAccountCloudTests.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DesktopAccountEarningsTests.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DesktopCoolingAuthorizationTests.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DesktopMacStatsTests.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DesktopUsageHistoryTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Coordinator/DesktopSessionUsageTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 872ddefc63..37008627c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ ## Unreleased — macOS desktop app +- Keep Electron on the same `darkbloom` CLI backend. Swift owns coordinator requests, shared resource caches, browser account sign-in and sign-out, and catalog refresh independent of local snapshots. Add a separate read-only dashboard session with bounded expiry; provider credentials and serving stay independent. Reuse existing account/fleet and ledger APIs, including full 7/30-day aggregates through the existing earnings route. Refresh visible pages from the native clock, and use streamed operation progress with a polling fallback. + +- Reorganize the Home chip panel into a larger diagram and a hardware/memory sidebar, with prominent GPU/CPU measurements and individually labeled model footprints. Move live status to the header and stack sections at narrow widths. Retry only the specific transient fan-ownership firmware restore failure through the verified signed CLI; preserve permanent hardware errors and distinguish canceled authorization. + +- Populate this Mac’s Stats and Activity from verified existing settlement records, including exact input/output tokens, session earnings and model totals. Hide unavailable Home activity readouts; retain a seven-day earnings axis with explicit gaps for missing history. Use the verified signed installed runtime for fan status and cooling authorization, reflect its active policy, and restrict controls to the supported 60–90% range. + +- Populate desktop account earnings, daily charts and model rankings by aggregating the existing account-earnings response when desktop-specific analytics are unavailable. Preserve authoritative lifetime totals, deduplicate settlements, separate base rewards, and label truncated history as recent rather than a complete week or month. + - Replace the desktop preview's step diagram with a continuous particle scene: incoming requests gather around orbiting model cores, then spread into token trails. Preserve pause, reduced-motion, inactive-provider, and off-screen behavior; keep illustrative motion separate from native activity. - Replace Analysis with Stats and add a visual-first traffic preview with animated request stages, model traffic shares, an inspectable traffic curve, and milestones. Keep illustrative metrics confined to development preview; live mode uses existing native observations until richer APIs are added. diff --git a/console-ui/__tests__/pages.test.tsx b/console-ui/__tests__/pages.test.tsx index ad6151fba1..c68533c367 100644 --- a/console-ui/__tests__/pages.test.tsx +++ b/console-ui/__tests__/pages.test.tsx @@ -196,7 +196,7 @@ describe("BillingPage", () => { describe("LinkPage", () => { it("renders without crashing and shows heading", async () => { const LinkPage = (await import("@/app/link/page")).default; - render(); + render(await LinkPage({ searchParams: Promise.resolve({}) })); expect(screen.getByText("Link Your Device")).toBeInTheDocument(); expect( @@ -206,7 +206,7 @@ describe("LinkPage", () => { it("shows the device code input form when authenticated", async () => { const LinkPage = (await import("@/app/link/page")).default; - render(); + render(await LinkPage({ searchParams: Promise.resolve({}) })); // The DeviceLinkForm renders code input when authenticated expect( @@ -215,6 +215,14 @@ describe("LinkPage", () => { expect(screen.getByPlaceholderText("XXXX-XXXX")).toBeInTheDocument(); expect(screen.getByText("Link Device")).toBeInTheDocument(); }); + it("labels desktop authorization separately from provider linking", async () => { + const LinkPage = (await import("@/app/link/page")).default; + render(await LinkPage({ searchParams: Promise.resolve({ purpose: "desktop_account" }) })); + expect(screen.getByText("Sign in to Darkbloom Desktop")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Authorize Desktop" })).toBeInTheDocument(); + expect(screen.queryByText("Link Device")).not.toBeInTheDocument(); + }); + }); // ========================================================================= diff --git a/console-ui/src/app/link/DeviceLinkForm.tsx b/console-ui/src/app/link/DeviceLinkForm.tsx index 3449addf56..3cd8c88736 100644 --- a/console-ui/src/app/link/DeviceLinkForm.tsx +++ b/console-ui/src/app/link/DeviceLinkForm.tsx @@ -6,7 +6,7 @@ import { trackEvent } from "@/lib/google-analytics"; type LinkStatus = "idle" | "submitting" | "success" | "error"; -export function DeviceLinkForm() { +export function DeviceLinkForm({ account = false }: { account?: boolean }) { const { ready, authenticated, login, getAccessToken, user } = useAuthContext(); const [code, setCode] = useState(""); const [status, setStatus] = useState("idle"); @@ -41,7 +41,7 @@ export function DeviceLinkForm() { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, - body: JSON.stringify({ user_code: code.trim().toUpperCase() }), + body: JSON.stringify({ user_code: code.trim().toUpperCase(), purpose: account ? "desktop_account" : "provider" }), }); const data = await res.json(); @@ -71,7 +71,7 @@ export function DeviceLinkForm() { setStatus("error"); } }, - [code, getAccessToken] + [code, getAccessToken, account] ); // Format input as XXXX-XXXX @@ -112,13 +112,12 @@ export function DeviceLinkForm() {

- Device Linked! + {account ? "Signed In!" : "Device Linked!"}

- Your provider is now connected to your account. Earnings will be - credited automatically. + {account ? "Return to the desktop app to view your account." : "Your provider is now connected to your account. Earnings will be credited automatically."}

-

Return to your terminal to finish starting the provider.

+ {!account &&

Return to your terminal to finish starting the provider.

} Open your provider workspace ); @@ -129,7 +128,7 @@ export function DeviceLinkForm() { return (

- Sign in to your Darkbloom account to link your device. + {account ? "Sign in to view your Macs and earnings." : "Sign in to your Darkbloom account to link your device."}

-
+ {!account &&
Run{" "} darkbloom login {" "} on your Mac to get a code. -
+
}
); } diff --git a/console-ui/src/app/link/page.tsx b/console-ui/src/app/link/page.tsx index 23511a7b29..1543620b9e 100644 --- a/console-ui/src/app/link/page.tsx +++ b/console-ui/src/app/link/page.tsx @@ -1,8 +1,7 @@ -"use client"; - import { DeviceLinkForm } from "./DeviceLinkForm"; -export default function LinkPage() { +export default async function LinkPage({ searchParams }: { searchParams: Promise<{ purpose?: string }> }) { + const account = (await searchParams).purpose === "desktop_account"; return (
@@ -19,14 +18,13 @@ export default function LinkPage() {

- Link Your Device + {account ? "Sign in to Darkbloom Desktop" : "Link Your Device"}

- Connect your Mac to your Darkbloom account to receive - earnings for providing compute. + {account ? "View your Macs and earnings." : "Connect your Mac to your Darkbloom account to receive earnings for providing compute."}

- +
); diff --git a/coordinator/api/billing_handlers.go b/coordinator/api/billing_handlers.go index 7d42087b68..f52fe0d294 100644 --- a/coordinator/api/billing_handlers.go +++ b/coordinator/api/billing_handlers.go @@ -576,6 +576,10 @@ func (s *Server) handleModelCatalog(w http.ResponseWriter, r *http.Request) { // for the authenticated provider account. // Cached for 20s per account — dashboard polls this frequently. func (s *Server) handleAccountEarnings(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("window") != "" { + s.handleDesktopInsights(w, r) + return + } accountID := s.resolveAccountID(r) limit := 50 diff --git a/coordinator/api/desktop_account_auth.go b/coordinator/api/desktop_account_auth.go new file mode 100644 index 0000000000..22c43bab71 --- /dev/null +++ b/coordinator/api/desktop_account_auth.go @@ -0,0 +1,97 @@ +package api + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net/http" + "strings" + "time" + + "github.com/eigeninference/d-inference/coordinator/auth" + "github.com/eigeninference/d-inference/coordinator/store" +) + +const desktopAccountPurpose = "desktop_account" +const desktopAccountCodePrefix = "desktop-account-" +const desktopAccountTokenPrefix = "darkbloom-at-" +const desktopAccountLifetime = 30 * 24 * time.Hour + +// Account sessions reuse the hashed-token store, but have a separate scope and expiry. +// Only the three read-only dashboard routes opt into this middleware. +func (s *Server) desktopAccountToken(r *http.Request) (*store.ProviderToken, error) { + token := extractBearerToken(r) + if !strings.HasPrefix(token, desktopAccountTokenPrefix) { + return nil, http.ErrNoCookie + } + pt, err := s.store.GetProviderToken(token) + if err != nil || pt == nil || !pt.Active || !strings.HasPrefix(pt.Label, desktopAccountCodePrefix) || pt.CreatedAt.IsZero() || !time.Now().Before(pt.CreatedAt.Add(desktopAccountLifetime)) { + return nil, http.ErrNoCookie + } + return pt, nil +} + +func (s *Server) requireAccountRead(fallback http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(extractBearerToken(r), desktopAccountTokenPrefix) { + fallback(w, r) + return + } + pt, err := s.desktopAccountToken(r) + if err != nil { + writeJSON(w, http.StatusUnauthorized, errorResponse("authentication_error", "account session expired or revoked")) + return + } + user, err := s.store.GetUserByAccountID(pt.AccountID) + if err != nil || user == nil { + writeJSON(w, http.StatusUnauthorized, errorResponse("authentication_error", "account unavailable")) + return + } + ctx := context.WithValue(r.Context(), ctxKeyConsumer, pt.AccountID) + ctx = context.WithValue(ctx, auth.CtxKeyUser, user) + // The fallback middleware is deliberately bypassed only after read-only scope validation. + switch r.URL.Path { + case "/v1/me/providers": + s.handleMyProviders(w, r.WithContext(ctx)) + case "/v1/me/summary": + s.handleMySummary(w, r.WithContext(ctx)) + case "/v1/provider/account-earnings": + s.handleAccountEarnings(w, r.WithContext(ctx)) + default: + writeJSON(w, http.StatusForbidden, errorResponse("forbidden", "read-only account session")) + } + } +} + +func (s *Server) issueDesktopAccountToken(w http.ResponseWriter, dc *store.DeviceCode) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + writeJSON(w, 500, errorResponse("server_error", "failed to create session")) + return + } + token := desktopAccountTokenPrefix + hex.EncodeToString(b) + now := time.Now() + pt := &store.ProviderToken{TokenHash: sha256Hash(token), AccountID: dc.AccountID, Label: desktopAccountCodePrefix + dc.UserCode, Active: true, CreatedAt: now} + if err := s.store.CreateProviderToken(pt); err != nil { + writeJSON(w, 500, errorResponse("server_error", "failed to save session")) + return + } + if err := s.store.ConsumeDeviceCode(dc.DeviceCode); err != nil { + _ = s.store.RevokeProviderToken(token) + writeJSON(w, http.StatusGone, errorResponse("invalid_grant", "account grant already exchanged or expired")) + return + } + writeJSON(w, http.StatusOK, map[string]any{"status": "authorized", "purpose": desktopAccountPurpose, "token": token, "account_id": dc.AccountID, "expires_in": int(desktopAccountLifetime.Seconds())}) +} + +func (s *Server) revokeDesktopAccountToken(w http.ResponseWriter, r *http.Request) { + if _, err := s.desktopAccountToken(r); err != nil { + writeJSON(w, 401, errorResponse("authentication_error", "invalid account session")) + return + } + if err := s.store.RevokeProviderToken(extractBearerToken(r)); err != nil { + writeJSON(w, 500, errorResponse("server_error", "failed to revoke account session")) + return + } + w.WriteHeader(http.StatusNoContent) +} diff --git a/coordinator/api/desktop_account_auth_test.go b/coordinator/api/desktop_account_auth_test.go new file mode 100644 index 0000000000..9acc665643 --- /dev/null +++ b/coordinator/api/desktop_account_auth_test.go @@ -0,0 +1,135 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestDesktopAccountGrantIsPurposeBoundAndSingleUse(t *testing.T) { + srv, st := deviceTestServer() + w := httptest.NewRecorder() + srv.handleDeviceCode(w, httptest.NewRequest("POST", "/v1/device/code", strings.NewReader(`{"purpose":"desktop_account"}`))) + var code struct { + Device string `json:"device_code"` + User string `json:"user_code"` + Purpose string `json:"purpose"` + URL string `json:"verification_uri"` + } + if err := json.Unmarshal(w.Body.Bytes(), &code); err != nil || w.Code != 200 || code.Purpose != desktopAccountPurpose || !strings.Contains(code.URL, "purpose=desktop_account") { + t.Fatalf("bad grant: %s", w.Body) + } + approve := func(purpose string) int { + req := httptest.NewRequest("POST", "/v1/device/approve", strings.NewReader(`{"user_code":"`+code.User+`","purpose":"`+purpose+`"}`)) + req = req.WithContext(withUser(req.Context(), "owner", "owner@example.com")) + w := httptest.NewRecorder() + srv.handleDeviceApprove(w, req) + return w.Code + } + if approve("provider") != 400 { + t.Fatal("provider consent granted account access") + } + if approve(desktopAccountPurpose) != 200 { + t.Fatal("account approval failed") + } + var successes atomic.Int32 + var wg sync.WaitGroup + for range 16 { + wg.Add(1) + go func() { + defer wg.Done() + req := httptest.NewRequest("POST", "/v1/device/token", strings.NewReader(`{"device_code":"`+code.Device+`"}`)) + w := httptest.NewRecorder() + srv.handleDeviceToken(w, req) + if w.Code == 200 { + successes.Add(1) + } + }() + } + wg.Wait() + if successes.Load() != 1 { + t.Fatalf("grant exchanged %d times", successes.Load()) + } + dc, _ := st.GetDeviceCode(code.Device) + if dc.Status != "consumed" { + t.Fatal("grant not consumed") + } +} + +func TestDesktopAccountScopeOwnerExpiryAndRevocation(t *testing.T) { + srv, st := deviceTestServer() + if err := st.CreateUser(&store.User{AccountID: "owner", PrivyUserID: "did:privy:owner", Email: "owner@example.com"}); err != nil { + t.Fatal(err) + } + token := desktopAccountTokenPrefix + strings.Repeat("a", 64) + pt := &store.ProviderToken{TokenHash: sha256Hash(token), AccountID: "owner", Active: true, Label: desktopAccountCodePrefix + "TEST", CreatedAt: time.Now()} + if err := st.CreateProviderToken(pt); err != nil { + t.Fatal(err) + } + request := func(method, path string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, nil) + req.Header.Set("Authorization", "Bearer "+token) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + return w + } + for _, path := range []string{"/v1/me/providers", "/v1/me/summary", "/v1/provider/account-earnings?account_id=other", "/v1/provider/account-earnings?window=7d"} { + w := request("GET", path) + if w.Code != 200 || strings.Contains(w.Body.String(), `"account_id":"other"`) { + t.Fatalf("%s: %d %s", path, w.Code, w.Body) + } + } + for _, route := range []struct{ method, path string }{{"GET", "/v1/payments/balance"}, {"POST", "/v1/chat/completions"}, {"POST", "/v1/device/approve"}, {"DELETE", "/v1/me/providers/machine"}, {"GET", "/v1/provider/desktop"}} { + w := request(route.method, route.path) + if w.Code != http.StatusUnauthorized && w.Code != http.StatusForbidden { + t.Fatalf("scope escape: %s %d", route.path, w.Code) + } + } + if request("DELETE", "/v1/device/token").Code != 204 { + t.Fatal("revoke failed") + } + if request("GET", "/v1/me/providers").Code != 401 { + t.Fatal("revoked token used cached account data") + } + expired := desktopAccountTokenPrefix + strings.Repeat("b", 64) + pt.TokenHash = sha256Hash(expired) + pt.CreatedAt = time.Now().Add(-desktopAccountLifetime - time.Minute) + if err := st.CreateProviderToken(pt); err != nil { + t.Fatal(err) + } + token = expired + if request("GET", "/v1/me/summary").Code != 401 { + t.Fatal("expired session accepted") + } +} + +func TestAccountEarningsWindowIncludesRowsBeyondRecentPage(t *testing.T) { + srv, st := deviceTestServer() + now := time.Now().UTC() + for i := 0; i < 1002; i++ { + row := &store.ProviderEarning{AccountID: "owner", JobID: fmt.Sprintf("job-%d", i), Model: "model", ProviderID: "machine", AmountMicroUSD: 1, PromptTokens: 2, CompletionTokens: 3, CreatedAt: now.Add(-time.Hour)} + if err := st.RecordProviderEarning(row); err != nil { + t.Fatal(err) + } + } + req := httptest.NewRequest("GET", "/v1/provider/account-earnings?window=7d&limit=1", nil) + req = req.WithContext(context.WithValue(req.Context(), ctxKeyConsumer, "owner")) + w := httptest.NewRecorder() + srv.handleAccountEarnings(w, req) + var result desktopInsights + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil || w.Code != 200 { + t.Fatalf("aggregate failed %s", w.Body) + } + if result.Totals.Jobs != 1002 || result.Totals.WorkMicroUSD != 1002 || len(result.Days) != 7 { + t.Fatalf("truncated aggregate: %+v", result) + } +} diff --git a/coordinator/api/desktop_handlers.go b/coordinator/api/desktop_handlers.go index dfaa8337cf..3a1d637d01 100644 --- a/coordinator/api/desktop_handlers.go +++ b/coordinator/api/desktop_handlers.go @@ -6,6 +6,7 @@ import ( "errors" "net/http" "strconv" + "strings" "time" "github.com/eigeninference/d-inference/coordinator/store" @@ -56,7 +57,7 @@ func (s *Server) requireDesktopProviderToken(next http.HandlerFunc) http.Handler return func(w http.ResponseWriter, r *http.Request) { setOutcomeStage(r, "auth") token, err := s.store.GetProviderToken(extractBearerToken(r)) - if err != nil || token == nil || !token.Active || token.AccountID == "" { + if err != nil || token == nil || !token.Active || token.AccountID == "" || strings.HasPrefix(extractBearerToken(r), desktopAccountTokenPrefix) { writeJSON(w, http.StatusUnauthorized, errorResponse("authentication_error", "a linked provider token is required")) return } diff --git a/coordinator/api/device_auth.go b/coordinator/api/device_auth.go index 76e10ea123..10e4ca149f 100644 --- a/coordinator/api/device_auth.go +++ b/coordinator/api/device_auth.go @@ -14,6 +14,7 @@ import ( "encoding/hex" "encoding/json" "fmt" + "io" "math/big" "net/http" "strings" @@ -35,6 +36,17 @@ const ( // POST /v1/device/code // No auth required — the provider CLI is not yet authenticated. func (s *Server) handleDeviceCode(w http.ResponseWriter, r *http.Request) { + var options struct { + Purpose string `json:"purpose"` + } + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxControlPlaneBodyBytes)).Decode(&options); err != nil && err != io.EOF { + writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request", "invalid device code request")) + return + } + if options.Purpose != "" && options.Purpose != "provider" && options.Purpose != desktopAccountPurpose { + writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request", "unsupported authorization purpose")) + return + } // Generate device code (opaque, high-entropy secret). deviceCodeBytes := make([]byte, 32) if _, err := rand.Read(deviceCodeBytes); err != nil { @@ -42,6 +54,9 @@ func (s *Server) handleDeviceCode(w http.ResponseWriter, r *http.Request) { return } deviceCode := hex.EncodeToString(deviceCodeBytes) + if options.Purpose == desktopAccountPurpose { + deviceCode = desktopAccountCodePrefix + deviceCode + } // Generate user code (short, human-readable, uppercase alphanumeric). userCode, err := generateUserCode() @@ -80,7 +95,11 @@ func (s *Server) handleDeviceCode(w http.ResponseWriter, r *http.Request) { verificationURI = fmt.Sprintf("%s://%s/link", scheme, r.Host) } + if options.Purpose == desktopAccountPurpose { + verificationURI += "?purpose=" + desktopAccountPurpose + } writeJSON(w, http.StatusOK, map[string]any{ + "purpose": options.Purpose, "device_code": deviceCode, "user_code": userCode, "verification_uri": verificationURI, @@ -129,6 +148,10 @@ func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) { }) case "approved": + if strings.HasPrefix(dc.DeviceCode, desktopAccountCodePrefix) { + s.issueDesktopAccountToken(w, dc) + return + } // Generate a long-lived provider token. tokenBytes := make([]byte, 32) if _, err := rand.Read(tokenBytes); err != nil { @@ -177,6 +200,7 @@ func (s *Server) handleDeviceApprove(w http.ResponseWriter, r *http.Request) { var req struct { UserCode string `json:"user_code"` + Purpose string `json:"purpose"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.UserCode == "" { writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request", "user_code is required")) @@ -197,6 +221,10 @@ func (s *Server) handleDeviceApprove(w http.ResponseWriter, r *http.Request) { return } + if strings.HasPrefix(dc.DeviceCode, desktopAccountCodePrefix) != (req.Purpose == desktopAccountPurpose) { + writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request", "authorization purpose does not match this code")) + return + } if dc.Status != "pending" { writeJSON(w, http.StatusConflict, errorResponse("already_used", "this code has already been used")) return @@ -213,9 +241,14 @@ func (s *Server) handleDeviceApprove(w http.ResponseWriter, r *http.Request) { "email", user.Email, ) + message := "Device linked successfully. Your provider will connect to your account shortly." + if req.Purpose == desktopAccountPurpose { + message = "Desktop account access approved. Return to the app." + } writeJSON(w, http.StatusOK, map[string]any{ + "purpose": req.Purpose, "status": "approved", - "message": "Device linked successfully. Your provider will connect to your account shortly.", + "message": message, }) } diff --git a/coordinator/api/provider.go b/coordinator/api/provider.go index d1c1dcdbdc..8930521df4 100644 --- a/coordinator/api/provider.go +++ b/coordinator/api/provider.go @@ -545,6 +545,10 @@ func (s *Server) providerReadLoop(ctx context.Context, conn *websocket.Conn, pro _ = conn.Close(websocket.StatusPolicyViolation, "invalid prefix-cache capabilities") return } + if strings.HasPrefix(regMsg.AuthToken, desktopAccountTokenPrefix) { + _ = conn.Close(websocket.StatusPolicyViolation, "account sessions cannot register providers") + return + } // Resolve the token once before choosing the identity rollout path. // Keep linkage after attestation restoration, as with legacy clients; // only this validated account may select the App Attest cohort. @@ -553,7 +557,7 @@ func (s *Server) providerReadLoop(ctx context.Context, conn *websocket.Conn, pro resolveAccount := func() { accountResolved = true pt, err := s.store.GetProviderToken(regMsg.AuthToken) - if err != nil || pt == nil { + if err != nil || pt == nil || strings.HasPrefix(regMsg.AuthToken, desktopAccountTokenPrefix) { s.logger.Warn("provider auth token invalid", "provider_id", providerID, "error", err) } else { authenticatedAccountID, authenticatedTokenLabel = pt.AccountID, pt.Label diff --git a/coordinator/api/server.go b/coordinator/api/server.go index 691cd9a42f..1676f55872 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -2697,17 +2697,17 @@ func (s *Server) routes() { s.mux.HandleFunc("GET /v1/payments/balance", s.requireAuth(s.handleBalance)) s.mux.HandleFunc("GET /v1/payments/usage", s.requireAuth(s.handleUsage)) - s.mux.HandleFunc("GET /v1/provider/account-earnings", s.requireAuth(s.handleAccountEarnings)) + s.mux.HandleFunc("GET /v1/provider/account-earnings", s.requireAccountRead(s.requireAuth(s.handleAccountEarnings))) s.mux.HandleFunc("GET /v1/provider/desktop", s.requireDesktopProviderToken(s.rateLimitDesktop(s.handleDesktopAccount))) s.mux.HandleFunc("GET /v1/provider/desktop/insights", s.requireDesktopProviderToken(s.rateLimitDesktop(s.handleDesktopInsights))) // Account-scoped provider dashboard. - s.mux.HandleFunc("GET /v1/me/providers", s.requirePrivyAuth(s.handleMyProviders)) + s.mux.HandleFunc("GET /v1/me/providers", s.requireAccountRead(s.requirePrivyAuth(s.handleMyProviders))) s.mux.HandleFunc("GET /v1/me/token-promotions", s.requirePrivyAuth(s.handleMyModelTokenPromotions)) s.mux.HandleFunc("POST /v1/me/token-promotions/claim", s.requirePrivyAuth(s.rateLimitFinancial(s.handleMyModelTokenPromotions))) s.mux.HandleFunc("GET /v1/admin/token-promotions", s.handleAdminModelTokenPromotions) s.mux.HandleFunc("PUT /v1/admin/token-promotions", s.handleAdminModelTokenPromotions) - s.mux.HandleFunc("GET /v1/me/summary", s.requirePrivyAuth(s.handleMySummary)) + s.mux.HandleFunc("GET /v1/me/summary", s.requireAccountRead(s.requirePrivyAuth(s.handleMySummary))) // Alias-aware owned live-model ids for the console's self-route key picker. s.mux.HandleFunc("GET /v1/me/self-route-models", s.requirePrivyAuth(s.handleMySelfRouteModels)) // Ownership-checked hard delete of a retired/offline machine's record(s). @@ -2743,8 +2743,9 @@ func (s *Server) routes() { s.mux.HandleFunc("GET /v1/releases/latest", s.handleLatestRelease) // public (install.sh) // Device authorization flow — providers link to user accounts. - s.mux.HandleFunc("POST /v1/device/code", s.handleDeviceCode) // no auth — provider not yet authenticated - s.mux.HandleFunc("POST /v1/device/token", s.handleDeviceToken) // no auth — polls with device_code secret + s.mux.HandleFunc("POST /v1/device/code", s.handleDeviceCode) // no auth — provider not yet authenticated + s.mux.HandleFunc("POST /v1/device/token", s.handleDeviceToken) + s.mux.HandleFunc("DELETE /v1/device/token", s.revokeDesktopAccountToken) // no auth — polls with device_code secret // Device approve issues a long-lived provider→account linking token — // same risk class as /v1/auth/keys, so financial-tier limit applies. // Uses requirePrivyAuth to reject API keys (interactive session only). @@ -3262,7 +3263,7 @@ func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc { // Cache the API-key result (positive or negative). Provider-token // fallbacks are deliberately NOT cached below. s.storeAPIKeyCache(token, apiKeyCacheEntry{key: keyRec, cachedAt: time.Now()}) - } else if pt, err := s.store.GetProviderToken(token); err == nil && pt != nil && pt.Active { + } else if pt, err := s.store.GetProviderToken(token); err == nil && pt != nil && pt.Active && !strings.HasPrefix(token, desktopAccountTokenPrefix) { // Provider device-login tokens authenticate as an account-scoped // identity with no per-key limits (ID left empty). These are NOT // cached: provider-token revocation has no api-key-cache diff --git a/coordinator/store/device_code_consumption_test.go b/coordinator/store/device_code_consumption_test.go new file mode 100644 index 0000000000..6826b89202 --- /dev/null +++ b/coordinator/store/device_code_consumption_test.go @@ -0,0 +1,75 @@ +package store + +import ( + "fmt" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestConsumeDeviceCodeMemory(t *testing.T) { deviceCodeConsumptionContract(t, NewMemory(Config{})) } +func TestConsumeDeviceCodePostgres(t *testing.T) { + deviceCodeConsumptionContract(t, testPostgresStore(t)) +} + +func deviceCodeConsumptionContract(t *testing.T, s Store) { + t.Helper() + for _, scenario := range []struct { + name, status string + expired bool + allowed bool + }{ + {"approved", "approved", false, true}, + {"pending", "pending", false, false}, + {"consumed", "consumed", false, false}, + {"expired", "approved", true, false}, + } { + t.Run(scenario.name, func(t *testing.T) { + expiry := time.Now().Add(time.Hour) + if scenario.expired { + expiry = time.Now().Add(-time.Hour) + } + code := "consumption-" + scenario.name + if err := s.CreateDeviceCode(&DeviceCode{DeviceCode: code, UserCode: fmt.Sprintf("C-%s", scenario.name), Status: scenario.status, AccountID: "consumption-account", ExpiresAt: expiry}); err != nil { + t.Fatal(err) + } + var winners atomic.Int32 + var group sync.WaitGroup + for range 16 { + group.Add(1) + go func() { + defer group.Done() + if s.ConsumeDeviceCode(code) == nil { + winners.Add(1) + } + }() + } + group.Wait() + want := int32(0) + if scenario.allowed { + want = 1 + } + if got := winners.Load(); got != want { + t.Fatalf("successful exchanges = %d, want %d", got, want) + } + stored, err := s.GetDeviceCode(code) + if err != nil { + t.Fatal(err) + } + wantStatus := scenario.status + if scenario.allowed { + wantStatus = "consumed" + } + if stored.Status != wantStatus || stored.AccountID != "consumption-account" { + t.Fatalf("unexpected grant after exchange: %+v", stored) + } + if err := s.ConsumeDeviceCode(code); err == nil { + t.Fatal("grant exchanged again") + } + }) + } + if err := s.ConsumeDeviceCode("missing-grant"); err == nil { + t.Fatal("unknown grant exchanged") + } +} diff --git a/coordinator/store/interface_domains.go b/coordinator/store/interface_domains.go index dd4303454a..cc8376058d 100644 --- a/coordinator/store/interface_domains.go +++ b/coordinator/store/interface_domains.go @@ -472,6 +472,9 @@ type DeviceAuthStore interface { // ApproveDeviceCode links a device code to an account, marking it approved. ApproveDeviceCode(deviceCode, accountID string) error + // ConsumeDeviceCode atomically exchanges an approved, unexpired grant once. + ConsumeDeviceCode(deviceCode string) error + // DeleteExpiredDeviceCodes removes device codes that have passed their expiry. DeleteExpiredDeviceCodes() error diff --git a/coordinator/store/memory.go b/coordinator/store/memory.go index 23518be3b2..218aeb4ded 100644 --- a/coordinator/store/memory.go +++ b/coordinator/store/memory.go @@ -2403,6 +2403,17 @@ func (s *MemoryStore) ApproveDeviceCode(deviceCode, accountID string) error { return nil } +func (s *MemoryStore) ConsumeDeviceCode(code string) error { + s.mu.Lock() + defer s.mu.Unlock() + dc := s.deviceCodesByCode[code] + if dc == nil || dc.Status != "approved" || !time.Now().Before(dc.ExpiresAt) { + return errors.New("device grant unavailable") + } + dc.Status = "consumed" + return nil +} + func (s *MemoryStore) DeleteExpiredDeviceCodes() error { s.mu.Lock() defer s.mu.Unlock() diff --git a/coordinator/store/postgres.go b/coordinator/store/postgres.go index cf04b2ab3c..c20418033e 100644 --- a/coordinator/store/postgres.go +++ b/coordinator/store/postgres.go @@ -3421,6 +3421,19 @@ func (s *PostgresStore) ApproveDeviceCode(deviceCode, accountID string) error { return nil } +func (s *PostgresStore) ConsumeDeviceCode(code string) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + tag, err := s.pool.Exec(ctx, `UPDATE device_codes SET status = 'consumed' WHERE device_code = $1 AND status = 'approved' AND expires_at > NOW()`, code) + if err != nil { + return fmt.Errorf("store: consume device grant: %w", err) + } + if tag.RowsAffected() != 1 { + return errors.New("device grant unavailable") + } + return nil +} + func (s *PostgresStore) DeleteExpiredDeviceCodes() error { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() diff --git a/desktop-app/src/renderer/App.tsx b/desktop-app/src/renderer/App.tsx index 1aa5d91e86..8ced99b66a 100644 --- a/desktop-app/src/renderer/App.tsx +++ b/desktop-app/src/renderer/App.tsx @@ -1,5 +1,5 @@ import { useCallback, useEffect, useState } from 'react'; -import { Box, ChevronRight, Home as HomeIcon, Monitor, Trophy, Zap } from 'lucide-react'; +import { Box, Home as HomeIcon, Monitor, Trophy, Zap } from 'lucide-react'; import type { Route } from '../shared/contracts'; import { api, isPreview, useBackend } from './useBackend'; import { Home } from './features/Home'; @@ -12,6 +12,7 @@ import { Onboarding } from './components/Onboarding'; import { onboardingScenario } from './previewEligibility'; import { Earnings } from './features/Earnings'; import { Appearance } from './components/Appearance'; +import { AccountControl } from './components/AccountControl'; import { SocialLinks } from './components/SocialLinks'; const navigation = [ { id: 'home', label: 'Home', icon: HomeIcon }, @@ -40,15 +41,6 @@ export default function App() { setOnboarding(false); }; useEffect(() => api?.onNavigate(navigate), [navigate]); - const title = [ - ...navigation, - { id: 'settings', label: 'Settings' }, - { id: 'models', label: 'Models' }, - { id: 'studio', label: 'Studio' }, - { id: 'analysis', label: 'Stats' }, - { id: 'earnings', label: 'Earnings' }, - { id: 'cooling', label: 'Cooling' }, - ].find((item) => item.id === route)?.label; if (!backend.state || onboarding) return ( <> @@ -85,7 +77,8 @@ export default function App() {
- + {pending && state.link && ( +
+ {state.link.code} + + +
+ )} +
+ ); +} diff --git a/desktop-app/src/renderer/components/UI.tsx b/desktop-app/src/renderer/components/UI.tsx index 2543fbc4d0..f361e6d5c5 100644 --- a/desktop-app/src/renderer/components/UI.tsx +++ b/desktop-app/src/renderer/components/UI.tsx @@ -96,7 +96,13 @@ export function OperationFeed({ backend: BackendState; inline?: boolean; }) { - const [dismissed, setDismissed] = useState(''); + const [dismissed, setDismissed] = useState(() => { + try { + return localStorage.getItem('darkbloom.dismissed-operation') ?? ''; + } catch { + return ''; + } + }); const operation = backend.state?.operations[0]; if (!operation || operation.id === dismissed) return null; return ( @@ -136,7 +142,14 @@ export function OperationFeed({ diff --git a/desktop-app/src/renderer/components/onboarding/ScanFooter.tsx b/desktop-app/src/renderer/components/onboarding/ScanFooter.tsx index 3d6860974a..07c75aa1b8 100644 --- a/desktop-app/src/renderer/components/onboarding/ScanFooter.tsx +++ b/desktop-app/src/renderer/components/onboarding/ScanFooter.tsx @@ -11,10 +11,12 @@ export function ScanFooter({ scan, proceed, explore, + waitlist = true, }: { scan: MacScan; proceed: () => void; explore: () => void; + waitlist?: boolean; }) { const { result, settled } = scan; if (!result) return null; @@ -51,7 +53,7 @@ export function ScanFooter({ ); return result.verdict === 'ineligible' ? ( <> - check.id)} /> + {waitlist && check.id)} />} {links} ) : ( diff --git a/desktop-app/src/renderer/components/onboarding/ScanStep.tsx b/desktop-app/src/renderer/components/onboarding/ScanStep.tsx index 422963fb3e..9fde2a586f 100644 --- a/desktop-app/src/renderer/components/onboarding/ScanStep.tsx +++ b/desktop-app/src/renderer/components/onboarding/ScanStep.tsx @@ -65,7 +65,12 @@ export function ScanStep({ verdict={verdict} caption={caption(scan, backend)} /> - + ); } diff --git a/desktop-app/src/renderer/components/onboarding/StartServing.tsx b/desktop-app/src/renderer/components/onboarding/StartServing.tsx index 76d50dcf9d..a029606723 100644 --- a/desktop-app/src/renderer/components/onboarding/StartServing.tsx +++ b/desktop-app/src/renderer/components/onboarding/StartServing.tsx @@ -47,13 +47,18 @@ export function StartServing({ done: () => void; }) { const [mode, setMode] = useState('network'); - const [pinned, setPinned] = useState([]); + const [pinned, setPinned] = useState(() => { + if (!snapshot.capabilities || snapshot.capabilities.includes('autopilot')) return []; + const model = startingModel(snapshot); + return model ? [model.id] : []; + }); const [open, setOpen] = useState(false); const starting = startingModel(snapshot); const serving = useStartServing(backend, done, () => setPinned((current) => (current.length || !starting ? current : [starting.id])), ); - const method = methodFor(mode, serving.rejected); + const manualOnly = !!snapshot.capabilities && !snapshot.capabilities.includes('autopilot'); + const method = methodFor(mode, serving.rejected || manualOnly); const text = copy[method]; const empty = !startModels(snapshot, method, pinned).length; const tooLarge = pinnedMemory(snapshot, pinned).exceeds; diff --git a/desktop-app/src/renderer/data/pageResources.ts b/desktop-app/src/renderer/data/pageResources.ts new file mode 100644 index 0000000000..b2acaf007e --- /dev/null +++ b/desktop-app/src/renderer/data/pageResources.ts @@ -0,0 +1,18 @@ +import type { Resource, Route } from '../../shared/contracts'; + +// Resources are requested only by screens that display them. Native code owns freshness. +export function pageResources(route: Route): Resource[] { + switch (route) { + case 'home': + return ['cloud', 'network']; + case 'machines': + case 'earnings': + return ['cloud']; + case 'leaderboard': + return ['leaderboard']; + case 'updates': + return ['release', 'release-history']; + default: + return []; + } +} diff --git a/desktop-app/src/renderer/features/Cooling.tsx b/desktop-app/src/renderer/features/Cooling.tsx index dec8dd118c..1bace6af79 100644 --- a/desktop-app/src/renderer/features/Cooling.tsx +++ b/desktop-app/src/renderer/features/Cooling.tsx @@ -36,7 +36,7 @@ export function Cooling({ {fans.length > 0 && } - {cooling?.supported ? ( + {cooling?.supported && cooling.control_available !== false ? ( ) : ( diff --git a/desktop-app/src/renderer/features/Earnings.tsx b/desktop-app/src/renderer/features/Earnings.tsx index b5ba5474da..60810ffa56 100644 --- a/desktop-app/src/renderer/features/Earnings.tsx +++ b/desktop-app/src/renderer/features/Earnings.tsx @@ -21,14 +21,16 @@ export function Earnings({ backend }: { backend: BackendState }) { const rows = [ 'date_utc,inference_micro_usd,base_reward_micro_usd,settled_requests,input_tokens,output_tokens', ...data.days.map((d) => - [ - d.id, - d.work_micro_usd, - d.base_reward_micro_usd, - d.jobs, - d.prompt_tokens, - d.completion_tokens, - ].join(','), + d.available === false + ? `${d.id},,,,,` + : [ + d.id, + d.work_micro_usd, + d.base_reward_micro_usd, + d.jobs, + d.prompt_tokens, + d.completion_tokens, + ].join(','), ), ]; try { @@ -79,7 +81,15 @@ export function Earnings({ backend }: { backend: BackendState }) { )}
- Earned in this period + + {data.history_complete ? 'Earned in this period' : 'Recorded earnings'} + {money(earned(data.totals))} {money(data.totals.work_micro_usd)} inference +{' '} @@ -119,9 +129,11 @@ export function Earnings({ backend }: { backend: BackendState }) { {copied ? : } {copied ? 'Copied' : 'Copy CSV'}
- + - + {data.lifetime.completion_tokens !== null && ( + + )}

Settled through {new Date(data.as_of).toLocaleString()}. Calendar days are UTC; today is partial. Balances and withdrawals remain in the console. diff --git a/desktop-app/src/renderer/features/Home.tsx b/desktop-app/src/renderer/features/Home.tsx index 0136c1f303..628cb94b5f 100644 --- a/desktop-app/src/renderer/features/Home.tsx +++ b/desktop-app/src/renderer/features/Home.tsx @@ -1,9 +1,9 @@ -import { ArrowUpRight, Pause, Play } from 'lucide-react'; +import { Pause, Play } from 'lucide-react'; import type { BackendState } from '../useBackend'; import { api, isPreview } from '../useBackend'; import type { Route } from '../../shared/contracts'; -import { count } from '../format'; import { Button, Header } from '../components/UI'; +import { ContributionMetrics } from './home/ContributionMetrics'; import { ChipStage } from './home/chip/ChipStage'; import { FleetSummary } from './home/FleetSummary'; import { NetworkMilestone } from './home/NetworkMilestone'; @@ -24,7 +24,6 @@ export function Home({

-
-
- Tokens shared this session - {count(state.activity.tokens)} - - {count(state.activity.requests)} requests served{' '} - - -
-
+ navigate('analysis')} />
@@ -56,17 +44,18 @@ export function Home({ openMachine={openMachine} onEarnings={() => navigate('earnings')} /> -
- {isPreview ? 'Simulated activity' : state.readiness} - {!state.linked && ( - - )} - {state.link && ( - - )} -
+ {(!state.linked || state.link) && ( +
+ {!state.linked && ( + + )} + {state.link && ( + + )} +
+ )}
); } diff --git a/desktop-app/src/renderer/features/Machines.tsx b/desktop-app/src/renderer/features/Machines.tsx index 3b976d1cf5..37e841f7a8 100644 --- a/desktop-app/src/renderer/features/Machines.tsx +++ b/desktop-app/src/renderer/features/Machines.tsx @@ -43,7 +43,7 @@ export function Machines({ />
{local && } - {backend.cloud?.error && {backend.cloud.error}} + {backend.cloud?.error && route === 'machines' && {backend.cloud.error}}
My Macs / diff --git a/desktop-app/src/renderer/features/Stats.tsx b/desktop-app/src/renderer/features/Stats.tsx index ccaf5f0ce0..6dc152c4a9 100644 --- a/desktop-app/src/renderer/features/Stats.tsx +++ b/desktop-app/src/renderer/features/Stats.tsx @@ -39,7 +39,11 @@ export function Stats({ {view === 'performance' ? ( ) : ( - + )}
diff --git a/desktop-app/src/renderer/features/cooling/CoolingControls.tsx b/desktop-app/src/renderer/features/cooling/CoolingControls.tsx index 0a50038d31..0397d7999b 100644 --- a/desktop-app/src/renderer/features/cooling/CoolingControls.tsx +++ b/desktop-app/src/renderer/features/cooling/CoolingControls.tsx @@ -1,4 +1,4 @@ -import { useId, useState } from 'react'; +import { useEffect, useId, useState } from 'react'; import type { BackendState } from '../../useBackend'; import { Button } from '../../components/UI'; import styles from './cooling.module.css'; @@ -9,6 +9,10 @@ export function CoolingControls({ backend }: { backend: BackendState }) { const [speed, setSpeed] = useState(70); const [temperature, setTemperature] = useState(50); const titleID = useId(); + useEffect(() => { + if (backend.cooling?.speed != null) setSpeed(backend.cooling.speed); + if (backend.cooling?.threshold != null) setTemperature(backend.cooling.threshold); + }, [backend.cooling?.speed, backend.cooling?.threshold]); return (

Provider cooling

@@ -20,8 +24,8 @@ export function CoolingControls({ backend }: { backend: BackendState }) { setSpeed(Number(e.target.value))} /> diff --git a/desktop-app/src/renderer/features/home/ContributionMetrics.tsx b/desktop-app/src/renderer/features/home/ContributionMetrics.tsx new file mode 100644 index 0000000000..9480cb49cd --- /dev/null +++ b/desktop-app/src/renderer/features/home/ContributionMetrics.tsx @@ -0,0 +1,54 @@ +import { ArrowUpRight } from 'lucide-react'; +import type { Snapshot } from '../../../shared/contracts'; +import { count } from '../../format'; +import { contribution } from './contribution'; +import styles from './home.module.css'; + +export function ContributionMetrics({ + activity, + explore, +}: { + activity: Snapshot['activity']; + explore: () => void; +}) { + const totals = contribution(activity); + return ( +
+
+ {totals.label} + {totals.tokens} +
+ + Input {totals.input} + + + Cached {totals.cached} + + + Output {totals.output} + + + Reasoning {totals.reasoning} + +
+ + {count(activity.requests)} requests served{' '} + {totals.pending && ( + + · {totals.pending} pending{' '} + + )} + + +
+
+ + {totals.earnings} + + Generated this session +
+
+ ); +} diff --git a/desktop-app/src/renderer/features/home/FleetEarnings.tsx b/desktop-app/src/renderer/features/home/FleetEarnings.tsx index 432cb2fdf0..625432538b 100644 --- a/desktop-app/src/renderer/features/home/FleetEarnings.tsx +++ b/desktop-app/src/renderer/features/home/FleetEarnings.tsx @@ -1,6 +1,6 @@ import { ArrowUpRight } from 'lucide-react'; import type { BackendState } from '../../useBackend'; -import { money } from '../../format'; +import { count, money } from '../../format'; import { useInsights } from '../insights/useInsights'; import { EarningsTimeline } from '../insights/EarningsTimeline'; import styles from './fleet.module.css'; @@ -14,6 +14,10 @@ export function FleetEarnings({ }) { const { data, error } = useInsights(backend.state!); const week = backend.cloud?.week_micro_usd; + const complete = backend.cloud?.earnings_complete !== false; + const since = backend.cloud?.earnings_since + ? new Date(backend.cloud.earnings_since * 1000).toLocaleString() + : undefined; const pace = week && /^\d+$/.test(week) ? money(((BigInt(week) * 365n) / 7n).toString(), 0) : '—'; return (
@@ -23,40 +27,46 @@ export function FleetEarnings({ {money(backend.cloud?.lifetime_micro_usd)}
- Past 7 days + + {complete ? 'Past 7 days' : 'Recent earnings'} + {money(week)}
- Annualized pace - - {pace} - /yr - + {complete ? ( + <> + Annualized pace + + {pace} + /yr + + + ) : ( + <> + Settled payments + {count(backend.cloud?.settled_records)} + + )}
- Daily earnings · 7 calendar days + Daily earnings · 7 days
{data ? ( - + ) : (

- {backend.state!.linked - ? error || 'Loading earnings history…' - : 'Link this Mac to view earnings history.'} + {backend.state!.linked ? (error ? 'Unavailable' : 'Loading…') : 'Account not linked'}

)} {data && error && (

- {error} Showing the last observation. + Last known

)} -

- Annualized from the past 7 days. A pace, not guaranteed income. -

); } diff --git a/desktop-app/src/renderer/features/home/FleetMacs.tsx b/desktop-app/src/renderer/features/home/FleetMacs.tsx index 7b103a0900..b4e75e4331 100644 --- a/desktop-app/src/renderer/features/home/FleetMacs.tsx +++ b/desktop-app/src/renderer/features/home/FleetMacs.tsx @@ -11,10 +11,12 @@ export function FleetMacs({ machines, localID, onOpen, + recent = false, }: { machines: Machine[]; localID: string; onOpen: (id: string) => void; + recent?: boolean; }) { const [query, setQuery] = useState(''); const [filter, setFilter] = useState('all'); @@ -54,7 +56,7 @@ export function FleetMacs({ Mac Status Models - Usage earnings · 7d + Usage earnings · {recent ? 'Recent' : '7d'} {visible.map((machine) => (
- )} +
+
+ Tokens processed this session + {usage.tokens}
- {models.length ? ( - <> -
- {models.map((m, i) => ( - - ))} -
-
- Model - Requests - Share - Generation -
- {models.map((m, i) => ( - - ))} - - ) : ( -

- Per-model traffic history is not yet available from the runtime. -

+ {state.activity.cached_input_tokens != null && ( +
+ Cached input + {usage.cached} +
+ )} + {state.activity.reasoning_tokens != null && ( +
+ Reasoning + {usage.reasoning} +
)} - - {insights && } -
- Runtime & readiness -

{state.readiness}

-

- Runtime {state.version} · Local API {state.endpoint ? 'available' : 'not enabled'} -

- Troubleshooting guide -
+
+ {points.length > 0 && ( + + )} + {history && } ); } diff --git a/desktop-app/src/renderer/features/stats/PreviewPerformance.tsx b/desktop-app/src/renderer/features/stats/PreviewPerformance.tsx new file mode 100644 index 0000000000..1aa834be72 --- /dev/null +++ b/desktop-app/src/renderer/features/stats/PreviewPerformance.tsx @@ -0,0 +1,130 @@ +import { useMemo, useState } from 'react'; +import type { BackendState } from '../../useBackend'; +import { isPreview } from '../../useBackend'; +import { compact, gb } from '../../format'; +import { External } from '../../components/UI'; +import { LiveModels } from '../insights/LiveModels'; +import { previewStats } from '../../previewStats'; +import { observedTraffic } from './data'; +import { RequestFlow } from './RequestFlow'; +import { TrafficChart, type TrafficMetric } from './TrafficChart'; +import styles from './stats.module.css'; + +export function PreviewPerformance({ backend }: { backend: BackendState }) { + const state = backend.state!, + [metric, setMetric] = useState('requests'), + [model, setModel] = useState('all'); + const models = useMemo(() => (isPreview ? previewStats(Date.now() / 1000) : []), []); + const points = isPreview + ? model === 'all' + ? models[0].points.map((p, i) => ({ + at: p.at, + requests: models.reduce((n, m) => n + m.points[i].requests, 0), + tokens: models.reduce((n, m) => n + m.points[i].tokens, 0), + input: models.reduce((n, m) => n + (m.points[i].input ?? 0), 0), + cached: models.reduce((n, m) => n + (m.points[i].cached ?? 0), 0), + })) + : models.find((m) => m.id === model)!.points + : observedTraffic(state); + const totalRequests = models.reduce((n, m) => n + m.requests, 0), + totalTokens = models.reduce((n, m) => n + m.tokens, 0); + return ( + <> + {isPreview && ( +
Design preview · simulated traffic and performance
+ )} +
+
+ Requests served + {compact(isPreview ? totalRequests : state.activity.requests)} + {isPreview ? 'Past 24 hours' : 'This session'} +
+
+ Output tokens + {compact(isPreview ? totalTokens : state.activity.tokens)} + {isPreview ? 'Past 24 hours' : 'This session'} +
+
+ Success rate + {isPreview ? '99.8%' : '—'} + {isPreview ? 'Completed requests' : 'Awaiting outcome data'} +
+
+ Active model memory + {gb(state.memory.active_gb)} + of {gb(state.memory.total_gb)} +
+
+ {isPreview ? : } + m.id === model)?.name} · Past 24 hours · 30-minute intervals` + : 'Observed intervals · this session' + } + /> +
+
+

Which models get the work

+ {models.length > 0 && ( + + )} +
+ {models.length ? ( + <> +
+ {models.map((m, i) => ( + + ))} +
+
+ Model + Requests + Share + Generation +
+ {models.map((m, i) => ( + + ))} + + ) : ( +

+ Per-model traffic history is not yet available from the runtime. +

+ )} +
+
+ Runtime & readiness +

{state.readiness}

+

+ Runtime {state.version} · Local API {state.endpoint ? 'available' : 'not enabled'} +

+ Troubleshooting guide +
+ + ); +} diff --git a/desktop-app/src/renderer/features/stats/TokenBars.tsx b/desktop-app/src/renderer/features/stats/TokenBars.tsx index 7a5c93cf31..ac0e5c97e9 100644 --- a/desktop-app/src/renderer/features/stats/TokenBars.tsx +++ b/desktop-app/src/renderer/features/stats/TokenBars.tsx @@ -10,7 +10,9 @@ export function TokenBars({ points }: { points: TrafficPoint[] }) { const [selected, setSelected] = useState(null); const refs = useRef<(HTMLButtonElement | null)[]>([]); const prompt = reportsPromptTokens(data); - const series = prompt ? tokenSeries : tokenSeries.filter((entry) => entry.key === 'output'); + const series = tokenSeries.filter( + (entry) => entry.key === 'output' || data.some((bar) => bar[entry.key] !== undefined), + ); const max = Math.max(1, ...data.map((bar) => bar.total)); const bar = selected === null ? undefined : data[selected]; const focus = selected ?? data.length - 1; diff --git a/desktop-app/src/renderer/features/stats/activity/RequestActivity.tsx b/desktop-app/src/renderer/features/stats/activity/RequestActivity.tsx index 27fd607ca7..d626170c58 100644 --- a/desktop-app/src/renderer/features/stats/activity/RequestActivity.tsx +++ b/desktop-app/src/renderer/features/stats/activity/RequestActivity.tsx @@ -12,8 +12,16 @@ import styles from './activity.module.css'; const PAGE = 25; -export function RequestActivity({ models }: { models: NativeModel[] }) { - const { history, loading, failed, refresh } = useRequestHistory(); +export function RequestActivity({ + models, + scope, + revision, +}: { + models: NativeModel[]; + scope?: string; + revision?: string; +}) { + const { history, loading, failed, refresh } = useRequestHistory(scope, revision); const [filter, setFilter] = useState({ model: 'all', outcome: 'all' }); const [shown, setShown] = useState(PAGE); const titleID = useId(); @@ -32,7 +40,7 @@ export function RequestActivity({ models }: { models: NativeModel[] }) {

Requests served

- Every request this Mac has served + Recorded requests from this Mac {history?.since ? ` since ${clockTime(history.since, history.observed_at)}` : ''}.

diff --git a/desktop-app/src/renderer/features/stats/activity/RequestTable.tsx b/desktop-app/src/renderer/features/stats/activity/RequestTable.tsx index 0205fefc57..a90c3caf17 100644 --- a/desktop-app/src/renderer/features/stats/activity/RequestTable.tsx +++ b/desktop-app/src/renderer/features/stats/activity/RequestTable.tsx @@ -1,6 +1,6 @@ import type { RequestRecord } from '../../../../shared/contracts'; import { clockTime, count, money } from '../../../format'; -import { duration, outcomes, tokensPerSecond } from './requests'; +import { duration, outcomes, tokensPerSecond, requestTime } from './requests'; import styles from './activity.module.css'; export function RequestTable({ @@ -12,12 +12,14 @@ export function RequestTable({ names: Map; now: number; }) { + const timing = records.some((record) => record.duration_ms !== undefined); + const settled = records.every((record) => record.settled_at !== undefined); return (
- + - - + {timing && ( + <> + + + + )} {records.map((record) => { const speed = tokensPerSecond(record); + const timing = records.some((record) => record.duration_ms !== undefined); + const settled = records.every((record) => record.settled_at !== undefined); return ( - + - - + {timing && ( + <> + + + + )}
Time{settled ? 'Settled at' : 'Time'} Model Input tokens @@ -25,12 +27,16 @@ export function RequestTable({ Output tokens - Duration - - Tokens/s - + Duration + + Tokens/s + Outcome Earned @@ -40,14 +46,24 @@ export function RequestTable({
{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)} + {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/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/styles/layout.css b/desktop-app/src/renderer/styles/layout.css index 1c9aa10035..725d41595b 100644 --- a/desktop-app/src/renderer/styles/layout.css +++ b/desktop-app/src/renderer/styles/layout.css @@ -146,7 +146,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; @@ -258,3 +258,25 @@ padding: 18px 26px 14px; } } + +.account-control { + padding: 0 12px 8px; +} +.account-control button { + color: var(--text-secondary); + cursor: pointer; + padding: 6px 0; + font-size: 12px; +} +.account-control button:disabled { + opacity: 0.5; + cursor: default; +} +.account-control strong { + display: block; + font-family: monospace; + letter-spacing: 0.08em; +} +.account-control div button { + margin-right: 12px; +} 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/useBackend.ts b/desktop-app/src/renderer/useBackend.ts index 430944df62..51dee50c33 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'; @@ -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/contracts.ts b/desktop-app/src/shared/contracts.ts index c0db587cb7..40de480ff4 100644 --- a/desktop-app/src/shared/contracts.ts +++ b/desktop-app/src/shared/contracts.ts @@ -79,6 +79,9 @@ export interface Snapshot { installation_id: string; linked: boolean; account_revision?: string; + resource_revision?: string; + capabilities?: string[]; + account?: { signed_in: boolean; expires_at?: number; legacy_data?: boolean }; state: 'stopped' | 'starting' | 'running' | 'draining' | 'stale'; readiness: string; machine: Machine; @@ -88,6 +91,20 @@ export interface Snapshot { 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 +140,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 +156,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; } @@ -162,6 +186,9 @@ export interface CoolingData { mode: string; temperature?: number; fans: { name: string; rpm: number; max_rpm: number }[]; + control_available?: boolean; + speed?: number; + threshold?: number; error?: string; } export interface ReleaseData { @@ -185,7 +212,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/app.test.tsx b/desktop-app/tests/app.test.tsx index 874462681b..ebb6369854 100644 --- a/desktop-app/tests/app.test.tsx +++ b/desktop-app/tests/app.test.tsx @@ -113,9 +113,7 @@ describe('desktop operator journeys', () => { 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/ })); - expect( - await within(row).findByRole('progressbar', { name: 'Download progress' }), - ).toBeVisible(); + await within(row).findByRole('progressbar', { name: 'Download progress' }); 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 () => { 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..17cc9cce07 100644 --- a/desktop-app/tests/coolingRefresh.test.tsx +++ b/desktop-app/tests/coolingRefresh.test.tsx @@ -26,7 +26,7 @@ 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 }; } @@ -69,3 +69,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/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/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/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/modelsRanking.test.tsx b/desktop-app/tests/modelsRanking.test.tsx new file mode 100644 index 0000000000..1138b2f097 --- /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', 'Qwen 3.6 35B A3B', 'Kimi K2.6']); + expect(screen.getByText('Most earned · 30d')).toBeVisible(); + fireEvent.click(screen.getByRole('button', { name: enabled ? 'In pool' : '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/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/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/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/remoteOverview.test.tsx b/desktop-app/tests/remoteOverview.test.tsx index beb1aa55bf..b1ab8606d4 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); diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index aee0b3e5f2..1705ab386e 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-05 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 @@ -415,3 +415,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.

+
Reuse account APIsSwift account session → existing /me endpoints
Reuse the darkbloom CLISame executable · existing desktop serve API
Keep Electron thinUI + IPC · backend observations drive every page
+ +
+

Before

Previous local test build

Mixed refreshes
+

01 · Renderer

+

02 · Fetch & refresh

+

03 · Native gateway

+

04 · Data sources

+ + + +
FRICTIONNetwork latency can delay local state. Missing endpoints create repeated failed requests.
+

After

Implemented locally · sign-in rollout pending

Shared sources
+

01 · Renderer

+

02 · Thin Electron bridge

+

03 · Same darkbloom CLI executable · desktop serve

+ + + +
+

04 · Data sources

+ + + +
RESULTSame CLI executable. Account views work while inference is stopped; its desktop serve process stays available.
+
+ +

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 / resourceDecisionAfter
/v1/provider/desktopPR-added · live check: 404ReplaceUse 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: 404Merge into earningsExtend 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 rowsKeep + extendComplete 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 matchingRemove dashboard pollingSigned-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 403Reuse with user loginOwned fleet, live/stored machine state, account totals and balances. No new fleet endpoint required.
/v1/stats/v1/leaderboardKeep · fetch selectivelyCache 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: 404Consolidate release readsShare one latest-release read; show only its available notes. Preserve signed runtime update verification.
/v1/models/catalog/v1/models/catalog/manifest/{id}Keep · decoupleRefresh catalog in the background; fetch manifests on download. Catalog requests cannot block local state snapshots.
/control/v1/state/control/v1/eventsKeep · stream firstOne shared state subscription. Snapshot reads for startup/resync and fallback; operation completion comes from the stream.
POST /control/v1/actionsKeep one action interfaceOne 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 localRead 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 SwiftKeep 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 joinRead 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 adaptersSwift 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.
+
Based on the PR 1318 checkout and local app changes. Endpoint status checks: Oct 04, 2026. Local implementation: Oct 05, 2026.After = local implementation · same CLI backend · rollout pending
+
+ + + 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/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/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..60e1af7f62 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-05 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,10 @@ 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 read-only 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`). 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..e3464601d9 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-05 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` | 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..15dc12a346 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-05 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,10 +64,11 @@ 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/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` | 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/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` | @@ -102,13 +106,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 +read-only 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. @@ -188,6 +195,7 @@ that cleanup completes, then the operation becomes `cancelled`. | `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 +208,39 @@ 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. +## 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`). + +`account-signin` and `darkbloom desktop login` reuse the browser device-code flow +with `purpose=desktop_account`. The browser uses its Privy session to approve +read-only access. Swift requires the coordinator to echo the purpose before +opening the browser; an older coordinator fails explicitly. It stores the separate +30-day session 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; offline sign-out can leave +the server credential valid until expiry. 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 +251,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..2f07a8563e 100644 --- a/provider-swift/Sources/ProviderCore/Auth/DeviceAuth.swift +++ b/provider-swift/Sources/ProviderCore/Auth/DeviceAuth.swift @@ -89,12 +89,14 @@ private struct DeviceCodeResponse: Decodable, Sendable { let verification_uri: String let expires_in: Int let interval: Int + let purpose: String? } /// Response from POST /v1/device/token private struct DeviceTokenResponse: Decodable, Sendable { let status: String? let token: String? + let purpose: String? let error: TokenError? struct TokenError: Decodable, Sendable { @@ -158,10 +160,11 @@ public func coordinatorHTTPBase(_ wsURL: String) -> String { public func performDeviceCodeLogin( coordinatorURL: String, onDisplayCode: @Sendable (String, String, Int) -> Void, - onPollTick: (@Sendable () -> Void)? = nil + onPollTick: (@Sendable () -> Void)? = nil, + purpose: String? = nil ) async throws -> String { // Check if already logged in. - if let existingToken = AuthTokenStore.load() { + if purpose == nil, let existingToken = AuthTokenStore.load() { let prefix = String(existingToken.prefix(min(20, existingToken.count))) throw DeviceAuthError.alreadyLoggedIn(tokenPrefix: prefix) } @@ -173,6 +176,11 @@ public func performDeviceCodeLogin( 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 @@ -197,6 +205,9 @@ public func performDeviceCodeLogin( throw DeviceAuthError.invalidResponse("could not decode device code response: \(error)") } + if let purpose, dc.purpose != purpose { + throw DeviceAuthError.authorizationFailed("This coordinator does not support desktop account sign-in yet.") + } // Display the code to the user. onDisplayCode(dc.user_code, dc.verification_uri, dc.expires_in) @@ -253,7 +264,9 @@ public func performDeviceCodeLogin( guard let token = tokenResp.token, !token.isEmpty else { throw DeviceAuthError.invalidResponse("authorized but no token in response") } - try AuthTokenStore.save(token) + if let purpose { + guard tokenResp.purpose == purpose, token.hasPrefix("darkbloom-at-") else { throw DeviceAuthError.invalidResponse("wrong account token scope") } + } else { try AuthTokenStore.save(token) } return token default: 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..91fabe670f --- /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") + 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..16186797b0 --- /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") + 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..d4c8b38f06 --- /dev/null +++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountCredential.swift @@ -0,0 +1,67 @@ +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 + + 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, value.token.hasPrefix("darkbloom-at-"), value.expiresAt > Date() + else { return nil } + return value + } + static func save(token: String, base: String) throws { + try DesktopStorage.write(true, name: "disabled-" + filename(base: base)) + // Server lifetime is 30 days; expire locally one minute early. + 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), "expires_at": .number(credential.expiresAt.timeIntervalSince1970)]) + } + func clearAccountResources() { + resourceGeneration += 1 + 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 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..a16123914e --- /dev/null +++ b/provider-swift/Sources/darkbloom/Desktop/DesktopAccountEarningsCache.swift @@ -0,0 +1,24 @@ +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) } + accountEarningsCache = (key, Date(), value) + return value + } +} 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/DesktopBackend.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopBackend.swift index 0283a5e015..47eff158d0 100644 --- a/provider-swift/Sources/darkbloom/Desktop/DesktopBackend.swift +++ b/provider-swift/Sources/darkbloom/Desktop/DesktopBackend.swift @@ -20,11 +20,21 @@ 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() /// Shared `fan status` read; `coolingReadAt` is nil while it is in flight. var coolingRead: Task? @@ -66,7 +76,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"].contains(request.action)) requests[request.id] = request operations.insert(operation, at: 0) operations = Array(operations.prefix(32)) @@ -101,6 +111,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") @@ -144,7 +156,7 @@ 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)) } } @@ -190,7 +202,7 @@ 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 } @@ -202,7 +214,7 @@ actor DesktopBackend { else { return } operations[index].message = String(output.suffix(8000)) } - 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..812c0f26db 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 { @@ -94,23 +94,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..94f31c0fe0 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) @@ -47,7 +48,12 @@ extension DesktopBackend { } return .dict([ "supported": diagnostic.field("supported"), - "mode": status.field("helper").field("mode").text.map(DV.string) ?? .string("automatic"), + "control_available": .bool(signed != nil), + "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..418bfd574d 100644 --- a/provider-swift/Sources/darkbloom/Desktop/DesktopResources.swift +++ b/provider-swift/Sources/darkbloom/Desktop/DesktopResources.swift @@ -17,61 +17,42 @@ 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")), @@ -99,15 +80,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..e18f0c1615 100644 --- a/provider-swift/Sources/darkbloom/Desktop/DesktopSnapshot.swift +++ b/provider-swift/Sources/darkbloom/Desktop/DesktopSnapshot.swift @@ -11,14 +11,7 @@ extension DesktopBackend { 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 @@ -78,6 +71,18 @@ 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 machine: JSONValue = .dict([ "id": .string("this-mac"), "name": .string(loaded.config.provider.name), @@ -90,8 +95,11 @@ extension DesktopBackend { "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"].map(DV.string)), "state": .string(phase), "readiness": .string( fresh @@ -106,13 +114,7 @@ extension DesktopBackend { "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..c5e9513c35 100644 --- a/provider-swift/Sources/darkbloom/Desktop/DesktopTypes.swift +++ b/provider-swift/Sources/darkbloom/Desktop/DesktopTypes.swift @@ -61,7 +61,7 @@ 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", ] guard known.contains(action) else { throw ValidationError("Unknown action") } if ["start", "switch"].contains(action) { @@ -83,7 +83,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") } } } 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..0f9ef8fb10 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/DesktopAccountCloudTests.swift @@ -0,0 +1,53 @@ +import Foundation +import ProviderCore +import Testing +@testable import darkbloom + +struct DesktopAccountCloudTests { + @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/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/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/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..5712948c89 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,13 @@ 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": + assert self.headers.get("Authorization") in ("Bearer fixture-provider-token", "Bearer fixture-provider-token-2") 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() + body = json.dumps({"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"}]}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.end_headers() @@ -72,6 +73,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 +123,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 +182,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 +204,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 +217,25 @@ 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 + 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 (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"}) From 7f8d7b4070bea14eb3fdfd4236bdcf55406c54c9 Mon Sep 17 00:00:00 2001 From: kydo-researcher Date: Wed, 7 Oct 2026 01:27:37 -0400 Subject: [PATCH 2/2] feat(desktop): make models Autopilot-first and polish account, cooling and notifications --- CHANGELOG.md | 14 +- coordinator/api/account_identity_test.go | 47 ++++ coordinator/api/billing_handlers.go | 8 +- coordinator/api/network_model_earnings.go | 40 ++++ .../api/network_model_earnings_test.go | 69 ++++++ coordinator/api/stats.go | 1 + coordinator/store/network_model_earnings.go | 63 ++++++ .../store/network_model_earnings_test.go | 61 +++++ desktop-app/src/renderer/App.tsx | 24 +- .../renderer/components/AccountControl.tsx | 100 +++++++-- desktop-app/src/renderer/components/UI.tsx | 74 +----- .../account/AccountSignInProgress.tsx | 135 +++++++++++ .../components/account/account.module.css | 134 +++++++++++ .../components/account/useAccountSignIn.ts | 26 +++ .../components/onboarding/ServingSummary.tsx | 2 +- .../components/onboarding/StartServing.tsx | 69 ++++-- .../components/onboarding/startPlan.ts | 14 +- .../components/operations/OperationFeed.tsx | 39 ++++ .../components/operations/OperationToast.tsx | 48 ++++ .../renderer/components/operations/labels.ts | 42 ++++ .../operations/useOperationDismissal.ts | 44 ++++ .../src/renderer/data/pageResources.ts | 2 + desktop-app/src/renderer/features/Cooling.tsx | 7 +- .../src/renderer/features/Earnings.tsx | 2 +- desktop-app/src/renderer/features/Home.tsx | 7 +- .../src/renderer/features/Machines.tsx | 7 +- desktop-app/src/renderer/features/Studio.tsx | 4 +- .../src/renderer/features/cooling/status.ts | 14 ++ .../src/renderer/features/home/FleetMacs.tsx | 3 +- .../renderer/features/home/chip/ChipStage.tsx | 13 +- .../renderer/features/home/chip/FanStatus.tsx | 36 +++ .../features/home/chip/fanStatus.module.css | 23 ++ .../renderer/features/insights/LiveModels.tsx | 16 +- .../renderer/features/insights/useInsights.ts | 2 +- .../features/machines/MachineRail.tsx | 3 +- .../features/machines/overview/FanHealth.tsx | 2 +- .../features/machines/overview/HealthBar.tsx | 6 +- .../machines/overview/LocalOverview.tsx | 2 +- .../machines/overview/RemoteStatus.tsx | 3 +- .../machines/overview/ServingModels.tsx | 8 +- .../machines/overview/TokensChart.tsx | 7 +- .../features/machines/overview/readiness.ts | 212 +++--------------- .../machines/overview/readinessSteps.ts | 197 ++++++++++++++++ .../features/models/AutopilotCard.tsx | 80 ++----- .../features/models/AutopilotModels.tsx | 107 +++++++-- .../features/models/ExpandableModelList.tsx | 33 +++ .../renderer/features/models/ManualModels.tsx | 22 +- .../renderer/features/models/ModelToolbar.tsx | 6 +- .../src/renderer/features/models/PoolRow.tsx | 64 +++++- .../features/models/RecommendedModels.tsx | 120 ++++++++++ .../features/models/RemoveModelDialog.tsx | 2 +- .../features/models/TurnOnAutopilot.tsx | 19 +- .../features/models/autopilot.module.css | 110 ++++----- .../models/expandableModels.module.css | 23 ++ .../src/renderer/features/models/pool.ts | 38 ++-- .../models/recommendations.module.css | 73 ++++++ .../features/models/recommendations.ts | 68 ++++++ .../features/models/useModelActions.ts | 17 ++ .../features/stats/PreviewPerformance.tsx | 11 +- .../stats/activity/RequestActivity.tsx | 7 +- .../features/updates/RuntimeVersion.tsx | 2 +- desktop-app/src/renderer/models/facts.ts | 2 +- desktop-app/src/renderer/models/selection.ts | 9 +- .../src/renderer/presentation/status.ts | 39 ++++ desktop-app/src/renderer/previewResources.ts | 1 + .../src/renderer/styles/components.css | 46 +--- desktop-app/src/renderer/styles/layout.css | 78 +------ .../src/renderer/styles/onboarding.css | 11 - .../src/renderer/styles/responsive.css | 3 +- desktop-app/src/renderer/styles/theme.css | 4 - desktop-app/src/renderer/useBackend.ts | 4 +- desktop-app/src/shared/autopilot.ts | 10 +- desktop-app/src/shared/contracts.ts | 39 +++- .../tests/accountSignInProgress.test.tsx | 161 +++++++++++++ desktop-app/tests/app.test.tsx | 11 +- desktop-app/tests/coolingRefresh.test.tsx | 11 +- desktop-app/tests/fanStatus.test.tsx | 45 ++++ desktop-app/tests/insights.test.tsx | 8 +- desktop-app/tests/machines.test.tsx | 53 ++++- desktop-app/tests/modelsAutopilot.test.tsx | 121 ++++++---- desktop-app/tests/modelsManual.test.tsx | 4 +- desktop-app/tests/modelsPool.test.ts | 6 +- desktop-app/tests/modelsRanking.test.tsx | 4 +- .../tests/modelsRecommendations.test.tsx | 188 ++++++++++++++++ desktop-app/tests/onboarding.test.tsx | 2 +- desktop-app/tests/onboardingAdvanced.test.tsx | 3 +- desktop-app/tests/onboardingStartPlan.test.ts | 1 + .../tests/operationNotifications.test.tsx | 124 ++++++++++ desktop-app/tests/overview.test.tsx | 22 +- desktop-app/tests/productStatus.test.ts | 36 +++ desktop-app/tests/readiness.test.ts | 34 ++- desktop-app/tests/remoteOverview.test.tsx | 6 +- desktop-app/tests/requestActivity.test.tsx | 4 +- docs/architecture/storage.md | 9 +- docs/assets/desktop-autopilot-browse.png | Bin 0 -> 295062 bytes docs/consumer/models.md | 8 +- docs/developer/desktop-app.md | 102 +++++++-- docs/provider/cli-reference.md | 7 +- docs/reference/api-contracts.md | 23 +- docs/reference/desktop-control.md | 70 +++++- .../ProviderCore/Auth/DeviceAuth.swift | 145 +----------- .../ProviderCore/Auth/DeviceCodeLogin.swift | 137 +++++++++++ .../ProviderCore/Auth/DeviceLoginScope.swift | 57 +++++ .../Desktop/DesktopAccountActions.swift | 2 +- .../Desktop/DesktopAccountCommands.swift | 2 +- .../Desktop/DesktopAccountCredential.swift | 15 +- .../Desktop/DesktopAccountEarningsCache.swift | 1 + .../Desktop/DesktopAccountIdentity.swift | 36 +++ .../darkbloom/Desktop/DesktopAutopilot.swift | 98 ++++++++ .../darkbloom/Desktop/DesktopBackend.swift | 36 ++- .../darkbloom/Desktop/DesktopCommand.swift | 6 +- .../darkbloom/Desktop/DesktopCooling.swift | 14 +- .../darkbloom/Desktop/DesktopResources.swift | 1 + .../darkbloom/Desktop/DesktopSnapshot.swift | 22 +- .../darkbloom/Desktop/DesktopTypes.swift | 20 +- .../DesktopAccountCloudTests.swift | 5 + .../DesktopAccountIdentityTests.swift | 39 ++++ .../DesktopActionArgumentsTests.swift | 53 +++++ .../DesktopAutopilotTests.swift | 44 ++++ .../DesktopCoolingCacheTests.swift | 10 + .../Auth/DeviceCodeLoginTests.swift | 88 ++++++++ scripts/test-desktop-api.py | 19 +- 122 files changed, 3588 insertions(+), 1003 deletions(-) create mode 100644 coordinator/api/account_identity_test.go create mode 100644 coordinator/api/network_model_earnings.go create mode 100644 coordinator/api/network_model_earnings_test.go create mode 100644 coordinator/store/network_model_earnings.go create mode 100644 coordinator/store/network_model_earnings_test.go create mode 100644 desktop-app/src/renderer/components/account/AccountSignInProgress.tsx create mode 100644 desktop-app/src/renderer/components/account/account.module.css create mode 100644 desktop-app/src/renderer/components/account/useAccountSignIn.ts create mode 100644 desktop-app/src/renderer/components/operations/OperationFeed.tsx create mode 100644 desktop-app/src/renderer/components/operations/OperationToast.tsx create mode 100644 desktop-app/src/renderer/components/operations/labels.ts create mode 100644 desktop-app/src/renderer/components/operations/useOperationDismissal.ts create mode 100644 desktop-app/src/renderer/features/cooling/status.ts create mode 100644 desktop-app/src/renderer/features/home/chip/FanStatus.tsx create mode 100644 desktop-app/src/renderer/features/home/chip/fanStatus.module.css create mode 100644 desktop-app/src/renderer/features/machines/overview/readinessSteps.ts create mode 100644 desktop-app/src/renderer/features/models/ExpandableModelList.tsx create mode 100644 desktop-app/src/renderer/features/models/RecommendedModels.tsx create mode 100644 desktop-app/src/renderer/features/models/expandableModels.module.css create mode 100644 desktop-app/src/renderer/features/models/recommendations.module.css create mode 100644 desktop-app/src/renderer/features/models/recommendations.ts create mode 100644 desktop-app/src/renderer/presentation/status.ts create mode 100644 desktop-app/tests/accountSignInProgress.test.tsx create mode 100644 desktop-app/tests/fanStatus.test.tsx create mode 100644 desktop-app/tests/modelsRecommendations.test.tsx create mode 100644 desktop-app/tests/operationNotifications.test.tsx create mode 100644 desktop-app/tests/productStatus.test.ts create mode 100644 docs/assets/desktop-autopilot-browse.png create mode 100644 provider-swift/Sources/ProviderCore/Auth/DeviceCodeLogin.swift create mode 100644 provider-swift/Sources/ProviderCore/Auth/DeviceLoginScope.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopAccountIdentity.swift create mode 100644 provider-swift/Sources/darkbloom/Desktop/DesktopAutopilot.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DesktopAccountIdentityTests.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DesktopAutopilotTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Auth/DeviceCodeLoginTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 37008627c9..1d50fe8024 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ ## Unreleased — macOS desktop app +- Use one bottom operation notification across Home, My Macs and its tabs, Leaderboard, Updates and onboarding. Dismiss success after ten seconds without restarting on navigation or state refresh, retain failures until Close, and route immediate action errors through the same popup. Preserve cancellation and expandable diagnostics; keep sign-in in its dedicated dialog. + +- Show the signed-in email and status in the sidebar account control. Reuse the existing account-earnings response for verified identity, retain it across desktop restarts, truncate long addresses visually with their full value accessible, and clear it on sign-out. Add an optional owner email to the coordinator response; older coordinators keep the generic Account label. + +- Replace backend event text with current desktop readiness and a loaded-model count; respect coordinator verification and offline status. Use product labels for operations, Mac/model activity, fan policy, model memory preferences, cached-data notices and connection/version descriptions. Keep diagnostic failure details accessible. +- Replace the sidebar machine-name card with a bottom-left account control. Sign in opens a connection-code modal with Copy code, Open sign-in, Cancel and retry; use a short instruction and a prominent Continue in browser button, then show waiting status after that click. Reopen pending approval across pages without duplicate requests, confirm completion in the dialog, and preserve automatic browser opening for CLI login. +- Replace Home's chip live-status label with a Cooling shortcut: blue while automatic provider cooling is enabled, and increasingly red above 60°C when disabled. Read the helper's enabled state independently of its current SMC mode; unavailable observations stay neutral. +- Fix desktop sign-in with existing coordinators by accepting their standard browser device-code grant into a separate dashboard credential. Prefer scoped account sessions when acknowledged, validate token scope, and preserve provider linkage and serving credentials. +- Show the top three Models rows by default, with a full-width expansion bar for the remaining models. Preserve ranking and reset the compact view when searching or changing filters. +- Fix Browse models crashing on unmeasured memory estimates from the native catalog. Treat null estimates as unknown and preserve the download-size fallback for pin capacity. +- Make Models Autopilot-first for new installations: open Your models by default, separate Browse models, recommend the top three compatible models by seven-day network inference earnings, and let users edit the downloads before starting. Keep personal earnings separate from network rankings. Add directly clickable Keep in memory and Download & keep in memory controls, observed residency, download progress and bounded pin capacity. Collapse descriptions and phase explanations. +- Connect desktop Autopilot enrollment, pinning, pause/resume, disabling and inventory refresh to the existing Swift CLI. Complete selected downloads before one enrollment, preserve startup/endpoint choices during noninteractive refresh, and reject removal of resident or advertised models. Add settled model payout aggregates to existing public stats; unavailable rankings remain unavailable. - Keep Electron on the same `darkbloom` CLI backend. Swift owns coordinator requests, shared resource caches, browser account sign-in and sign-out, and catalog refresh independent of local snapshots. Add a separate read-only dashboard session with bounded expiry; provider credentials and serving stay independent. Reuse existing account/fleet and ledger APIs, including full 7/30-day aggregates through the existing earnings route. Refresh visible pages from the native clock, and use streamed operation progress with a polling fallback. - Reorganize the Home chip panel into a larger diagram and a hardware/memory sidebar, with prominent GPU/CPU measurements and individually labeled model footprints. Move live status to the header and stack sections at narrow widths. Retry only the specific transient fan-ownership firmware restore failure through the verified signed CLI; preserve permanent hardware errors and distinguish canceled authorization. @@ -25,7 +37,7 @@ - Give This Mac's Overview a health bar (readiness with next steps, memory, and a fan that turns with reported RPM), per-Mac earnings and an hourly tokens-shared chart. Add a Stats Activity table of served-request metadata, show Tokens served as stacked input, cached input and output bars, make the view-only Mac page a compact read-only summary, and fit Cooling on one screen. Values the runtime does not report yet show as unavailable. -- Make Models Autopilot-first: downloading builds the pool, pinning keeps a model loaded, and runtimes with Autopilot off or unsupported keep manual selection. Replace the idle-memory select with a Keep models loaded switch and a custom duration, remove the Preload models option without changing its native value, and fix the switch geometry. +- Make Models Autopilot-first: downloading builds the pool, pinning protects a model from unloading during active Autopilot control, and runtimes with Autopilot explicitly off or unsupported keep manual selection. Replace the idle-memory select with a Keep models loaded switch and a custom duration, remove the Preload models option without changing its native value, and fix the switch geometry. - Open onboarding with a paced eligibility scan that advances eligible Macs and explains why others can't serve yet, with an email waitlist. Merge model choice into one Start serving with Autopilot step with Advanced pinning, and fall back to manual selection on runtimes without Autopilot. diff --git a/coordinator/api/account_identity_test.go b/coordinator/api/account_identity_test.go new file mode 100644 index 0000000000..d805cc78ab --- /dev/null +++ b/coordinator/api/account_identity_test.go @@ -0,0 +1,47 @@ +package api + +import ( + "encoding/json" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestAccountEarningsEmailBelongsToAuthenticatedOwner(t *testing.T) { + for _, prefix := range []string{"eigeninference-pt-", desktopAccountTokenPrefix} { + t.Run(prefix, func(t *testing.T) { + srv, st := deviceTestServer() + for i, owner := range []string{"alice", "bob"} { + if err := st.CreateUser(&store.User{AccountID: owner, PrivyUserID: "did:privy:" + owner, Email: owner + "@example.com"}); err != nil { + t.Fatal(err) + } + token := prefix + strings.Repeat(string(rune('a'+i)), 64) + if err := st.CreateProviderToken(&store.ProviderToken{TokenHash: sha256Hash(token), AccountID: owner, Active: true, Label: desktopAccountCodePrefix + "TEST", CreatedAt: time.Now()}); err != nil { + t.Fatal(err) + } + // Query parameters must never select another person's identity, including cached reads. + for range 2 { + req := httptest.NewRequest("GET", "/v1/provider/account-earnings?account_id=someone-else", nil) + req.Header.Set("Authorization", "Bearer "+token) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + var body struct { + Email string `json:"email"` + AccountID string `json:"account_id"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != 200 || body.Email != owner+"@example.com" || body.AccountID != owner { + t.Fatalf("incorrect identity: status=%d body=%s", w.Code, w.Body) + } + } + } + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, httptest.NewRequest("GET", "/v1/provider/account-earnings", nil)) + if w.Code != 401 || strings.Contains(w.Body.String(), "@example.com") { + t.Fatal("unauthenticated email disclosure") + } + }) + } +} diff --git a/coordinator/api/billing_handlers.go b/coordinator/api/billing_handlers.go index f52fe0d294..f356d2b948 100644 --- a/coordinator/api/billing_handlers.go +++ b/coordinator/api/billing_handlers.go @@ -614,7 +614,7 @@ func (s *Server) handleAccountEarnings(w http.ResponseWriter, r *http.Request) { availableBalance, withdrawableBalance := s.store.GetBalanceWithWithdrawable(accountID) - body, err := json.Marshal(map[string]any{ + response := map[string]any{ "account_id": accountID, "earnings": earnings, "total_micro_usd": summary.TotalMicroUSD, @@ -626,7 +626,11 @@ func (s *Server) handleAccountEarnings(w http.ResponseWriter, r *http.Request) { "available_balance_usd": fmt.Sprintf("%.6f", float64(availableBalance)/1_000_000), "withdrawable_balance_micro_usd": withdrawableBalance, "withdrawable_balance_usd": fmt.Sprintf("%.6f", float64(withdrawableBalance)/1_000_000), - }) + } + if user := auth.UserFromContext(r.Context()); user != nil && user.AccountID == accountID && user.Email != "" { + response["email"] = user.Email + } + body, err := json.Marshal(response) if err != nil { writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to marshal earnings")) return diff --git a/coordinator/api/network_model_earnings.go b/coordinator/api/network_model_earnings.go new file mode 100644 index 0000000000..0b172b1462 --- /dev/null +++ b/coordinator/api/network_model_earnings.go @@ -0,0 +1,40 @@ +package api + +import ( + "context" + "github.com/eigeninference/d-inference/coordinator/store" + "sort" + "strconv" + "time" +) + +type networkModelEarning struct { + ID string `json:"id"` + MicroUSD string `json:"earnings_micro_usd"` +} + +func (s *Server) networkModelEarnings(now time.Time) any { + reader, ok := store.As[store.NetworkModelEarningsReader](s.store) + if !ok { + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + since := now.Add(-7 * 24 * time.Hour) + amounts, err := reader.NetworkModelEarnings(ctx, since, now) + if err != nil { + s.logger.Warn("network model earnings unavailable", "error", err) + return nil + } + rows := make([]networkModelEarning, 0, len(amounts)) + for id, amount := range amounts { + rows = append(rows, networkModelEarning{id, strconv.FormatInt(amount, 10)}) + } + sort.Slice(rows, func(i, j int) bool { + if amounts[rows[i].ID] != amounts[rows[j].ID] { + return amounts[rows[i].ID] > amounts[rows[j].ID] + } + return rows[i].ID < rows[j].ID + }) + return map[string]any{"window": "7d", "since": since, "as_of": now, "models": rows} +} diff --git a/coordinator/api/network_model_earnings_test.go b/coordinator/api/network_model_earnings_test.go new file mode 100644 index 0000000000..34e145563d --- /dev/null +++ b/coordinator/api/network_model_earnings_test.go @@ -0,0 +1,69 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestStatsIncludesPublicSevenDayModelEarnings(t *testing.T) { + st := store.NewMemory(store.Config{}) + now := time.Now().UTC() + for i, row := range []store.ProviderEarning{ + {AccountID: "private-account", ProviderID: "private-mac", Model: "large", AmountMicroUSD: 9007199254740993}, + {AccountID: "other-account", Model: "small", AmountMicroUSD: 20}, + {AccountID: "private-account", Model: "base_reward", AmountMicroUSD: 9999999}, + } { + row.CreatedAt = now.Add(-time.Hour) + row.JobID = string(rune('a' + i)) + if err := st.RecordProviderEarning(&row); err != nil { + t.Fatal(err) + } + } + body, capturedAt, _ := readStatsSnapshot(t, newStatsSnapshotServer(st)) + var response struct { + Earnings struct { + Window string `json:"window"` + Since time.Time `json:"since"` + AsOf time.Time `json:"as_of"` + Models []networkModelEarning `json:"models"` + } `json:"model_earnings"` + } + if err := json.Unmarshal(body, &response); err != nil { + t.Fatal(err) + } + e := response.Earnings + if e.Window != "7d" || !e.AsOf.Equal(capturedAt) || e.AsOf.Sub(e.Since) != 7*24*time.Hour { + t.Fatalf("wrong window: %+v", e) + } + if len(e.Models) != 2 || e.Models[0].ID != "large" || e.Models[0].MicroUSD != "9007199254740993" || e.Models[1].ID != "small" { + t.Fatalf("wrong ranking or precision: %+v", e.Models) + } + for _, private := range []string{"private-account", "private-mac", "other-account"} { + if strings.Contains(string(body), private) { + t.Fatal("public aggregate exposed identity") + } + } +} + +type unavailableModelEarningsStore struct{ store.Store } + +func (unavailableModelEarningsStore) NetworkModelEarnings(context.Context, time.Time, time.Time) (map[string]int64, error) { + return nil, errors.New("database unavailable") +} + +func TestStatsModelEarningsFailurePreservesOtherStats(t *testing.T) { + body, _, _ := readStatsSnapshot(t, newStatsSnapshotServer(unavailableModelEarningsStore{store.NewMemory(store.Config{})})) + var response map[string]json.RawMessage + if err := json.Unmarshal(body, &response); err != nil { + t.Fatal(err) + } + if string(response["model_earnings"]) != "null" || response["total_tokens"] == nil { + t.Fatalf("failed aggregate changed stats: %s", body) + } +} diff --git a/coordinator/api/stats.go b/coordinator/api/stats.go index 8549e6bbe6..be933e51e5 100644 --- a/coordinator/api/stats.go +++ b/coordinator/api/stats.go @@ -341,6 +341,7 @@ func (s *Server) computeStats() ([]byte, error) { "location_privacy_min_providers": minProvidersPerCityBucket, } geography.addTo(resp) + resp["model_earnings"] = s.networkModelEarnings(snapshotAt) return json.Marshal(resp) } diff --git a/coordinator/store/network_model_earnings.go b/coordinator/store/network_model_earnings.go new file mode 100644 index 0000000000..53ae02065d --- /dev/null +++ b/coordinator/store/network_model_earnings.go @@ -0,0 +1,63 @@ +package store + +import ( + "context" + "fmt" + "math" + "time" +) + +// NetworkModelEarningsReader exposes only aggregate settled inference payouts. +// Account identities and base rewards never enter this public projection. +type NetworkModelEarningsReader interface { + NetworkModelEarnings(context.Context, time.Time, time.Time) (map[string]int64, error) +} + +func (s *MemoryStore) NetworkModelEarnings(ctx context.Context, since, until time.Time) (map[string]int64, error) { + if err := validateInsightWindow(since, until); err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + s.mu.RLock() + defer s.mu.RUnlock() + out := map[string]int64{} + for _, e := range s.providerEarnings { + if err := ctx.Err(); err != nil { + return nil, err + } + if e.Model != "" && e.Model != "base_reward" && e.AmountMicroUSD > 0 && !e.CreatedAt.Before(since) && e.CreatedAt.Before(until) { + if out[e.Model] > math.MaxInt64-e.AmountMicroUSD { + return nil, fmt.Errorf("network model earnings overflow for %s", e.Model) + } + out[e.Model] += e.AmountMicroUSD + } + } + return out, nil +} + +func (s *PostgresStore) NetworkModelEarnings(ctx context.Context, since, until time.Time) (map[string]int64, error) { + if err := validateInsightWindow(since, until); err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + rows, err := s.pool.Query(ctx, `SELECT model, SUM(amount_micro_usd) + FROM provider_earnings WHERE created_at >= $1 AND created_at < $2 + AND model <> '' AND model <> 'base_reward' AND amount_micro_usd > 0 GROUP BY model`, since, until) + if err != nil { + return nil, fmt.Errorf("network model earnings: %w", err) + } + defer rows.Close() + out := map[string]int64{} + for rows.Next() { + var id string + var amount int64 + if err := rows.Scan(&id, &amount); err != nil { + return nil, err + } + out[id] = amount + } + return out, rows.Err() +} diff --git a/coordinator/store/network_model_earnings_test.go b/coordinator/store/network_model_earnings_test.go new file mode 100644 index 0000000000..1d3c1c6f55 --- /dev/null +++ b/coordinator/store/network_model_earnings_test.go @@ -0,0 +1,61 @@ +package store + +import ( + "context" + "reflect" + "testing" + "time" +) + +func TestNetworkModelEarningsSettledWindowAcrossAccounts(t *testing.T) { + start := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC) + end := start.Add(7 * 24 * time.Hour) + for name, st := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + rows := []ProviderEarning{ + {AccountID: "one", Model: "a", JobID: "one", AmountMicroUSD: 10, CreatedAt: start}, + {AccountID: "two", Model: "a", JobID: "two", AmountMicroUSD: 20, CreatedAt: start.Add(time.Hour)}, + {AccountID: "two", Model: "b", JobID: "three", AmountMicroUSD: 50, CreatedAt: end.Add(-time.Second)}, + {Model: "a", JobID: "old", AmountMicroUSD: 900, CreatedAt: start.Add(-time.Nanosecond)}, + {Model: "a", JobID: "future", AmountMicroUSD: 900, CreatedAt: end}, + {Model: "base_reward", JobID: "reward", AmountMicroUSD: 900, CreatedAt: start}, + {Model: "", JobID: "unknown", AmountMicroUSD: 900, CreatedAt: start}, + {Model: "a", JobID: "zero", AmountMicroUSD: 0, CreatedAt: start}, + {Model: "a", JobID: "negative", AmountMicroUSD: -5, CreatedAt: start}, + } + for i := range rows { + if err := st.RecordProviderEarning(&rows[i]); err != nil { + t.Fatal(err) + } + } + reader, ok := As[NetworkModelEarningsReader](NewCached(st, CacheConfig{})) + if !ok { + t.Fatal("cache decorator hid aggregate capability") + } + got, err := reader.NetworkModelEarnings(context.Background(), start, end) + if err != nil { + t.Fatal(err) + } + if want := map[string]int64{"a": 30, "b": 50}; !reflect.DeepEqual(got, want) { + t.Fatalf("got %v, want %v", got, want) + } + if _, err := reader.NetworkModelEarnings(context.Background(), start, start); err == nil { + t.Fatal("invalid window accepted") + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := reader.NetworkModelEarnings(ctx, start, end); err == nil { + t.Fatal("cancelled query returned earnings") + } + }) + } +} + +func TestNetworkModelEarningsDatabaseFailureIsUnavailable(t *testing.T) { + st := testPostgresStore(t) + st.Close() + now := time.Now() + if _, err := st.NetworkModelEarnings(context.Background(), now.Add(-7*24*time.Hour), now); err == nil { + t.Fatal("failed query returned successful zero totals") + } +} diff --git a/desktop-app/src/renderer/App.tsx b/desktop-app/src/renderer/App.tsx index 8ced99b66a..64751a992b 100644 --- a/desktop-app/src/renderer/App.tsx +++ b/desktop-app/src/renderer/App.tsx @@ -46,11 +46,6 @@ export default function App() { <>
- {backend.error && ( -
- backend.setError('')}>{backend.error} -
- )} ); @@ -78,18 +73,6 @@ export default function App() {
-
@@ -98,16 +81,15 @@ export default function App() { {isPreview && Development preview} - {backend.status.state === 'ready' ? 'Runtime connected' : 'Reconnecting'} + {backend.status.state === 'ready' ? 'Connected to this Mac' : 'Reconnecting'}
- {backend.error && backend.setError('')}>{backend.error}} {backend.status.state !== 'ready' && ( - {backend.status.message || 'Connecting to the native runtime…'} + {backend.status.message || 'Connecting to this Mac…'} )} {route === 'home' && ( @@ -131,7 +113,7 @@ export default function App() { Compute, powered by people.
- {!machineRoute && } +
); diff --git a/desktop-app/src/renderer/components/AccountControl.tsx b/desktop-app/src/renderer/components/AccountControl.tsx index cbdd140441..f4f4587d46 100644 --- a/desktop-app/src/renderer/components/AccountControl.tsx +++ b/desktop-app/src/renderer/components/AccountControl.tsx @@ -1,32 +1,92 @@ +import { ChevronRight, UserRound } from 'lucide-react'; +import { useCallback, useState } from 'react'; +import { createPortal } from 'react-dom'; import type { BackendState } from '../useBackend'; -import { api } from '../useBackend'; +import { Modal } from './UI'; +import { AccountSignInProgress } from './account/AccountSignInProgress'; +import { useAccountSignIn } from './account/useAccountSignIn'; +import styles from './account/account.module.css'; export function AccountControl({ backend }: { backend: BackendState }) { + const [dialog, setDialog] = useState<'account' | 'signin' | null>(null); + const close = useCallback(() => setDialog(null), []); + const login = useAccountSignIn(backend); const state = backend.state; if (!state?.capabilities?.includes('account-signin')) return null; const signedIn = state.account?.signed_in; - const pending = state.operations.find( - (operation) => operation.action === 'account-signin' && operation.state === 'running', - ); + const email = signedIn ? state.account?.email?.trim() : undefined; + const label = signedIn ? 'Account' : login.pending ? 'Continue sign-in' : 'Sign in'; + + function open() { + setDialog(signedIn ? 'account' : 'signin'); + if (!signedIn) void login.begin(); + } + return ( -
+ <> - {pending && state.link && ( -
- {state.link.code} - - -
- )} -
+ {dialog && + createPortal( + + {dialog === 'account' ? ( + <> +

+ {email ? ( + <> + {email}Signed in + + ) : ( + 'You’re signed in to Darkbloom.' + )} +

+
+ + +
+ + ) : ( + void login.begin()} + onClose={close} + /> + )} +
, + document.body, + )} + ); } diff --git a/desktop-app/src/renderer/components/UI.tsx b/desktop-app/src/renderer/components/UI.tsx index f361e6d5c5..f80853a6b5 100644 --- a/desktop-app/src/renderer/components/UI.tsx +++ b/desktop-app/src/renderer/components/UI.tsx @@ -1,7 +1,7 @@ -import { ArrowUpRight, Check, LoaderCircle, Monitor, X } from 'lucide-react'; -import { useEffect, useRef, useState, type ButtonHTMLAttributes, type ReactNode } from 'react'; +import { ArrowUpRight, Monitor, X } from 'lucide-react'; +import { useEffect, useRef, type ButtonHTMLAttributes, type ReactNode } from 'react'; import { api } from '../useBackend'; -import type { BackendState } from '../useBackend'; +export { OperationFeed } from './operations/OperationFeed'; export function Button({ children, variant = 'secondary', @@ -89,74 +89,6 @@ export function Notice({ children, onClose }: { children: ReactNode; onClose?: ( ); } -export function OperationFeed({ - backend, - inline = false, -}: { - backend: BackendState; - inline?: boolean; -}) { - const [dismissed, setDismissed] = useState(() => { - try { - return localStorage.getItem('darkbloom.dismissed-operation') ?? ''; - } catch { - return ''; - } - }); - const operation = backend.state?.operations[0]; - if (!operation || operation.id === dismissed) return null; - return ( - - ); -} export function Modal({ title, children, diff --git a/desktop-app/src/renderer/components/account/AccountSignInProgress.tsx b/desktop-app/src/renderer/components/account/AccountSignInProgress.tsx new file mode 100644 index 0000000000..741306f8a4 --- /dev/null +++ b/desktop-app/src/renderer/components/account/AccountSignInProgress.tsx @@ -0,0 +1,135 @@ +import { ArrowUpRight, Check, Copy, LoaderCircle } from 'lucide-react'; +import { useState } from 'react'; +import type { Operation } from '../../../shared/contracts'; +import { api, type BackendState } from '../../useBackend'; +import styles from './account.module.css'; + +export function AccountSignInProgress({ + backend, + operation, + requestFailed, + submitting, + onRetry, + onClose, +}: { + backend: BackendState; + operation?: Operation; + requestFailed: boolean; + submitting: boolean; + onRetry: () => void; + onClose: () => void; +}) { + const complete = operation?.state === 'succeeded' || backend.state?.account?.signed_in; + const failed = requestFailed || operation?.state === 'failed' || operation?.state === 'cancelled'; + const code = operation?.state === 'running' ? backend.state?.link?.code : undefined; + const [copied, setCopied] = useState(''); + const [error, setError] = useState(''); + const [openedOperation, setOpenedOperation] = useState(''); + const browserOpened = !!operation && openedOperation === operation.id; + async function copyCode() { + if (!code || !api) return; + try { + await api.copy(code); + setCopied(code); + setError(''); + } catch { + setError('Could not copy the connection code.'); + } + } + async function openSignIn() { + try { + await api?.openExternal('link'); + setOpenedOperation(operation?.id ?? ''); + setError(''); + } catch { + setError('Could not open sign-in. Try again.'); + } + } + + if (complete) + return ( +
+

+ You’re signed in. +

+ +
+ ); + if (failed) + return ( +
+

+ {operation?.state === 'cancelled' ? 'Sign-in cancelled.' : 'Could not complete sign-in.'} +

+ {operation?.state === 'failed' && ( +
+ Details +
{operation.message}
+
+ )} + {requestFailed && backend.error && ( +

+ {backend.error} +

+ )} + +
+ ); + return ( +
+ {!code && ( +

+ Getting a connection code… +

+ )} + {code && ( + <> +

+ {browserOpened + ? 'Approve the connection in your browser.' + : 'Enter this code in your browser.'} +

+
+
+ Sign-in code + + {code} + +
+ +
+ {browserOpened && ( +

+ Waiting for approval +

+ )} + + )} + {error && ( +

+ {error} +

+ )} +
+ + {operation?.cancellable && ( + + )} +
+
+ ); +} diff --git a/desktop-app/src/renderer/components/account/account.module.css b/desktop-app/src/renderer/components/account/account.module.css new file mode 100644 index 0000000000..5d3a5c6a72 --- /dev/null +++ b/desktop-app/src/renderer/components/account/account.module.css @@ -0,0 +1,134 @@ +.control { + border-top: 1px solid var(--line); + display: flex; + align-items: center; + gap: 10px; + width: 100%; + margin-top: 12px; + padding: 18px 6px 6px; + text-align: left; + -webkit-app-region: no-drag; +} +.control:disabled { + opacity: 0.5; +} +.icon { + display: grid; + place-items: center; + height: 32px; + width: 32px; + flex-shrink: 0; + border-radius: 6px; + background: rgba(var(--contrast-rgb), 0.031); +} +.control:hover .icon { + background: rgba(var(--contrast-rgb), 0.07); +} +.identity { + flex: 1; + min-width: 0; +} +.identity strong { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + display: block; + font-size: 12px; + font-weight: 500; +} +.identity small { + display: block; + margin-top: 5px; + color: var(--muted); + font-size: 10px; +} +.chevron { + margin-left: auto; + color: var(--muted); +} +.state, +.codeRow, +.actions { + display: flex; + align-items: center; + gap: 10px; +} +.state { + margin: 20px 0; + color: var(--text-secondary); + font-size: 13px; +} +.codeRow { + justify-content: space-between; + flex-wrap: wrap; + padding: 16px; + border: 1px solid color-mix(in srgb, var(--blue) 30%, transparent); + border-radius: 8px; + background: color-mix(in srgb, var(--blue) 6%, transparent); +} +.label { + display: block; + margin-bottom: 6px; + color: var(--muted); + font-size: 11px; +} +.code { + display: block; + font-family: monospace; + font-size: 25px; + font-weight: 500; + letter-spacing: 0.12em; + user-select: text; + white-space: nowrap; +} +.hint { + margin: 16px 0 22px; + font-size: 13px; + line-height: 1.6; + color: var(--muted); +} +.actions { + justify-content: space-between; +} +.details { + margin-bottom: 20px; + font-size: 12px; +} +.details pre { + white-space: pre-wrap; + overflow-wrap: anywhere; +} +@media (max-width: 760px) { + .control { + justify-content: center; + padding: 12px 0 0; + } + .identity, + .chevron { + display: none; + } +} + +.instruction { + margin: 0 0 16px; + text-wrap: balance; +} +.signInActions { + display: grid; + gap: 8px; + margin-top: 20px; +} +.signInActions > :global(.primary) { + width: 100%; + justify-content: center; +} +.signInActions > :global(.quiet) { + justify-self: center; +} + +.accountEmail { + display: block; + color: var(--text-primary); + font-weight: 500; + overflow-wrap: anywhere; +} diff --git a/desktop-app/src/renderer/components/account/useAccountSignIn.ts b/desktop-app/src/renderer/components/account/useAccountSignIn.ts new file mode 100644 index 0000000000..05d4a1e352 --- /dev/null +++ b/desktop-app/src/renderer/components/account/useAccountSignIn.ts @@ -0,0 +1,26 @@ +import { useState } from 'react'; +import type { BackendState } from '../../useBackend'; + +// Only show results from this attempt, never a previous code or failed login. +export function useAccountSignIn(backend: BackendState) { + const operations = backend.state?.operations ?? []; + const pending = operations.find((op) => op.action === 'account-signin' && op.state === 'running'); + const [ignored, setIgnored] = useState>(new Set()); + const [requestFailed, setRequestFailed] = useState(false); + const [submitting, setSubmitting] = useState(false); + const operation = operations.find((op) => op.action === 'account-signin' && !ignored.has(op.id)); + + async function begin() { + setRequestFailed(false); + setIgnored(new Set(operations.filter((op) => op.id !== pending?.id).map((op) => op.id))); + if (pending) return; + setSubmitting(true); + try { + setRequestFailed(!(await backend.act({ action: 'account-signin' }))); + } finally { + setSubmitting(false); + } + } + + return { pending, operation, requestFailed, submitting, begin }; +} diff --git a/desktop-app/src/renderer/components/onboarding/ServingSummary.tsx b/desktop-app/src/renderer/components/onboarding/ServingSummary.tsx index a508bc73b0..69386a4450 100644 --- a/desktop-app/src/renderer/components/onboarding/ServingSummary.tsx +++ b/desktop-app/src/renderer/components/onboarding/ServingSummary.tsx @@ -59,7 +59,7 @@ export function ServingSummary({ { icon: , text: snapshot.settings.auto_update - ? 'Updates on · managed by the native runtime.' + ? 'Automatic updates on.' : 'Updates off · turn them on any time in Updates.', }, { icon: , text: 'Stop any time from the app or the menu bar.' }, diff --git a/desktop-app/src/renderer/components/onboarding/StartServing.tsx b/desktop-app/src/renderer/components/onboarding/StartServing.tsx index a029606723..d353bfa25a 100644 --- a/desktop-app/src/renderer/components/onboarding/StartServing.tsx +++ b/desktop-app/src/renderer/components/onboarding/StartServing.tsx @@ -11,6 +11,8 @@ import { pinnedMemory, startingModel } from '../../models/selection'; import { methodFor, startAction, startModels, type StartMethod } from './startPlan'; import { useStartServing } from './useStartServing'; import styles from './startServing.module.css'; +import { networkEarnings, recommendedModels } from '../../features/models/recommendations'; +import { RecommendedModels } from '../../features/models/RecommendedModels'; const copy: Record = { autopilot: { @@ -60,14 +62,22 @@ export function StartServing({ const manualOnly = !!snapshot.capabilities && !snapshot.capabilities.includes('autopilot'); const method = methodFor(mode, serving.rejected || manualOnly); const text = copy[method]; + const network = networkEarnings(backend.network); + const recommended = + method === 'autopilot' && !pinned.length ? recommendedModels(snapshot.models, network) : []; + const showRecommendations = recommended.length > 0; const empty = !startModels(snapshot, method, pinned).length; const tooLarge = pinnedMemory(snapshot, pinned).exceeds; const running = snapshot.operations.find((operation) => operation.state === 'running'); return ( <>

Ready to serve.

-

{text.lead}

- + {!showRecommendations && ( + <> +

{text.lead}

+ + + )} {serving.rejected && method === 'manual' && (
Autopilot isn’t available in this version of Darkbloom. @@ -84,27 +94,40 @@ export function StartServing({ ) : ( <> - + {showRecommendations ? ( + + void serving.serve({ ...action, endpoint: true }, !snapshot.linked) + } + /> + ) : ( + + )}
{serving.phase === 'starting' && running?.message ? running.message diff --git a/desktop-app/src/renderer/components/onboarding/startPlan.ts b/desktop-app/src/renderer/components/onboarding/startPlan.ts index dbb50c353b..c1f29838a2 100644 --- a/desktop-app/src/renderer/components/onboarding/startPlan.ts +++ b/desktop-app/src/renderer/components/onboarding/startPlan.ts @@ -19,7 +19,17 @@ export function startModels(snapshot: Snapshot, method: StartMethod, pinned: str export function startAction(snapshot: Snapshot, method: StartMethod, pinned: string[]): Action { const models = startModels(snapshot, method, pinned); - if (method === 'autopilot') - return { action: 'autopilot', models, pinned: [...pinned].sort(), endpoint: true }; + if (method === 'autopilot') { + const downloads = snapshot.models + .filter((model) => models.includes(model.id) && !model.downloaded) + .map((model) => model.id); + return { + action: 'autopilot', + models, + pinned: [...pinned].sort(), + ...(downloads.length ? { downloads } : {}), + endpoint: true, + }; + } return { action: 'start', models, local: method === 'local', endpoint: true }; } diff --git a/desktop-app/src/renderer/components/operations/OperationFeed.tsx b/desktop-app/src/renderer/components/operations/OperationFeed.tsx new file mode 100644 index 0000000000..647e82750e --- /dev/null +++ b/desktop-app/src/renderer/components/operations/OperationFeed.tsx @@ -0,0 +1,39 @@ +import type { BackendState } from '../../useBackend'; +import { operationLabel } from './labels'; +import { OperationToast } from './OperationToast'; +import { useOperationDismissal } from './useOperationDismissal'; + +// Mounted by App outside route content so location and timers survive navigation. +export function OperationFeed({ backend }: { backend: BackendState }) { + const operation = backend.state?.operations.find((item) => item.action !== 'account-signin'); + const { hidden, dismiss } = useOperationDismissal(operation); + const error = backend.error; + if (error) { + const matchingFailure = operation?.state === 'failed' && operation.message === error; + return ( + { + backend.setError(''); + if (matchingFailure) dismiss(operation.id); + }} + /> + ); + } + if (!operation || hidden) return null; + return ( + void backend.act({ action: 'cancel', operation: operation.id }) + : undefined + } + onClose={operation.state !== 'running' ? () => dismiss(operation.id) : undefined} + /> + ); +} diff --git a/desktop-app/src/renderer/components/operations/OperationToast.tsx b/desktop-app/src/renderer/components/operations/OperationToast.tsx new file mode 100644 index 0000000000..3ec97558b2 --- /dev/null +++ b/desktop-app/src/renderer/components/operations/OperationToast.tsx @@ -0,0 +1,48 @@ +import { Check, LoaderCircle, X } from 'lucide-react'; +import { createPortal } from 'react-dom'; +import type { Operation } from '../../../shared/contracts'; + +export function OperationToast({ + state, + title, + message, + onCancel, + onClose, +}: { + state: Operation['state']; + title: string; + message: string; + onCancel?: () => void; + onClose?: () => void; +}) { + return createPortal( + , + document.body, + ); +} diff --git a/desktop-app/src/renderer/components/operations/labels.ts b/desktop-app/src/renderer/components/operations/labels.ts new file mode 100644 index 0000000000..9664b67ef0 --- /dev/null +++ b/desktop-app/src/renderer/components/operations/labels.ts @@ -0,0 +1,42 @@ +import type { Action, Operation } from '../../../shared/contracts'; + +const actions: Record = { + start: { name: 'Provider start', running: 'Starting provider' }, + stop: { name: 'Provider stop', running: 'Stopping provider' }, + restart: { name: 'Provider restart', running: 'Restarting provider' }, + switch: { name: 'Model selection', running: 'Changing models' }, + update: { name: 'Darkbloom update', running: 'Updating Darkbloom' }, + diagnose: { name: 'Health check', running: 'Checking this Mac' }, + link: { name: 'Mac linking', running: 'Linking this Mac' }, + unlink: { name: 'Mac unlinking', running: 'Unlinking this Mac' }, + 'account-signin': { name: 'Sign-in', running: 'Signing in' }, + 'account-signout': { name: 'Sign-out', running: 'Signing out' }, + download: { name: 'Model download', running: 'Downloading model' }, + remove: { name: 'Model removal', running: 'Removing model' }, + cancel: { name: 'Cancellation', running: 'Cancelling' }, + settings: { name: 'Settings', running: 'Saving settings' }, + cooling: { name: 'Fan settings', running: 'Updating fan settings' }, + waitlist: { name: 'Waitlist signup', running: 'Joining the waitlist' }, + autopilot: { name: 'Autopilot setup', running: 'Setting up Autopilot' }, + autopilot_pin: { name: 'Keep in memory', running: 'Keeping models in memory' }, + autopilot_unpin: { name: 'Memory preference', running: 'Updating memory preference' }, + autopilot_pause: { name: 'Autopilot pause', running: 'Pausing Autopilot' }, + autopilot_resume: { name: 'Autopilot resume', running: 'Resuming Autopilot' }, + autopilot_disable: { name: 'Manual mode', running: 'Switching to manual' }, + autopilot_models: { name: 'Model refresh', running: 'Refreshing available models' }, +}; +const states: Record, string> = { + succeeded: 'Complete', + failed: 'Failed', + cancelled: 'Cancelled', + interrupted: 'Interrupted', +}; +export function operationLabel(operation: Pick): string { + const action = actions[operation.action]; + // A newer runtime may add an operation before this app updates. + if (!action) + return operation.state === 'running' ? 'Working…' : `Action · ${states[operation.state]}`; + return operation.state === 'running' + ? action.running + : `${action.name} · ${states[operation.state]}`; +} diff --git a/desktop-app/src/renderer/components/operations/useOperationDismissal.ts b/desktop-app/src/renderer/components/operations/useOperationDismissal.ts new file mode 100644 index 0000000000..8e4808309a --- /dev/null +++ b/desktop-app/src/renderer/components/operations/useOperationDismissal.ts @@ -0,0 +1,44 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import type { Operation } from '../../../shared/contracts'; + +const storageKey = 'darkbloom.dismissed-operation'; +const successLifetime = 10_000; + +export function useOperationDismissal(operation?: Operation) { + const [dismissed, setDismissed] = useState(() => { + try { + return localStorage.getItem(storageKey) ?? ''; + } catch { + return ''; + } + }); + const deadline = useRef<{ id: string; at: number } | undefined>(undefined); + const dismiss = useCallback((id: string) => { + try { + localStorage.setItem(storageKey, id); + } catch { + // The current window still remembers dismissal when storage is disabled. + } + setDismissed(id); + }, []); + + useEffect(() => { + if (!operation || operation.state !== 'succeeded' || operation.id === dismissed) return; + if (deadline.current?.id !== operation.id) { + const completedAt = operation.finished_at ? operation.finished_at * 1000 : Date.now(); + deadline.current = { + id: operation.id, + at: Math.min(completedAt, Date.now()) + successLifetime, + }; + } + const remaining = deadline.current.at - Date.now(); + if (remaining <= 0) { + dismiss(operation.id); + return; + } + const timer = setTimeout(() => dismiss(operation.id), remaining); + return () => clearTimeout(timer); + }, [operation?.id, operation?.state, operation?.finished_at, dismissed, dismiss]); + + return { hidden: operation?.id === dismissed, dismiss }; +} diff --git a/desktop-app/src/renderer/data/pageResources.ts b/desktop-app/src/renderer/data/pageResources.ts index b2acaf007e..05a6f723b8 100644 --- a/desktop-app/src/renderer/data/pageResources.ts +++ b/desktop-app/src/renderer/data/pageResources.ts @@ -5,6 +5,8 @@ export function pageResources(route: Route): Resource[] { switch (route) { case 'home': return ['cloud', 'network']; + case 'models': + return ['network']; case 'machines': case 'earnings': return ['cloud']; diff --git a/desktop-app/src/renderer/features/Cooling.tsx b/desktop-app/src/renderer/features/Cooling.tsx index 1bace6af79..d88c074a57 100644 --- a/desktop-app/src/renderer/features/Cooling.tsx +++ b/desktop-app/src/renderer/features/Cooling.tsx @@ -1,5 +1,6 @@ import type { BackendState } from '../useBackend'; import { Empty, Header, Notice, Status } from '../components/UI'; +import { coolingStatus } from './cooling/status'; import { CoolingControls } from './cooling/CoolingControls'; import { FanCards } from './cooling/FanCards'; import styles from './cooling/cooling.module.css'; @@ -19,11 +20,7 @@ export function Cooling({ level={embedded ? 2 : 1} title="Cooling" description="Keep sustained workloads comfortable." - action={ - - {cooling?.mode || 'Checking'} - - } + action={{coolingStatus(cooling)}} /> {cooling?.error && {cooling.error}}
diff --git a/desktop-app/src/renderer/features/Earnings.tsx b/desktop-app/src/renderer/features/Earnings.tsx index 60810ffa56..6172ee5ec5 100644 --- a/desktop-app/src/renderer/features/Earnings.tsx +++ b/desktop-app/src/renderer/features/Earnings.tsx @@ -76,7 +76,7 @@ export function Earnings({ backend }: { backend: BackendState }) {
{error && (

- {error} Showing the last observation. + {error} Showing previously loaded earnings.

)}
diff --git a/desktop-app/src/renderer/features/Home.tsx b/desktop-app/src/renderer/features/Home.tsx index 628cb94b5f..c6bd13e793 100644 --- a/desktop-app/src/renderer/features/Home.tsx +++ b/desktop-app/src/renderer/features/Home.tsx @@ -37,7 +37,12 @@ export function Home({ navigate('analysis')} />
- + navigate('cooling')} + />
- {local && } - {backend.cloud?.error && route === 'machines' && {backend.cloud.error}} + {backend.cloud?.error && route === 'machines' && ( + Couldn’t refresh account data. + )}
My Macs / diff --git a/desktop-app/src/renderer/features/Studio.tsx b/desktop-app/src/renderer/features/Studio.tsx index 4981af9f05..51dda3cd80 100644 --- a/desktop-app/src/renderer/features/Studio.tsx +++ b/desktop-app/src/renderer/features/Studio.tsx @@ -37,7 +37,7 @@ export function Studio({

Your Mac. Your endpoint.

-

OpenAI-compatible inference, backed by the same Swift runtime.

+

Run models through an OpenAI-compatible API.

{endpoint && Listening}
@@ -124,7 +124,7 @@ export function Studio({ {key ? 'Hide' : 'Reveal'}
- Authenticated and bound to this Mac’s loopback interface. + Requires an API key. Accessible only on this Mac.
diff --git a/desktop-app/src/renderer/features/cooling/status.ts b/desktop-app/src/renderer/features/cooling/status.ts new file mode 100644 index 0000000000..0d7a8d081c --- /dev/null +++ b/desktop-app/src/renderer/features/cooling/status.ts @@ -0,0 +1,14 @@ +import type { CoolingData } from '../../../shared/contracts'; + +export function coolingStatus(cooling?: CoolingData): string { + if (!cooling) return 'Checking fans'; + if ( + cooling.error || + cooling.mode === 'unavailable' || + (cooling.observed_at != null && Date.now() / 1000 - cooling.observed_at > 60) + ) + return 'Fan status unavailable'; + // The policy can be enabled while macOS controls the fans below its threshold. + if (cooling.enabled != null) return cooling.enabled ? 'Auto fan on' : 'Auto fan off'; + return cooling.mode === 'manual' ? 'Darkbloom control' : 'macOS control'; +} diff --git a/desktop-app/src/renderer/features/home/FleetMacs.tsx b/desktop-app/src/renderer/features/home/FleetMacs.tsx index b4e75e4331..fa7e6eb521 100644 --- a/desktop-app/src/renderer/features/home/FleetMacs.tsx +++ b/desktop-app/src/renderer/features/home/FleetMacs.tsx @@ -1,3 +1,4 @@ +import { machineStatus } from '../../presentation/status'; import { useState } from 'react'; import { Search } from 'lucide-react'; import type { Machine } from '../../../shared/contracts'; @@ -76,7 +77,7 @@ export function FleetMacs({ - {machine.status} + {machineStatus(machine.status)} {machine.models.length} {money(machine.earnings_micro_usd)} diff --git a/desktop-app/src/renderer/features/home/chip/ChipStage.tsx b/desktop-app/src/renderer/features/home/chip/ChipStage.tsx index 41ab18e407..5e2235c449 100644 --- a/desktop-app/src/renderer/features/home/chip/ChipStage.tsx +++ b/desktop-app/src/renderer/features/home/chip/ChipStage.tsx @@ -1,10 +1,11 @@ import { useMemo, useState, type CSSProperties } from 'react'; import { Pause, Play } from 'lucide-react'; -import type { DesktopAPI, Snapshot } from '../../../../shared/contracts'; +import type { CoolingData, DesktopAPI, Snapshot } from '../../../../shared/contracts'; import { useHardwareLoad } from '../../../hardware/useHardwareLoad'; import { useReducedMotion } from '../../../useReducedMotion'; import { ChipCanvas } from './ChipCanvas'; import { ChipStatus } from './ChipStatus'; +import { FanStatus } from './FanStatus'; import { ChipReadouts } from './ChipReadouts'; import { hardwareReadout } from './hardware/readouts'; import { useChipPalette } from './hooks/useChipPalette'; @@ -40,10 +41,14 @@ export function ChipStage({ state, preview, source, + cooling, + onCooling, }: { state: Snapshot; preview: boolean; source?: DesktopAPI; + cooling?: CoolingData; + onCooling?: () => void; }) { const load = useHardwareLoad(source); const override = useMemo(() => (preview ? previewChip() : null), [preview]); @@ -118,7 +123,11 @@ export function ChipStage({

- + {onCooling ? ( + + ) : ( + + )} {preview && } + ); +} diff --git a/desktop-app/src/renderer/features/home/chip/fanStatus.module.css b/desktop-app/src/renderer/features/home/chip/fanStatus.module.css new file mode 100644 index 0000000000..5e9f7a9e45 --- /dev/null +++ b/desktop-app/src/renderer/features/home/chip/fanStatus.module.css @@ -0,0 +1,23 @@ +.status { + display: inline-flex; + align-items: center; + gap: 7px; + min-height: 30px; + padding: 5px 9px; + border-radius: 6px; + font-size: 11px; + white-space: nowrap; + color: var(--muted); + transition: + color 0.4s ease, + background var(--hover-duration); +} +.status[data-enabled='true'] { + color: var(--blue); +} +.status:hover { + background: var(--raised-bg); +} +.status span { + font-variant-numeric: tabular-nums; +} diff --git a/desktop-app/src/renderer/features/insights/LiveModels.tsx b/desktop-app/src/renderer/features/insights/LiveModels.tsx index 94e98fe1b0..52f186e533 100644 --- a/desktop-app/src/renderer/features/insights/LiveModels.tsx +++ b/desktop-app/src/renderer/features/insights/LiveModels.tsx @@ -1,3 +1,4 @@ +import { modelActivity } from '../../presentation/status'; import { useEffect, useState } from 'react'; import { Activity, Pause, Play } from 'lucide-react'; import type { Snapshot } from '../../../shared/contracts'; @@ -51,9 +52,9 @@ export function LiveModels({ state }: { state: Snapshot }) {
{stale ? '—' : running} - requests running + requests processing
- Native activity · refreshes every 2 seconds + Live activity
@@ -67,7 +68,8 @@ export function LiveModels({ state }: { state: Snapshot }) { {modelName(state.models, model.model)} - {model.state} · {stale ? '—' : model.waiting} waiting + {stale ? 'Status unavailable' : modelActivity(model.state, model.running)} ·{' '} + {stale ? '—' : model.waiting} waiting @@ -81,11 +83,7 @@ export function LiveModels({ state }: { state: Snapshot }) { ))} - {stale - ? 'Not current' - : serving(model.state) - ? `${model.running} running` - : model.state} + {stale ? 'Not current' : modelActivity(model.state, model.running)}
@@ -96,7 +94,7 @@ export function LiveModels({ state }: { state: Snapshot }) { {state.state === 'stopped' ? 'Start providing to see your models working.' : stale - ? 'Waiting for the runtime to report model activity.' + ? 'Waiting for model activity.' : 'No models are currently loaded.'}

)} diff --git a/desktop-app/src/renderer/features/insights/useInsights.ts b/desktop-app/src/renderer/features/insights/useInsights.ts index 29041bf4cf..dbcdf52323 100644 --- a/desktop-app/src/renderer/features/insights/useInsights.ts +++ b/desktop-app/src/renderer/features/insights/useInsights.ts @@ -28,7 +28,7 @@ export function useInsights(state: Snapshot, window: '7d' | '30d' = '7d') { setSnapshot((previous) => ({ key: current.key, data: previous.key === current.key ? previous.data : null, - error: 'Earnings insights are unavailable. Check your connection and runtime version.', + error: 'Couldn’t load earnings. Try again shortly.', })); } finally { current.busy = false; diff --git a/desktop-app/src/renderer/features/machines/MachineRail.tsx b/desktop-app/src/renderer/features/machines/MachineRail.tsx index 3c7a6df760..d297060d80 100644 --- a/desktop-app/src/renderer/features/machines/MachineRail.tsx +++ b/desktop-app/src/renderer/features/machines/MachineRail.tsx @@ -1,3 +1,4 @@ +import { machineStatus } from '../../presentation/status'; import type { Machine } from '../../../shared/contracts'; import { MachineIcon } from './MachineIcon'; import { isOnline, memoryLabel } from './fleet'; @@ -38,7 +39,7 @@ export function MachineRail({ - {machine.status} + {machineStatus(machine.status)} diff --git a/desktop-app/src/renderer/features/machines/overview/FanHealth.tsx b/desktop-app/src/renderer/features/machines/overview/FanHealth.tsx index 25a98a340f..455a861741 100644 --- a/desktop-app/src/renderer/features/machines/overview/FanHealth.tsx +++ b/desktop-app/src/renderer/features/machines/overview/FanHealth.tsx @@ -22,7 +22,7 @@ function fanReading(cooling?: CoolingData) { value: spinning.length ? `Spinning · ${rpmLabel(average)}` : 'Stopped', detail: [ share, - cooling.supported && cooling.mode === 'manual' ? 'Provider cooling' : 'macOS managed', + cooling.supported && cooling.mode === 'manual' ? 'Darkbloom control' : 'macOS control', ] .filter(Boolean) .join(' · '), diff --git a/desktop-app/src/renderer/features/machines/overview/HealthBar.tsx b/desktop-app/src/renderer/features/machines/overview/HealthBar.tsx index 46a051e9e9..e55be12fdd 100644 --- a/desktop-app/src/renderer/features/machines/overview/HealthBar.tsx +++ b/desktop-app/src/renderer/features/machines/overview/HealthBar.tsx @@ -36,11 +36,7 @@ export function HealthBar({
diff --git a/desktop-app/src/renderer/features/machines/overview/LocalOverview.tsx b/desktop-app/src/renderer/features/machines/overview/LocalOverview.tsx index 08fadeea64..2c49e62ed5 100644 --- a/desktop-app/src/renderer/features/machines/overview/LocalOverview.tsx +++ b/desktop-app/src/renderer/features/machines/overview/LocalOverview.tsx @@ -34,7 +34,7 @@ export function LocalOverview({ ? 'Link this Mac to see what it earns.' : cloud && (!cloud.local_lifetime_micro_usd || !cloud.local_day_micro_usd) && - 'Per-Mac totals appear here once your Darkbloom runtime reports them.'} + 'Some earnings totals are not available yet.'}