all: a usage read says what it means for the sign-in, and a renewal clears the mark whatever follows, as the built-ins did (要保证插件跟内置的所有逻辑都要一模一样) — auth.usage returns signIn on every path: expired where the built-in's quota read marked the account (Zed's /users/me 401, Factory's and MiMo's refused renewals, Qoder's refused job refresh), renewed after a renewal, which took the mark off, kept everywhere else, so magpie no longer guesses from the words 'sign in again' (Kiro's, Devin's and ZCode's usage errors marked accounts their built-ins never did) nor clears on a clean read. A request after a renewal says renewed on any status; one without says kept, as the built-ins cleared only on renewal. Kiro, Cursor, Devin, Command Code, WorkBuddy, Grok and ZCode, whose built-ins never marked an account, say kept on every answer. New tests fail against 85d7dd0's index.mjs.
This commit is contained in:
+53
-28
@@ -759,6 +759,17 @@ async function bodyText(input, init) {
|
||||
return typeof b === "string" ? b : new TextDecoder().decode(b)
|
||||
}
|
||||
|
||||
// signed is res saying what it means for the sign-in, as the built-in's
|
||||
// answer did: a renewed job token cleared the mark whatever came of the
|
||||
// request; without one, a success left the mark as it was.
|
||||
function signed(res, renewed) {
|
||||
const said = renewed ? "renewed" : res.ok ? "kept" : null
|
||||
if (!said) return res
|
||||
const headers = new Headers(res.headers)
|
||||
headers.set("X-Magpie-Sign-In", said)
|
||||
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
||||
}
|
||||
|
||||
// ---- usage --------------------------------------------------------------------
|
||||
//
|
||||
// The account's allowance as magpie's built-in Qoder account shows it
|
||||
@@ -880,6 +891,9 @@ export async function QoderAuthPlugin({ client }) {
|
||||
}
|
||||
// each account's listing, the model configs a request carries
|
||||
const listings = new Map()
|
||||
// the accounts fresh renewed: the built-in took the lapse mark off on a
|
||||
// renewed job token (qoderPersist), whatever the request then met
|
||||
const renewals = new WeakSet()
|
||||
|
||||
// fresh is the account with a live job token, refreshed and saved near
|
||||
// its end.
|
||||
@@ -891,6 +905,7 @@ export async function QoderAuthPlugin({ client }) {
|
||||
const jt = await refreshJob(a.refresh, a.accountId || a.email || a.uid)
|
||||
const next = { ...a, access: jt.token, refresh: jt.refresh_token, expires: expiresAt(jt) }
|
||||
await client.auth.set({ path: { id: ID }, body: next })
|
||||
renewals.add(next)
|
||||
return next
|
||||
})
|
||||
|
||||
@@ -914,10 +929,15 @@ export async function QoderAuthPlugin({ client }) {
|
||||
return dt.token
|
||||
})
|
||||
|
||||
// usage is the account's allowance, magpie's own hook
|
||||
// usage is the account's allowance, magpie's own hook. signIn is what the read means for the sign-in, as the built-in's did:
|
||||
// a refused job refresh marks it, a renewed one clears it, and nothing
|
||||
// else does — not a clean read, nor a refused device token, which serves
|
||||
// only the account pages
|
||||
const usage = async (getAuth) => {
|
||||
let signIn = "kept"
|
||||
try {
|
||||
const cred = await fresh(getAuth)
|
||||
if (renewals.has(cred)) signIn = "renewed"
|
||||
let env
|
||||
try {
|
||||
env = await fetchUsage(cred.deviceToken)
|
||||
@@ -925,9 +945,9 @@ export async function QoderAuthPlugin({ client }) {
|
||||
if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e
|
||||
env = await fetchUsage(await deviceToken(getAuth, cred.deviceToken))
|
||||
}
|
||||
return parseUsage(env)
|
||||
return { ...parseUsage(env), signIn }
|
||||
} catch (e) {
|
||||
return { error: e?.message ?? String(e) }
|
||||
return { error: e?.message ?? String(e), signIn: e?.expired ? "expired" : signIn }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -938,6 +958,35 @@ export async function QoderAuthPlugin({ client }) {
|
||||
signIn: e?.expired ? "expired" : undefined,
|
||||
})
|
||||
|
||||
// ask is the answer to a chat completion on the live account cred.
|
||||
const ask = async (chat, cred, init) => {
|
||||
let m
|
||||
try {
|
||||
m = (await models(cred)).find((x) => x.key === chat.model) ?? (await models(cred, true)).find((x) => x.key === chat.model)
|
||||
} catch (e) {
|
||||
// the built-in answered any failure to read the list 400
|
||||
// (QoderModelOf), a refused one included, marking nothing
|
||||
return errorResponse({ status: 400, message: e.message })
|
||||
}
|
||||
if (!m) return errorResponse({ status: 400, message: `unknown or disabled model "${chat.model}"` })
|
||||
const wire = encodeBody(JSON.stringify(qoderBody(chat, m)))
|
||||
const headers = {
|
||||
...cosyHeaders(CHAT_URL, cred, wire),
|
||||
Accept: "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"X-Model-Key": m.key,
|
||||
"X-Model-Source": m.source,
|
||||
}
|
||||
let res
|
||||
try {
|
||||
res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal: init.signal })
|
||||
} catch (e) {
|
||||
return errorResponse({ status: 502, message: e.message })
|
||||
}
|
||||
if (!res.ok) return errorResponse(failure(res.status, (await res.text()).slice(0, 1 << 20)))
|
||||
return answer(res, chat)
|
||||
}
|
||||
|
||||
return {
|
||||
auth: {
|
||||
provider: ID,
|
||||
@@ -964,31 +1013,7 @@ export async function QoderAuthPlugin({ client }) {
|
||||
} catch (e) {
|
||||
return signedInError(e)
|
||||
}
|
||||
let m
|
||||
try {
|
||||
m = (await models(cred)).find((x) => x.key === chat.model) ?? (await models(cred, true)).find((x) => x.key === chat.model)
|
||||
} catch (e) {
|
||||
// the built-in answered any failure to read the list 400
|
||||
// (QoderModelOf), a refused one included, marking nothing
|
||||
return errorResponse({ status: 400, message: e.message })
|
||||
}
|
||||
if (!m) return errorResponse({ status: 400, message: `unknown or disabled model "${chat.model}"` })
|
||||
const wire = encodeBody(JSON.stringify(qoderBody(chat, m)))
|
||||
const headers = {
|
||||
...cosyHeaders(CHAT_URL, cred, wire),
|
||||
Accept: "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"X-Model-Key": m.key,
|
||||
"X-Model-Source": m.source,
|
||||
}
|
||||
let res
|
||||
try {
|
||||
res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal: init.signal })
|
||||
} catch (e) {
|
||||
return errorResponse({ status: 502, message: e.message })
|
||||
}
|
||||
if (!res.ok) return errorResponse(failure(res.status, (await res.text()).slice(0, 1 << 20)))
|
||||
return answer(res, chat)
|
||||
return signed(await ask(chat, cred, init), renewals.has(cred))
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
@@ -65,6 +65,7 @@ test("a refused device token is rotated, saved, and the usage read with it", asy
|
||||
{ name: "Shared credits", used: 50, display: "10 / 20 credits" },
|
||||
{ name: "Team", used: 20, display: "2 / 10 credits" },
|
||||
],
|
||||
signIn: "kept",
|
||||
})
|
||||
expect(p.seen).toEqual(["/sash/api/v2/me/usage", "/api/v1/deviceToken/refresh", "/sash/api/v2/me/usage"])
|
||||
expect(p.auth()).toMatchObject({ deviceToken: "dt-new", deviceRefresh: "drt-new", access: "jt-one", refresh: "rt-one" })
|
||||
@@ -75,25 +76,26 @@ test("a refused device refresh says usage is unavailable, chat still working", a
|
||||
expect(await p.usage()).toEqual({
|
||||
error:
|
||||
"Qoder usage is unavailable: Qoder refused the account-page sign-in (chat still works) — sign in again to see usage (qoder device token refresh: upstream HTTP 403)",
|
||||
signIn: "kept",
|
||||
})
|
||||
expect(p.auth().deviceToken).toBe("dt-old")
|
||||
})
|
||||
|
||||
test("another failure is Qoder's status", async () => {
|
||||
const p = await plugin(() => new Response("", { status: 500 }))
|
||||
expect(await p.usage()).toEqual({ error: "qoder usage: upstream HTTP 500" })
|
||||
expect(await p.usage()).toEqual({ error: "qoder usage: upstream HTTP 500", signIn: "kept" })
|
||||
})
|
||||
|
||||
test("an enterprise account has a plan and no windows", async () => {
|
||||
const p = await plugin(() => json({ displayMode: "enterprise" }))
|
||||
expect(await p.usage()).toEqual({ plan: "Enterprise" })
|
||||
expect(await p.usage()).toEqual({ plan: "Enterprise", signIn: "kept" })
|
||||
})
|
||||
|
||||
test("an unknown display mode, or no quota, is an error", async () => {
|
||||
let p = await plugin(() => json({ displayMode: "team" }))
|
||||
expect(await p.usage()).toEqual({ error: "qoder usage: unknown display mode" })
|
||||
expect(await p.usage()).toEqual({ error: "qoder usage: unknown display mode", signIn: "kept" })
|
||||
p = await plugin(() => json({ displayMode: "qoder", qoderUsage: null }))
|
||||
expect(await p.usage()).toEqual({ error: "qoder usage: missing quota data" })
|
||||
expect(await p.usage()).toEqual({ error: "qoder usage: missing quota data", signIn: "kept" })
|
||||
})
|
||||
|
||||
test("snake_case fields, an expiry, units, and pools too thin to show", () => {
|
||||
@@ -230,3 +232,61 @@ test("a model Qoder lists free (is_free, or a price_factor of 0) is marked free"
|
||||
expect(Object.fromEntries(Object.entries(ms).map(([k, m]) => [k, m.free]))).toEqual({ qmodel: false, fmodel: true, pmodel: true, cmodel: false })
|
||||
expect(_internal.modelInfo({ key: "x", isFree: true }).free).toBe(true)
|
||||
})
|
||||
|
||||
// a usage read on an account whose job token is due, the refresh answered by refresh()
|
||||
async function dueUsage(refresh, read) {
|
||||
let auth = { ...account(), expires: 0 }
|
||||
globalThis.fetch = async (url) => {
|
||||
const path = new URL(String(url)).pathname
|
||||
if (path === "/api/v1/jobToken/refresh") return refresh()
|
||||
if (path === "/sash/api/v2/me/usage") return read()
|
||||
return new Response("", { status: 404 })
|
||||
}
|
||||
const hooks = await QoderAuthPlugin({ client: { auth: { set: async ({ body }) => (auth = body) } } })
|
||||
return hooks.auth.usage(async () => auth)
|
||||
}
|
||||
|
||||
const RENEWED = () => json({ token: "jt-new", refresh_token: "rt-new", expire_time: Date.now() + 3_600_000 })
|
||||
|
||||
test("a usage read marks the sign-in only on a refused job refresh and clears it only on a renewed one, as the built-in's", async () => {
|
||||
// a clean read cleared nothing in the built-in
|
||||
expect((await dueUsage(RENEWED, () => json(USAGE))).signIn).toBe("renewed")
|
||||
expect((await (await plugin(() => json(USAGE))).usage()).signIn).toBe("kept")
|
||||
// renewed, the mark came off whatever the read then met
|
||||
expect(await dueUsage(RENEWED, () => new Response("", { status: 500 }))).toEqual({ error: "qoder usage: upstream HTTP 500", signIn: "renewed" })
|
||||
for (const status of [401, 403]) {
|
||||
const u = await dueUsage(() => new Response("", { status }), () => json(USAGE))
|
||||
expect(u).toEqual({ error: `one@x's Qoder sign-in has expired — sign in again (qoder job token refresh: status ${status})`, signIn: "expired" })
|
||||
}
|
||||
expect((await dueUsage(() => new Response("", { status: 500 }), () => json(USAGE))).signIn).toBe("kept")
|
||||
})
|
||||
|
||||
// a chat on an account whose job token is due, renewed, Qoder answering reply()
|
||||
async function renewedChat(reply) {
|
||||
const auth = { ...account(), machineId: "m1", expires: 0 }
|
||||
globalThis.fetch = async (url) => {
|
||||
const path = new URL(String(url)).pathname
|
||||
if (path === "/api/v1/jobToken/refresh") return RENEWED()
|
||||
if (path.endsWith("/model/list")) return json(LISTING)
|
||||
return reply()
|
||||
}
|
||||
const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const l = await hooks.auth.loader(async () => auth)
|
||||
return l.fetch(API_CHAT, ASK)
|
||||
}
|
||||
|
||||
const OK = () =>
|
||||
new Response(`data: ${JSON.stringify({ statusCodeValue: 200, body: JSON.stringify({ choices: [{ delta: { content: "hi" }, finish_reason: "stop" }] }) })}\n\n`, {
|
||||
headers: { "Content-Type": "text/event-stream" },
|
||||
})
|
||||
|
||||
test("an answer that went through keeps the mark, as the built-in's did; after a renewed job token, every answer clears it", async () => {
|
||||
const { fetch } = await chat(LISTING, OK)
|
||||
let res = await fetch(API_CHAT, ASK)
|
||||
expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([200, "kept"])
|
||||
expect((await res.json()).choices[0].message.content).toBe("hi")
|
||||
for (const [reply, status] of [[OK, 200], [() => new Response("", { status: 500 }), 500], [() => new Response("", { status: 401 }), 401]]) {
|
||||
res = await renewedChat(reply)
|
||||
expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([status, "renewed"])
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user