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() { <>
+ {email ? ( + <> + {email}Signed in + > + ) : ( + 'You’re signed in to Darkbloom.' + )} +
+
+
+ {operation?.state === 'cancelled' ? 'Sign-in cancelled.' : 'Could not complete sign-in.'} +
+ {operation?.state === 'failed' && ( +{operation.message}
+ + {backend.error} +
+ )} + +
+
+ {browserOpened + ? 'Approve the connection in your browser.' + : 'Enter this code in your browser.'} +
+
+
+ {error} +
+ )} + +{text.lead}
-{text.lead}
+- {error} Showing the last observation. + {error} Showing previously loaded earnings.
)}OpenAI-compatible inference, backed by the same Swift runtime.
+Run models through an OpenAI-compatible API.
- Output tokens generated on this Mac each hour. Blank hours have no observations, because - the provider wasn’t running or the runtime wasn’t reporting; they aren’t counted as zero. + Output tokens generated per hour. Blank hours have no data.
)} diff --git a/desktop-app/src/renderer/features/machines/overview/readiness.ts b/desktop-app/src/renderer/features/machines/overview/readiness.ts index d4005625ed..0bbeea320f 100644 --- a/desktop-app/src/renderer/features/machines/overview/readiness.ts +++ b/desktop-app/src/renderer/features/machines/overview/readiness.ts @@ -1,12 +1,6 @@ -import type { - Action, - DesktopStatus, - NativeModel, - Operation, - Route, - Snapshot, -} from '../../../../shared/contracts'; -import { modelName } from '../../../models/facts'; +import type { Action, DesktopStatus, Route, Snapshot } from '../../../../shared/contracts'; +import { operationLabel } from '../../../components/operations/labels'; +import { runtimeStep, operationStep, updateStep, linkStep, providerStep } from './readinessSteps'; export type ReadinessTone = 'ready' | 'pending' | 'blocked'; export type StepAction = @@ -22,6 +16,7 @@ export interface ReadinessStep { } export interface Readiness { tone: ReadinessTone; + status: string; summary: string; steps: ReadinessStep[]; } @@ -32,179 +27,6 @@ export interface ReadinessFacts { } const lifecycle: Action['action'][] = ['start', 'switch', 'stop', 'restart', 'update']; -const chooseModels: StepAction = { kind: 'route', route: 'models', label: 'Choose models' }; -const restart: StepAction = { - kind: 'act', - action: { action: 'restart' }, - label: 'Restart provider', -}; - -function modelList(names: string[]) { - return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0] || ''; -} -const displayNames = (models: NativeModel[]) => - modelList(models.map((model) => model.display_name)); -const isAre = (count: number) => (count === 1 ? 'is' : 'are'); - -function runtimeStep(status: DesktopStatus): ReadinessStep { - if (status.state === 'connecting' || status.state === 'installing') - return { - id: 'runtime', - title: - status.state === 'installing' ? 'Installing the runtime' : 'Reconnecting to the runtime', - detail: - status.state === 'installing' - ? 'This can take a few minutes.' - : 'The app reconnects automatically.', - actions: [], - }; - const missing = status.state === 'missing'; - return { - id: 'runtime', - title: missing ? 'Install the Darkbloom runtime' : 'Repair the Darkbloom runtime', - detail: status.message || 'The app can’t reach the runtime on this Mac.', - actions: [{ kind: 'install', label: missing ? 'Install runtime' : 'Repair runtime' }], - }; -} - -const operationStep = (operation: Operation): ReadinessStep => ({ - id: 'operation', - title: `${operation.action.charAt(0).toUpperCase()}${operation.action.slice(1)} in progress`, - detail: 'Wait for it to finish.', - actions: [], -}); - -function updateStep(available: boolean): ReadinessStep { - return { - id: 'update', - title: 'Update Darkbloom', - detail: available - ? 'This version can no longer receive network requests.' - : 'This version can no longer receive network requests, and a compatible update isn’t available yet.', - actions: available ? [{ kind: 'act', action: { action: 'update' }, label: 'Update now' }] : [], - }; -} - -function startStep(startable: NativeModel[]): ReadinessStep { - return startable.length - ? { - id: 'start', - title: 'Start providing', - detail: `${displayNames(startable)} ${isAre(startable.length)} selected and ready to serve.`, - actions: [ - { - kind: 'act', - action: { action: 'start', models: startable.map((model) => model.id) }, - label: 'Start providing', - }, - chooseModels, - ], - } - : { - id: 'choose', - title: 'Choose models to serve', - detail: 'Select at least one downloaded model, then start providing.', - actions: [chooseModels], - }; -} - -function linkStep(state: Snapshot): ReadinessStep { - return state.link - ? { - id: 'link', - title: 'Finish linking this Mac', - detail: `Enter code ${state.link.code} in your browser to attribute this Mac’s earnings to your account.`, - actions: [{ kind: 'link-page', label: 'Open link page' }], - } - : { - id: 'link', - title: 'Link this Mac', - detail: 'Linking attributes this Mac’s earnings to your account.', - actions: [{ kind: 'act', action: { action: 'link' }, label: 'Link account' }], - }; -} - -// The single most relevant provider fact that keeps This Mac from serving. -function providerStep(state: Snapshot): [ReadinessStep, 'block' | 'wait'] | undefined { - const downloaded = state.models.filter((model) => model.downloaded); - const chosen = state.models.filter((model) => model.serving); - const crashed = (state.activity.models || []) - .filter((slot) => slot.state === 'crashed') - .map((slot) => modelName(state.models, slot.model)); - if (state.state === 'draining') - return [ - { - id: 'draining', - title: 'Finishing current requests', - detail: 'The provider takes no new requests while it drains.', - actions: [], - }, - 'wait', - ]; - if (state.state === 'starting') - return [ - { - id: 'starting', - title: 'Starting the provider', - detail: 'Requests are served once it connects.', - actions: [], - }, - 'wait', - ]; - if (state.state === 'stale') - return [ - { - id: 'stale', - title: 'Restart the provider', - detail: 'The provider is running but its status is out of date. Restart it if this lasts.', - actions: [restart], - }, - 'block', - ]; - if (!downloaded.length) - return [ - { - id: 'download', - title: 'Download a model', - detail: 'This Mac has no models on disk yet.', - actions: [{ kind: 'route', route: 'models', label: 'Browse models' }], - }, - 'block', - ]; - if (state.state === 'stopped') - return [startStep(chosen.filter((model) => model.downloaded && model.eligible)), 'block']; - if (!chosen.length) - return [ - { - id: 'choose', - title: 'Choose models to serve', - detail: 'Select at least one downloaded model.', - actions: [chooseModels], - }, - 'block', - ]; - if (crashed.length) - return [ - { - id: 'crashed', - title: 'Restart the provider', - detail: `${modelList(crashed)} stopped unexpectedly.`, - actions: [restart], - }, - 'block', - ]; - if (!chosen.some((model) => model.loaded)) - return [ - { - id: 'loading', - title: 'Loading models', - detail: `${displayNames(chosen)} ${isAre(chosen.length)} loading into memory. Requests are served once loading finishes.`, - actions: [], - }, - 'wait', - ]; -} - // Next steps from reported facts only; admission and routing policy stay with // the runtime and coordinator. Linking is advice: it never changes the tone. export function assessReadiness({ status, state, update }: ReadinessFacts): Readiness { @@ -212,7 +34,15 @@ export function assessReadiness({ status, state, update }: ReadinessFacts): Read const step = runtimeStep(status); return { tone: step.actions.length ? 'blocked' : 'pending', - summary: 'Status unknown while disconnected', + status: + status.state === 'installing' + ? 'Setting up Darkbloom' + : status.state === 'connecting' + ? 'Connecting to this Mac' + : status.state === 'missing' + ? 'Setup required' + : 'Connection unavailable', + summary: 'Serving status unavailable', steps: [step], }; } @@ -230,11 +60,25 @@ export function assessReadiness({ status, state, update }: ReadinessFacts): Read if (operation && tone !== 'ready') steps.unshift(operationStep(operation)); if (!state.linked) steps.push(linkStep(state)); const loaded = state.models.filter((model) => model.serving && model.loaded); + const primary = steps.find((step) => !['link', 'operation'].includes(step.id)); + const statusLabel = + tone === 'ready' + ? 'Ready to serve' + : !update.required && transitioning && operation + ? operationLabel(operation) + : primary?.id === 'start' + ? 'Stopped' + : primary?.id === 'stale' + ? 'Status unavailable' + : primary?.id === 'crashed' + ? 'Needs restart' + : (primary?.title ?? 'Not ready'); return { tone, + status: statusLabel, summary: tone === 'ready' - ? `Serving ${displayNames(loaded)}` + ? `${loaded.length} ${loaded.length === 1 ? 'model' : 'models'} loaded` : tone === 'pending' ? 'Not serving new requests' : 'Not serving requests', diff --git a/desktop-app/src/renderer/features/machines/overview/readinessSteps.ts b/desktop-app/src/renderer/features/machines/overview/readinessSteps.ts new file mode 100644 index 0000000000..67dbef397c --- /dev/null +++ b/desktop-app/src/renderer/features/machines/overview/readinessSteps.ts @@ -0,0 +1,197 @@ +import type { DesktopStatus, NativeModel, Operation, Snapshot } from '../../../../shared/contracts'; +import { operationLabel } from '../../../components/operations/labels'; +import { modelName } from '../../../models/facts'; +import type { ReadinessStep, StepAction } from './readiness'; + +const chooseModels: StepAction = { kind: 'route', route: 'models', label: 'Choose models' }; +const restart: StepAction = { + kind: 'act', + action: { action: 'restart' }, + label: 'Restart provider', +}; + +function modelList(names: string[]) { + return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0] || ''; +} +const displayNames = (models: NativeModel[]) => + modelList(models.map((model) => model.display_name)); +const isAre = (count: number) => (count === 1 ? 'is' : 'are'); + +export function runtimeStep(status: DesktopStatus): ReadinessStep { + if (status.state === 'connecting' || status.state === 'installing') + return { + id: 'runtime', + title: + status.state === 'installing' ? 'Installing the runtime' : 'Reconnecting to the runtime', + detail: + status.state === 'installing' + ? 'This can take a few minutes.' + : 'The app reconnects automatically.', + actions: [], + }; + const missing = status.state === 'missing'; + return { + id: 'runtime', + title: missing ? 'Install the Darkbloom runtime' : 'Repair the Darkbloom runtime', + detail: status.message || 'The app can’t reach the runtime on this Mac.', + actions: [{ kind: 'install', label: missing ? 'Install runtime' : 'Repair runtime' }], + }; +} + +export const operationStep = (operation: Operation): ReadinessStep => ({ + id: 'operation', + title: operationLabel(operation), + detail: 'Wait for it to finish.', + actions: [], +}); + +export function updateStep(available: boolean): ReadinessStep { + return { + id: 'update', + title: 'Update Darkbloom', + detail: available + ? 'This version can no longer receive network requests.' + : 'This version can no longer receive network requests, and a compatible update isn’t available yet.', + actions: available ? [{ kind: 'act', action: { action: 'update' }, label: 'Update now' }] : [], + }; +} + +function startStep(startable: NativeModel[]): ReadinessStep { + return startable.length + ? { + id: 'start', + title: 'Start providing', + detail: `${displayNames(startable)} ${isAre(startable.length)} selected and ready to serve.`, + actions: [ + { + kind: 'act', + action: { action: 'start', models: startable.map((model) => model.id) }, + label: 'Start providing', + }, + chooseModels, + ], + } + : { + id: 'choose', + title: 'Choose models to serve', + detail: 'Select at least one downloaded model, then start providing.', + actions: [chooseModels], + }; +} + +export function linkStep(state: Snapshot): ReadinessStep { + return state.link + ? { + id: 'link', + title: 'Finish linking this Mac', + detail: `Enter code ${state.link.code} in your browser to attribute this Mac’s earnings to your account.`, + actions: [{ kind: 'link-page', label: 'Open link page' }], + } + : { + id: 'link', + title: 'Link this Mac', + detail: 'Linking attributes this Mac’s earnings to your account.', + actions: [{ kind: 'act', action: { action: 'link' }, label: 'Link account' }], + }; +} + +// The single most relevant provider fact that keeps This Mac from serving. +export function providerStep(state: Snapshot): [ReadinessStep, 'block' | 'wait'] | undefined { + const downloaded = state.models.filter((model) => model.downloaded); + const chosen = state.models.filter((model) => model.serving); + const crashed = (state.activity.models || []) + .filter((slot) => slot.state === 'crashed') + .map((slot) => modelName(state.models, slot.model)); + if (state.state === 'draining') + return [ + { + id: 'draining', + title: 'Finishing current requests', + detail: 'The provider takes no new requests while it drains.', + actions: [], + }, + 'wait', + ]; + if (state.state === 'starting') + return [ + { + id: 'starting', + title: 'Starting the provider', + detail: 'Requests are served once it connects.', + actions: [], + }, + 'wait', + ]; + if (state.state === 'stale') + return [ + { + id: 'stale', + title: 'Restart the provider', + detail: 'The provider is running but its status is out of date. Restart it if this lasts.', + actions: [restart], + }, + 'block', + ]; + if (state.provider_status === 'untrusted') + return [ + { + id: 'verification', + title: 'Verification needed', + detail: 'This Mac is not authorized to receive network requests yet.', + actions: [], + }, + 'block', + ]; + if (state.provider_status === 'offline') + return [ + { + id: 'connection', + title: 'Connecting to the network', + detail: 'Waiting for the network connection.', + actions: [], + }, + 'wait', + ]; + if (!downloaded.length) + return [ + { + id: 'download', + title: 'Download a model', + detail: 'This Mac has no models on disk yet.', + actions: [{ kind: 'route', route: 'models', label: 'Browse models' }], + }, + 'block', + ]; + if (state.state === 'stopped') + return [startStep(chosen.filter((model) => model.downloaded && model.eligible)), 'block']; + if (!chosen.length) + return [ + { + id: 'choose', + title: 'Choose models to serve', + detail: 'Select at least one downloaded model.', + actions: [chooseModels], + }, + 'block', + ]; + if (crashed.length) + return [ + { + id: 'crashed', + title: 'Restart the provider', + detail: `${modelList(crashed)} stopped unexpectedly.`, + actions: [restart], + }, + 'block', + ]; + if (!chosen.some((model) => model.loaded)) + return [ + { + id: 'loading', + title: 'Loading models', + detail: `${displayNames(chosen)} ${isAre(chosen.length)} loading into memory. Requests are served once loading finishes.`, + actions: [], + }, + 'wait', + ]; +} diff --git a/desktop-app/src/renderer/features/models/AutopilotCard.tsx b/desktop-app/src/renderer/features/models/AutopilotCard.tsx index 35766dd6be..63f7fd582d 100644 --- a/desktop-app/src/renderer/features/models/AutopilotCard.tsx +++ b/desktop-app/src/renderer/features/models/AutopilotCard.tsx @@ -1,26 +1,13 @@ -import { Pause, Play, Power, RefreshCw, Sparkles } from 'lucide-react'; +import { Pause, Play, RefreshCw, Sparkles } from 'lucide-react'; import type { Snapshot } from '../../../shared/contracts'; import { Button } from '../../components/UI'; -import { gb } from '../../format'; -import { modelName, pinnedMemoryLine } from '../../models/facts'; import { phaseCopy } from './pool'; import styles from './autopilot.module.css'; -const names = (snapshot: Snapshot, ids: string[]) => - ids.map((id) => modelName(snapshot.models, id)); - -function Fact({ label, values, empty }: { label: string; values: string[]; empty: string }) { - return ( -- You choose which models live on this Mac. Autopilot decides which ones to load into memory - as demand changes. -
{phase.detail && ( -{phase.detail}
{phase.refresh && !working && ( -
- {gb(state.memory.total_gb)} unified memory
-
- The runtime checks each load before allocating.
-
{gb(state.memory.total_gb)} unified memory
{model.description || model.id}
{model.description || model.id}
{model.description || model.id}
{modelFacts(model)} - {pinned && Unpin it to remove it from this Mac.} + {model.description && ( +{model.description}
+{inPool - ? `This deletes ${model.display_name} from this Mac and takes it out of the Autopilot pool.${model.loaded ? ' Autopilot unloads it first.' : ''} You can download it again later.` + ? `This deletes ${model.display_name} from this Mac. Update available models afterward to refresh Autopilot’s inventory. You can download it again later.` : 'This deletes the downloaded model from this Mac. You can download it again later.'}
- You choose which models live on this Mac: downloaded models form Autopilot’s pool, and you - can pin the ones that must always stay loaded. Autopilot decides which ones to load into - memory as demand changes. -
+ Autopilot + Choose downloads. Autopilot manages what’s loaded.{state.readiness}
++ { + assessReadiness({ + state, + status: backend.status, + update: { required: false, available: false }, + }).status + } +
Runtime {state.version} · Local API {state.endpoint ? 'available' : 'not enabled'}
diff --git a/desktop-app/src/renderer/features/stats/activity/RequestActivity.tsx b/desktop-app/src/renderer/features/stats/activity/RequestActivity.tsx index d626170c58..b440e9ad7a 100644 --- a/desktop-app/src/renderer/features/stats/activity/RequestActivity.tsx +++ b/desktop-app/src/renderer/features/stats/activity/RequestActivity.tsx @@ -55,10 +55,7 @@ export function RequestActivity({ failed ? (- The Darkbloom runtime on this Mac didn’t return its request history. Runtimes that - predate this view don’t report it yet. -
+Couldn’t load requests from this Mac.
- Couldn’t refresh request history. Showing the last observation. + Couldn’t refresh request history. Showing previously loaded requests.
)}