Skip to content

Commit f217b38

Browse files
committed
show copilot quota for copilot models (only show when copilot model is selected)
1 parent 80a5c3d commit f217b38

5 files changed

Lines changed: 178 additions & 1 deletion

File tree

‎packages/opencode/src/cli/cmd/tui/context/sync.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import type {
1616
SessionStatus,
1717
ProviderListResponse,
1818
ProviderAuthMethod,
19+
CopilotQuota,
1920
VcsInfo,
2021
} from "@opencode-ai/sdk/v2"
2122
import { createStore, produce, reconcile } from "solid-js/store"
@@ -72,6 +73,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
7273
}
7374
formatter: FormatterStatus[]
7475
vcs: VcsInfo | undefined
76+
copilot_quota: CopilotQuota | null
7577
path: Path
7678
}>({
7779
provider_next: {
@@ -99,6 +101,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
99101
mcp_resource: {},
100102
formatter: [],
101103
vcs: undefined,
104+
copilot_quota: null,
102105
path: { state: "", config: "", worktree: "", directory: "" },
103106
})
104107

@@ -393,6 +396,10 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
393396
setStore("session_status", reconcile(x.data!))
394397
}),
395398
sdk.client.provider.auth().then((x) => setStore("provider_auth", reconcile(x.data ?? {}))),
399+
sdk.client.provider.copilot.quota({}, { throwOnError: false }).then((x) => {
400+
if (x.data === undefined) return
401+
setStore("copilot_quota", x.data ?? null)
402+
}),
396403
sdk.client.vcs.get().then((x) => setStore("vcs", reconcile(x.data))),
397404
sdk.client.path.get().then((x) => setStore("path", reconcile(x.data!))),
398405
]).then(() => {

‎packages/opencode/src/cli/cmd/tui/routes/session/sidebar.tsx‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@ import { useSync } from "@tui/context/sync"
22
import { createMemo, For, Show, Switch, Match } from "solid-js"
33
import { createStore } from "solid-js/store"
44
import { useTheme } from "../../context/theme"
5-
import { Locale } from "@/util/locale"
65
import path from "path"
76
import type { AssistantMessage } from "@opencode-ai/sdk/v2"
87
import { Global } from "@/global"
98
import { Installation } from "@/installation"
109
import { useKeybind } from "../../context/keybind"
1110
import { useDirectory } from "../../context/directory"
1211
import { useKV } from "../../context/kv"
12+
import { useLocal } from "../../context/local"
1313
import { TodoItem } from "../../component/todo-item"
1414

1515
export function Sidebar(props: { sessionID: string; overlay?: boolean }) {
@@ -59,6 +59,22 @@ export function Sidebar(props: { sessionID: string; overlay?: boolean }) {
5959
percentage: model?.limit.context ? Math.round((total / model.limit.context) * 100) : null,
6060
}
6161
})
62+
const copilot = createMemo(() => sync.data.copilot_quota)
63+
const percent = (value?: number | null) => (value === null || value === undefined ? "n/a" : `${Math.round(value)}%`)
64+
const local = useLocal()
65+
const active = createMemo(() => {
66+
const model = local.model.current()
67+
if (!model) return false
68+
return model.providerID.startsWith("github-copilot")
69+
})
70+
const quota = createMemo(() => (active() ? copilot() : null))
71+
const reset = createMemo(() => {
72+
const value = quota()?.reset
73+
if (!value) return
74+
const date = new Date(value)
75+
if (Number.isNaN(date.valueOf())) return value
76+
return date.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" })
77+
})
6278

6379
const directory = useDirectory()
6480
const kv = useKV()
@@ -97,6 +113,20 @@ export function Sidebar(props: { sessionID: string; overlay?: boolean }) {
97113
<text fg={theme.textMuted}>{context()?.tokens ?? 0} tokens</text>
98114
<text fg={theme.textMuted}>{context()?.percentage ?? 0}% used</text>
99115
<text fg={theme.textMuted}>{cost()} spent</text>
116+
<Show when={quota()}>
117+
{(info) => (
118+
<>
119+
<text> </text>
120+
<text fg={theme.textMuted}>Remaining:</text>
121+
<text fg={theme.textMuted}>Code completions {percent(info().completions)}</text>
122+
<text fg={theme.textMuted}>Chat messages {percent(info().chat)}</text>
123+
<text fg={theme.textMuted}>Premium requests {percent(info().premium)}</text>
124+
<Show when={reset()}>
125+
{(value) => <text fg={theme.textMuted}>Resets {value()}</text>}
126+
</Show>
127+
</>
128+
)}
129+
</Show>
100130
</box>
101131
<Show when={mcpEntries().length > 0}>
102132
<box>

‎packages/opencode/src/server/routes/provider.ts‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,45 @@ import { Hono } from "hono"
22
import { describeRoute, validator, resolver } from "hono-openapi"
33
import z from "zod"
44
import { Config } from "../../config/config"
5+
import { Auth } from "../../auth"
56
import { Provider } from "../../provider/provider"
67
import { ModelsDev } from "../../provider/models"
78
import { ProviderAuth } from "../../provider/auth"
89
import { mapValues } from "remeda"
910
import { errors } from "../error"
1011
import { lazy } from "../../util/lazy"
12+
import { Installation } from "../../installation"
13+
14+
const CopilotQuota = z
15+
.object({
16+
completions: z.number().nullable(),
17+
chat: z.number().nullable(),
18+
premium: z.number().nullable(),
19+
reset: z.string().optional(),
20+
updated: z.string().optional(),
21+
})
22+
.meta({ ref: "CopilotQuota" })
23+
24+
const CopilotSnapshot = z
25+
.object({
26+
percent_remaining: z.number().optional(),
27+
timestamp_utc: z.string().optional(),
28+
})
29+
.partial()
30+
31+
const CopilotApi = z
32+
.object({
33+
quota_snapshots: z
34+
.object({
35+
chat: CopilotSnapshot.optional(),
36+
completions: CopilotSnapshot.optional(),
37+
premium_interactions: CopilotSnapshot.optional(),
38+
})
39+
.optional(),
40+
quota_reset_date_utc: z.string().optional(),
41+
quota_reset_date: z.string().optional(),
42+
})
43+
.passthrough()
1144

1245
export const ProviderRoutes = lazy(() =>
1346
new Hono()
@@ -161,5 +194,59 @@ export const ProviderRoutes = lazy(() =>
161194
})
162195
return c.json(true)
163196
},
197+
)
198+
.get(
199+
"/copilot/quota",
200+
describeRoute({
201+
summary: "Get GitHub Copilot quota",
202+
description: "Get GitHub Copilot remaining quota percentages for chat, completions, and premium requests.",
203+
operationId: "provider.copilot.quota",
204+
responses: {
205+
200: {
206+
description: "Copilot quota",
207+
content: {
208+
"application/json": {
209+
schema: resolver(CopilotQuota.nullable()),
210+
},
211+
},
212+
},
213+
},
214+
}),
215+
async (c) => {
216+
const auth = (await Auth.get("github-copilot")) ?? (await Auth.get("github-copilot-enterprise"))
217+
if (!auth || auth.type !== "oauth") return c.json(null)
218+
219+
const domain = auth.enterpriseUrl
220+
? auth.enterpriseUrl.replace(/^https?:\/\//, "").replace(/\/$/, "")
221+
: undefined
222+
const url = domain
223+
? `https://${domain}/api/v3/copilot_internal/user`
224+
: "https://api.github.com/copilot_internal/user"
225+
const response = await fetch(url, {
226+
headers: {
227+
Authorization: `Bearer ${auth.refresh}`,
228+
"User-Agent": `opencode/${Installation.VERSION}`,
229+
Accept: "application/json",
230+
},
231+
})
232+
if (!response.ok) return c.json(null)
233+
234+
const data = await response.json()
235+
const parsed = CopilotApi.safeParse(data)
236+
if (!parsed.success) return c.json(null)
237+
238+
const snapshots = parsed.data.quota_snapshots
239+
const quota = {
240+
completions: snapshots?.completions?.percent_remaining ?? null,
241+
chat: snapshots?.chat?.percent_remaining ?? null,
242+
premium: snapshots?.premium_interactions?.percent_remaining ?? null,
243+
reset: parsed.data.quota_reset_date_utc ?? parsed.data.quota_reset_date,
244+
updated:
245+
snapshots?.premium_interactions?.timestamp_utc ??
246+
snapshots?.chat?.timestamp_utc ??
247+
snapshots?.completions?.timestamp_utc,
248+
}
249+
return c.json(quota)
250+
},
164251
),
165252
)

