Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 42 additions & 3 deletions apps/controller/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -3208,20 +3208,33 @@
"type": "integer",
"minimum": 0
},
"giftBalance": {
"type": "integer",
"minimum": 0,
"default": 0
},
"totalRecharged": {
"type": "integer",
"minimum": 0
},
"totalConsumed": {
"type": "integer",
"minimum": 0
},
"syncedAt": {
"type": "string"
},
"updatedAt": {
"type": "string"
}
},
"default": null,
"required": [
"totalBalance",
"totalRecharged",
"totalConsumed"
"totalConsumed",
"syncedAt",
"updatedAt"
]
},
"autoFallbackTriggered": {
Expand Down Expand Up @@ -3514,20 +3527,33 @@
"type": "integer",
"minimum": 0
},
"giftBalance": {
"type": "integer",
"minimum": 0,
"default": 0
},
"totalRecharged": {
"type": "integer",
"minimum": 0
},
"totalConsumed": {
"type": "integer",
"minimum": 0
},
"syncedAt": {
"type": "string"
},
"updatedAt": {
"type": "string"
}
},
"default": null,
"required": [
"totalBalance",
"totalRecharged",
"totalConsumed"
"totalConsumed",
"syncedAt",
"updatedAt"
]
},
"autoFallbackTriggered": {
Expand Down Expand Up @@ -3746,20 +3772,33 @@
"type": "integer",
"minimum": 0
},
"giftBalance": {
"type": "integer",
"minimum": 0,
"default": 0
},
"totalRecharged": {
"type": "integer",
"minimum": 0
},
"totalConsumed": {
"type": "integer",
"minimum": 0
},
"syncedAt": {
"type": "string"
},
"updatedAt": {
"type": "string"
}
},
"default": null,
"required": [
"totalBalance",
"totalRecharged",
"totalConsumed"
"totalConsumed",
"syncedAt",
"updatedAt"
]
},
"autoFallbackTriggered": {
Expand Down
45 changes: 45 additions & 0 deletions apps/controller/src/services/cloud-reward-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import {
type DesktopRewardClaimProof,
creditSummaryResponseSchema,
rewardRepeatModeSchema,
rewardShareModeSchema,
} from "@nexu/shared";
Expand Down Expand Up @@ -62,6 +63,7 @@ const cloudErrorResponseSchema = z.object({

export type RewardStatusResponse = z.infer<typeof rewardStatusResponseSchema>;
export type RewardClaimResponse = z.infer<typeof rewardClaimResponseSchema>;
export type CreditSummaryResponse = z.infer<typeof creditSummaryResponseSchema>;

export type CloudRewardErrorReason =
| "auth_failed"
Expand All @@ -74,6 +76,7 @@ export type CloudRewardResult<T> =

export type CloudRewardService = {
getRewardsStatus(): Promise<CloudRewardResult<RewardStatusResponse>>;
getCreditsSummary(): Promise<CloudRewardResult<CreditSummaryResponse>>;
claimReward(
taskId: string,
proof?: DesktopRewardClaimProof,
Expand Down Expand Up @@ -158,6 +161,48 @@ export function createCloudRewardService(
}
},

async getCreditsSummary() {
try {
const res = await fetchWithAuth("/api/v1/credits/summary");
if (res.status === 401 || res.status === 403) {
return {
ok: false,
reason: "auth_failed",
message: await readCloudErrorMessage(res),
};
}
if (!res.ok) {
logger.warn(
{ status: res.status, url: `${cloudUrl}/api/v1/credits/summary` },
"cloud_credits_summary_http_error",
);
return { ok: false, reason: "network_error" };
}
const data: unknown = await res.json();
const parsed = creditSummaryResponseSchema.safeParse(data);
if (!parsed.success) {
logger.warn(
{
issues: parsed.error.issues.slice(0, 5),
url: `${cloudUrl}/api/v1/credits/summary`,
},
"cloud_credits_summary_parse_error",
);
return { ok: false, reason: "parse_error" };
}
return { ok: true, data: parsed.data };
} catch (error: unknown) {
logger.warn(
{
error: error instanceof Error ? error.message : String(error),
url: `${cloudUrl}/api/v1/credits/summary`,
},
"cloud_credits_summary_network_error",
);
return { ok: false, reason: "network_error" };
}
},

async claimReward(taskId, proof) {
try {
const res = await fetchWithAuth("/api/v1/rewards/claim", {
Expand Down
95 changes: 74 additions & 21 deletions apps/controller/src/store/nexu-config-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { logger } from "../lib/logger.js";
import { resolveManagedCloudModel } from "../lib/managed-models.js";
import { proxyFetch } from "../lib/proxy-fetch.js";
import {
type CreditSummaryResponse,
type RewardStatusResponse,
createCloudRewardService,
} from "../services/cloud-reward-service.js";
Expand Down Expand Up @@ -93,6 +94,8 @@ type DesktopRewardClaimResponse = z.infer<
typeof claimDesktopRewardResponseSchema
>;

const CLOUD_REWARD_CREDITS_SUMMARY_BEST_EFFORT_MS = 1500;

const defaultCloudProfile: CloudProfileEntry = {
name: "Default",
cloudUrl: "https://nexu.io",
Expand Down Expand Up @@ -492,6 +495,7 @@ function convertCloudStatusToDesktop(
activeModelId: string | null;
activeManagedModel: { provider?: string } | null | undefined;
},
creditsBalance: CreditSummaryResponse["balance"] | null,
): DesktopRewardsStatus {
const { cloudConnected, activeModelId, activeManagedModel } = viewer;
const tasks = cloudStatus.tasks.flatMap((task) => {
Expand Down Expand Up @@ -532,13 +536,18 @@ function convertCloudStatusToDesktop(
totalCount: tasks.length,
},
tasks,
cloudBalance: cloudStatus.cloudBalance
? {
totalBalance: cloudStatus.cloudBalance.totalBalance,
totalRecharged: cloudStatus.cloudBalance.totalRecharged,
totalConsumed: cloudStatus.cloudBalance.totalConsumed,
}
: null,
cloudBalance:
creditsBalance ??
(cloudStatus.cloudBalance
Comment thread
nettee marked this conversation as resolved.
? {
totalBalance: cloudStatus.cloudBalance.totalBalance,
giftBalance: 0,
totalRecharged: cloudStatus.cloudBalance.totalRecharged,
totalConsumed: cloudStatus.cloudBalance.totalConsumed,
syncedAt: cloudStatus.cloudBalance.syncedAt,
updatedAt: cloudStatus.cloudBalance.updatedAt,
}
: null),
};
}

Expand Down Expand Up @@ -730,6 +739,24 @@ export class NexuConfigStore {
});
}

private async readBestEffortCreditsBalance(
creditsSummaryPromise: Promise<
| { ok: true; data: CreditSummaryResponse }
| { ok: false; reason: string; message?: string }
>,
): Promise<CreditSummaryResponse["balance"] | null> {
const result = await Promise.race([
creditsSummaryPromise,
this.sleep(CLOUD_REWARD_CREDITS_SUMMARY_BEST_EFFORT_MS).then(() => null),
]);

if (!result || !result.ok) {
return null;
}

return result.data.balance;
}

private isCurrentPollingSignal(signal: AbortSignal): boolean {
// The polling loop may still be processing a response when a newer
// connectDesktopCloud() call has already aborted it and installed a fresh
Expand Down Expand Up @@ -1712,7 +1739,7 @@ export class NexuConfigStore {
activeModelId,
cloud.models ?? [],
);

let creditsBalance: CreditSummaryResponse["balance"] | null = null;
if (cloud.connected && cloud.apiKey) {
const { activeProfile } =
await this.readConfiguredDesktopCloudProfile(config);
Expand All @@ -1721,15 +1748,34 @@ export class NexuConfigStore {
cloudUrl,
apiKey: cloud.apiKey,
});
const creditsSummaryPromise = service.getCreditsSummary();
const cloudResult = await service.getRewardsStatus();

if (cloudResult.ok) {
const cloudStatus = cloudResult.data;
return convertCloudStatusToDesktop(cloudStatus, {
cloudConnected: true,
activeModelId,
activeManagedModel,
});
const creditsBalance = await this.readBestEffortCreditsBalance(
creditsSummaryPromise,
);
return convertCloudStatusToDesktop(
cloudResult.data,
{
cloudConnected: true,
activeModelId,
activeManagedModel,
},
creditsBalance,
);
Comment thread
nettee marked this conversation as resolved.
}

const creditsSummaryResult = await creditsSummaryPromise;
creditsBalance = creditsSummaryResult.ok
? creditsSummaryResult.data.balance
: null;

if (!creditsSummaryResult.ok) {
logger.warn(
{ reason: creditsSummaryResult.reason },
"desktop_credits_summary_cloud_fallback",
);
}

if (cloudResult.reason === "auth_failed") {
Expand All @@ -1746,7 +1792,7 @@ export class NexuConfigStore {
},
progress: { claimedCount: 0, totalCount: 0, earnedCredits: 0 },
tasks: [],
cloudBalance: null,
cloudBalance: creditsBalance,
};
}

Expand All @@ -1769,7 +1815,7 @@ export class NexuConfigStore {
},
progress: { claimedCount: 0, totalCount: 0, earnedCredits: 0 },
tasks: [],
cloudBalance: null,
cloudBalance: creditsBalance,
};
}

Expand Down Expand Up @@ -1813,15 +1859,22 @@ export class NexuConfigStore {
activeModelId2,
cloud2.models ?? [],
);
const creditsBalance = await this.readBestEffortCreditsBalance(
service.getCreditsSummary(),
);

return {
ok: claimData.ok,
alreadyClaimed: claimData.alreadyClaimed,
status: convertCloudStatusToDesktop(claimData.status, {
cloudConnected: true,
activeModelId: activeModelId2,
activeManagedModel: activeManagedModel2,
}),
status: convertCloudStatusToDesktop(
claimData.status,
{
cloudConnected: true,
activeModelId: activeModelId2,
activeManagedModel: activeManagedModel2,
},
creditsBalance,
),
};
}

Expand Down
Loading
Loading