Skip to content
Draft
Show file tree
Hide file tree
Changes from 3 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
68 changes: 47 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 @@ -492,6 +493,7 @@ function convertCloudStatusToDesktop(
activeModelId: string | null;
activeManagedModel: { provider?: string } | null | undefined;
},
creditsSummary: CreditSummaryResponse | null,
): DesktopRewardsStatus {
const { cloudConnected, activeModelId, activeManagedModel } = viewer;
const tasks = cloudStatus.tasks.flatMap((task) => {
Expand Down Expand Up @@ -532,13 +534,18 @@ function convertCloudStatusToDesktop(
totalCount: tasks.length,
},
tasks,
cloudBalance: cloudStatus.cloudBalance
? {
totalBalance: cloudStatus.cloudBalance.totalBalance,
totalRecharged: cloudStatus.cloudBalance.totalRecharged,
totalConsumed: cloudStatus.cloudBalance.totalConsumed,
}
: null,
cloudBalance:
creditsSummary?.balance ??
(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 @@ -1712,7 +1719,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 @@ -1724,12 +1731,27 @@ export class NexuConfigStore {
const cloudResult = await service.getRewardsStatus();

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

const creditsSummaryResult = await service.getCreditsSummary();
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 +1768,7 @@ export class NexuConfigStore {
},
progress: { claimedCount: 0, totalCount: 0, earnedCredits: 0 },
tasks: [],
cloudBalance: null,
cloudBalance: creditsBalance,
};
}

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

Expand Down Expand Up @@ -1817,11 +1839,15 @@ export class NexuConfigStore {
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,
},
null,
),
};
}

Expand Down
65 changes: 65 additions & 0 deletions apps/controller/tests/cloud-reward-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,24 @@ const mockRewardStatusResponse = {
},
};

const mockCreditsSummaryResponse = {
appUserId: "user-1",
balance: {
totalBalance: 500,
giftBalance: 125,
totalRecharged: 600,
totalConsumed: 100,
syncedAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
},
usageSummary: {
totalEntries: 1,
totalDueCredits: 100,
totalChargedCredits: 100,
totalCostUsd: "0.00",
},
};

const mockClaimResponse = {
ok: true,
alreadyClaimed: false,
Expand Down Expand Up @@ -265,6 +283,53 @@ describe("createCloudRewardService", () => {
});
});

describe("getCreditsSummary", () => {
it("returns ok:true with parsed summary on success", async () => {
vi.stubGlobal(
"fetch",
vi.fn(
async () =>
new Response(JSON.stringify(mockCreditsSummaryResponse), {
status: 200,
}),
),
);

const service = createCloudRewardService({
cloudUrl: CLOUD_URL,
apiKey: API_KEY,
});
const result = await service.getCreditsSummary();

expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.data.balance.totalBalance).toBe(500);
expect(result.data.balance.giftBalance).toBe(125);
});

it("returns ok:false reason:parse_error when summary body does not match schema", async () => {
vi.stubGlobal(
"fetch",
vi.fn(
async () =>
new Response(JSON.stringify({ unexpected: "shape" }), {
status: 200,
}),
),
);

const service = createCloudRewardService({
cloudUrl: CLOUD_URL,
apiKey: API_KEY,
});
const result = await service.getCreditsSummary();

expect(result.ok).toBe(false);
if (result.ok) throw new Error("unreachable");
expect(result.reason).toBe("parse_error");
});
});

describe("claimReward", () => {
it("returns ok:true with claim result on success", async () => {
vi.stubGlobal(
Expand Down
2 changes: 2 additions & 0 deletions apps/controller/tests/desktop-rewards-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ describe("registerDesktopRewardsRoutes", () => {
tasks: [],
cloudBalance: {
totalBalance: 0,
giftBalance: 0,
totalRecharged: 900,
totalConsumed: 900,
},
Expand Down Expand Up @@ -71,6 +72,7 @@ describe("registerDesktopRewardsRoutes", () => {
tasks: [],
cloudBalance: {
totalBalance: 1337,
giftBalance: 0,
totalRecharged: 1337,
totalConsumed: 0,
},
Expand Down
Loading
Loading