‎packages/sdk/js/src/v2/gen/sdk.gen.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ import type {
7474
ProjectUpdateErrors,
7575
ProjectUpdateResponses,
7676
ProviderAuthResponses,
77+
ProviderCopilotQuotaResponses,
7778
ProviderListResponses,
7879
ProviderOauthAuthorizeErrors,
7980
ProviderOauthAuthorizeResponses,
@@ -2116,6 +2117,27 @@ export class Oauth extends HeyApiClient {
21162117
}
21172118
}
21182119

2120+
export class Copilot extends HeyApiClient {
2121+
/**
2122+
* Get GitHub Copilot quota
2123+
*
2124+
* Get GitHub Copilot remaining quota percentages for chat, completions, and premium requests.
2125+
*/
2126+
public quota<ThrowOnError extends boolean = false>(
2127+
parameters?: {
2128+
directory?: string
2129+
},
2130+
options?: Options<never, ThrowOnError>,
2131+
) {
2132+
const params = buildClientParams([parameters], [{ args: [{ in: "query", key: "directory" }] }])
2133+
return (options?.client ?? this.client).get<ProviderCopilotQuotaResponses, unknown, ThrowOnError>({
2134+
url: "/provider/copilot/quota",
2135+
...options,
2136+
...params,
2137+
})
2138+
}
2139+
}
2140+
21192141
export class Provider extends HeyApiClient {
21202142
/**
21212143
* List providers
@@ -2159,6 +2181,11 @@ export class Provider extends HeyApiClient {
21592181
get oauth(): Oauth {
21602182
return (this._oauth ??= new Oauth({ client: this.client }))
21612183
}
2184+
2185+
private _copilot?: Copilot
2186+
get copilot(): Copilot {
2187+
return (this._copilot ??= new Copilot({ client: this.client }))
2188+
}
21622189
}
21632190

21642191
export class Find extends HeyApiClient {

‎packages/sdk/js/src/v2/gen/types.gen.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2048,6 +2048,14 @@ export type ProviderAuthAuthorization = {
20482048
instructions: string
20492049
}
20502050

2051+
export type CopilotQuota = {
2052+
completions: number | null
2053+
chat: number | null
2054+
premium: number | null
2055+
reset?: string
2056+
updated?: string
2057+
}
2058+
20512059
export type Symbol = {
20522060
name: string
20532061
kind: number
@@ -4127,6 +4135,24 @@ export type ProviderOauthCallbackResponses = {
41274135

41284136
export type ProviderOauthCallbackResponse = ProviderOauthCallbackResponses[keyof ProviderOauthCallbackResponses]
41294137

4138+
export type ProviderCopilotQuotaData = {
4139+
body?: never
4140+
path?: never
4141+
query?: {
4142+
directory?: string
4143+
}
4144+
url: "/provider/copilot/quota"
4145+
}
4146+
4147+
export type ProviderCopilotQuotaResponses = {
4148+
/**
4149+
* Copilot quota
4150+
*/
4151+
200: CopilotQuota | null
4152+
}
4153+
4154+
export type ProviderCopilotQuotaResponse = ProviderCopilotQuotaResponses[keyof ProviderCopilotQuotaResponses]
4155+
41304156
export type FindTextData = {
41314157
body?: never
41324158
path?: never

0 commit comments

Comments
 (0)