magpie-multi-usage 0.3.1 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/README.zh-CN.md +2 -2
- package/package.json +1 -1
- package/src/aggregator.mjs +1 -1
- package/src/github-store.mjs +94 -12
- package/src/http-server.mjs +1 -1
- package/src/sync-engine.mjs +1 -1
- package/src/ui/app.js +16 -8
- package/src/ui/index.html +1 -1
- package/src/ui/view-model.mjs +21 -2
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ Bundled vendor logos load in the Models and Providers tabs in Magpie Desktop and
|
|
|
32
32
|
|
|
33
33
|
### 1. Create a dedicated private GitHub repository
|
|
34
34
|
|
|
35
|
-
Create a new **Private** repository solely for sanitized usage stats (for example, `<you>/magpie-usage-stats`)
|
|
35
|
+
Create a new **Private** repository solely for sanitized usage stats (for example, `<you>/magpie-usage-stats`). Leaving it completely empty is fine — the first sync automatically initializes its default branch (such as `main`) when **Branch** is left blank or set to the default branch.
|
|
36
36
|
|
|
37
37
|
> [!IMPORTANT]
|
|
38
38
|
> Do **not** reuse your Magpie configuration sync repository, and do **not** use a public repository. This plugin verifies `private === true` before every read and ref update, and refuses public repositories (`PUBLIC_REPO_REFUSED`).
|
|
@@ -112,7 +112,7 @@ Only aggregate counters (`calls`, `errors`, `excludedForwarded`, `input`, `outpu
|
|
|
112
112
|
## FAQ
|
|
113
113
|
|
|
114
114
|
- **`PUBLIC_REPO_REFUSED`**: the configured repository is public; switch to a dedicated private one.
|
|
115
|
-
- **`BRANCH_NOT_FOUND` on Test connection**: the
|
|
115
|
+
- **`BRANCH_NOT_FOUND` on Test connection**: the configured custom branch does not exist yet (or the repository is empty and a non-default branch was specified); leave **Branch** blank to use the repository's default branch, or create the custom branch on GitHub first.
|
|
116
116
|
- **Device name shows the hostname**: set a friendly name in **Settings → Device display name**, then save and sync.
|
|
117
117
|
- **Want to reset local plugin state**: remove `<dataDir>` (default `~/.local/share/magpie-multi-usage`); Magpie's own data is untouched and re-ingests cleanly on next open.
|
|
118
118
|
|
package/README.zh-CN.md
CHANGED
|
@@ -32,7 +32,7 @@ Magpie 桌面端和 Web 端的模型与供应商标签页均支持加载内置
|
|
|
32
32
|
|
|
33
33
|
### 1. 创建专用私有 GitHub 仓库
|
|
34
34
|
|
|
35
|
-
新建一个仅用于存放脱敏用量统计的 **Private** 仓库(例如 `<you>/magpie-usage-stats
|
|
35
|
+
新建一个仅用于存放脱敏用量统计的 **Private** 仓库(例如 `<you>/magpie-usage-stats`)。空仓库即可,无需手动创建初始提交——只要**分支**留空或填写默认分支(如 `main`),首次同步会自动初始化。
|
|
36
36
|
|
|
37
37
|
> [!IMPORTANT]
|
|
38
38
|
> 请**不要**复用 Magpie 配置同步仓库,也**不要**使用公共仓库。本插件在每次读取和 ref 更新前都会校验 `private === true`,并拒绝公共仓库(`PUBLIC_REPO_REFUSED`)。
|
|
@@ -112,7 +112,7 @@ devices/
|
|
|
112
112
|
## 常见问题
|
|
113
113
|
|
|
114
114
|
- **提示 `PUBLIC_REPO_REFUSED`**:配置的是公共仓库,请改用专用私有仓库。
|
|
115
|
-
- **测试连接提示 `BRANCH_NOT_FOUND
|
|
115
|
+
- **测试连接提示 `BRANCH_NOT_FOUND`**:填写的自定义分支不存在(或空仓库指定了非默认分支);可将**分支**留空以使用仓库默认分支,或先在 GitHub 上创建该分支。
|
|
116
116
|
- **设备名显示成主机名**:在 **设置 → 设备显示名** 里填一个名字,再保存并同步。
|
|
117
117
|
- **想清空插件本地数据重来**:删除 `<dataDir>`(默认 `~/.local/share/magpie-multi-usage`)即可,Magpie 自身数据不受影响。
|
|
118
118
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "magpie-multi-usage",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"description": "Multi-device token usage dashboard plugin for Magpie using a dedicated private GitHub repository relay (no decryption passphrase required).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|
package/src/aggregator.mjs
CHANGED
package/src/github-store.mjs
CHANGED
|
@@ -179,6 +179,18 @@ export function validateRemoteMonthSnapshot(snapshot, expectedDeviceId, expected
|
|
|
179
179
|
return snapshot;
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
+
function isEmptyRepoResponse(status, bodyText) {
|
|
183
|
+
if (status !== 409 || !bodyText) {
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
try {
|
|
187
|
+
const parsed = JSON.parse(bodyText);
|
|
188
|
+
return parsed?.message === "Git Repository is empty.";
|
|
189
|
+
} catch {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
182
194
|
function sanitizeGitHubErrorMessage(status, bodyText) {
|
|
183
195
|
let detail = "";
|
|
184
196
|
if (bodyText) {
|
|
@@ -224,7 +236,7 @@ export function createGitHubRelayStore({
|
|
|
224
236
|
apiBaseUrl = DEFAULT_API_BASE_URL,
|
|
225
237
|
fetchImpl = globalThis.fetch,
|
|
226
238
|
timeoutMs = 15000,
|
|
227
|
-
pluginVersion = "0.3.
|
|
239
|
+
pluginVersion = "0.3.4",
|
|
228
240
|
} = {}) {
|
|
229
241
|
const normalizedRepo = normalizeRepo(repo);
|
|
230
242
|
if (!normalizedRepo) {
|
|
@@ -330,7 +342,8 @@ export function createGitHubRelayStore({
|
|
|
330
342
|
}
|
|
331
343
|
verifiedRepoId = repoId;
|
|
332
344
|
|
|
333
|
-
const
|
|
345
|
+
const defaultBranch = (typeof meta.default_branch === "string" && meta.default_branch.trim()) || "main";
|
|
346
|
+
const resolvedBranch = configuredBranch || defaultBranch;
|
|
334
347
|
const canPush = typeof meta?.permissions?.push === "boolean" ? meta.permissions.push : null;
|
|
335
348
|
|
|
336
349
|
if (requirePush && canPush === false) {
|
|
@@ -346,6 +359,7 @@ export function createGitHubRelayStore({
|
|
|
346
359
|
repoId,
|
|
347
360
|
private: true,
|
|
348
361
|
branch: resolvedBranch,
|
|
362
|
+
defaultBranch,
|
|
349
363
|
prefix: normalizedPrefix,
|
|
350
364
|
canPush,
|
|
351
365
|
};
|
|
@@ -361,8 +375,7 @@ export function createGitHubRelayStore({
|
|
|
361
375
|
}
|
|
362
376
|
}
|
|
363
377
|
|
|
364
|
-
|
|
365
|
-
const res = await request(method, apiPath, { body });
|
|
378
|
+
function parseJsonResponseOrThrow(res, label) {
|
|
366
379
|
if (!res.ok) {
|
|
367
380
|
throw new GitHubStoreError(
|
|
368
381
|
res.status === 409 || res.status === 422 ? "GITHUB_CONFLICT" : res.status === 403 ? "GITHUB_FORBIDDEN" : "GITHUB_HTTP_ERROR",
|
|
@@ -379,6 +392,42 @@ export function createGitHubRelayStore({
|
|
|
379
392
|
}
|
|
380
393
|
}
|
|
381
394
|
|
|
395
|
+
async function requestJsonOrThrow(method, apiPath, { body, label }) {
|
|
396
|
+
const res = await request(method, apiPath, { body });
|
|
397
|
+
return parseJsonResponseOrThrow(res, label);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async function initializeEmptyRepo(verified) {
|
|
401
|
+
if (verified.branch !== verified.defaultBranch) {
|
|
402
|
+
throw new GitHubStoreError(
|
|
403
|
+
"BRANCH_NOT_FOUND",
|
|
404
|
+
`Repository ${verified.repo} is empty; leave branch blank or use its default branch "${verified.defaultBranch}" for the first sync.`,
|
|
405
|
+
{ status: 409 },
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
const readmePath = `${normalizedPrefix}/README.md`;
|
|
409
|
+
const note = "This folder holds magpie-multi-usage sanitized usage snapshots.\n";
|
|
410
|
+
// Omitting `branch` lets GitHub Contents API create the default branch's initial commit.
|
|
411
|
+
const initRes = await request(
|
|
412
|
+
"PUT",
|
|
413
|
+
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/contents/${encodeRepoPath(readmePath)}`,
|
|
414
|
+
{
|
|
415
|
+
body: {
|
|
416
|
+
message: "chore(usage): initialize relay repository",
|
|
417
|
+
content: Buffer.from(note, "utf8").toString("base64"),
|
|
418
|
+
},
|
|
419
|
+
},
|
|
420
|
+
);
|
|
421
|
+
if (initRes.ok || initRes.status === 409 || initRes.status === 422) {
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
throw new GitHubStoreError(
|
|
425
|
+
initRes.status === 403 ? "GITHUB_FORBIDDEN" : "GITHUB_HTTP_ERROR",
|
|
426
|
+
sanitizeGitHubErrorMessage(initRes.status, initRes.text),
|
|
427
|
+
{ status: initRes.status },
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
|
|
382
431
|
async function fetchBlobJson(sha, label) {
|
|
383
432
|
const blob = await requestJsonOrThrow(
|
|
384
433
|
"GET",
|
|
@@ -408,28 +457,55 @@ export function createGitHubRelayStore({
|
|
|
408
457
|
|
|
409
458
|
async testConnection() {
|
|
410
459
|
const verified = await verifyPrivateRepo({ requirePush: false });
|
|
411
|
-
const
|
|
460
|
+
const refRes = await request(
|
|
412
461
|
"GET",
|
|
413
|
-
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/
|
|
462
|
+
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/git/ref/heads/${encodeRepoPath(verified.branch)}`,
|
|
414
463
|
);
|
|
415
|
-
if (
|
|
464
|
+
if (isEmptyRepoResponse(refRes.status, refRes.text)) {
|
|
465
|
+
if (verified.branch !== verified.defaultBranch) {
|
|
466
|
+
return {
|
|
467
|
+
ok: false,
|
|
468
|
+
code: "BRANCH_NOT_FOUND",
|
|
469
|
+
error: `Repository ${verified.repo} is empty; leave branch blank or use its default branch "${verified.defaultBranch}" for the first sync.`,
|
|
470
|
+
repo: verified.repo,
|
|
471
|
+
repoId: verified.repoId,
|
|
472
|
+
private: true,
|
|
473
|
+
branch: verified.branch,
|
|
474
|
+
branchExists: false,
|
|
475
|
+
emptyRepo: true,
|
|
476
|
+
canPush: verified.canPush,
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
return {
|
|
480
|
+
ok: true,
|
|
481
|
+
repo: verified.repo,
|
|
482
|
+
repoId: verified.repoId,
|
|
483
|
+
private: true,
|
|
484
|
+
branch: verified.branch,
|
|
485
|
+
branchExists: false,
|
|
486
|
+
emptyRepo: true,
|
|
487
|
+
canPush: verified.canPush,
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
if (refRes.status === 404) {
|
|
416
491
|
return {
|
|
417
492
|
ok: false,
|
|
418
493
|
code: "BRANCH_NOT_FOUND",
|
|
419
|
-
error: `Branch "${verified.branch}" does not exist yet in ${verified.repo}.
|
|
494
|
+
error: `Branch "${verified.branch}" does not exist yet in ${verified.repo}. Create the branch first or leave branch blank to use "${verified.defaultBranch}".`,
|
|
420
495
|
repo: verified.repo,
|
|
421
496
|
repoId: verified.repoId,
|
|
422
497
|
private: true,
|
|
423
498
|
branch: verified.branch,
|
|
424
499
|
branchExists: false,
|
|
500
|
+
emptyRepo: false,
|
|
425
501
|
canPush: verified.canPush,
|
|
426
502
|
};
|
|
427
503
|
}
|
|
428
|
-
if (!
|
|
504
|
+
if (!refRes.ok) {
|
|
429
505
|
throw new GitHubStoreError(
|
|
430
506
|
"GITHUB_HTTP_ERROR",
|
|
431
|
-
sanitizeGitHubErrorMessage(
|
|
432
|
-
{ status:
|
|
507
|
+
sanitizeGitHubErrorMessage(refRes.status, refRes.text),
|
|
508
|
+
{ status: refRes.status },
|
|
433
509
|
);
|
|
434
510
|
}
|
|
435
511
|
|
|
@@ -440,6 +516,7 @@ export function createGitHubRelayStore({
|
|
|
440
516
|
private: true,
|
|
441
517
|
branch: verified.branch,
|
|
442
518
|
branchExists: true,
|
|
519
|
+
emptyRepo: false,
|
|
443
520
|
canPush: verified.canPush,
|
|
444
521
|
};
|
|
445
522
|
},
|
|
@@ -491,7 +568,12 @@ export function createGitHubRelayStore({
|
|
|
491
568
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
492
569
|
const verified = await verifyPrivateRepo({ requirePush: true });
|
|
493
570
|
const refPath = `${repoApiBase}/git/ref/heads/${encodeRepoPath(verified.branch)}`;
|
|
494
|
-
|
|
571
|
+
let refRes = await request("GET", refPath);
|
|
572
|
+
if (isEmptyRepoResponse(refRes.status, refRes.text)) {
|
|
573
|
+
await initializeEmptyRepo(verified);
|
|
574
|
+
refRes = await request("GET", refPath);
|
|
575
|
+
}
|
|
576
|
+
const refObj = parseJsonResponseOrThrow(refRes, `ref heads/${verified.branch}`);
|
|
495
577
|
const headSha = refObj?.object?.sha;
|
|
496
578
|
if (typeof headSha !== "string" || !headSha) {
|
|
497
579
|
throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", "Branch reference response is missing head SHA.");
|
package/src/http-server.mjs
CHANGED
|
@@ -19,7 +19,7 @@ import { createSyncEngine } from "./sync-engine.mjs";
|
|
|
19
19
|
|
|
20
20
|
export const TOKEN_HEADER = "x-multi-usage-token";
|
|
21
21
|
export const DEFAULT_PORT = DEFAULT_CONFIG.port;
|
|
22
|
-
export const PLUGIN_VERSION = "0.3.
|
|
22
|
+
export const PLUGIN_VERSION = "0.3.4";
|
|
23
23
|
|
|
24
24
|
const MAX_JSON_BODY_BYTES = 256 * 1024;
|
|
25
25
|
const ALLOWED_RANGES = new Set(["today", "7d", "30d", "all"]);
|
package/src/sync-engine.mjs
CHANGED
package/src/ui/app.js
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
formatCoverageWindow,
|
|
11
11
|
formatExactNumber,
|
|
12
12
|
formatPercent,
|
|
13
|
+
formatTestConnectionFeedback,
|
|
13
14
|
formatTimestamp,
|
|
14
15
|
formatTrendPointTitle,
|
|
15
16
|
formatUsd,
|
|
@@ -989,13 +990,7 @@ async function handleTestConnection() {
|
|
|
989
990
|
githubToken: payload.githubToken,
|
|
990
991
|
},
|
|
991
992
|
});
|
|
992
|
-
|
|
993
|
-
? t(state.lang, "readWriteNote")
|
|
994
|
-
: t(state.lang, "readOnlyNote");
|
|
995
|
-
const branchNote = res.branchExists
|
|
996
|
-
? `${res.branch}`
|
|
997
|
-
: `${res.branch} (${t(state.lang, "branchMissingWarning")})`;
|
|
998
|
-
setFeedback(`${t(state.lang, "testSuccess")}: ${res.repo} [${branchNote}, ${permNote}]`, "ok");
|
|
993
|
+
setFeedback(formatTestConnectionFeedback(res, state.lang), "ok");
|
|
999
994
|
} catch (err) {
|
|
1000
995
|
setFeedback(err.message, "err");
|
|
1001
996
|
} finally {
|
|
@@ -1005,8 +1000,11 @@ async function handleTestConnection() {
|
|
|
1005
1000
|
}
|
|
1006
1001
|
|
|
1007
1002
|
async function handleSaveSettings(event) {
|
|
1008
|
-
event
|
|
1003
|
+
event?.preventDefault?.();
|
|
1009
1004
|
const btn = document.getElementById("save-cfg-btn");
|
|
1005
|
+
if (btn.disabled) {
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1010
1008
|
btn.disabled = true;
|
|
1011
1009
|
btn.textContent = t(state.lang, "saving");
|
|
1012
1010
|
setFeedback("");
|
|
@@ -1084,7 +1082,17 @@ function wireEvents() {
|
|
|
1084
1082
|
document.getElementById("clear-token-btn").classList.add("hidden");
|
|
1085
1083
|
});
|
|
1086
1084
|
document.getElementById("test-conn-btn").addEventListener("click", handleTestConnection);
|
|
1085
|
+
document.getElementById("save-cfg-btn").addEventListener("click", handleSaveSettings);
|
|
1087
1086
|
document.getElementById("settings-form").addEventListener("submit", handleSaveSettings);
|
|
1087
|
+
document.getElementById("settings-form").addEventListener("keydown", (event) => {
|
|
1088
|
+
if (event.key !== "Enter") {
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
const tag = event.target?.tagName?.toUpperCase();
|
|
1092
|
+
if (tag === "INPUT") {
|
|
1093
|
+
handleSaveSettings(event);
|
|
1094
|
+
}
|
|
1095
|
+
});
|
|
1088
1096
|
document.addEventListener("keydown", (event) => {
|
|
1089
1097
|
if (event.key === "Escape") {
|
|
1090
1098
|
closeSettingsDrawer();
|
package/src/ui/index.html
CHANGED
|
@@ -125,7 +125,7 @@
|
|
|
125
125
|
<div id="drawer-feedback" class="feedback hidden" aria-live="polite"></div>
|
|
126
126
|
<div class="sheet-footer">
|
|
127
127
|
<button id="test-conn-btn" type="button" class="pill-btn"></button>
|
|
128
|
-
<button id="save-cfg-btn" type="
|
|
128
|
+
<button id="save-cfg-btn" type="button" class="pill-btn pill-btn-primary"></button>
|
|
129
129
|
</div>
|
|
130
130
|
</form>
|
|
131
131
|
</aside>
|
package/src/ui/view-model.mjs
CHANGED
|
@@ -112,7 +112,7 @@ export const MESSAGES = Object.freeze({
|
|
|
112
112
|
saving: "Saving...",
|
|
113
113
|
testSuccess: "Private repository verified",
|
|
114
114
|
savedSuccess: "Settings saved and synced.",
|
|
115
|
-
branchMissingWarning: "
|
|
115
|
+
branchMissingWarning: "empty repo, will initialize on first sync",
|
|
116
116
|
readOnlyNote: "read-only token",
|
|
117
117
|
readWriteNote: "read/write token",
|
|
118
118
|
}),
|
|
@@ -224,7 +224,7 @@ export const MESSAGES = Object.freeze({
|
|
|
224
224
|
saving: "保存中...",
|
|
225
225
|
testSuccess: "私有仓库校验通过",
|
|
226
226
|
savedSuccess: "设置已保存并完成同步。",
|
|
227
|
-
branchMissingWarning: "
|
|
227
|
+
branchMissingWarning: "空仓库,首次同步将自动初始化",
|
|
228
228
|
readOnlyNote: "只读权限",
|
|
229
229
|
readWriteNote: "读写权限",
|
|
230
230
|
}),
|
|
@@ -652,3 +652,22 @@ export function isUnverifiedEmptyTrendPoint(point, availability = "ok") {
|
|
|
652
652
|
return ["totalTokens", "calls", "errors", "cost", "input", "output", "cacheRead", "cacheWrite"]
|
|
653
653
|
.every((key) => !Number(point[key]));
|
|
654
654
|
}
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* Format /api/test-connection success feedback using top-level canPush
|
|
658
|
+
* (true -> read/write, false -> read-only, null/absent -> omitted so unknown
|
|
659
|
+
* permissions are never mislabeled as read-only).
|
|
660
|
+
*/
|
|
661
|
+
export function formatTestConnectionFeedback(res, lang = "en") {
|
|
662
|
+
const branch = res?.branch || "";
|
|
663
|
+
const branchNote = res?.branchExists
|
|
664
|
+
? branch
|
|
665
|
+
: `${branch} (${t(lang, "branchMissingWarning")})`;
|
|
666
|
+
const parts = [branchNote];
|
|
667
|
+
if (res?.canPush === true) {
|
|
668
|
+
parts.push(t(lang, "readWriteNote"));
|
|
669
|
+
} else if (res?.canPush === false) {
|
|
670
|
+
parts.push(t(lang, "readOnlyNote"));
|
|
671
|
+
}
|
|
672
|
+
return `${t(lang, "testSuccess")}: ${res?.repo || ""} [${parts.join(", ")}]`;
|
|
673
|
+
}
|