diff --git a/CHANGELOG.md b/CHANGELOG.md index 872ddefc63..1d50fe8024 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,26 @@ ## 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. + +- 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. @@ -17,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/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/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 7d42087b68..f356d2b948 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 @@ -610,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, @@ -622,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/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/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/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/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/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/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/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..64751a992b 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,25 +41,11 @@ 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 ( <>
- {backend.error && ( -
- backend.setError('')}>{backend.error} -
- )} ); @@ -85,39 +72,24 @@ export default function App() {
- +
- - Workspace {title} - {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' && ( @@ -141,7 +113,7 @@ export default function App() { Compute, powered by people.
- {!machineRoute && } +
); diff --git a/desktop-app/src/renderer/actions.ts b/desktop-app/src/renderer/actions.ts index d30a7ce613..cfd38c51ad 100644 --- a/desktop-app/src/renderer/actions.ts +++ b/desktop-app/src/renderer/actions.ts @@ -1,9 +1,7 @@ import type { Action, DesktopAPI, Operation, Snapshot } from '../shared/contracts'; -const pollMs = 750; - -// The runtime answers an action with an operation that may still be running, so it counts -// only once that operation has succeeded. +// Subscribe before submitting, so a fast terminal event cannot race registration. +// Poll only after the state stream has been silent for ten seconds. export async function submitAction( api: DesktopAPI, action: Action, @@ -13,16 +11,50 @@ export async function submitAction( onSubmitted, }: { timeoutMs: number; timeout: string; onSubmitted?: (operation: Operation) => void }, ) { - let operation: Operation | undefined = await api.act(action); - onSubmitted?.(operation); + let operation: Operation | undefined; + let latest: Snapshot | undefined; + let observedAt = Date.now(); + let wake: (() => void) | undefined; + const streamed = typeof api.onState === 'function'; + const off = + api.onState?.((snapshot) => { + latest = snapshot; + observedAt = Date.now(); + wake?.(); + }) ?? (() => {}); const deadline = Date.now() + timeoutMs; - while (operation?.state === 'running') { - if (Date.now() > deadline) throw new Error(timeout); - await new Promise((resolve) => setTimeout(resolve, pollMs)); - const id: string = operation.id; - operation = (await api.read('state')).operations.find((item) => item.id === id); + try { + operation = await api.act(action); + onSubmitted?.(operation); + const id = operation.id; + while (operation.state === 'running') { + operation = latest?.operations.find((item) => item.id === id) ?? operation; + if (operation.state !== 'running') break; + if (Date.now() >= deadline) throw new Error(timeout); + await new Promise((resolve) => { + const timer = setTimeout( + () => { + wake = undefined; + resolve(); + }, + Math.min(5000, deadline - Date.now()), + ); + wake = () => { + clearTimeout(timer); + wake = undefined; + resolve(); + }; + }); + if (!streamed || Date.now() - observedAt >= 10_000) { + latest = await api.read('state'); + observedAt = Date.now(); + } + } + if (operation.state !== 'succeeded') throw new Error(operation.message || 'Operation failed'); + } finally { + off(); + wake = undefined; } - if (operation?.state !== 'succeeded') throw new Error(operation?.message || ''); } // Electron prefixes errors that cross IPC; a runtime without the action rejects it by name. diff --git a/desktop-app/src/renderer/components/AccountControl.tsx b/desktop-app/src/renderer/components/AccountControl.tsx new file mode 100644 index 0000000000..f4f4587d46 --- /dev/null +++ b/desktop-app/src/renderer/components/AccountControl.tsx @@ -0,0 +1,92 @@ +import { ChevronRight, UserRound } from 'lucide-react'; +import { useCallback, useState } from 'react'; +import { createPortal } from 'react-dom'; +import type { BackendState } 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 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 ( + <> + + {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 2543fbc4d0..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,61 +89,6 @@ export function Notice({ children, onClose }: { children: ReactNode; onClose?: ( ); } -export function OperationFeed({ - backend, - inline = false, -}: { - backend: BackendState; - inline?: boolean; -}) { - const [dismissed, setDismissed] = useState(''); - 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/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/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 76d50dcf9d..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: { @@ -47,22 +49,35 @@ 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 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. @@ -79,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 new file mode 100644 index 0000000000..05a6f723b8 --- /dev/null +++ b/desktop-app/src/renderer/data/pageResources.ts @@ -0,0 +1,20 @@ +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 'models': + return ['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..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}}
@@ -36,7 +33,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..6172ee5ec5 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 { @@ -74,12 +76,20 @@ export function Earnings({ backend }: { backend: BackendState }) {
{error && (

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

)}
- 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..c6bd13e793 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')} />
- + navigate('cooling')} + />
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..c25860077d 100644 --- a/desktop-app/src/renderer/features/Machines.tsx +++ b/desktop-app/src/renderer/features/Machines.tsx @@ -1,7 +1,7 @@ import { ArrowUpRight } from 'lucide-react'; import type { BackendState } from '../useBackend'; import type { Route } from '../../shared/contracts'; -import { Notice, OperationFeed } from '../components/UI'; +import { Notice } from '../components/UI'; import { Models } from './models/Models'; import { Cooling } from './Cooling'; import { Stats } from './Stats'; @@ -42,8 +42,9 @@ export function Machines({ onSelect={onSelect} />
- {local && } - {backend.cloud?.error && {backend.cloud.error}} + {backend.cloud?.error && route === 'machines' && ( + Couldn’t refresh account data. + )}
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/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/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/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/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..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'; @@ -11,10 +12,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 +57,7 @@ export function FleetMacs({ Mac Status Models - Usage earnings · 7d + Usage earnings · {recent ? 'Recent' : '7d'}
{visible.map((machine) => ( ))} - {!visible.length && Try another name or filter.} + {!visible.length && } ); } diff --git a/desktop-app/src/renderer/features/home/FleetSummary.tsx b/desktop-app/src/renderer/features/home/FleetSummary.tsx index a3d645e7e4..a50b1d6a7d 100644 --- a/desktop-app/src/renderer/features/home/FleetSummary.tsx +++ b/desktop-app/src/renderer/features/home/FleetSummary.tsx @@ -20,19 +20,14 @@ export function FleetSummary({

Across your Macs

-

Earnings and status for every Mac on your account.

- {!backend.cloud?.linked && ( -

- Link each Mac to the same account to see its status and earnings here. -

- )}
); } diff --git a/desktop-app/src/renderer/features/home/NetworkMilestone.tsx b/desktop-app/src/renderer/features/home/NetworkMilestone.tsx index f6ed3368d9..f9dc17b452 100644 --- a/desktop-app/src/renderer/features/home/NetworkMilestone.tsx +++ b/desktop-app/src/renderer/features/home/NetworkMilestone.tsx @@ -7,7 +7,7 @@ const CELLS = 24; const STATUS_LABEL = { connecting: 'Connecting', live: 'Live', - stale: 'Last known, reconnecting', + stale: 'Reconnecting', unavailable: 'Unavailable', }; @@ -19,14 +19,8 @@ export function NetworkMilestone({ network }: { network?: NetworkData }) { return (
- {total === undefined ? 'Network progress' : compact(total)} - - {total !== undefined - ? 'tokens processed by the network' - : status === 'connecting' - ? 'Connecting to public network statistics' - : 'Statistics unavailable. Retrying automatically.'} - + {total === undefined ? '—' : compact(total)} + Network tokens
{total !== undefined && (
@@ -43,9 +37,8 @@ export function NetworkMilestone({ network }: { network?: NetworkData }) {
)}
-
+
{milestone ? `Next milestone ${compact(milestone.next)}` : 'Next milestone'} - Proposed
- - {mode} - -
- {count(tokensPerSecond)} - tokens per second -
-
-
-
In progress
-
{count(running)}
+ {showMode && } + {tokensPerSecond !== null && ( +
+ {count(tokensPerSecond)} + tokens per second
-
-
Waiting
-
{count(waiting)}
-
-
+ )} + {(running !== null || waiting !== null) && ( +
+ {running !== null && ( +
+
In progress
+
{count(running)}
+
+ )} + {waiting !== null && ( +
+
Waiting
+
{count(waiting)}
+
+ )} +
+ )} {hardware && } - - {PHASE_TEXT[phase]} - + {phase && ( + + {phase[0].toUpperCase() + phase.slice(1)} + + )}
); } diff --git a/desktop-app/src/renderer/features/home/chip/ChipStage.tsx b/desktop-app/src/renderer/features/home/chip/ChipStage.tsx index 6ec1f519f7..5e2235c449 100644 --- a/desktop-app/src/renderer/features/home/chip/ChipStage.tsx +++ b/desktop-app/src/renderer/features/home/chip/ChipStage.tsx @@ -1,15 +1,19 @@ 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'; import { useChipWorkload } from './hooks/useChipWorkload'; import { useHardwareFeed } from './hooks/useHardwareFeed'; import { usePoliteSummary } from './hooks/usePoliteSummary'; +import { MemoryLegend } from './MemoryLegend'; +import { providerMemory, otherMemory } from './memoryUsage'; import { loadedModels, memoryMap } from './memoryMap'; import { css, type ChipPalette } from './palette'; import { PhaseLegend } from './PhaseLegend'; @@ -30,17 +34,21 @@ const paletteVars = (palette: ChipPalette) => /** * Home hero: this Mac's chip drawn as an anatomy, lit by its measured load while the hardware - * stream is fresh and by the simulated inference workload otherwise. `source` defaults to the + * stream is fresh. Missing measurements stay inactive. `source` defaults to the * desktop bridge. */ 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]); @@ -56,18 +64,24 @@ export function ChipStage({ const loaded = loadedModels(state.models), loadedKey = loaded.map((model) => `${model.id}:${model.gb}:${model.name}`).join('|'); // Keyed by content: every snapshot is a fresh object, but the map only changes with the models. - const memory = useMemo(() => memoryMap(anatomy.memoryGb, loaded), [anatomy.memoryGb, loadedKey]); + const providerGb = providerMemory(state); + const mappedGb = providerGb === null ? null : Math.round(providerGb * 4) / 4; + const memory = useMemo( + () => memoryMap(anatomy.memoryGb, loaded, mappedGb), + [anatomy.memoryGb, loadedKey, mappedGb], + ); const [variant, setVariant] = useState(readVariant); const [paused, setPaused] = useState(false); const reduced = useReducedMotion(), palette = useChipPalette(); - const { feed, live } = useHardwareFeed(load, anatomy); + const { feed, live } = useHardwareFeed(load, anatomy, providerGb); const { advance, stats, reading, powered } = useChipWorkload({ state, preview, anatomy, memory, hardware: feed, + providerGb, }); const readout = hardwareReadout(load.sample, live); const text = stageText({ @@ -97,10 +111,23 @@ export function ChipStage({

{anatomy.name}

{text.memoryLine} - {text.modelsLine} + {anatomy.source === 'topology' && ( + <> + + {anatomy.superCores + anatomy.performanceCores + anatomy.efficiencyCores} CPU + cores + + {anatomy.gpuCores} GPU cores + + )}

+ {onCooling ? ( + + ) : ( + + )} {preview && }
-
- +
- +

{summary} diff --git a/desktop-app/src/renderer/features/home/chip/ChipStatus.tsx b/desktop-app/src/renderer/features/home/chip/ChipStatus.tsx new file mode 100644 index 0000000000..1ee86d9498 --- /dev/null +++ b/desktop-app/src/renderer/features/home/chip/ChipStatus.tsx @@ -0,0 +1,8 @@ +import styles from './chip.module.css'; +export function ChipStatus({ mode, live }: { mode: string; live: boolean }) { + return ( + + {mode} + + ); +} diff --git a/desktop-app/src/renderer/features/home/chip/FanStatus.tsx b/desktop-app/src/renderer/features/home/chip/FanStatus.tsx new file mode 100644 index 0000000000..163e27a0ca --- /dev/null +++ b/desktop-app/src/renderer/features/home/chip/FanStatus.tsx @@ -0,0 +1,36 @@ +import { Fan } from 'lucide-react'; +import type { CoolingData } from '../../../../shared/contracts'; +import styles from './fanStatus.module.css'; + +export function FanStatus({ cooling, onOpen }: { cooling?: CoolingData; onOpen: () => void }) { + const stale = cooling?.observed_at != null && Date.now() / 1000 - cooling.observed_at > 60; + const known = cooling?.supported && !cooling.error && !stale && cooling.enabled != null; + const enabled = known && cooling.enabled; + const temperature = + known && cooling.temperature != null && Number.isFinite(cooling.temperature) + ? cooling.temperature + : null; + const heat = + !enabled && temperature != null ? Math.max(0, Math.min(1, (temperature - 60) / 30)) : 0; + const label = !cooling + ? 'Checking fans' + : !known + ? 'Fan status unavailable' + : enabled + ? 'Auto fan on' + : 'Auto fan off'; + return ( + + ); +} diff --git a/desktop-app/src/renderer/features/home/chip/HardwareReadouts.tsx b/desktop-app/src/renderer/features/home/chip/HardwareReadouts.tsx index 41d14f598d..54b20feb40 100644 --- a/desktop-app/src/renderer/features/home/chip/HardwareReadouts.tsx +++ b/desktop-app/src/renderer/features/home/chip/HardwareReadouts.tsx @@ -1,5 +1,5 @@ import type { HardwareReadout } from './hardware/readouts'; -import styles from './chip.module.css'; +import styles from './hardwareReadouts.module.css'; export const WHOLE_GPU_NOTE = 'macOS reports GPU busy for the whole GPU, not per core.'; @@ -17,6 +17,10 @@ export function HardwareReadouts({ readout }: { readout: HardwareReadout }) { )}

+
+
CPU busy
+
{readout.cpu}
+
GPU power
{readout.power}
@@ -25,19 +29,7 @@ export function HardwareReadouts({ readout }: { readout: HardwareReadout }) {
GPU clock
{readout.clock}
-
-
Memory traffic
-
- {readout.memory} - {readout.memoryEstimated && Estimated} -
-
-
-
CPU busy
-
{readout.cpu}
-
-

{WHOLE_GPU_NOTE}

); } diff --git a/desktop-app/src/renderer/features/home/chip/MemoryLegend.tsx b/desktop-app/src/renderer/features/home/chip/MemoryLegend.tsx new file mode 100644 index 0000000000..40a3035810 --- /dev/null +++ b/desktop-app/src/renderer/features/home/chip/MemoryLegend.tsx @@ -0,0 +1,79 @@ +import type { MemoryMap } from './memoryMap'; +import { modelCSS } from './memoryStyle'; +import styles from './memoryLegend.module.css'; + +const amount = (value: number | null, estimated = false) => + value === null ? '—' : `${estimated ? '~' : ''}${value.toFixed(1)} GB`; +export function MemoryLegend({ + memory, + providerGb, + otherGb, +}: { + memory: MemoryMap; + providerGb: number | null; + otherGb: number | null; +}) { + const total = memory.totalGb || 1; + const weights = memory.segments.filter((s) => s.kind === 'weights'); + const weightShare = weights.reduce((sum, s) => sum + s.to - s.from, 0); + const providerShare = Math.min(1, Math.max(weightShare, (providerGb ?? 0) / total)); + const otherShare = Math.min(1 - providerShare, (otherGb ?? 0) / total); + const shared = providerGb === null ? null : Math.max(0, providerGb - memory.weightsGb); + const free = + providerGb !== null && otherGb !== null + ? Math.max(0, memory.totalGb - providerGb - otherGb) + : null; + return ( +
+
+

Unified memory

+ {memory.totalGb} GB +
+
+ Darkbloom + {amount(providerGb)} +
+ +
    + {memory.models.map((model, i) => ( +
  • + + {model.name} + {amount(model.gb > 0 ? model.gb : null, true)} +
  • + ))} + {shared !== null && shared > 0.1 && ( +
  • + + Shared KV / cache + {amount(shared, true)} +
  • + )} +
  • + + Other apps + macOS + {amount(otherGb, true)} +
  • +
  • + + Free + {amount(free, true)} +
  • +
+
+ ); +} diff --git a/desktop-app/src/renderer/features/home/chip/PhaseLegend.tsx b/desktop-app/src/renderer/features/home/chip/PhaseLegend.tsx index fe128343d7..cacdcb6518 100644 --- a/desktop-app/src/renderer/features/home/chip/PhaseLegend.tsx +++ b/desktop-app/src/renderer/features/home/chip/PhaseLegend.tsx @@ -1,19 +1,11 @@ import styles from './chip.module.css'; -type Phase = 'prefill' | 'decode' | 'kv' | 'traffic' | 'neural'; -const ITEMS: { id: Phase; label: string; note: string }[] = [ - { id: 'prefill', label: 'Prefill', note: 'Prompts processed in parallel on the GPU' }, - { id: 'decode', label: 'Decode', note: 'Every token streams the weights from memory' }, - { id: 'kv', label: 'KV cache', note: 'Context held in unified memory' }, - { - id: 'traffic', - label: 'Memory traffic', - note: 'DRAM bandwidth through the system cache, not cache hits', - }, - { id: 'neural', label: 'Neural Engine', note: 'Idle: Darkbloom runs on the GPU' }, +type Phase = 'prefill' | 'decode' | 'kv'; +const ITEMS: { id: Phase; label: string }[] = [ + { id: 'prefill', label: 'Prefill' }, + { id: 'decode', label: 'Decode' }, + { id: 'kv', label: 'KV cache' }, ]; -/** Below this the Neural Engine reads as idle. */ -const NEURAL_ACTIVE = 0.02; /** Distinct shapes per phase, so the legend never relies on colour alone. */ function Glyph({ phase }: { phase: Phase }) { @@ -33,46 +25,22 @@ function Glyph({ phase }: { phase: Phase }) { [1, 5.5, 10].map((y, i) => ( ))} - {phase === 'traffic' && - [2, 7, 12].map((y) => ( - - ))} - {phase === 'traffic' && - [2, 7, 12].map((y) => )} - {phase === 'neural' && ( - - )} ); } export function PhaseLegend({ levels }: { levels: Record }) { - const neuralIdle = levels.neural < NEURAL_ACTIVE; return (
    - {ITEMS.map(({ id, label, note }) => ( + {ITEMS.map(({ id, label }) => (
  • {label} - {id === 'neural' && !neuralIdle ? 'In use by another app' : note} - {id === 'neural' && neuralIdle ? ( - Idle - ) : ( - - )} +
  • ))}
diff --git a/desktop-app/src/renderer/features/home/chip/blueprint/paintActivity.ts b/desktop-app/src/renderer/features/home/chip/blueprint/paintActivity.ts index 8523af267b..8b7358b625 100644 --- a/desktop-app/src/renderer/features/home/chip/blueprint/paintActivity.ts +++ b/desktop-app/src/renderer/features/home/chip/blueprint/paintActivity.ts @@ -1,16 +1,14 @@ +import { modelColor, crossMemory } from '../memoryStyle'; import { center, type Rect } from '../geometry'; import type { Trace } from '../layout'; import { css, mix, rgba, type RGB } from '../palette'; import { - cacheLevel, cpuLevel, gpuGlow, gpuLevel, gpuShare, interfaceLevel, - ioPulse, memoryCell, - neuralLevel, tracePulses, } from '../render/activity'; import { along, roundRect, strokeTicks, tileRadius, type GlowCache } from '../render/canvas'; @@ -37,8 +35,7 @@ export function paintBlueprintActivity( const looks = { tile: dark ? { fill: 0.34, edge: 0.95, halo: 0.42 } : { fill: 0.72, edge: 0.9, halo: 0.16 }, strip: dark ? { fill: 0.28, edge: 0.55, halo: 0.22 } : { fill: 0.55, edge: 0.7, halo: 0.1 }, - resident: dark ? 0.34 : 0.22, - other: dark ? 0.16 : 0.14, + resident: dark ? 0.8 : 0.6, kv: dark ? { fill: 0.62, edge: 0.75, halo: 0.18 } : { fill: 0.74, edge: 0.8, halo: 0.08 }, flash: dark ? { fill: 0.5, edge: 1, halo: 0.5 } : { fill: 0.65, edge: 1, halo: 0.18 }, }; @@ -63,7 +60,6 @@ export function paintBlueprintActivity( const glowScale = gpuGlow(frame), share = gpuShare(frame), - neural = neuralLevel(frame), gpuLook = { ...looks.tile, halo: looks.tile.halo * glowScale }; spill(ctx, scene, (w.prefill * 0.9 + w.decode * 0.35) * glowScale, dark); @@ -81,18 +77,15 @@ export function paintBlueprintActivity( radius: 1, }); - const cache = cacheLevel(frame); for (const tile of layout.tiles) { if (tile.filler) continue; - if (tile.kind === 'neural') light(tile, neural, palette.accent, looks.tile); - else if (tile.kind === 'gpu') { + if (tile.kind === 'gpu') { const { prefill, decode } = gpuLevel(tile, frame), streamed = decode * 0.85, level = Math.max(prefill, streamed), phase = mix(palette.decode, palette.prefill, prefill / (prefill + streamed + 1e-6)); light(tile, level, mix(palette.neutral, phase, share), gpuLook); - } else if (tile.kind === 'slc') light(tile, cache, palette.decode, looks.strip); - else light(tile, cpuLevel(tile, frame), palette.cpu, looks.tile); + } else light(tile, cpuLevel(tile, frame), palette.cpu, looks.tile); } for (const pkg of layout.memory) { @@ -100,17 +93,10 @@ export function paintBlueprintActivity( pkg.cells.forEach((cell, i) => { const lit = memoryCell(i / n, 1 / n, memory, frame), radius = Math.min(2, Math.min(cell.w, cell.h) * 0.25); - if (lit.other > 0.01) { - roundRect(ctx, cell, radius); - ctx.fillStyle = rgba(palette.neutral, lit.other * looks.other); - ctx.fill(); - } + if (lit.other > 0.01) crossMemory(ctx, cell, palette.neutral, lit.other); if (lit.kind === 'weights') { roundRect(ctx, cell, radius); - ctx.fillStyle = rgba( - mix(palette.accent, palette.decode, Math.min(1, lit.model * 0.4)), - lit.weights * looks.resident, - ); + ctx.fillStyle = rgba(modelColor(lit.model), lit.weights * looks.resident); ctx.fill(); light(cell, lit.sweep, palette.decode, { ...looks.flash, radius }); } else if (lit.kind === 'kv') { @@ -131,24 +117,6 @@ export function paintBlueprintActivity( pulse.write ? palette.kv : palette.decode, dark, ); - - const arrival = ioPulse(frame); - if (arrival) { - const [port, end] = layout.io.path, - at = along(port, end, arrival.at), - size = Math.max(2.5, layout.unit * 0.012); - light( - { x: at.x - size, y: at.y - size, w: size * 2, h: size * 2 }, - arrival.strength, - palette.accent, - { - fill: 1, - edge: 1, - halo: 1, - radius: size, - }, - ); - } } /** Soft light thrown onto the package around the dies while the GPU works (dark theme only). */ diff --git a/desktop-app/src/renderer/features/home/chip/blueprint/paintStatic.ts b/desktop-app/src/renderer/features/home/chip/blueprint/paintStatic.ts index 00c24a77b4..99ba154fa7 100644 --- a/desktop-app/src/renderer/features/home/chip/blueprint/paintStatic.ts +++ b/desktop-app/src/renderer/features/home/chip/blueprint/paintStatic.ts @@ -1,6 +1,6 @@ import { inset } from '../geometry'; import type { Block, ChipLayout, Tile } from '../layout'; -import { css, rgba, type ChipPalette } from '../palette'; +import { rgba, type ChipPalette } from '../palette'; import { roundRect, strokeTicks, tileRadius } from '../render/canvas'; import type { ChipScene } from '../render/types'; import { drawLabel, labelPlacements } from './labels'; @@ -21,7 +21,6 @@ export function paintBlueprintStatic(ctx: CanvasRenderingContext2D, scene: ChipS for (const block of layout.blocks) paintBlock(ctx, block, layout.unit, ink, dark); for (const tile of layout.tiles) paintTile(ctx, tile, ink, dark); labels(ctx, layout, palette); - ioPort(ctx, layout, ink, palette); } function dotGrid(ctx: CanvasRenderingContext2D, layout: ChipLayout, color: string) { @@ -143,14 +142,7 @@ function paintTile(ctx: CanvasRenderingContext2D, tile: Tile, ink: Ink, dark: bo ctx.fill(); return; } - if (tile.kind === 'neural') { - ctx.setLineDash([2, 2]); - ctx.strokeStyle = ink(dark ? 0.17 : 0.2); - ctx.stroke(); - ctx.setLineDash([]); - return; - } - if (tile.kind === 'l2' || tile.kind === 'slc') { + if (tile.kind === 'l2') { ctx.fillStyle = ink(0.03); ctx.fill(); ctx.save(); @@ -199,15 +191,8 @@ function labels(ctx: CanvasRenderingContext2D, layout: ChipLayout, palette: Chip ctx.letterSpacing = `${(size * 0.12).toFixed(2)}px`; for (const block of layout.blocks) { if (block.kind === 'interface') continue; - const minor = block.kind === 'media' || block.kind === 'display' || block.kind === 'io'; - ctx.fillStyle = rgba(palette.text, minor ? 0.32 : palette.dark ? 0.52 : 0.58); - drawLabel( - ctx, - block.label.toUpperCase(), - labelPlacements(block), - minor ? size * 0.9 : size, - font, - ); + ctx.fillStyle = rgba(palette.text, palette.dark ? 0.52 : 0.58); + drawLabel(ctx, block.label.toUpperCase(), labelPlacements(block), size, font); } const first = layout.memory[0]; if (first) { @@ -219,24 +204,3 @@ function labels(ctx: CanvasRenderingContext2D, layout: ChipLayout, palette: Chip } ctx.letterSpacing = '0px'; } - -function ioPort(ctx: CanvasRenderingContext2D, layout: ChipLayout, ink: Ink, palette: ChipPalette) { - const [port, end] = layout.io.path, - u = layout.unit, - dark = palette.dark, - across = layout.io.side === 'left' || layout.io.side === 'right'; - ctx.setLineDash([3, 3]); - ctx.strokeStyle = ink(dark ? 0.24 : 0.26); - ctx.beginPath(); - ctx.moveTo(port.x, port.y); - ctx.lineTo(end.x, end.y); - ctx.stroke(); - ctx.setLineDash([]); - const w = across ? u * 0.03 : u * 0.09, - h = across ? u * 0.09 : u * 0.03; - roundRect(ctx, { x: port.x - w / 2, y: port.y - h / 2, w, h }, 2); - ctx.fillStyle = dark ? css(palette.surface) : '#fff'; - ctx.fill(); - ctx.strokeStyle = ink(dark ? 0.32 : 0.3); - ctx.stroke(); -} diff --git a/desktop-app/src/renderer/features/home/chip/chip.module.css b/desktop-app/src/renderer/features/home/chip/chip.module.css index ee3112327e..1f4024f111 100644 --- a/desktop-app/src/renderer/features/home/chip/chip.module.css +++ b/desktop-app/src/renderer/features/home/chip/chip.module.css @@ -4,9 +4,8 @@ display: flex; flex-direction: column; width: 100%; - height: 100%; - min-height: 440px; - padding: 20px 24px 22px; + min-height: 0; + padding: 24px; border: 1px solid var(--line); border-radius: 14px; background: @@ -89,20 +88,25 @@ background: var(--raised-bg); } .body { - flex: 1; - min-height: 0; display: grid; - grid-template-columns: minmax(140px, 180px) minmax(0, 1fr) minmax(190px, 228px); - grid-template-areas: 'readouts canvas legend'; - gap: 12px; - margin-top: 4px; + grid-template-columns: minmax(0, 1fr) minmax(250px, 290px); + grid-template-areas: 'canvas details'; + align-items: stretch; + gap: 28px; + margin-top: 24px; +} +.details { + grid-area: details; + display: grid; + align-content: start; + gap: 24px; + min-width: 0; + border-left: 1px solid var(--line); + padding-left: 24px; } .readouts { - grid-area: readouts; - align-self: center; - display: flex; - flex-direction: column; - gap: 18px; + display: grid; + gap: 16px; } .mode { display: inline-flex; @@ -159,52 +163,6 @@ font-size: 17px; font-variant-numeric: tabular-nums; } -.hardware dl { - display: grid; - gap: 6px; - margin: 0; -} -.hardware dl div { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 8px; -} -.hardware dt { - font-size: 10px; - color: var(--muted); -} -.hardware dd { - display: flex; - flex-wrap: wrap; - justify-content: flex-end; - align-items: baseline; - gap: 2px 6px; - margin: 0; - font-size: 12px; - text-align: right; - font-variant-numeric: tabular-nums; -} -.share { - flex-basis: 100%; - font-size: 9px; - color: var(--chip-prefill); -} -.badge { - padding: 1px 4px; - border: 1px solid var(--line); - border-radius: 3px; - font-size: 8px; - letter-spacing: 0.2px; - text-transform: uppercase; - color: var(--muted); -} -.note { - margin-top: 8px; - font-size: 9px; - line-height: 1.35; - color: var(--muted); -} .phase { padding-top: 12px; border-top: 1px solid var(--line); @@ -216,7 +174,7 @@ grid-area: canvas; position: relative; min-width: 0; - min-height: 0; + min-height: 380px; perspective: 1400px; } .canvas { @@ -234,7 +192,6 @@ transform: none; } .legend { - grid-area: legend; align-self: center; display: grid; gap: 15px; @@ -257,12 +214,6 @@ .legend li[data-phase='kv'] { color: var(--chip-kv); } -.legend li[data-phase='traffic'] { - color: var(--chip-decode); -} -.legend li[data-phase='neural'] { - color: var(--muted); -} .glyph { width: 14px; height: 14px; @@ -277,13 +228,6 @@ font-weight: 500; color: var(--text-primary); } -.legendText small { - display: block; - margin-top: 3px; - font-size: 10px; - line-height: 1.35; - color: var(--muted); -} .meter { height: 3px; margin-top: 6px; @@ -298,12 +242,6 @@ transform-origin: left; transition: transform 0.4s ease; } -.idle { - font-size: 10px; - font-style: normal; - text-align: right; - color: var(--muted); -} .srOnly { position: absolute; width: 1px; @@ -312,54 +250,39 @@ clip-path: inset(50%); white-space: nowrap; } -@container chip (max-width: 860px) { +@container chip (max-width: 720px) { .body { - grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); - grid-template-rows: minmax(0, 1fr) auto; - grid-template-areas: - 'canvas canvas' - 'readouts legend'; - gap: 12px 24px; + grid-template-columns: minmax(0, 1fr); + grid-template-areas: 'canvas' 'details'; + gap: 20px; + margin-top: 18px; + } + .details { + border-left: 0; + padding-left: 0; + border-top: 1px solid var(--line); + padding-top: 20px; } - .readouts { - align-self: end; - display: grid; - grid-template-columns: auto minmax(0, 1fr); - align-items: end; - gap: 10px 24px; + .viewport { + min-height: 320px; } - .mode { - grid-column: 1 / -1; + .legend { + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 10px; } .rate strong { font-size: 30px; } - .phase, - .note { - display: none; - } - .hardware { - grid-column: 1 / -1; - } - .hardware dl { - grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); - gap: 8px 16px; - } - .hardware dl div { - flex-direction: column; - align-items: flex-start; - gap: 3px; - } - .hardware dd { - justify-content: flex-start; - text-align: left; +} +@container chip (max-width: 440px) { + .head { + flex-wrap: wrap; } - .legend { - align-self: end; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 10px 16px; + .controls { + width: 100%; + justify-content: space-between; } - .legendText small { - display: none; + .viewport { + min-height: 260px; } } diff --git a/desktop-app/src/renderer/features/home/chip/dieLayout.ts b/desktop-app/src/renderer/features/home/chip/dieLayout.ts index 3998cba5b2..77cce2c18d 100644 --- a/desktop-app/src/renderer/features/home/chip/dieLayout.ts +++ b/desktop-app/src/renderer/features/home/chip/dieLayout.ts @@ -2,9 +2,8 @@ import type { CoreKind } from '../../../../shared/hardware'; import type { ChipTier, CoreCluster } from './anatomy'; import { columns, fitGrid, grid, inset, rows, share, type Rect, type Side } from './geometry'; -export type BlockKind = - 'cpu' | 'gpu' | 'cache' | 'neural' | 'media' | 'display' | 'io' | 'interface'; -export type TileKind = 'gpu' | CoreKind | 'neural' | 'l2' | 'slc'; +export type BlockKind = 'cpu' | 'gpu' | 'interface'; +export type TileKind = 'gpu' | CoreKind | 'l2'; export interface DieBlock extends Rect { kind: BlockKind; label: string; @@ -33,23 +32,16 @@ export interface DieSpec { gpuGroups: number[]; /** Cores drawn per partition: the chip's largest, so binned cores show as fillers. */ gpuSlots: number; - neural: number; - cacheBanks: number; } export const BLOCK_LABELS: Record = { cpu: 'CPU', gpu: 'GPU', - cache: 'Memory traffic', - neural: 'Neural Engine', - media: 'Media', - display: 'Display', - io: 'I/O', interface: 'Memory interface', }; /** * One die in its canonical frame: memory interface strips on the left/right edges - * (right only for base chips), CPU at the top of the centre column and I/O at the bottom. + * (right only for base chips), with GPU wings beside the CPU column. */ export function canonicalDie(spec: DieSpec, w: number, h: number) { const blocks: DieBlock[] = [], @@ -95,17 +87,7 @@ export function canonicalDie(spec: DieSpec, w: number, h: number) { }); }); - const [cpu, cache, neural, misc] = rows(centre, [0.37, 0.16, 0.31, 0.16], gap); - cpuClusters(spec.clusters, block(cpu, 'cpu'), gap, tiles); - const banks = Math.max(2, spec.cacheBanks); - place(grid(block(cache, 'cache'), Math.ceil(banks / 2), 2, gap * 0.6), 'slc', banks); - const neuralBody = block(neural, 'neural'), - neuralShape = fitGrid(spec.neural, neuralBody, 1.15); - place(grid(neuralBody, neuralShape.cols, neuralShape.rows, gap * 0.6), 'neural', spec.neural); - const [media, display, io] = columns(misc, [0.36, 0.28, 0.36], gap); - block(media, 'media', false); - block(display, 'display', false); - block(io, 'io', false); + cpuClusters(spec.clusters, block(centre, 'cpu'), gap, tiles); return { blocks, tiles }; } 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/home/chip/hardware/drive.ts b/desktop-app/src/renderer/features/home/chip/hardware/drive.ts index 8800dcacdb..388c00c9a4 100644 --- a/desktop-app/src/renderer/features/home/chip/hardware/drive.ts +++ b/desktop-app/src/renderer/features/home/chip/hardware/drive.ts @@ -8,9 +8,9 @@ export interface Eased { value: number; known: number; } -/** Measured load eased for drawing, crossfading with the simulation by `weight`. */ +/** Measured load eased for drawing, with `weight` easing the initial connection. */ export interface HardwareLight { - /** 0 while the simulation drives the chip, 1 while fresh measurements do. */ + /** 0 without measurements, 1 while fresh measurements drive the chip. */ weight: number; /** By logical CPU id. */ cpu: Eased[]; @@ -59,11 +59,7 @@ const pulseRate = (tokensPerSecond: number, traffic: number) => ? clamp(0.6 + 0.9 * Math.log2(1 + tokensPerSecond / 25), 0.6, 4) : 0.6 + 1.2 * traffic; -/** - * Eases measured targets between samples and overlays them on the simulated frame: GPU, memory - * traffic and CPU come from the hardware, while requests, the KV cache and the prefill/decode - * split stay provider-derived. Without fresh targets it fades back to the simulation. - */ +/** Eases fresh measurements. Only explicit synthetic preview frames get illustrative motion. */ export function createHardwareDrive() { const light: HardwareLight = { weight: 0, @@ -84,6 +80,11 @@ export function createHardwareDrive() { return { step(elapsed: number, w: WorkloadFrame, targets: HardwareTargets | null): LitFrame { + const liveOnly = w.mode !== 'synthetic'; + if (liveOnly && !targets) { + light.weight = 0; + return { workload: w, hardware: null }; + } const k = 1 - Math.exp(-Math.max(0, elapsed) / TAU), phase = targets ? resolvePhase(w.phase, w.mode, targets.phase, targets.serving) : w.phase; light.weight += ((targets ? 1 : 0) - light.weight) * k; @@ -99,6 +100,7 @@ export function createHardwareDrive() { ease(light.ane, targets.ane, k); ease(light.other, targets.other, k); } + if (liveOnly) return { workload: w, hardware: light }; const mix = MIX[phase]; if (mix !== undefined) light.prefillMix += (mix - light.prefillMix) * k; light.wave += elapsed * (0.25 + 1.5 * light.clock.value); @@ -116,7 +118,11 @@ export function createHardwareDrive() { power: lerp(w.power, 1, weight), prefill: lerp(w.prefill, darkbloom * light.prefillMix, known), decode: lerp(w.decode, darkbloom * (1 - light.prefillMix), known), - memoryRead: measured(w.memoryRead, light.traffic), + memoryRead: + targets?.traffic === null + ? lerp(w.memoryRead, 0, weight) + : measured(w.memoryRead, light.traffic), + kvWrite: targets?.traffic === null ? lerp(w.kvWrite, 0, weight) : w.kvWrite, cpu: measured(w.cpu, light.cpuBusy), stepPhase: weight >= 0.5 ? pulse : w.stepPhase, }, diff --git a/desktop-app/src/renderer/features/home/chip/hardware/targets.ts b/desktop-app/src/renderer/features/home/chip/hardware/targets.ts index a34f8ed2b4..55c3ec5537 100644 --- a/desktop-app/src/renderer/features/home/chip/hardware/targets.ts +++ b/desktop-app/src/renderer/features/home/chip/hardware/targets.ts @@ -58,15 +58,15 @@ export function hardwareTargets( sample: HardwareSample, anatomy: ChipAnatomy, peakPowerW: number, + providerMemoryGb: number | null = null, ): HardwareTargets { const { gpu, ane, memory } = sample, running = sample.provider.running; const cpu = sample.cpu.load.map(fraction), busy = fraction(gpu.utilization), share = running ? fraction(gpu.provider_share) : 0; - const darkbloomGb = running - ? Math.max(known(gpu.memory_in_use_gb) ? gpu.memory_in_use_gb : 0, 0) - : 0, + // Driver GPU memory is whole-device, not attributable to this provider. + const darkbloomGb = running ? providerMemoryGb : 0, usedGb = known(memory.used_gb) ? memory.used_gb : null; const aneLevel = known(ane.active) || known(ane.bandwidth_gbps) @@ -89,7 +89,7 @@ export function hardwareTargets( trafficEstimated: sample.capabilities.memory_bandwidth === 'estimated', ane: aneLevel, other: - usedGb === null || anatomy.memoryGb <= 0 + usedGb === null || darkbloomGb === null || anatomy.memoryGb <= 0 ? null : clamp((usedGb - darkbloomGb) / anatomy.memoryGb), phase: hardwarePhase(sample), diff --git a/desktop-app/src/renderer/features/home/chip/hardwareReadouts.module.css b/desktop-app/src/renderer/features/home/chip/hardwareReadouts.module.css new file mode 100644 index 0000000000..6ef9d8d89e --- /dev/null +++ b/desktop-app/src/renderer/features/home/chip/hardwareReadouts.module.css @@ -0,0 +1,44 @@ +.hardware dl { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 18px 16px; + margin: 0; +} +.hardware dl > div { + min-width: 0; +} +.hardware dt { + font-size: 11px; + color: var(--muted); +} +.hardware dd { + margin: 6px 0 0; + font-size: 17px; + letter-spacing: -0.3px; + font-variant-numeric: tabular-nums; +} +.hardware dl > div:nth-child(-n + 2) dd { + font-size: 34px; + line-height: 1.15; + letter-spacing: -1px; +} +.share { + display: block; + margin-top: 5px; + font-size: 10px; + letter-spacing: 0; + color: var(--chip-prefill); +} +@container chip (max-width: 720px) { + .hardware dl { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } + .hardware dl > div:nth-child(-n + 2) dd { + font-size: 26px; + } +} +@container chip (max-width: 440px) { + .hardware dl { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} diff --git a/desktop-app/src/renderer/features/home/chip/hooks/useChipWorkload.ts b/desktop-app/src/renderer/features/home/chip/hooks/useChipWorkload.ts index bbd047d4de..454003288d 100644 --- a/desktop-app/src/renderer/features/home/chip/hooks/useChipWorkload.ts +++ b/desktop-app/src/renderer/features/home/chip/hooks/useChipWorkload.ts @@ -5,6 +5,7 @@ import type { LitFrame } from '../hardware/drive'; import type { MemoryMap } from '../memoryMap'; import { hashString } from '../random'; import { createWorkloadEngine } from '../workload/engine'; +import { measuredFrame } from '../workload/measured'; import { providerUp, readLive, type LiveReading, type LiveSample } from '../workload/live'; import { IDLE_INPUTS, type WorkloadInputs, type WorkloadPhase } from '../workload/types'; import type { HardwareFeed } from './useHardwareFeed'; @@ -39,36 +40,37 @@ const summarize = ({ workload: frame, hardware }: LitFrame): ChipStats => ({ const sameStats = (a: ChipStats, b: ChipStats) => (Object.keys(a) as (keyof ChipStats)[]).every((key) => a[key] === b[key]); -/** - * Owns the workload engine: synthetic arrivals in preview, otherwise targets read from runtime - * snapshots. `advance` steps it from the frame loop and overlays the measured hardware; stats - * refresh a few times a second. - */ +/** Drives live allocation/count frames and hardware measurements; simulations exist only in preview. */ export function useChipWorkload({ state, preview, anatomy, memory, hardware, + providerGb, }: { state: Snapshot; preview: boolean; anatomy: ChipAnatomy; memory: MemoryMap; hardware: HardwareFeed; + providerGb: number | null; }) { const modelIds = useMemo(() => memory.models.map((model) => model.id), [memory]); const engine = useMemo( () => - createWorkloadEngine({ - seed: hashString(`${anatomy.name}:${preview ? 'preview' : 'live'}`), - anatomy, - models: modelIds.length, - warmup: preview ? PREVIEW_WARMUP : 0, - }), + preview + ? createWorkloadEngine({ + seed: hashString(`${anatomy.name}:preview`), + anatomy, + models: modelIds.length, + warmup: PREVIEW_WARMUP, + }) + : null, [anatomy, modelIds.length, preview], ); const sample = useRef(null); + const liveReading = useRef({ inputs: IDLE_INPUTS, sample: null, fresh: false }); const [reading, setReading] = useState({ inputs: IDLE_INPUTS, sample: null, @@ -82,6 +84,7 @@ export function useChipWorkload({ useEffect(() => { const next = readLive(state, modelIds, sample.current, Date.now() / 1000); sample.current = next.sample; + liveReading.current = next; setReading(next); }, [state, modelIds, clock]); @@ -93,7 +96,12 @@ export function useChipWorkload({ : reading.inputs; }, [preview, powered, reading]); - const [stats, setStats] = useState(() => summarize({ workload: engine.frame, hardware: null })); + const [stats, setStats] = useState(() => + summarize({ + workload: engine?.frame ?? measuredFrame(reading, memory, providerGb), + hardware: null, + }), + ); const sinceStats = useRef(0); const advance = useCallback( (elapsed: number) => { @@ -102,7 +110,9 @@ export function useChipWorkload({ const idle = preview && measured && !measured.serving && inputs.current.mode === 'synthetic'; const lit = hardware.drive.step( elapsed, - engine.step(elapsed, idle ? PREVIEW_IDLE : inputs.current), + preview + ? engine!.step(elapsed, idle ? PREVIEW_IDLE : inputs.current) + : measuredFrame(liveReading.current, memory, providerGb), measured, ); sinceStats.current += elapsed; @@ -113,7 +123,7 @@ export function useChipWorkload({ } return lit; }, - [engine, hardware, preview], + [engine, hardware, preview, memory, providerGb], ); return { advance, stats, reading, powered }; } diff --git a/desktop-app/src/renderer/features/home/chip/hooks/useHardwareFeed.ts b/desktop-app/src/renderer/features/home/chip/hooks/useHardwareFeed.ts index ae5ed89c2e..3246f52ff4 100644 --- a/desktop-app/src/renderer/features/home/chip/hooks/useHardwareFeed.ts +++ b/desktop-app/src/renderer/features/home/chip/hooks/useHardwareFeed.ts @@ -15,7 +15,11 @@ export interface HardwareFeed { * without re-rendering per frame. Measurements drive the chip only while they are fresh and * the drawing is this Mac's reported topology. */ -export function useHardwareFeed(load: HardwareLoadState, anatomy: ChipAnatomy) { +export function useHardwareFeed( + load: HardwareLoadState, + anatomy: ChipAnatomy, + providerGb: number | null = null, +) { const live = anatomy.source === 'topology' && load.fresh && load.sample !== null; const targets = useRef(null), peak = useRef(0); @@ -25,8 +29,8 @@ export function useHardwareFeed(load: HardwareLoadState, anatomy: ChipAnatomy) { return; } peak.current = sessionPeakPower(peak.current, load.sample, anatomy); - targets.current = hardwareTargets(load.sample, anatomy, peak.current); - }, [live, load.sample, anatomy]); + targets.current = hardwareTargets(load.sample, anatomy, peak.current, providerGb); + }, [live, load.sample, anatomy, providerGb]); const feed = useMemo( () => ({ current: () => targets.current, drive: createHardwareDrive() }), [], diff --git a/desktop-app/src/renderer/features/home/chip/layout.ts b/desktop-app/src/renderer/features/home/chip/layout.ts index 90010f6968..f59a6d2d03 100644 --- a/desktop-app/src/renderer/features/home/chip/layout.ts +++ b/desktop-app/src/renderer/features/home/chip/layout.ts @@ -1,4 +1,4 @@ -import type { ChipAnatomy, ChipTier } from './anatomy'; +import type { ChipAnatomy } from './anatomy'; import { canonicalDie, type BlockKind, type DieCluster, type TileKind } from './dieLayout'; import { center, @@ -75,11 +75,9 @@ export interface ChipLayout { phy: PhySegment[]; memory: MemoryPackage[]; traces: Trace[]; - io: { side: Side; path: Point[] }; dispatch: Point; } -const CACHE_BANKS: Record = { base: 4, pro: 6, max: 8, ultra: 8 }; const distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y); const rectDistance = (r: Rect, p: Point) => Math.hypot(Math.max(r.x - p.x, 0, p.x - r.x - r.w), Math.max(r.y - p.y, 0, p.y - r.y - r.h)); @@ -141,8 +139,6 @@ export function chipLayout( clusters: clusters.filter((cluster) => cluster.die === index), gpuGroups: groupsOf(index), gpuSlots, - neural: share(anatomy.neuralCores, anatomy.dies, index), - cacheBanks: CACHE_BANKS[anatomy.tier], }, frame.w, frame.h, @@ -183,8 +179,6 @@ export function chipLayout( }; }); - const io = blocks.find((block) => block.kind === 'io' && block.die === 0)!, - ioSide = orientSide('bottom', dies[0].orientation); return { width, height, @@ -205,34 +199,6 @@ export function chipLayout( phy, memory, traces, - io: { side: ioSide, path: ioPath(io, substrate, ioSide) }, dispatch, }; } - -/** Straight run from the substrate edge on `side` into the die's I/O block. */ -function ioPath(io: Rect, substrate: Rect, side: Side): Point[] { - const middle = center(io); - switch (side) { - case 'bottom': - return [ - { x: middle.x, y: substrate.y + substrate.h }, - { x: middle.x, y: io.y + io.h }, - ]; - case 'top': - return [ - { x: middle.x, y: substrate.y }, - { x: middle.x, y: io.y }, - ]; - case 'left': - return [ - { x: substrate.x, y: middle.y }, - { x: io.x, y: middle.y }, - ]; - case 'right': - return [ - { x: substrate.x + substrate.w, y: middle.y }, - { x: io.x + io.w, y: middle.y }, - ]; - } -} diff --git a/desktop-app/src/renderer/features/home/chip/memoryLegend.module.css b/desktop-app/src/renderer/features/home/chip/memoryLegend.module.css new file mode 100644 index 0000000000..a12fabf5a2 --- /dev/null +++ b/desktop-app/src/renderer/features/home/chip/memoryLegend.module.css @@ -0,0 +1,104 @@ +.memory { + min-width: 0; + border-top: 1px solid var(--line); + padding-top: 20px; +} +.heading, +.total { + display: flex; + justify-content: space-between; + align-items: baseline; + gap: 12px; +} +.heading h3 { + margin: 0; + font-size: 12px; + font-weight: 500; +} +.heading > span { + font-size: 11px; + color: var(--muted); +} +.total { + margin: 13px 0 10px; + font-size: 11px; + color: var(--muted); +} +.total strong { + font-size: 19px; + font-weight: 500; + color: var(--text-primary); + font-variant-numeric: tabular-nums; +} +.bar { + display: flex; + height: 9px; + overflow: hidden; + border-radius: 3px; + background: var(--line); +} +.bar i { + height: 100%; + flex: none; +} +.memory ul { + display: grid; + gap: 11px; + padding: 0; + margin: 16px 0 0; + list-style: none; +} +.memory li { + display: grid; + grid-template-columns: 9px minmax(0, 1fr) auto; + align-items: center; + gap: 8px; + font-size: 11px; + color: var(--text-secondary); +} +.memory li span { + min-width: 0; + line-height: 1.35; +} +.memory li b { + font-size: 10px; + font-weight: 400; + font-variant-numeric: tabular-nums; + color: var(--muted); + white-space: nowrap; +} +.memory li i { + width: 9px; + height: 9px; + border-radius: 2px; +} +.system { + border-top: 1px solid var(--line); + margin-top: 3px; + padding-top: 13px; +} +.other { + background-color: var(--raised-bg); + background-image: + repeating-linear-gradient(45deg, transparent 0 3px, var(--muted) 3px 4px), + repeating-linear-gradient(-45deg, transparent 0 3px, var(--muted) 3px 4px); +} +.free { + background: var(--line); +} +@container chip (max-width: 720px) { + .memory ul { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px 24px; + } + .system { + border: 0; + margin-top: 0; + padding-top: 0; + } +} +@container chip (max-width: 440px) { + .memory ul { + grid-template-columns: minmax(0, 1fr); + } +} diff --git a/desktop-app/src/renderer/features/home/chip/memoryMap.ts b/desktop-app/src/renderer/features/home/chip/memoryMap.ts index 80618aca6c..3666fe829d 100644 --- a/desktop-app/src/renderer/features/home/chip/memoryMap.ts +++ b/desktop-app/src/renderer/features/home/chip/memoryMap.ts @@ -32,11 +32,18 @@ export const loadedModels = (models: NativeModel[]) => * resident weights per model, room for the KV cache, and the headroom the provider leaves the * OS (its load cap is 90% of RAM with at least 2 GB kept back). */ -export function memoryMap(totalGb: number, models: MemoryMap['models']): MemoryMap { +export function memoryMap( + totalGb: number, + models: MemoryMap['models'], + providerGb?: number | null, +): MemoryMap { const total = totalGb > 0 ? totalGb : 1, reserved = clamp(Math.max(0.1, 2 / total), 0.1, 0.3), weightsGb = models.reduce((sum, model) => sum + model.gb, 0), - room = 1 - reserved - MIN_KV_SHARE, + room = Math.min( + 1 - reserved - MIN_KV_SHARE, + providerGb == null ? 1 : Math.max(0, providerGb / total), + ), scale = weightsGb / total > room ? room / (weightsGb / total) : 1; const segments: MemorySegment[] = []; let at = 0; diff --git a/desktop-app/src/renderer/features/home/chip/memoryStyle.ts b/desktop-app/src/renderer/features/home/chip/memoryStyle.ts new file mode 100644 index 0000000000..2dc3a13cb1 --- /dev/null +++ b/desktop-app/src/renderer/features/home/chip/memoryStyle.ts @@ -0,0 +1,26 @@ +import type { Rect } from './geometry'; +import { css, rgba, type RGB } from './palette'; + +const COLORS: RGB[] = [ + [108, 160, 255], + [67, 206, 168], + [245, 176, 76], + [202, 130, 246], +]; +export const modelColor = (index: number): RGB => COLORS[Math.max(0, index) % COLORS.length]; +export const modelCSS = (index: number) => css(modelColor(index)); + +/** Crosses mark memory belonging to other apps and macOS in both canvas variants. */ +export function crossMemory(ctx: CanvasRenderingContext2D, r: Rect, color: RGB, intensity: number) { + ctx.fillStyle = rgba(color, intensity * 0.14); + ctx.fillRect(r.x, r.y, r.w, r.h); + ctx.strokeStyle = rgba(color, intensity * 0.7); + ctx.lineWidth = 0.8; + const p = Math.min(r.w, r.h) * 0.2; + ctx.beginPath(); + ctx.moveTo(r.x + p, r.y + p); + ctx.lineTo(r.x + r.w - p, r.y + r.h - p); + ctx.moveTo(r.x + r.w - p, r.y + p); + ctx.lineTo(r.x + p, r.y + r.h - p); + ctx.stroke(); +} diff --git a/desktop-app/src/renderer/features/home/chip/memoryUsage.ts b/desktop-app/src/renderer/features/home/chip/memoryUsage.ts new file mode 100644 index 0000000000..889a1acdea --- /dev/null +++ b/desktop-app/src/renderer/features/home/chip/memoryUsage.ts @@ -0,0 +1,17 @@ +import type { Snapshot } from '../../../../shared/contracts'; + +/** MLX active + buffer cache belong to Darkbloom, unlike whole-device driver memory. */ +export function providerMemory(state: Snapshot): number | null { + const active = state.memory.active_gb; + return typeof active === 'number' && Number.isFinite(active) && active >= 0 + ? active + Math.max(0, state.memory.cache_gb ?? 0) + : null; +} +export function otherMemory( + used: number | null | undefined, + provider: number | null, +): number | null { + return typeof used === 'number' && Number.isFinite(used) && provider !== null + ? Math.max(0, used - provider) + : null; +} diff --git a/desktop-app/src/renderer/features/home/chip/photoreal/dieParts.ts b/desktop-app/src/renderer/features/home/chip/photoreal/dieParts.ts index 20264beaa0..1e376cd00c 100644 --- a/desktop-app/src/renderer/features/home/chip/photoreal/dieParts.ts +++ b/desktop-app/src/renderer/features/home/chip/photoreal/dieParts.ts @@ -66,12 +66,6 @@ function sramArray(tile: Rect): Part[] { ]; } -function neuralCore(tile: Rect): Part[] { - const { body, gap } = frame(tile, 0.08, 0.05), - [mac, buffer] = along(body, [0.74, 0.26], gap); - return [as('mac')(mac), as('cache')(buffer)]; -} - export function tileParts(tile: Tile): Part[] { switch (tile.kind) { case 'gpu': @@ -80,8 +74,6 @@ export function tileParts(tile: Tile): Part[] { case 'performance': case 'efficiency': return cpuCore(tile, tile.kind === 'efficiency'); - case 'neural': - return neuralCore(tile); default: return sramArray(tile); } @@ -89,21 +81,6 @@ export function tileParts(tile: Tile): Part[] { const blockSeed = (block: Block) => block.x * 0.137 + block.y * 0.291 + block.die * 5.3; -/** Engines without counted tiles: a few strips of SRAM buffers and control logic. */ -export function engineParts(block: Block): Part[] { - const { body, gap } = frame(block, 0.08, 0.05), - seed = blockSeed(block); - const strips = along( - body, - [0, 1, 2].map((i) => 0.6 + noise(seed + i)), - gap, - ); - return strips.flatMap((strip, i) => { - const [a, b] = across(strip, [0.5 + 0.35 * noise(seed + i * 3.1), 0.5], gap); - return [as(noise(seed + i * 5.7) > 0.4 ? 'cache' : 'logic')(a), as('logic')(b)]; - }); -} - /** The label band of a block (its widest margin outside the body), or null when unbanded. */ function bandOf(block: Block): Rect | null { const { body } = block, diff --git a/desktop-app/src/renderer/features/home/chip/photoreal/emissive.ts b/desktop-app/src/renderer/features/home/chip/photoreal/emissive.ts index 2fdf11e11b..67d6b213a1 100644 --- a/desktop-app/src/renderer/features/home/chip/photoreal/emissive.ts +++ b/desktop-app/src/renderer/features/home/chip/photoreal/emissive.ts @@ -6,7 +6,7 @@ import { noise } from '../random'; import type { ChipScene } from '../render/types'; import { createAtlas, type Sprite } from './atlas'; import { createBrush, longAxis, snap, type Brush } from './brush'; -import { engineParts, tileParts } from './dieParts'; +import { tileParts } from './dieParts'; import { haloOf, paintCellsGlow, @@ -34,7 +34,6 @@ export interface PackageLight extends Point { pkg: MemoryPackage; /** What each cell holds; the split repeats in every package because memory is interleaved. */ kinds: MemoryKind[]; - weights: Sprite | null; kv: Sprite | null; traces: Sprite | null; } @@ -42,11 +41,8 @@ export interface PackageLight extends Point { export interface Emissive { gpu: GpuLight[]; cpu: TileLight[]; - slc: TileLight[]; - neural: TileLight[]; phy: (Sprite | null)[]; bridge: Sprite | null; - io: Sprite | null; memory: PackageLight[]; atlas: HTMLCanvasElement | null; } @@ -89,20 +85,16 @@ export function buildEmissive( }; const gpu: { tile: Tile; prefill: number; decode: number; neutral: number }[] = [], - cpu: { tile: Tile; slot: number }[] = [], - slc: { tile: Tile; slot: number }[] = [], - neural: { tile: Tile; slot: number }[] = []; + cpu: { tile: Tile; slot: number }[] = []; for (const tile of layout.tiles) { if (tile.filler) continue; - if (tile.kind === 'neural') neural.push({ tile, slot: tileSlot(tile, glow.accent, 0.3, 6) }); - else if (tile.kind === 'gpu') + if (tile.kind === 'gpu') gpu.push({ tile, prefill: tileSlot(tile, glow.prefill, 0.36, 9), decode: tileSlot(tile, glow.decode, 0.36, 9), neutral: tileSlot(tile, glow.neutral, 0.36, 9), }); - else if (tile.kind === 'slc') slc.push({ tile, slot: tileSlot(tile, glow.decode, 0.3, 6) }); else cpu.push({ tile, slot: tileSlot(tile, glow.cpu, 0.42, 7) }); } const phy = layout.phy.map((segment) => @@ -116,14 +108,7 @@ export function buildEmissive( paintStripGlow(b, seam, glow.prefill, b.tex.glow.lanes[longAxis(seam)], haloAlpha), ) : -1; - const ioBlock = layout.blocks.find((block) => block.kind === 'io' && block.die === 0), - io = ioBlock - ? queue(ioBlock, 12, (b) => - paintPartsGlow(b, ioBlock, engineParts(ioBlock), glow.accent, 6, haloAlpha), - ) - : -1; - - const regions = new Map(); + const regions = new Map(); const packages = layout.memory.map((pkg) => { const kinds = cellKinds(pkg.cells.length, memory), at = origin(pkg), @@ -135,12 +120,8 @@ export function buildEmissive( pkg.cells .filter((_, i) => kinds[i] === kind) .map((cell) => ({ ...cell, x: cell.x - at.x, y: cell.y - at.y })), - weights = cells('weights'), kv = cells('kv'); slots = { - weights: weights.length - ? queue(local, unit * 0.034, (b) => paintCellsGlow(b, weights, glow.accent, true)) - : -1, kv: kv.length ? queue(local, 2, (b) => paintCellsGlow(b, kv, glow.kv, false)) : -1, }; regions.set(key, slots); @@ -173,16 +154,12 @@ export function buildEmissive( neutral: sprite(neutral), })), cpu: cpu.map(tileLight), - slc: slc.map(tileLight), - neural: neural.map(tileLight), phy: phy.map(sprite), bridge: sprite(bridge), - io: sprite(io), - memory: packages.map(({ pkg, kinds, at, weights, kv, traces }) => ({ + memory: packages.map(({ pkg, kinds, at, kv, traces }) => ({ pkg, kinds, ...at, - weights: sprite(weights), kv: sprite(kv), traces: sprite(traces), })), diff --git a/desktop-app/src/renderer/features/home/chip/photoreal/layoutFit.ts b/desktop-app/src/renderer/features/home/chip/photoreal/layoutFit.ts index a924395810..1cb62ce53c 100644 --- a/desktop-app/src/renderer/features/home/chip/photoreal/layoutFit.ts +++ b/desktop-app/src/renderer/features/home/chip/photoreal/layoutFit.ts @@ -29,7 +29,6 @@ export function fitLayout(layout: ChipLayout, scale: number): ChipLayout { from: point(trace.from), to: point(trace.to), })), - io: { ...layout.io, path: layout.io.path.map(point) }, dispatch: point(layout.dispatch), }; } diff --git a/desktop-app/src/renderer/features/home/chip/photoreal/memoryLight.ts b/desktop-app/src/renderer/features/home/chip/photoreal/memoryLight.ts index 17d6bedd30..852d336c4b 100644 --- a/desktop-app/src/renderer/features/home/chip/photoreal/memoryLight.ts +++ b/desktop-app/src/renderer/features/home/chip/photoreal/memoryLight.ts @@ -1,3 +1,4 @@ +import { modelColor, crossMemory } from '../memoryStyle'; import { inset, type Rect } from '../geometry'; import type { MemoryPackage } from '../layout'; import { rgba } from '../palette'; @@ -77,22 +78,19 @@ export function paintMemory( const { emissive, kit, scene, glow } = built, power = frame.workload.power, dark = scene.palette.dark, - bus = interfaceLevel(frame) * power, - otherAlpha = dark ? 0.1 : 0.08; + bus = interfaceLevel(frame) * power; let cells: CellLight[] = []; for (const light of emissive.memory) { const n = light.pkg.cells.length; if (cells.length !== n) cells = Array.from({ length: n }, (_, i) => memoryCell(i / n, 1 / n, scene.memory, frame)); drawSprite(ctx, light.traces, bus * 0.3); - const resident = cells.find((cell) => cell.kind === 'weights')?.weights ?? 0; - drawSprite(ctx, light.weights, resident * power * (dark ? 0.4 : 0.36), light.x, light.y); paintKv(ctx, light, cells, kit, power * (dark ? 0.95 : 0.9)); cells.forEach((cell, i) => { - if (cell.other > 0.01) { - ctx.globalAlpha = 1; - ctx.fillStyle = rgba(glow.neutral, cell.other * otherAlpha); - const r = light.pkg.cells[i]; + const r = light.pkg.cells[i]; + if (cell.other > 0.01) crossMemory(ctx, r, glow.neutral, cell.other); + if (cell.kind === 'weights') { + ctx.fillStyle = rgba(modelColor(cell.model), cell.weights * (dark ? 0.65 : 0.55)); ctx.fillRect(r.x, r.y, r.w, r.h); } if (cell.sweep < 0.02) return; diff --git a/desktop-app/src/renderer/features/home/chip/photoreal/paintLight.ts b/desktop-app/src/renderer/features/home/chip/photoreal/paintLight.ts index 736f85d3ba..0c377aeab9 100644 --- a/desktop-app/src/renderer/features/home/chip/photoreal/paintLight.ts +++ b/desktop-app/src/renderer/features/home/chip/photoreal/paintLight.ts @@ -1,22 +1,15 @@ -import { smoothstep } from '../geometry'; -import { rgba } from '../palette'; import { - cacheLevel, cpuLevel, foreignGpu, gpuGlow, gpuLevel, gpuShare, interfaceLevel, - ioPulse, - neuralLevel, } from '../render/activity'; -import { along } from '../render/canvas'; import type { RenderFrame } from '../render/types'; import { drawSprite } from './atlas'; import { paintComets } from './comets'; -import { drawAround, drawBlob } from './lightKit'; -import { hot } from './materials'; +import { drawBlob } from './lightKit'; import { paintMemory } from './memoryLight'; import type { PhotorealScene } from './scene'; @@ -46,30 +39,6 @@ function paintSpill(ctx: CanvasRenderingContext2D, built: PhotorealScene, frame: ctx.restore(); } -/** A request entering through the I/O pad, racing to the I/O block, which flares as it lands. */ -function paintArrival(ctx: CanvasRenderingContext2D, built: PhotorealScene, frame: RenderFrame) { - const pulse = ioPulse(frame); - if (!pulse || pulse.strength < 0.01) return; - const { scene, kit, glow, emissive } = built, - unit = scene.layout.unit, - [port, end] = scene.layout.io.path, - head = along(port, end, pulse.at), - tail = along(port, end, Math.max(0, pulse.at - 0.5)); - const streak = ctx.createLinearGradient(tail.x, tail.y, head.x, head.y); - streak.addColorStop(0, rgba(glow.accent, 0)); - streak.addColorStop(1, rgba(hot(glow.accent, 0.4), 0.95)); - ctx.globalAlpha = Math.min(1, pulse.strength); - ctx.strokeStyle = streak; - ctx.lineWidth = Math.max(1.2, unit * 0.006); - ctx.lineCap = 'round'; - ctx.beginPath(); - ctx.moveTo(tail.x, tail.y); - ctx.lineTo(head.x, head.y); - ctx.stroke(); - drawAround(ctx, kit.blob.accent, { ...head, w: 0, h: 0 }, unit * 0.045, pulse.strength); - drawSprite(ctx, emissive.io, pulse.strength * smoothstep(0.55, 1, pulse.at)); -} - /** The frame's light pass, composited additively over the static layer. */ export function paintLight( ctx: CanvasRenderingContext2D, @@ -94,16 +63,11 @@ export function paintLight( } for (const light of emissive.cpu) drawSprite(ctx, light.sprite, cpuLevel(light.tile, frame) * power, light.x, light.y); - const cache = cacheLevel(frame) * power; - for (const light of emissive.slc) drawSprite(ctx, light.sprite, cache, light.x, light.y); - const neural = neuralLevel(frame); - for (const light of emissive.neural) drawSprite(ctx, light.sprite, neural, light.x, light.y); const phy = interfaceLevel(frame) * power; for (const sprite of emissive.phy) drawSprite(ctx, sprite, phy); drawSprite(ctx, emissive.bridge, Math.max(w.prefill, w.decode * 0.6) * 0.8 * power); paintMemory(ctx, built, frame); paintComets(ctx, built, frame); - paintArrival(ctx, built, frame); ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'; } diff --git a/desktop-app/src/renderer/features/home/chip/photoreal/paintSilicon.ts b/desktop-app/src/renderer/features/home/chip/photoreal/paintSilicon.ts index 7cfc4ac689..0391ddda8b 100644 --- a/desktop-app/src/renderer/features/home/chip/photoreal/paintSilicon.ts +++ b/desktop-app/src/renderer/features/home/chip/photoreal/paintSilicon.ts @@ -3,7 +3,7 @@ import type { Block, Tile } from '../layout'; import { css, mix, rgba } from '../palette'; import { noise } from '../random'; import { longAxis, snap, texture, type Brush } from './brush'; -import { bandParts, engineParts, tileParts, type Part, type PartRole } from './dieParts'; +import { bandParts, tileParts, type Part, type PartRole } from './dieParts'; import type { Silicon } from './materials'; import type { Textures } from './textures'; @@ -56,8 +56,8 @@ export function paintTile(brush: Brush, tile: Tile) { texture(brush, tile, tex.logic, 0.3); for (const part of tileParts(tile)) paintPart(brush, part, anchor); const variation = (noise(tile.x * 0.173 + tile.y * 0.311 + tile.die * 7.7) - 0.5) * 0.07; - // Binned cores and the idle Neural Engine read slightly darker than powered logic. - const dim = tile.filler ? 0.22 : tile.kind === 'neural' ? 0.1 : 0; + // Binned cores read slightly darker than powered logic. + const dim = tile.filler ? 0.22 : 0; shade(brush, tile, variation - dim); outline(brush, tile, 'rgba(0,0,0,0.3)'); } @@ -65,11 +65,6 @@ export function paintTile(brush: Brush, tile: Tile) { export function paintBlock(brush: Brush, block: Block) { if (block.kind === 'interface') return paintPhy(brush, block); for (const part of bandParts(block)) paintPart(brush, part); - if (block.kind === 'media' || block.kind === 'display' || block.kind === 'io') { - for (const part of engineParts(block)) paintPart(brush, part); - outline(brush, block, 'rgba(0,0,0,0.4)'); - return; - } shade(brush, block.body, -0.1); } diff --git a/desktop-app/src/renderer/features/home/chip/photoreal/paintSubstrate.ts b/desktop-app/src/renderer/features/home/chip/photoreal/paintSubstrate.ts index 7066b1ec85..e22d22da67 100644 --- a/desktop-app/src/renderer/features/home/chip/photoreal/paintSubstrate.ts +++ b/desktop-app/src/renderer/features/home/chip/photoreal/paintSubstrate.ts @@ -6,7 +6,7 @@ import { texture, type Brush } from './brush'; export const substrateRadius = (unit: number) => unit * 0.034; -/** Solder-mask substrate: copper under the mask, vias, gold edge ring, marks and the I/O pad. */ +/** Solder-mask substrate: copper under the mask, vias, gold edge ring, and marks. */ export function paintSubstrate(brush: Brush, layout: ChipLayout, vias: Point[]) { const { ctx, mats, unit, tex } = brush, s = layout.substrate, @@ -38,7 +38,6 @@ export function paintSubstrate(brush: Brush, layout: ChipLayout, vias: Point[]) ctx.restore(); paintRing(brush, s, radius); paintMarks(brush, s); - paintPort(brush, layout); paintEdge(brush, s, radius); } @@ -51,27 +50,19 @@ const dot = (path: Path2D, p: Point, r: number) => { function paintCopper(brush: Brush, layout: ChipLayout) { const { ctx, mats, unit } = brush, traces = new Path2D(), - pads = new Path2D(), - io = new Path2D(), - [port, end] = layout.io.path; + pads = new Path2D(); for (const { from, to } of layout.traces) { traces.moveTo(from.x, from.y); traces.lineTo(to.x, to.y); dot(pads, from, Math.max(0.8, unit * 0.0045)); } - io.moveTo(port.x, port.y); - io.lineTo(end.x, end.y); ctx.lineCap = 'round'; ctx.strokeStyle = rgba(mix(mats.copper, mats.mask, 0.6), 0.85); ctx.lineWidth = Math.max(1, unit * 0.0062); ctx.stroke(traces); - ctx.lineWidth = Math.max(1.4, unit * 0.012); - ctx.stroke(io); ctx.strokeStyle = rgba(mats.copper, mats.dark ? 0.3 : 0.36); ctx.lineWidth = Math.max(0.5, unit * 0.0024); ctx.stroke(traces); - ctx.lineWidth = Math.max(0.6, unit * 0.004); - ctx.stroke(io); ctx.fillStyle = rgba(mats.copper, 0.28); ctx.fill(pads); } @@ -153,24 +144,6 @@ function paintMarks(brush: Brush, s: Rect) { ctx.fill(); } -/** Gold contact where requests enter, just inside the edge ring. */ -function paintPort(brush: Brush, layout: ChipLayout) { - const { ctx, mats, unit } = brush, - [port, end] = layout.io.path, - across = layout.io.side === 'left' || layout.io.side === 'right', - w = unit * (across ? 0.028 : 0.07), - h = unit * (across ? 0.07 : 0.028), - x = port.x + Math.sign(end.x - port.x) * unit * 0.05, - y = port.y + Math.sign(end.y - port.y) * unit * 0.05, - pad = { x: x - w / 2, y: y - h / 2, w, h }; - roundRect(ctx, inset(pad, -1.5), unit * 0.006); - ctx.fillStyle = 'rgba(0,0,0,0.4)'; - ctx.fill(); - roundRect(ctx, pad, unit * 0.005); - ctx.fillStyle = goldFill(ctx, pad, mats.gold); - ctx.fill(); -} - /** The cut laminate edge, and the rim or key light catching the lit edges. */ function paintEdge(brush: Brush, s: Rect, radius: number) { const { ctx, mats, unit } = brush; diff --git a/desktop-app/src/renderer/features/home/chip/photoreal/substrateLayout.ts b/desktop-app/src/renderer/features/home/chip/photoreal/substrateLayout.ts index 8f83c3c875..6038776ffa 100644 --- a/desktop-app/src/renderer/features/home/chip/photoreal/substrateLayout.ts +++ b/desktop-app/src/renderer/features/home/chip/photoreal/substrateLayout.ts @@ -12,16 +12,6 @@ const CAP = { length: 0.032, width: 0.017, pitch: 0.031, standoff: 0.02 }; const SIDES: Side[] = ['top', 'bottom', 'left', 'right']; const inside = (r: Rect, p: Point) => p.x > r.x && p.x < r.x + r.w && p.y > r.y && p.y < r.y + r.h; -export function ioCorridor(layout: ChipLayout, half: number): Rect { - const [a, b] = layout.io.path; - return { - x: Math.min(a.x, b.x) - half, - y: Math.min(a.y, b.y) - half, - w: Math.abs(a.x - b.x) + half * 2, - h: Math.abs(a.y - b.y) + half * 2, - }; -} - /** Whether `other` lies beyond `side` of `r` and overlaps it along that edge. */ function beyond(r: Rect, other: Rect, side: Side) { const spanX = Math.min(r.x + r.w, other.x + other.w) > Math.max(r.x, other.x), @@ -109,7 +99,6 @@ export function capacitorLayout(layout: ChipLayout): Capacitor[] { keepOut = [ ...layout.dies.map((die) => inset(die, -unit * 0.01)), ...layout.memory.map((pkg) => inset(pkg, -unit * 0.006)), - ioCorridor(layout, unit * 0.03), ...(layout.bridge ? [layout.bridge] : []), ]; return caps.filter((cap) => contains(room, cap) && !keepOut.some((r) => overlaps(r, cap))); @@ -132,7 +121,6 @@ export function viaLayout(layout: ChipLayout, caps: Rect[]): Point[] { ...layout.dies.map((die) => inset(die, -unit * 0.03)), ...layout.memory.map((pkg) => inset(pkg, -unit * 0.022)), ...caps.map((cap) => inset(cap, -unit * 0.01)), - ioCorridor(layout, unit * 0.03), ...fields, ]; const vias: Point[] = []; diff --git a/desktop-app/src/renderer/features/home/chip/render/activity.ts b/desktop-app/src/renderer/features/home/chip/render/activity.ts index 92f2122d52..aac717dffe 100644 --- a/desktop-app/src/renderer/features/home/chip/render/activity.ts +++ b/desktop-app/src/renderer/features/home/chip/render/activity.ts @@ -44,9 +44,13 @@ function simulatedGpu(tile: Tile, w: WorkloadFrame, motion: boolean) { /** * GPU core light split into its prefill and decode shares. Measured, all cores share one - * intensity, with a shimmer outward from the dispatch point that quickens with the clock. + * intensity. Only synthetic previews add sweeps and shimmer. */ export function gpuLevel(tile: Tile, f: RenderFrame) { + if (f.workload.mode !== 'synthetic') { + const hw = f.hardware; + return { prefill: 0, decode: hw ? hw.weight * hw.gpu.known * hw.gpu.value : 0 }; + } const sim = simulatedGpu(tile, f.workload, f.motion), hw = f.hardware; if (!hw) return sim; @@ -62,7 +66,10 @@ export function gpuLevel(tile: Tile, f: RenderFrame) { } /** Darkbloom's share of the GPU light; the rest is drawn neutral. */ -export const gpuShare = (f: RenderFrame) => measured(f, 1, f.hardware?.share); +export const gpuShare = (f: RenderFrame) => + f.workload.mode === 'synthetic' + ? measured(f, 1, f.hardware?.share) + : measured(f, 0, f.hardware?.share); /** Measured GPU busy time that belongs to other apps. */ export const foreignGpu = (f: RenderFrame) => { @@ -86,27 +93,19 @@ export function cpuLevel(tile: Tile, f: RenderFrame) { const flicker = motion ? 0.85 + 0.15 * Math.sin(w.time * 9 + tile.index * 2.1) : 1; sim = w.cpu * (chosen ? 1 : 0.22) * flicker; } - if (!hw) return sim; + if (!hw) return w.mode === 'synthetic' ? sim : 0; const level = tile.kind === 'l2' ? hw.clusters[tile.cluster ?? -1] : (tile.cpu ?? -1) >= 0 ? hw.cpu[tile.cpu!] : hw.cpuBusy; - return measured(f, sim, level); + return measured(f, w.mode === 'synthetic' ? sim : 0, level); } -/** System-level cache banks: the conduit memory traffic flows through, not cache hits. */ -export const cacheLevel = ({ workload: w, motion }: RenderFrame) => - w.memoryRead * (0.42 + 0.3 * stepPulse(w, motion)); - export const interfaceLevel = ({ workload: w, motion }: RenderFrame) => clamp(w.memoryRead * (0.55 + 0.45 * stepPulse(w, motion)) + w.kvWrite * 0.3); -/** Dark unless something actually runs on the Neural Engine; Darkbloom never does. */ -export const neuralLevel = ({ hardware: hw }: RenderFrame) => - hw ? hw.weight * hw.ane.known * hw.ane.value : 0; - export interface CellLight { kind: MemoryKind; /** Loaded-model index for weight cells; -1 otherwise. */ @@ -138,11 +137,12 @@ export function memoryCell( : 0; const sweepAt = w.stepPhase * 1.25 - 0.12; if (segment.kind === 'weights') { - const breathe = motion ? 0.5 + 0.5 * Math.sin(w.time * 1.4) : 0.5; - const sweep = motion - ? (w.decodeByModel[segment.model] ?? w.decode) * - Math.exp(-((local + localSpan / 2 - sweepAt) ** 2) / 0.006) - : 0; + const breathe = motion && w.mode === 'synthetic' ? 0.5 + 0.5 * Math.sin(w.time * 1.4) : 0.5; + const sweep = + motion && w.mode === 'synthetic' + ? (w.decodeByModel[segment.model] ?? w.decode) * + Math.exp(-((local + localSpan / 2 - sweepAt) ** 2) / 0.006) + : 0; return { kind: 'weights', model: segment.model, @@ -153,13 +153,20 @@ export function memoryCell( }; } if (segment.kind === 'kv') { - const kv = clamp((w.kvFill - local) / localSpan), + const kv = clamp((w.kvFill - local) / localSpan) * (1 - other), frontier = Math.exp(-((local - w.kvFill) ** 2) / 0.003) * clamp(w.kvWrite * 1.4); const read = - motion && kv > 0 && w.kvFill > 0 + motion && w.mode === 'synthetic' && kv > 0 && w.kvFill > 0 ? w.decode * 0.6 * Math.exp(-((local / w.kvFill - sweepAt) ** 2) / 0.01) : 0; - return { kind: 'kv', model: -1, weights: 0, kv, sweep: Math.max(frontier, read), other }; + return { + kind: 'kv', + model: -1, + weights: 0, + kv, + sweep: Math.max(frontier, read) * (1 - other), + other, + }; } return { kind: 'reserved', model: -1, weights: 0, kv: 0, sweep: 0, other }; } @@ -172,7 +179,7 @@ export interface Pulse { } /** Reads stream from memory toward the die in step with decode; KV writes flow back. */ export function tracePulses(trace: Trace, { workload: w, motion }: RenderFrame): Pulse[] { - if (!motion) return []; + if (!motion || w.mode !== 'synthetic') return []; const seed = noise(trace.package * 17.3 + trace.lane * 3.1), pulses: Pulse[] = []; if (w.memoryRead > 0.04) { @@ -193,10 +200,3 @@ export function tracePulses(trace: Trace, { workload: w, motion }: RenderFrame): }); return pulses; } - -/** A request entering through the network/I/O block; null once it has arrived. */ -export function ioPulse({ workload: w, motion }: RenderFrame) { - const at = w.sinceArrival / 0.4; - if (!motion || at < 0 || at > 1.3) return null; - return { at: Math.min(1, at), strength: w.power * (1 - smoothstep(1, 1.3, at)) }; -} diff --git a/desktop-app/src/renderer/features/home/chip/render/types.ts b/desktop-app/src/renderer/features/home/chip/render/types.ts index a3dac53e85..4f245c9c52 100644 --- a/desktop-app/src/renderer/features/home/chip/render/types.ts +++ b/desktop-app/src/renderer/features/home/chip/render/types.ts @@ -16,9 +16,9 @@ export interface ChipScene { dpr: number; } export interface RenderFrame { - /** The simulation with measured load already overlaid where it is live. */ + /** Live allocations and counts, or an explicit synthetic preview. */ workload: WorkloadFrame; - /** Eased measurements for parts the workload cannot express, or null while simulated. */ + /** Fresh eased hardware measurements, or null when unavailable. */ hardware: HardwareLight | null; /** False under prefers-reduced-motion: draw steady levels, no sweeps, pulses or shimmer. */ motion: boolean; diff --git a/desktop-app/src/renderer/features/home/chip/stageText.ts b/desktop-app/src/renderer/features/home/chip/stageText.ts index 1ea29b5c75..1cbec764a6 100644 --- a/desktop-app/src/renderer/features/home/chip/stageText.ts +++ b/desktop-app/src/renderer/features/home/chip/stageText.ts @@ -9,12 +9,18 @@ import { providerUp, type LiveReading } from './workload/live'; const MODELS_SHOWN = 2; -/** What drives the drawing: fresh measurements from this Mac, or the simulation. */ -function modeText(provider: Snapshot['state'], measured: boolean) { +/** What drives the drawing: fresh measurements from this Mac, or an explicit development preview. */ +function modeText( + provider: Snapshot['state'], + measured: boolean, + preview: boolean, + fresh: boolean, +) { if (measured) return 'Live from this Mac'; if (provider === 'stopped') return 'Provider stopped'; if (provider === 'starting') return 'Provider starting'; - return 'Simulated activity'; + if (preview) return 'Simulated activity'; + return fresh ? 'Live from this Mac' : 'Waiting for live activity'; } /** @@ -53,15 +59,15 @@ export function stageText({ const machine = measured ? ` GPU ${measured.gpu} busy.` : ''; const summary = !powered ? `${anatomy.name}: provider ${provider === 'starting' ? 'starting' : 'stopped'}.${machine}` - : `${anatomy.name}: ${PHASE_TEXT[stats.phase].toLowerCase()}. ${ + : `${anatomy.name}: ${preview ? PHASE_TEXT[stats.phase].toLowerCase() : 'live activity'}. ${ running === null - ? 'Waiting for current activity.' + ? '' : `${running} in progress, ${waiting} waiting, about ${ Math.round((tokensPerSecond ?? 0) / 10) * 10 } tokens per second.` }${machine}`; return { - mode: modeText(provider, measured !== null), + mode: modeText(provider, measured !== null, preview, reading.fresh), measured: measured !== null, current: shown, tokensPerSecond, diff --git a/desktop-app/src/renderer/features/home/chip/workload/measured.ts b/desktop-app/src/renderer/features/home/chip/workload/measured.ts new file mode 100644 index 0000000000..d076f1bb56 --- /dev/null +++ b/desktop-app/src/renderer/features/home/chip/workload/measured.ts @@ -0,0 +1,38 @@ +import type { MemoryMap } from '../memoryMap'; +import { clamp } from '../geometry'; +import type { LiveReading } from './live'; +import type { WorkloadFrame } from './types'; + +/** Live allocation and request counts. No sampled sequences, request phases or traffic. */ +export function measuredFrame( + reading: LiveReading, + memory: MemoryMap, + providerGb: number | null, +): WorkloadFrame { + const weightsEnd = memory.segments.find((segment) => segment.kind === 'kv')?.from ?? 0; + const kvEnd = memory.segments.find((segment) => segment.kind === 'kv')?.to ?? weightsEnd; + const used = providerGb === null || memory.totalGb <= 0 ? null : providerGb / memory.totalGb; + return { + time: 0, + mode: reading.inputs.mode, + phase: reading.inputs.mode === 'stopped' ? 'stopped' : 'ready', + power: 1, + resident: memory.models.length ? 1 : 0, + prefill: 0, + decode: 0, + decodeByModel: [], + memoryRead: 0, + kvFill: + used === null || kvEnd <= weightsEnd ? 0 : clamp((used - weightsEnd) / (kvEnd - weightsEnd)), + kvWrite: 0, + cpu: 0, + tokensPerSecond: reading.fresh ? reading.inputs.tokensPerSecond : 0, + running: reading.fresh ? reading.inputs.running : 0, + waiting: reading.fresh ? reading.inputs.waiting : 0, + stepPhase: 0, + steps: 0, + sinceArrival: 0, + sincePrefill: 0, + sinceFlood: 0, + }; +} diff --git a/desktop-app/src/renderer/features/home/contribution.ts b/desktop-app/src/renderer/features/home/contribution.ts new file mode 100644 index 0000000000..a36fef8120 --- /dev/null +++ b/desktop-app/src/renderer/features/home/contribution.ts @@ -0,0 +1,31 @@ +import type { Snapshot } from '../../../shared/contracts'; +import { count, money } from '../../format'; + +const integer = (value: string | null | undefined) => + value != null && /^\d+$/.test(value) ? BigInt(value) : null; + +/** Cached input is part of input; reasoning is part of output. Neither is added twice. */ +export function contribution(activity: Snapshot['activity']) { + const output = integer(activity.processed_output_tokens ?? activity.tokens); + const input = integer(activity.processed_input_tokens ?? activity.prompt_tokens); + const verified = integer(activity.processed_tokens); + const gaps = (integer(activity.usage_gaps) ?? 0n) > 0n; + const total = verified ?? (input !== null && output !== null && !gaps ? input + output : null); + const pending = integer(activity.pending_usage_requests); + return { + tokens: count(total), + label: 'Tokens processed this session', + input: count(input), + output: count(output), + cached: count(integer(activity.cached_input_tokens)), + reasoning: count(integer(activity.reasoning_tokens)), + pending: pending !== null && pending > 0n ? count(pending) : null, + note: + total === null + ? 'Waiting for complete input and output usage' + : activity.usage_source === 'settled-history' + ? 'Confirmed input + output from this Mac’s session history; updates after settlement' + : 'Input + output, including cached input and reasoning', + earnings: money(activity.earnings_micro_usd ?? undefined, 4), + }; +} diff --git a/desktop-app/src/renderer/features/home/fleet.module.css b/desktop-app/src/renderer/features/home/fleet.module.css index 8aebd286db..c601771e91 100644 --- a/desktop-app/src/renderer/features/home/fleet.module.css +++ b/desktop-app/src/renderer/features/home/fleet.module.css @@ -8,11 +8,6 @@ font-size: 22px; letter-spacing: -0.5px; } -.heading p { - margin-top: 8px; - font-size: 12px; - color: var(--muted); -} .earnings { padding: 24px; border-radius: 12px; @@ -71,7 +66,7 @@ margin-top: 16px; } .emptyChart { - padding: 24px 0; + padding: 8px 0; } .listHeading { margin-bottom: 18px; diff --git a/desktop-app/src/renderer/features/home/home.module.css b/desktop-app/src/renderer/features/home/home.module.css index 51f7e75bef..4aa63c5bce 100644 --- a/desktop-app/src/renderer/features/home/home.module.css +++ b/desktop-app/src/renderer/features/home/home.module.css @@ -8,12 +8,28 @@ .dashboard > header h1 { font-size: 28px; } -.dashboard > header p { - font-size: 12px; - margin-top: 8px; -} .contribution { padding: 4px 0 0; + display: flex; + justify-content: space-between; + align-items: flex-end; + gap: 24px; +} +.generated { + text-align: right; + padding-bottom: 2px; +} +.generated strong { + display: block; + font-size: 27px; + font-weight: 500; + font-variant-numeric: tabular-nums; +} +.generated span { + display: block; + font-size: 11px; + color: var(--muted); + margin-top: 5px; } .shared > span { display: block; @@ -51,7 +67,7 @@ .activity { display: flex; flex-direction: column; - height: clamp(440px, 54vh, 640px); + height: auto; min-width: 0; } .activity > * { @@ -101,3 +117,17 @@ font-size: 46px; } } + +.tokenBreakdown { + display: flex; + flex-wrap: wrap; + gap: 6px 18px; + margin: 8px 0; + color: var(--muted); + font-size: 11px; +} +.tokenBreakdown b { + font-weight: 500; + color: var(--text-primary); + font-variant-numeric: tabular-nums; +} diff --git a/desktop-app/src/renderer/features/home/milestone.module.css b/desktop-app/src/renderer/features/home/milestone.module.css index 6ec58611d7..080231ed2c 100644 --- a/desktop-app/src/renderer/features/home/milestone.module.css +++ b/desktop-app/src/renderer/features/home/milestone.module.css @@ -53,10 +53,6 @@ font-size: 11px; color: var(--text-secondary); } -.goalLabel small { - font-size: 10px; - color: var(--muted); -} .cells { display: grid; grid-template-columns: repeat(24, 1fr); diff --git a/desktop-app/src/renderer/features/insights/EarningsBreakdown.tsx b/desktop-app/src/renderer/features/insights/EarningsBreakdown.tsx index f89b30372d..fc58a55b5f 100644 --- a/desktop-app/src/renderer/features/insights/EarningsBreakdown.tsx +++ b/desktop-app/src/renderer/features/insights/EarningsBreakdown.tsx @@ -6,6 +6,7 @@ import { metricLabel, metricValue, type InsightMetric } from './EarningsTimeline import styles from './insights.module.css'; function rowLabel(row: InsightSlice, dimension: 'models' | 'machines') { + if (dimension === 'machines' && row.id === 'this-mac') return 'This Mac'; if (dimension === 'models') return row.id === 'base_reward' ? 'Base rewards' diff --git a/desktop-app/src/renderer/features/insights/EarningsTimeline.tsx b/desktop-app/src/renderer/features/insights/EarningsTimeline.tsx index 10febed5ce..92e5014b04 100644 --- a/desktop-app/src/renderer/features/insights/EarningsTimeline.tsx +++ b/desktop-app/src/renderer/features/insights/EarningsTimeline.tsx @@ -15,14 +15,18 @@ export const metricLabel = (value: bigint, metric: InsightMetric) => export function EarningsTimeline({ days, metric, + partial = false, }: { days: InsightSlice[]; metric: InsightMetric; + partial?: boolean; }) { const [selectedID, setSelectedID] = useState(null); const detailID = useId(); const selected = days.find((day) => day.id === selectedID) ?? days.at(-1); - const max = maximum(days.map((day) => metricValue(day, metric))); + const max = maximum( + days.filter((day) => day.available !== false).map((day) => metricValue(day, metric)), + ); return (
@@ -32,7 +36,8 @@ export function EarningsTimeline({
{days.map((day, index) => { - const value = metricValue(day, metric); + const available = day.available !== false; + const value = available ? metricValue(day, metric) : 0n; const base = metric === 'earnings' ? day.base_reward_micro_usd : 0n; return (
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/insights.module.css b/desktop-app/src/renderer/features/insights/insights.module.css index a85c4bc5e8..bcc60daade 100644 --- a/desktop-app/src/renderer/features/insights/insights.module.css +++ b/desktop-app/src/renderer/features/insights/insights.module.css @@ -555,3 +555,8 @@ color: var(--accent-brand); background: var(--bg-secondary); } + +.barButton[data-unavailable='true'] { + background: repeating-linear-gradient(135deg, transparent 0 5px, var(--line) 5px 6px); + opacity: 0.45; +} diff --git a/desktop-app/src/renderer/features/insights/types.ts b/desktop-app/src/renderer/features/insights/types.ts index 5c54227e4b..4f09f3c59a 100644 --- a/desktop-app/src/renderer/features/insights/types.ts +++ b/desktop-app/src/renderer/features/insights/types.ts @@ -9,17 +9,20 @@ export interface InsightAmounts { } export interface InsightSlice extends InsightAmounts { id: string; + available?: boolean; + complete?: boolean; } export interface ProviderInsights { account_id: string; window: '7d' | '30d'; + history_complete: boolean; since: string; as_of: string; lifetime: { count: bigint; total_micro_usd: bigint; - prompt_tokens: bigint; - completion_tokens: bigint; + prompt_tokens: bigint | null; + completion_tokens: bigint | null; }; totals: InsightAmounts; days: InsightSlice[]; @@ -45,6 +48,7 @@ export function parseInsights(value: any): ProviderInsights { !value || typeof value.account_id !== 'string' || !['7d', '30d'].includes(value.window) || + (value.history_complete !== undefined && typeof value.history_complete !== 'boolean') || !Number.isFinite(Date.parse(value.as_of)) ) throw new Error('Invalid earnings snapshot'); @@ -52,19 +56,30 @@ export function parseInsights(value: any): ProviderInsights { if (!Array.isArray(data)) throw new Error('Invalid earnings breakdown'); return data.map((row) => { if (typeof row.id !== 'string') throw new Error('Invalid earnings row'); - return { id: row.id, ...amounts(row) }; + if ( + [row.available, row.complete].some( + (flag) => flag !== undefined && typeof flag !== 'boolean', + ) + ) + throw new Error('Invalid earnings coverage'); + return { id: row.id, ...amounts(row), available: row.available, complete: row.complete }; }); }; return { account_id: value.account_id, window: value.window, + history_complete: value.history_complete !== false, since: value.since, as_of: value.as_of, lifetime: { count: integer(value.lifetime.count), total_micro_usd: integer(value.lifetime.total_micro_usd), - prompt_tokens: integer(value.lifetime.prompt_tokens), - completion_tokens: integer(value.lifetime.completion_tokens), + prompt_tokens: + value.lifetime.prompt_tokens === null ? null : integer(value.lifetime.prompt_tokens), + completion_tokens: + value.lifetime.completion_tokens === null + ? null + : integer(value.lifetime.completion_tokens), }, totals: amounts(value.totals), days: rows(value.days), diff --git a/desktop-app/src/renderer/features/insights/useInsights.ts b/desktop-app/src/renderer/features/insights/useInsights.ts index 6c98b8cbc7..dbcdf52323 100644 --- a/desktop-app/src/renderer/features/insights/useInsights.ts +++ b/desktop-app/src/renderer/features/insights/useInsights.ts @@ -4,7 +4,7 @@ import { api } from '../../useBackend'; import { parseInsights, type ProviderInsights } from './types'; export function useInsights(state: Snapshot, window: '7d' | '30d' = '7d') { - const key = state.linked + const key = (state.account ? state.account.signed_in || state.account.legacy_data : state.linked) ? `${state.installation_id}:${state.account_revision || 'legacy'}:${window}` : ''; const [snapshot, setSnapshot] = useState<{ @@ -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; @@ -39,19 +39,15 @@ export function useInsights(state: Snapshot, window: '7d' | '30d' = '7d') { const current = { key, alive: true, busy: false }; session.current = current; void refresh(); - const timer = setInterval(() => { - if (!document.hidden) void refresh(); - }, 30_000); const visible = () => { if (!document.hidden) void refresh(); }; document.addEventListener('visibilitychange', visible); return () => { current.alive = false; - clearInterval(timer); document.removeEventListener('visibilitychange', visible); if (session.current === current) session.current = null; }; - }, [key, refresh]); + }, [key, refresh, state.resource_revision]); return snapshot.key === key ? { ...snapshot, refresh } : { data: null, error: null, refresh }; } 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.'}