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

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

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

+ You’re signed in. +

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

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

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

+ {backend.error} +

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

+ Getting a connection code… +

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

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

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

+ Waiting for approval +

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

+ {error} +

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

Ready to serve.

-

{text.lead}

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

{text.lead}

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

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

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

Your Mac. Your endpoint.

-

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

+

Run models through an OpenAI-compatible API.

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

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

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