@openchamber/web 1.18.4 → 1.19.0
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 +1 -0
- package/dist/assets/{CodeMirrorCommentWidgets-4qZbrEXU.js → CodeMirrorCommentWidgets-DAvopJvy.js} +1 -1
- package/dist/assets/{CommitSection-MJmntVPJ.js → CommitSection-D9cV-qR9.js} +1 -1
- package/dist/assets/{DiagramEditor-jnG3Hbxg.js → DiagramEditor-B9NCadU7.js} +1 -1
- package/dist/assets/DiagramView-LKGBwf4G.js +1 -0
- package/dist/assets/{DiffView-DZIoOnV7.js → DiffView-BWNq-0ov.js} +2 -2
- package/dist/assets/FilesView-DB-Q0Gkz.js +14 -0
- package/dist/assets/{GitView-DBFrDDBv.js → GitView-DsWXqWx3.js} +3 -3
- package/dist/assets/{JsonTreeView-DLW2Wy1g.js → JsonTreeView-h4dHASlq.js} +1 -1
- package/dist/assets/MarkdownImageGallery-n0ikH-xm.js +1 -0
- package/dist/assets/MarkdownRendererImpl-CT2mjx-s.js +12 -0
- package/dist/assets/OnboardingScreen-CDjgzxEe.js +1 -0
- package/dist/assets/{PatchDiff-BuLPx7AN.js → PatchDiff-jPKTJje5.js} +1 -1
- package/dist/assets/{PierreDiffViewer-BHm4Yr0X.js → PierreDiffViewer-D_Gt4A_6.js} +1 -1
- package/dist/assets/PlanView-UvuxIl9-.js +4 -0
- package/dist/assets/SessionSwitcherDropdown-xKU4LRuQ.js +1 -0
- package/dist/assets/SettingsView-3B9VN6Ys.js +28 -0
- package/dist/assets/SettingsWindow-CqQNDKNd.js +1 -0
- package/dist/assets/{ToolOutputDialog-Za6V4VMJ.js → ToolOutputDialog-PmjlAxVE.js} +6 -6
- package/dist/assets/{ToolPartDiffPreview-BL-9ixyC.js → ToolPartDiffPreview-B34Xw9wq.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-CwGocYQd.js → VirtualizedFileDiff-B37yB9jZ.js} +3 -3
- package/dist/assets/{WalkthroughView-5DyvN03T.js → WalkthroughView-Bxun3k66.js} +2 -2
- package/dist/assets/{computeVirtualFileMetrics-Da00Jg7M.js → computeVirtualFileMetrics-DYFv_yZS.js} +2 -2
- package/dist/assets/contextPanelEmbeddedChat-BO1wRpaN.js +1 -0
- package/dist/assets/de-DbV6CLxv.js +9 -0
- package/dist/assets/document-attachments-DFAWlG3U.js +31 -0
- package/dist/assets/es-CVDlyzZ4.js +15 -0
- package/dist/assets/fr-Czc-p0g-.js +13 -0
- package/dist/assets/index-1OhiMDBz.css +1 -0
- package/dist/assets/index-BSvmTvZl.js +1 -0
- package/dist/assets/index-DzriVon2.js +7 -0
- package/dist/assets/{isDiffPlainText-D9YpoLrV.js → isDiffPlainText-DwHKxDYc.js} +1 -1
- package/dist/assets/{isFilePlainText-gTibdNIe.js → isFilePlainText-Dwq6ILxo.js} +1 -1
- package/dist/assets/ja-dwc9NM_S.js +15 -0
- package/dist/assets/ko-Ds1DZ8FX.js +15 -0
- package/dist/assets/{lua-BgMRiT3U.js → lua-VAEuO923.js} +1 -1
- package/dist/assets/main-BF51IOVF.js +921 -0
- package/dist/assets/{main-D7UcL3VQ.js → main-D7UPARut.js} +2 -2
- package/dist/assets/markdownCore-BgeBDwD3.js +2 -0
- package/dist/assets/{miniChat-O_GVoEbc.js → miniChat-BISXSGOo.js} +2 -2
- package/dist/assets/mobile-BnYxVuvw.js +2 -0
- package/dist/assets/{patchFileDiff-KNkxM1C1.js → patchFileDiff-BEDPDypx.js} +2 -2
- package/dist/assets/pl-CLiTO7i-.js +15 -0
- package/dist/assets/pt-BR-GIimJgpK.js +15 -0
- package/dist/assets/renderElectronMiniChatApp-BaOy72Gi.js +2 -0
- package/dist/assets/{renderMobileApp-toj9cXoh.js → renderMobileApp-BiMbzPq9.js} +7 -7
- package/dist/assets/runtimeEndpointReset-BMBRhIbf.js +15 -0
- package/dist/assets/scheduledTasksApi-01zzfzqH.js +1 -0
- package/dist/assets/{shikiHighlight-C7LTbwFx.js → shikiHighlight-DXYW46vW.js} +1 -1
- package/dist/assets/uk-DLfgD1ki.js +15 -0
- package/dist/assets/{useAppFontEffects-BikB6enL.js → useAppFontEffects-CbzHzFop.js} +139 -142
- package/dist/assets/{useInlineCommentController-CYPvYJDt.js → useInlineCommentController-CegKdDXi.js} +2 -2
- package/dist/assets/{vendor-base-ui-D_V6hAcE.js → vendor-base-ui-BYlZTzrw.js} +1 -1
- package/dist/assets/vendor-codemirror-autocomplete-DzPz9Wgq.js +1 -0
- package/dist/assets/vendor-codemirror-commands-B7H_j0iU.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-angular-CgY7_gQ1.js → vendor-codemirror-lang-angular-DEPs2M5t.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-B5Ta4enQ.js → vendor-codemirror-lang-cpp-DhkseaMo.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-VgNqFSH-.js → vendor-codemirror-lang-css-O0cZX78y.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-LxLz62pp.js → vendor-codemirror-lang-go-fMdQYcON.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-html-CfgK872x.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-java-Bksi1PH4.js → vendor-codemirror-lang-java-CQj4S3zl.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-javascript-Cc2ZYbgX.js +13 -0
- package/dist/assets/{vendor-codemirror-lang-jinja-C7npuDD7.js → vendor-codemirror-lang-jinja-BmZZv8g-.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-ryCw7nab.js → vendor-codemirror-lang-json-CMBS2tG9.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-BxsZJD6N.js → vendor-codemirror-lang-less-C6Eo8hVS.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-De6qch10.js → vendor-codemirror-lang-liquid-DSTR47-H.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-markdown-BPGOH9ye.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-php-Cm1es33p.js → vendor-codemirror-lang-php-DD9udfPH.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-N414WYK-.js → vendor-codemirror-lang-python-HahnQaAS.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-C_WuUStH.js → vendor-codemirror-lang-rust-nLTovbjv.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-8UHTCAOM.js → vendor-codemirror-lang-sass-pL2Yc72v.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-CV3sMA5D.js → vendor-codemirror-lang-sql-BVBnan19.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-DzvC1Dhk.js → vendor-codemirror-lang-vue-BqGzJVm1.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-jlr-LDdA.js → vendor-codemirror-lang-wast-B0_m5DqU.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-CrO63OVp.js → vendor-codemirror-lang-xml-Dj3voadT.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-dxi6CISW.js → vendor-codemirror-lang-yaml-yu-9Z5u7.js} +1 -1
- package/dist/assets/vendor-codemirror-language-BgPj_McA.js +3 -0
- package/dist/assets/{vendor-codemirror-language-data-CLHw8NWn.js → vendor-codemirror-language-data-CiAYDJXN.js} +2 -2
- package/dist/assets/vendor-codemirror-search-BmS-GmcX.js +2 -0
- package/dist/assets/{vendor-codemirror-state-CNWM3Q8V.js → vendor-codemirror-state-C9awkmn-.js} +5 -5
- package/dist/assets/vendor-codemirror-view-CiLROUVV.js +4 -0
- package/dist/assets/vendor-replit-codemirror-vim-B2DJlAhT.js +6 -0
- package/dist/assets/vendor-replit-codemirror-vim-core-FHzKdNUS.js +34 -0
- package/dist/assets/vendor-zod-adaMkgkm.js +39 -0
- package/dist/assets/{web-components-GMc3oR3i.js → web-components-DCLjCO9n.js} +1 -1
- package/dist/assets/zh-CN-DkeP5awK.js +15 -0
- package/dist/assets/zh-TW-BocaFm3d.js +15 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/index.js +116 -3
- package/server/lib/agent-memory/actions.js +243 -0
- package/server/lib/agent-memory/actions.test.js +343 -0
- package/server/lib/agent-memory/feature-flag.js +19 -0
- package/server/lib/agent-memory/feature-flag.test.js +38 -0
- package/server/lib/agent-memory/project-resolution.js +56 -0
- package/server/lib/agent-memory/project-resolution.test.js +85 -0
- package/server/lib/agent-memory/routes.http.test.js +270 -0
- package/server/lib/agent-memory/routes.js +169 -0
- package/server/lib/agent-memory/runtime.js +427 -0
- package/server/lib/agent-memory/runtime.test.js +344 -0
- package/server/lib/agent-memory/threat-patterns.js +61 -0
- package/server/lib/agent-memory/threat-patterns.test.js +61 -0
- package/server/lib/agent-tool/DOCUMENTATION.md +14 -0
- package/server/lib/agent-tool/runtime.js +63 -13
- package/server/lib/agent-tool/runtime.test.js +85 -2
- package/server/lib/context-obligatory/runtime.js +34 -3
- package/server/lib/context-obligatory/runtime.test.js +114 -0
- package/server/lib/fs/DOCUMENTATION.md +3 -0
- package/server/lib/fs/routes.js +149 -32
- package/server/lib/fs/routes.test.js +225 -0
- package/server/lib/git/DOCUMENTATION.md +8 -0
- package/server/lib/git/service.js +121 -67
- package/server/lib/git/service.test.js +129 -0
- package/server/lib/github/DOCUMENTATION.md +14 -3
- package/server/lib/github/pr-status.js +188 -83
- package/server/lib/github/pr-status.test.js +182 -0
- package/server/lib/github/routes.js +36 -30
- package/server/lib/notifications/template-runtime.js +2 -3
- package/server/lib/openchamber-control/action-resolution.test.js +65 -0
- package/server/lib/openchamber-control/actions.js +78 -0
- package/server/lib/openchamber-control/service.js +7 -0
- package/server/lib/openchamber-sessions/routes.js +14 -0
- package/server/lib/opencode/DOCUMENTATION.md +6 -4
- package/server/lib/opencode/claude-cli-auth.js +60 -0
- package/server/lib/opencode/claude-cli-auth.test.js +54 -0
- package/server/lib/opencode/feature-routes-runtime.js +11 -0
- package/server/lib/opencode/plugins.js +12 -3
- package/server/lib/opencode/plugins.test.js +18 -0
- package/server/lib/opencode/proxy-agent-wiring.test.js +152 -0
- package/server/lib/opencode/proxy.js +116 -6
- package/server/lib/opencode/proxy.test.js +158 -1
- package/server/lib/opencode/routes.js +4 -1
- package/server/lib/opencode/settings-helpers.js +11 -0
- package/server/lib/opencode/settings-helpers.test.js +35 -0
- package/server/lib/opencode/settings-runtime.js +51 -0
- package/server/lib/opencode/shared.js +120 -16
- package/server/lib/opencode/shared.test.js +185 -1
- package/server/lib/project-context/DOCUMENTATION.md +158 -0
- package/server/lib/project-context/routes.http.test.js +264 -0
- package/server/lib/project-context/routes.js +237 -0
- package/server/lib/project-context/runtime.js +667 -0
- package/server/lib/project-context/runtime.test.js +498 -0
- package/server/lib/quota/DOCUMENTATION.md +16 -1
- package/server/lib/quota/providers/claude/auth.js +113 -0
- package/server/lib/quota/providers/claude/auth.test.js +117 -0
- package/server/lib/quota/providers/claude/index.js +151 -0
- package/server/lib/quota/providers/claude/index.test.js +147 -0
- package/server/lib/quota/providers/claude/transforms.js +127 -0
- package/server/lib/quota/providers/claude/transforms.test.js +82 -0
- package/server/lib/quota/providers/command-code.js +90 -0
- package/server/lib/quota/providers/command-code.test.js +72 -0
- package/server/lib/quota/providers/index.js +22 -2
- package/server/lib/quota/providers/index.test.js +10 -1
- package/server/lib/quota/utils/formatters.js +2 -1
- package/server/lib/scheduled-tasks/runtime.js +21 -2
- package/server/lib/session-knowledge/DOCUMENTATION.md +87 -0
- package/server/lib/session-knowledge/routes.js +107 -0
- package/server/lib/session-knowledge/runtime.js +331 -0
- package/server/lib/session-knowledge/runtime.test.js +275 -0
- package/server/lib/skills-catalog/DOCUMENTATION.md +22 -22
- package/server/lib/skills-catalog/curated-sources.js +1 -1
- package/server/lib/skills-catalog/curated-sources.test.js +10 -0
- package/server/lib/small-model/index.js +8 -0
- package/server/lib/small-model/index.test.js +31 -1
- package/server/lib/small-model/routes.js +3 -1
- package/dist/assets/DiagramView-CFXxgg_a.js +0 -1
- package/dist/assets/FilesView-BKL6YlKG.js +0 -14
- package/dist/assets/MarkdownImageGallery-DKIylIK7.js +0 -1
- package/dist/assets/MarkdownRendererImpl-CLv8hxvv.js +0 -12
- package/dist/assets/OnboardingScreen-D2Y6djMw.js +0 -1
- package/dist/assets/PlanView-ZYEJn8A_.js +0 -4
- package/dist/assets/SessionSwitcherDropdown-rro-SsaO.js +0 -1
- package/dist/assets/SettingsView-5RmswFZe.js +0 -28
- package/dist/assets/SettingsWindow-BZhAYFdS.js +0 -1
- package/dist/assets/contextPanelEmbeddedChat-B-bSg3P5.js +0 -1
- package/dist/assets/de-u7gSnqWs.js +0 -9
- package/dist/assets/document-attachments-CX_YaDsu.js +0 -30
- package/dist/assets/es-T9O7aAOr.js +0 -15
- package/dist/assets/fr-Oor7ewbE.js +0 -13
- package/dist/assets/index-BzIpNlNE.css +0 -1
- package/dist/assets/index-C0yNhuZw.js +0 -1
- package/dist/assets/index-DRpChWux.js +0 -7
- package/dist/assets/ja-DHpqbVmr.js +0 -15
- package/dist/assets/ko-CwLkS3nx.js +0 -15
- package/dist/assets/main-DPMd2iKS.js +0 -915
- package/dist/assets/markdownCore-DDrHVneM.js +0 -2
- package/dist/assets/mobile-Br4TtAqc.js +0 -2
- package/dist/assets/pl-CcZILN8q.js +0 -15
- package/dist/assets/pt-BR-DYHhVK6o.js +0 -15
- package/dist/assets/renderElectronMiniChatApp-CJpdxTT1.js +0 -2
- package/dist/assets/runtimeEndpointReset-BVmispdD.js +0 -13
- package/dist/assets/scheduledTasksApi-ByKya3Un.js +0 -1
- package/dist/assets/uk-BA2kZR38.js +0 -15
- package/dist/assets/vendor-codemirror-autocomplete-BjbBRsUA.js +0 -1
- package/dist/assets/vendor-codemirror-commands-ARAOgp1x.js +0 -1
- package/dist/assets/vendor-codemirror-lang-html-B3Qe3OpS.js +0 -1
- package/dist/assets/vendor-codemirror-lang-javascript-Bbw3D7r0.js +0 -13
- package/dist/assets/vendor-codemirror-lang-markdown-FGQydhTc.js +0 -1
- package/dist/assets/vendor-codemirror-language-DUOssd4j.js +0 -3
- package/dist/assets/vendor-codemirror-search-8kyQdB3f.js +0 -2
- package/dist/assets/vendor-codemirror-view-DSzLbZiS.js +0 -4
- package/dist/assets/vendor-replit-codemirror-vim-B0Ecqnlh.js +0 -39
- package/dist/assets/zh-CN-dlOQK6v9.js +0 -15
- package/dist/assets/zh-TW-BnqQ-WL5.js +0 -15
- package/server/lib/quota/providers/claude.js +0 -107
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const execFileSync = vi.fn();
|
|
4
|
+
const files = new Map();
|
|
5
|
+
const openCodeAuth = vi.fn(() => ({}));
|
|
6
|
+
|
|
7
|
+
vi.mock('child_process', () => ({ execFileSync: (...args) => execFileSync(...args) }));
|
|
8
|
+
|
|
9
|
+
vi.mock('fs', () => {
|
|
10
|
+
const fs = {
|
|
11
|
+
existsSync: (filePath) => files.has(filePath),
|
|
12
|
+
readFileSync: (filePath) => {
|
|
13
|
+
if (!files.has(filePath)) throw new Error('ENOENT');
|
|
14
|
+
return files.get(filePath);
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
return { ...fs, default: fs };
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
vi.mock('../../../opencode/auth.js', () => ({ readAuthFile: () => openCodeAuth() }));
|
|
21
|
+
|
|
22
|
+
import { loadClaudeCredential } from './auth.js';
|
|
23
|
+
|
|
24
|
+
const claudeCodeBlob = (accessToken) => JSON.stringify({
|
|
25
|
+
mcpOAuth: { 'linear|abc': { accessToken: 'unrelated-mcp-token' } },
|
|
26
|
+
claudeAiOauth: {
|
|
27
|
+
accessToken,
|
|
28
|
+
refreshToken: `${accessToken}-refresh`,
|
|
29
|
+
expiresAt: 1786735755912,
|
|
30
|
+
subscriptionType: 'max',
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const withPlatform = (platform, run) => {
|
|
35
|
+
const original = Object.getOwnPropertyDescriptor(process, 'platform');
|
|
36
|
+
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
|
37
|
+
try {
|
|
38
|
+
return run();
|
|
39
|
+
} finally {
|
|
40
|
+
Object.defineProperty(process, 'platform', original);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
beforeEach(() => {
|
|
45
|
+
files.clear();
|
|
46
|
+
execFileSync.mockReset();
|
|
47
|
+
execFileSync.mockImplementation(() => { throw new Error('no keychain entry'); });
|
|
48
|
+
openCodeAuth.mockReturnValue({});
|
|
49
|
+
delete process.env.CLAUDE_CONFIG_DIR;
|
|
50
|
+
delete process.env.CLAUDE_CODE_OAUTH_TOKEN;
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
afterEach(() => {
|
|
54
|
+
delete process.env.CLAUDE_CONFIG_DIR;
|
|
55
|
+
delete process.env.CLAUDE_CODE_OAUTH_TOKEN;
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe('Claude credential discovery', () => {
|
|
59
|
+
it('prefers the macOS Keychain over a stale credentials file', () => {
|
|
60
|
+
execFileSync.mockReturnValue(claudeCodeBlob('keychain-token'));
|
|
61
|
+
files.set(`${process.env.HOME}/.claude/.credentials.json`, claudeCodeBlob('file-token'));
|
|
62
|
+
|
|
63
|
+
const credential = withPlatform('darwin', loadClaudeCredential);
|
|
64
|
+
|
|
65
|
+
expect(credential.accessToken).toBe('keychain-token');
|
|
66
|
+
expect(credential.refreshToken).toBe('keychain-token-refresh');
|
|
67
|
+
expect(credential.planLabel).toBe('max');
|
|
68
|
+
expect(credential.source).toBe('keychain');
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('reads the credentials file on Linux, where there is no Keychain', () => {
|
|
72
|
+
files.set(`${process.env.HOME}/.claude/.credentials.json`, claudeCodeBlob('file-token'));
|
|
73
|
+
|
|
74
|
+
const credential = withPlatform('linux', loadClaudeCredential);
|
|
75
|
+
|
|
76
|
+
expect(execFileSync).not.toHaveBeenCalled();
|
|
77
|
+
expect(credential.accessToken).toBe('file-token');
|
|
78
|
+
expect(credential.source).toBe('credentials-file');
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('honours CLAUDE_CONFIG_DIR when locating the credentials file', () => {
|
|
82
|
+
process.env.CLAUDE_CONFIG_DIR = '/tmp/claude-home';
|
|
83
|
+
files.set('/tmp/claude-home/.credentials.json', claudeCodeBlob('custom-dir-token'));
|
|
84
|
+
|
|
85
|
+
expect(withPlatform('linux', loadClaudeCredential).accessToken).toBe('custom-dir-token');
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('falls back to the OpenCode auth entry when Claude Code is not signed in', () => {
|
|
89
|
+
openCodeAuth.mockReturnValue({ anthropic: { access: 'opencode-token', refresh: 'opencode-refresh', expires: 1786735755912 } });
|
|
90
|
+
|
|
91
|
+
const credential = withPlatform('linux', loadClaudeCredential);
|
|
92
|
+
|
|
93
|
+
expect(credential.accessToken).toBe('opencode-token');
|
|
94
|
+
expect(credential.source).toBe('opencode-auth');
|
|
95
|
+
expect(credential.planLabel).toBeNull();
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('falls back to CLAUDE_CODE_OAUTH_TOKEN last, without a refresh token', () => {
|
|
99
|
+
process.env.CLAUDE_CODE_OAUTH_TOKEN = 'env-token';
|
|
100
|
+
|
|
101
|
+
const credential = withPlatform('linux', loadClaudeCredential);
|
|
102
|
+
|
|
103
|
+
expect(credential.accessToken).toBe('env-token');
|
|
104
|
+
expect(credential.refreshToken).toBeNull();
|
|
105
|
+
expect(credential.source).toBe('env');
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('ignores a Keychain blob that only holds unrelated MCP tokens', () => {
|
|
109
|
+
execFileSync.mockReturnValue(JSON.stringify({ mcpOAuth: { 'linear|abc': { accessToken: 'unrelated' } } }));
|
|
110
|
+
|
|
111
|
+
expect(withPlatform('darwin', loadClaudeCredential)).toBeNull();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('returns null when every source is empty', () => {
|
|
115
|
+
expect(withPlatform('darwin', loadClaudeCredential)).toBeNull();
|
|
116
|
+
});
|
|
117
|
+
});
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude subscription quota.
|
|
3
|
+
*
|
|
4
|
+
* Reports the plan limits Claude Code itself is bound by (rolling session
|
|
5
|
+
* window, weekly windows, model-scoped weekly windows, and paid extra usage)
|
|
6
|
+
* using the OAuth credential Claude Code already holds.
|
|
7
|
+
*
|
|
8
|
+
* @module quota/providers/claude
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { createHash } from 'crypto';
|
|
12
|
+
|
|
13
|
+
import { buildResult } from '../../utils/index.js';
|
|
14
|
+
import { loadClaudeCredential } from './auth.js';
|
|
15
|
+
import { toClaudeUsage } from './transforms.js';
|
|
16
|
+
|
|
17
|
+
export const providerId = 'claude';
|
|
18
|
+
export const providerName = 'Claude';
|
|
19
|
+
export const aliases = ['anthropic', 'claude'];
|
|
20
|
+
|
|
21
|
+
const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage';
|
|
22
|
+
const OAUTH_BETA_HEADER = 'oauth-2025-04-20';
|
|
23
|
+
const DEFAULT_COOLDOWN_MS = 5 * 60 * 1000;
|
|
24
|
+
const MAX_COOLDOWN_MS = 60 * 60 * 1000;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Last good payload, kept only to survive Anthropic's aggressive rate limiting.
|
|
28
|
+
* Keyed by credential fingerprint so a second account never sees the first
|
|
29
|
+
* account's numbers.
|
|
30
|
+
*
|
|
31
|
+
* @type {{ fingerprint: string, usage: object, planLabel: string|null }|null}
|
|
32
|
+
*/
|
|
33
|
+
let cachedUsage = null;
|
|
34
|
+
let cooldownUntil = 0;
|
|
35
|
+
let pendingFetch = null;
|
|
36
|
+
|
|
37
|
+
const fingerprintOf = (credential) =>
|
|
38
|
+
createHash('sha256').update(`${credential.accessToken}\0${credential.refreshToken ?? ''}`).digest('hex');
|
|
39
|
+
|
|
40
|
+
const cooldownFromHeader = (response) => {
|
|
41
|
+
const raw = response.headers.get('retry-after');
|
|
42
|
+
const retryAfter = Number(raw);
|
|
43
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0) {
|
|
44
|
+
return Math.min(retryAfter * 1000, MAX_COOLDOWN_MS);
|
|
45
|
+
}
|
|
46
|
+
const retryAt = raw ? Date.parse(raw) : Number.NaN;
|
|
47
|
+
if (Number.isFinite(retryAt) && retryAt > Date.now()) {
|
|
48
|
+
return Math.min(retryAt - Date.now(), MAX_COOLDOWN_MS);
|
|
49
|
+
}
|
|
50
|
+
return DEFAULT_COOLDOWN_MS;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const cachedResultFor = (fingerprint, planLabel) => {
|
|
54
|
+
if (!cachedUsage || cachedUsage.fingerprint !== fingerprint) return null;
|
|
55
|
+
return buildResult({
|
|
56
|
+
providerId,
|
|
57
|
+
providerName,
|
|
58
|
+
ok: true,
|
|
59
|
+
configured: true,
|
|
60
|
+
usage: cachedUsage.usage,
|
|
61
|
+
planLabel: planLabel ?? cachedUsage.planLabel
|
|
62
|
+
});
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const failure = (error, { configured = true } = {}) =>
|
|
66
|
+
buildResult({ providerId, providerName, ok: false, configured, error });
|
|
67
|
+
|
|
68
|
+
export const isConfigured = () => Boolean(loadClaudeCredential());
|
|
69
|
+
|
|
70
|
+
const fetchQuotaUncoalesced = async () => {
|
|
71
|
+
const credential = loadClaudeCredential();
|
|
72
|
+
if (!credential) {
|
|
73
|
+
return failure('Not configured', { configured: false });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const fingerprint = fingerprintOf(credential);
|
|
77
|
+
if (cachedUsage && cachedUsage.fingerprint !== fingerprint) {
|
|
78
|
+
cachedUsage = null;
|
|
79
|
+
cooldownUntil = 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (Date.now() < cooldownUntil) {
|
|
83
|
+
return cachedResultFor(fingerprint, credential.planLabel)
|
|
84
|
+
?? failure('Rate limited by Anthropic. Retrying shortly.');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
let response;
|
|
88
|
+
try {
|
|
89
|
+
response = await fetch(USAGE_URL, {
|
|
90
|
+
method: 'GET',
|
|
91
|
+
headers: {
|
|
92
|
+
Authorization: `Bearer ${credential.accessToken}`,
|
|
93
|
+
'anthropic-beta': OAUTH_BETA_HEADER
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
} catch (error) {
|
|
97
|
+
return failure(error instanceof Error ? error.message : 'Request failed');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (response.status === 429) {
|
|
101
|
+
cooldownUntil = Date.now() + cooldownFromHeader(response);
|
|
102
|
+
return cachedResultFor(fingerprint, credential.planLabel)
|
|
103
|
+
?? failure('Rate limited by Anthropic. Retrying shortly.');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (response.status === 401 || response.status === 403) {
|
|
107
|
+
return failure('Claude session expired. Open Claude Code to sign in again.');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (!response.ok) {
|
|
111
|
+
return failure(`API error: ${response.status}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
let payload;
|
|
115
|
+
try {
|
|
116
|
+
payload = await response.json();
|
|
117
|
+
} catch {
|
|
118
|
+
return failure('Unexpected response from Anthropic');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const { windows, models } = toClaudeUsage(payload);
|
|
122
|
+
const usage = Object.keys(models).length > 0 ? { windows, models } : { windows };
|
|
123
|
+
cachedUsage = { fingerprint, usage, planLabel: credential.planLabel };
|
|
124
|
+
|
|
125
|
+
return buildResult({
|
|
126
|
+
providerId,
|
|
127
|
+
providerName,
|
|
128
|
+
ok: true,
|
|
129
|
+
configured: true,
|
|
130
|
+
usage,
|
|
131
|
+
planLabel: credential.planLabel
|
|
132
|
+
});
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
export const fetchQuota = () => {
|
|
136
|
+
if (pendingFetch) return pendingFetch;
|
|
137
|
+
|
|
138
|
+
const request = fetchQuotaUncoalesced();
|
|
139
|
+
const pending = request.finally(() => {
|
|
140
|
+
if (pendingFetch === pending) pendingFetch = null;
|
|
141
|
+
});
|
|
142
|
+
pendingFetch = pending;
|
|
143
|
+
return pendingFetch;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/** Test seam: clears the rate-limit cache between cases. */
|
|
147
|
+
export const resetClaudeQuotaCache = () => {
|
|
148
|
+
cachedUsage = null;
|
|
149
|
+
cooldownUntil = 0;
|
|
150
|
+
pendingFetch = null;
|
|
151
|
+
};
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const credential = vi.fn();
|
|
4
|
+
|
|
5
|
+
vi.mock('./auth.js', () => ({
|
|
6
|
+
loadClaudeCredential: () => credential(),
|
|
7
|
+
}));
|
|
8
|
+
|
|
9
|
+
import { fetchQuota, isConfigured, resetClaudeQuotaCache } from './index.js';
|
|
10
|
+
|
|
11
|
+
const CREDENTIAL = {
|
|
12
|
+
accessToken: 'access-a',
|
|
13
|
+
refreshToken: 'refresh-a',
|
|
14
|
+
expiresAt: Date.now() + 3_600_000,
|
|
15
|
+
planLabel: 'max',
|
|
16
|
+
source: 'keychain',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const PAYLOAD = {
|
|
20
|
+
limits: [
|
|
21
|
+
{ kind: 'session', percent: 5, resets_at: '2026-08-14T19:10:00Z', scope: null },
|
|
22
|
+
{ kind: 'weekly_all', percent: 4, resets_at: '2026-08-20T15:00:00Z', scope: null },
|
|
23
|
+
],
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const jsonResponse = (body) => ({
|
|
27
|
+
ok: true,
|
|
28
|
+
status: 200,
|
|
29
|
+
headers: new Headers(),
|
|
30
|
+
json: async () => body,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const errorResponse = (status, headers = {}) => ({
|
|
34
|
+
ok: false,
|
|
35
|
+
status,
|
|
36
|
+
headers: new Headers(headers),
|
|
37
|
+
json: async () => ({}),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
beforeEach(() => {
|
|
41
|
+
resetClaudeQuotaCache();
|
|
42
|
+
credential.mockReturnValue(CREDENTIAL);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
afterEach(() => {
|
|
46
|
+
vi.unstubAllGlobals();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('Claude quota provider', () => {
|
|
50
|
+
it('reports not configured when no credential source has a token', async () => {
|
|
51
|
+
credential.mockReturnValue(null);
|
|
52
|
+
|
|
53
|
+
expect(isConfigured()).toBe(false);
|
|
54
|
+
const result = await fetchQuota();
|
|
55
|
+
expect(result.configured).toBe(false);
|
|
56
|
+
expect(result.ok).toBe(false);
|
|
57
|
+
expect(result.usage).toBeNull();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('returns windows and the plan label from the credential', async () => {
|
|
61
|
+
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse(PAYLOAD)));
|
|
62
|
+
|
|
63
|
+
const result = await fetchQuota();
|
|
64
|
+
|
|
65
|
+
expect(result.ok).toBe(true);
|
|
66
|
+
expect(result.planLabel).toBe('max');
|
|
67
|
+
expect(result.usage.windows['5h'].usedPercent).toBe(5);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('coalesces concurrent refreshes into one Anthropic request', async () => {
|
|
71
|
+
let resolveResponse;
|
|
72
|
+
const fetchMock = vi.fn().mockReturnValue(new Promise((resolve) => {
|
|
73
|
+
resolveResponse = resolve;
|
|
74
|
+
}));
|
|
75
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
76
|
+
|
|
77
|
+
const first = fetchQuota();
|
|
78
|
+
const second = fetchQuota();
|
|
79
|
+
resolveResponse(jsonResponse(PAYLOAD));
|
|
80
|
+
|
|
81
|
+
const [firstResult, secondResult] = await Promise.all([first, second]);
|
|
82
|
+
|
|
83
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
84
|
+
expect(firstResult.ok).toBe(true);
|
|
85
|
+
expect(secondResult.ok).toBe(true);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('keeps serving the last good values while Anthropic rate limits', async () => {
|
|
89
|
+
const fetchMock = vi.fn()
|
|
90
|
+
.mockResolvedValueOnce(jsonResponse(PAYLOAD))
|
|
91
|
+
.mockResolvedValueOnce(errorResponse(429, { 'retry-after': '120' }));
|
|
92
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
93
|
+
|
|
94
|
+
await fetchQuota();
|
|
95
|
+
const rateLimited = await fetchQuota();
|
|
96
|
+
|
|
97
|
+
expect(rateLimited.ok).toBe(true);
|
|
98
|
+
expect(rateLimited.usage.windows['5h'].usedPercent).toBe(5);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('does not call Anthropic again while the rate-limit cooldown is active', async () => {
|
|
102
|
+
const fetchMock = vi.fn()
|
|
103
|
+
.mockResolvedValueOnce(jsonResponse(PAYLOAD))
|
|
104
|
+
.mockResolvedValueOnce(errorResponse(429));
|
|
105
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
106
|
+
|
|
107
|
+
await fetchQuota();
|
|
108
|
+
await fetchQuota();
|
|
109
|
+
await fetchQuota();
|
|
110
|
+
|
|
111
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('never shows one account cached values after the credential changes', async () => {
|
|
115
|
+
const fetchMock = vi.fn()
|
|
116
|
+
.mockResolvedValueOnce(jsonResponse(PAYLOAD))
|
|
117
|
+
.mockResolvedValueOnce(errorResponse(429));
|
|
118
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
119
|
+
|
|
120
|
+
await fetchQuota();
|
|
121
|
+
credential.mockReturnValue({ ...CREDENTIAL, accessToken: 'access-b', refreshToken: 'refresh-b', planLabel: null });
|
|
122
|
+
const afterSwitch = await fetchQuota();
|
|
123
|
+
|
|
124
|
+
expect(afterSwitch.ok).toBe(false);
|
|
125
|
+
expect(afterSwitch.usage).toBeNull();
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it('explains an expired session instead of reporting a bare 401', async () => {
|
|
129
|
+
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(errorResponse(401)));
|
|
130
|
+
|
|
131
|
+
const result = await fetchQuota();
|
|
132
|
+
|
|
133
|
+
expect(result.ok).toBe(false);
|
|
134
|
+
expect(result.configured).toBe(true);
|
|
135
|
+
expect(result.error).toContain('Claude Code');
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('surfaces a network failure instead of an empty successful result', async () => {
|
|
139
|
+
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('socket hang up')));
|
|
140
|
+
|
|
141
|
+
const result = await fetchQuota();
|
|
142
|
+
|
|
143
|
+
expect(result.ok).toBe(false);
|
|
144
|
+
expect(result.usage).toBeNull();
|
|
145
|
+
expect(result.error).toBe('socket hang up');
|
|
146
|
+
});
|
|
147
|
+
});
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shapes Anthropic's OAuth usage payload into quota windows.
|
|
3
|
+
*
|
|
4
|
+
* The payload carries the same limit twice: a legacy set of named fields
|
|
5
|
+
* (`five_hour`, `seven_day`, ...) and a newer `limits` array. Only the array
|
|
6
|
+
* reports model-scoped limits, and Anthropic ships new limit kinds there under
|
|
7
|
+
* rotating internal code names, so limits are read from the array by `kind` and
|
|
8
|
+
* fall back to the legacy fields when the array is missing.
|
|
9
|
+
*
|
|
10
|
+
* @module quota/providers/claude/transforms
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { asObject, asNonEmptyString, toNumber, toTimestamp, toUsageWindow, formatMoney } from '../../utils/index.js';
|
|
14
|
+
|
|
15
|
+
const SESSION_WINDOW = '5h';
|
|
16
|
+
const WEEKLY_WINDOW = '7d';
|
|
17
|
+
const EXTRA_USAGE_WINDOW = 'extra_usage';
|
|
18
|
+
|
|
19
|
+
// Consumers rank limits by how soon they run out, so each window carries its
|
|
20
|
+
// duration. Extra usage is a monthly spend cap, not a rolling window.
|
|
21
|
+
const SESSION_WINDOW_SECONDS = 5 * 60 * 60;
|
|
22
|
+
const WEEKLY_WINDOW_SECONDS = 7 * 24 * 60 * 60;
|
|
23
|
+
|
|
24
|
+
const asArray = (value) => (Array.isArray(value) ? value : []);
|
|
25
|
+
|
|
26
|
+
/** Money in Anthropic's minor-unit form, e.g. `{ amount_minor: 10000, exponent: 2 }`. */
|
|
27
|
+
const toAmount = (value) => {
|
|
28
|
+
const money = asObject(value);
|
|
29
|
+
const minor = toNumber(money?.amount_minor);
|
|
30
|
+
if (minor === null) return null;
|
|
31
|
+
const exponent = toNumber(money?.exponent) ?? 2;
|
|
32
|
+
return minor / 10 ** exponent;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const formatSpendLabel = (used, limit, currency) => {
|
|
36
|
+
const usedLabel = formatMoney(used);
|
|
37
|
+
if (usedLabel === null) return null;
|
|
38
|
+
const prefix = currency === 'USD' || !currency ? '$' : `${currency} `;
|
|
39
|
+
const limitLabel = formatMoney(limit);
|
|
40
|
+
return limitLabel === null ? `${prefix}${usedLabel}` : `${prefix}${usedLabel} / ${prefix}${limitLabel}`;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const addWindow = (target, key, { percent, resetAt, valueLabel, windowSeconds = null }) => {
|
|
44
|
+
if (percent === null && !valueLabel) return;
|
|
45
|
+
target[key] = toUsageWindow({ usedPercent: percent, windowSeconds, resetAt, valueLabel });
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const applyLimitsArray = (limits, windows, models) => {
|
|
49
|
+
for (const entry of limits) {
|
|
50
|
+
const limit = asObject(entry);
|
|
51
|
+
if (!limit) continue;
|
|
52
|
+
const percent = toNumber(limit.percent);
|
|
53
|
+
const resetAt = toTimestamp(limit.resets_at);
|
|
54
|
+
const modelName = asNonEmptyString(asObject(asObject(limit.scope)?.model)?.display_name);
|
|
55
|
+
|
|
56
|
+
if (limit.kind === 'session') {
|
|
57
|
+
addWindow(windows, SESSION_WINDOW, { percent, resetAt, windowSeconds: SESSION_WINDOW_SECONDS });
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (limit.kind === 'weekly_all') {
|
|
61
|
+
addWindow(windows, WEEKLY_WINDOW, { percent, resetAt, windowSeconds: WEEKLY_WINDOW_SECONDS });
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (limit.kind === 'weekly_scoped' && modelName) {
|
|
65
|
+
const modelWindows = {};
|
|
66
|
+
addWindow(modelWindows, WEEKLY_WINDOW, { percent, resetAt, windowSeconds: WEEKLY_WINDOW_SECONDS });
|
|
67
|
+
if (Object.keys(modelWindows).length > 0) models[modelName] = { windows: modelWindows };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const applyLegacyFields = (payload, windows) => {
|
|
73
|
+
const fiveHour = asObject(payload.five_hour);
|
|
74
|
+
const sevenDay = asObject(payload.seven_day);
|
|
75
|
+
if (fiveHour) {
|
|
76
|
+
addWindow(windows, SESSION_WINDOW, {
|
|
77
|
+
percent: toNumber(fiveHour.utilization),
|
|
78
|
+
resetAt: toTimestamp(fiveHour.resets_at),
|
|
79
|
+
windowSeconds: SESSION_WINDOW_SECONDS
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (sevenDay) {
|
|
83
|
+
addWindow(windows, WEEKLY_WINDOW, {
|
|
84
|
+
percent: toNumber(sevenDay.utilization),
|
|
85
|
+
resetAt: toTimestamp(sevenDay.resets_at),
|
|
86
|
+
windowSeconds: WEEKLY_WINDOW_SECONDS
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Extra usage is the paid overflow beyond plan limits. It is only meaningful
|
|
93
|
+
* once the account has it enabled; a disabled block would render as a permanent
|
|
94
|
+
* empty bar.
|
|
95
|
+
*/
|
|
96
|
+
const applyExtraUsage = (payload, windows) => {
|
|
97
|
+
const spend = asObject(payload.spend);
|
|
98
|
+
if (!spend || spend.enabled !== true) return;
|
|
99
|
+
const used = toAmount(spend.used);
|
|
100
|
+
const limit = toAmount(spend.limit);
|
|
101
|
+
addWindow(windows, EXTRA_USAGE_WINDOW, {
|
|
102
|
+
percent: toNumber(spend.percent),
|
|
103
|
+
resetAt: null,
|
|
104
|
+
valueLabel: formatSpendLabel(used, limit, asNonEmptyString(asObject(spend.used)?.currency))
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* @param {unknown} rawPayload Parsed JSON body of the OAuth usage endpoint.
|
|
110
|
+
* @returns {{ windows: Record<string, object>, models: Record<string, object> }}
|
|
111
|
+
*/
|
|
112
|
+
export const toClaudeUsage = (rawPayload) => {
|
|
113
|
+
const payload = asObject(rawPayload) ?? {};
|
|
114
|
+
const windows = {};
|
|
115
|
+
const models = {};
|
|
116
|
+
|
|
117
|
+
const limits = asArray(payload.limits);
|
|
118
|
+
if (limits.length > 0) {
|
|
119
|
+
applyLimitsArray(limits, windows, models);
|
|
120
|
+
} else {
|
|
121
|
+
applyLegacyFields(payload, windows);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
applyExtraUsage(payload, windows);
|
|
125
|
+
|
|
126
|
+
return { windows, models };
|
|
127
|
+
};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { toClaudeUsage } from './transforms.js';
|
|
4
|
+
|
|
5
|
+
// Trimmed capture of GET https://api.anthropic.com/api/oauth/usage for a Max account.
|
|
6
|
+
const LIVE_PAYLOAD = {
|
|
7
|
+
five_hour: { utilization: 5.0, resets_at: '2026-08-14T19:10:00.313090+00:00' },
|
|
8
|
+
seven_day: { utilization: 4.0, resets_at: '2026-08-20T15:00:00.313112+00:00' },
|
|
9
|
+
seven_day_opus: null,
|
|
10
|
+
seven_day_sonnet: null,
|
|
11
|
+
nimbus_quill: { utilization: 0.0, resets_at: null },
|
|
12
|
+
limits: [
|
|
13
|
+
{ kind: 'session', group: 'session', percent: 5, resets_at: '2026-08-14T19:10:00.313090+00:00', scope: null, is_active: true },
|
|
14
|
+
{ kind: 'weekly_all', group: 'weekly', percent: 4, resets_at: '2026-08-20T15:00:00.313112+00:00', scope: null, is_active: false },
|
|
15
|
+
{
|
|
16
|
+
kind: 'weekly_scoped',
|
|
17
|
+
group: 'weekly',
|
|
18
|
+
percent: 12,
|
|
19
|
+
resets_at: '2026-08-20T15:00:00.313301+00:00',
|
|
20
|
+
scope: { model: { id: null, display_name: 'Fable' }, surface: null },
|
|
21
|
+
is_active: false
|
|
22
|
+
}
|
|
23
|
+
],
|
|
24
|
+
spend: {
|
|
25
|
+
used: { amount_minor: 250, currency: 'USD', exponent: 2 },
|
|
26
|
+
limit: { amount_minor: 10000, currency: 'USD', exponent: 2 },
|
|
27
|
+
percent: 2.5,
|
|
28
|
+
enabled: true
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
describe('Claude usage transforms', () => {
|
|
33
|
+
it('maps the limits array to session, weekly, and model-scoped windows', () => {
|
|
34
|
+
const { windows, models } = toClaudeUsage(LIVE_PAYLOAD);
|
|
35
|
+
|
|
36
|
+
expect(windows['5h'].usedPercent).toBe(5);
|
|
37
|
+
expect(windows['5h'].resetAt).toBe(Date.parse('2026-08-14T19:10:00.313090+00:00'));
|
|
38
|
+
expect(windows['7d'].usedPercent).toBe(4);
|
|
39
|
+
expect(models.Fable.windows['7d'].usedPercent).toBe(12);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('reports each window duration so callers can rank limits by urgency', () => {
|
|
43
|
+
const { windows, models } = toClaudeUsage(LIVE_PAYLOAD);
|
|
44
|
+
|
|
45
|
+
expect(windows['5h'].windowSeconds).toBe(5 * 60 * 60);
|
|
46
|
+
expect(windows['7d'].windowSeconds).toBe(7 * 24 * 60 * 60);
|
|
47
|
+
expect(models.Fable.windows['7d'].windowSeconds).toBe(7 * 24 * 60 * 60);
|
|
48
|
+
expect(windows.extra_usage.windowSeconds).toBeNull();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('reports extra usage as a spend window with a money label', () => {
|
|
52
|
+
const { windows } = toClaudeUsage(LIVE_PAYLOAD);
|
|
53
|
+
|
|
54
|
+
expect(windows.extra_usage.usedPercent).toBe(2.5);
|
|
55
|
+
expect(windows.extra_usage.valueLabel).toBe('$2.50 / $100.00');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('omits extra usage when the account has it disabled', () => {
|
|
59
|
+
const { windows } = toClaudeUsage({ ...LIVE_PAYLOAD, spend: { ...LIVE_PAYLOAD.spend, enabled: false } });
|
|
60
|
+
|
|
61
|
+
expect(windows.extra_usage).toBeUndefined();
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('falls back to the legacy named fields when no limits array is present', () => {
|
|
65
|
+
const { windows, models } = toClaudeUsage({ five_hour: LIVE_PAYLOAD.five_hour, seven_day: LIVE_PAYLOAD.seven_day });
|
|
66
|
+
|
|
67
|
+
expect(windows['5h'].usedPercent).toBe(5);
|
|
68
|
+
expect(windows['7d'].usedPercent).toBe(4);
|
|
69
|
+
expect(models).toEqual({});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('ignores unknown limit kinds instead of inventing windows for them', () => {
|
|
73
|
+
const { windows } = toClaudeUsage({ limits: [{ kind: 'iguana_necktie', percent: 90, resets_at: null }] });
|
|
74
|
+
|
|
75
|
+
expect(windows).toEqual({});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('returns empty usage for a malformed payload', () => {
|
|
79
|
+
expect(toClaudeUsage(null)).toEqual({ windows: {}, models: {} });
|
|
80
|
+
expect(toClaudeUsage({ limits: 'nope' })).toEqual({ windows: {}, models: {} });
|
|
81
|
+
});
|
|
82
|
+
});
|