zed 0.1.10: the organization with a plan is the one asked under, not a default without one, and a 402 for the saved one moves the account (#232, ReneXiong)
ReneXiong's account has two organizations: the personal one on
zed_student and a non-personal default with no plan. orgOf() always took
default_organization_id, minted the model token for it, and /models and
/completions answered 402 "Organization does not have an active
subscription". planOf() fell back to the account's plan_v3, so the card
said Student over an organization with none.
What Zed's editor does (zed-industries/zed 56934ec): user.rs
update_authenticated_user starts in the default organization, else the
first; the title bar's organization menu calls set_current_organization,
which the LLM token's auth context (language_models cloud.rs
ClientTokenProvider) follows; plan() is plans_by_organization[current],
none when it has no entry (current_organization_has_no_active_subscription
treats a missing entry as no subscription; an unknown plan as Free). The
plugin has no switcher, so it now picks as a user switching would:
- the organization the sign-in saved, while it still has a plan that
calls models (any but Free) and models aren't turned off for it;
- else the default, if it has one; else the personal one with one; else
any with one;
- none with one: what Zed picks (saved, else default, else first).
planOf names the picked organization's own plan ("" without an entry);
only a reply with no organizations falls back to plan_v3.
A sign-in saved before this under the unsubscribed default is moved on
the first 402 (llm_tokens, /models, /completions) or empty list: the
account is read again, moved if another organization has a plan, the
move saved through client.auth.set (and kept in memory in case the save
doesn't land), and the request asked once more. The usage hook re-picks
the same way. The model-token cache and the model list are keyed by
organization now, so a move mints and lists anew. There is no explicit
organization choice in the plugin or in magpie to respect; the saved
organization is the sticky one.
Run (bun 1.4.2, macOS, worktree at origin/main 8cdf2d2 + this):
- packages/zed/org.test.mjs (new, no network: fetch stubbed): 11 pass.
With the old index.mjs and the new tests: 10 fail, 1 pass (the
no-plan fallback the old code also did).
- HOME=$(mktemp -d) bun test (whole repo): 1802 pass, 0 fail.
- bun scripts/check.mjs: every package ok.
Not tried against a real Zed account; the reporter's /users/me shape is
from the issue's sanitized read.
This commit is contained in:
+23
-3
@@ -16,9 +16,29 @@ id: `zed`. Ported from magpie's built-in Zed account.
|
||||
user id and an access token encrypted to the key. The browser is then
|
||||
sent on to zed.dev's "signed in" page.
|
||||
4. The plugin asks Zed who the account is (`/client/users/me`). That gives
|
||||
the organization the models are called under: the default one, else the
|
||||
first. It also gives the plan. An organization with Zed's hosted models
|
||||
turned off is refused.
|
||||
the organization the models are called under, and its plan. An
|
||||
organization with Zed's hosted models turned off is refused.
|
||||
|
||||
## Organization
|
||||
|
||||
Zed asks for a model token per organization. The Zed editor starts in the
|
||||
account's default organization and lets you switch to another from its
|
||||
title bar. The plugin has no switcher, so it picks the organization with a
|
||||
plan that calls models (any plan but Free), in this order (#232):
|
||||
|
||||
1. the organization it saved before, while that one still has such a plan;
|
||||
2. the default organization, if it has one;
|
||||
3. the personal organization, if it has one;
|
||||
4. any other organization that has one.
|
||||
|
||||
When none has such a plan, it keeps what Zed picks: the saved organization,
|
||||
else the default, else the first. The plan shown is the picked
|
||||
organization's own (none when Zed lists none for it), never the account's
|
||||
plan in its place. When Zed answers 402 for the organization a sign-in was
|
||||
saved under ("Organization does not have an active subscription"), the
|
||||
plugin reads the account again, moves to an organization with a plan if
|
||||
there is one, saves it with the sign-in, and asks once more. The plan card
|
||||
re-checks the organization the same way.
|
||||
|
||||
The sign-in is kept as an `oauth` entry: `access` is the access token and
|
||||
`refresh` is JSON holding the user id, machine id, organization and plan.
|
||||
|
||||
+152
-35
@@ -177,18 +177,40 @@ function who(me) {
|
||||
return "Zed account"
|
||||
}
|
||||
|
||||
// orgOf is the organization the account's models are asked under: its
|
||||
// default one when it is among its organizations, else its first, as Zed
|
||||
// picks it.
|
||||
function orgOf(me) {
|
||||
const orgs = me.organizations ?? []
|
||||
// orgOf is the organization the account's models are asked under. Zed's
|
||||
// editor starts in the default organization, else the first, and asks for
|
||||
// its model token with whichever one is current (cloud.rs auth_context);
|
||||
// its title bar lets the user switch away from one without a subscription,
|
||||
// and plans_by_organization names each organization's plan (an
|
||||
// organization it leaves out has none: user.rs
|
||||
// current_organization_has_no_active_subscription). The plugin has no such
|
||||
// switcher, so it picks as a user would (#232, ReneXiong): the
|
||||
// organization it saved, while that one still has a plan that calls
|
||||
// models; else the default, if it has one; else such an organization, the
|
||||
// personal one first. When none has, it keeps what Zed would pick: the one
|
||||
// saved, else the default, else the first.
|
||||
function orgOf(me, saved = "") {
|
||||
const orgs = (me.organizations ?? []).filter((o) => o?.id)
|
||||
const usable = (o) => !!o && paid(me.plans_by_organization?.[o.id]) && !modelsOff(me, o.id)
|
||||
const keep = orgs.find((o) => o.id === saved)
|
||||
const def = orgs.find((o) => o.id === me.default_organization_id)
|
||||
if (def) return def.id
|
||||
if (orgs.length) return orgs[0].id
|
||||
return me.default_organization_id ?? ""
|
||||
const pick = [keep, def].find(usable) ?? orgs.find((o) => o.is_personal && usable(o)) ?? orgs.find(usable) ?? keep ?? def ?? orgs[0]
|
||||
if (pick) return pick.id
|
||||
return saved || me.default_organization_id || ""
|
||||
}
|
||||
|
||||
const planOf = (me, org) => me.plans_by_organization?.[org] || me.plan?.plan_v3 || ""
|
||||
// paid says a plan calls Zed's hosted models: any plan but none and Free.
|
||||
const paid = (plan) => typeof plan === "string" && plan !== "" && plan !== "zed_free"
|
||||
|
||||
// planOf is the plan of the organization the models are asked under, as
|
||||
// Zed's editor reads it (user.rs plan): that organization's entry, none
|
||||
// when it has none, never the account's own plan in its place. Only a
|
||||
// reply with no organizations at all falls back to the account's plan.
|
||||
function planOf(me, org) {
|
||||
const known = org && (me.organizations ?? []).some((o) => o?.id === org) && me.plans_by_organization && typeof me.plans_by_organization === "object"
|
||||
if (known) return me.plans_by_organization[org] || ""
|
||||
return me.plan?.plan_v3 || ""
|
||||
}
|
||||
|
||||
function modelsOff(me, org) {
|
||||
const c = me.configuration_by_organization?.[org]
|
||||
@@ -208,7 +230,49 @@ function stateOf(auth) {
|
||||
if (auth?.type !== "oauth" || !auth.access) return null
|
||||
const r = parse(auth.refresh ?? "")
|
||||
if (!r?.userId) return null
|
||||
return { access: auth.access, userId: String(r.userId), systemId: r.systemId ?? "", org: r.org ?? "", plan: r.plan ?? "", who: auth.accountId ?? "" }
|
||||
const s = { access: auth.access, userId: String(r.userId), systemId: r.systemId ?? "", org: r.org ?? "", saved: r.org ?? "", plan: r.plan ?? "", who: auth.accountId ?? "", auth }
|
||||
// an organization picked again since this sign-in was saved, in case the
|
||||
// save didn't reach it
|
||||
const p = picked.get(s.userId)
|
||||
if (p && p.from === s.org) s.org = p.to
|
||||
return s
|
||||
}
|
||||
|
||||
// picked is each account's organization picked again after the saved one
|
||||
// lost its plan: {from: the one its sign-in names, to: the new one}. Once
|
||||
// the sign-in is saved with the new one, from no longer matches.
|
||||
const picked = new Map()
|
||||
|
||||
// withOrg is a sign-in with its organization and plan replaced.
|
||||
function withOrg(auth, org, plan) {
|
||||
const r = parse(auth.refresh ?? "") ?? {}
|
||||
return { ...auth, refresh: JSON.stringify({ ...r, org, plan, planName: planName(plan) }) }
|
||||
}
|
||||
|
||||
// repick reads the account again after Zed refused its organization (a
|
||||
// 402: no active subscription) and moves it to one with a plan, if there
|
||||
// is one. It says whether the organization changed; s is moved, and the
|
||||
// sign-in saved with it when save is given.
|
||||
async function repick(s) {
|
||||
let me
|
||||
try {
|
||||
me = parse(await cloud("GET", "/client/users/me", s, undefined, 15_000))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (!me || typeof me !== "object") return false
|
||||
const org = orgOf(me, s.org)
|
||||
if (!org || org === s.org) return false
|
||||
move(s, org, planOf(me, org))
|
||||
return true
|
||||
}
|
||||
|
||||
// move puts s under org, remembers it and saves it with the sign-in.
|
||||
function move(s, org, plan) {
|
||||
picked.set(s.userId, { from: s.saved ?? "", to: org })
|
||||
s.org = org
|
||||
s.plan = plan
|
||||
if (s.save && s.auth) Promise.resolve(s.save(withOrg(s.auth, org, plan))).catch(() => {})
|
||||
}
|
||||
|
||||
// ---- the model token ------------------------------------------------------------
|
||||
@@ -221,7 +285,8 @@ const minting = new Map()
|
||||
// modelToken is a live model token for s, minted anew when renew is set
|
||||
// (the last one was refused) or none is kept.
|
||||
async function modelToken(s, renew) {
|
||||
const key = s.userId + " " + s.access
|
||||
// a token is minted for one organization
|
||||
const key = s.userId + " " + s.org + " " + s.access
|
||||
if (!renew && tokens.has(key)) return tokens.get(key)
|
||||
if (minting.has(key)) return minting.get(key)
|
||||
const run = (async () => {
|
||||
@@ -263,27 +328,43 @@ function guess(model) {
|
||||
|
||||
const vendorOf = (model) => vendors.get(model) ?? guess(model)
|
||||
|
||||
// fetchModels reads GET /models, minting the token again once if it is stale.
|
||||
// fetchModels reads GET /models, minting the token again once if it is
|
||||
// stale, and moving the account once to an organization with a plan when
|
||||
// Zed refuses the one it is under (402) or lists nothing callable for it.
|
||||
async function fetchModels(s) {
|
||||
let moved = false
|
||||
for (let t = 0; ; t++) {
|
||||
const tok = await modelToken(s, t > 0)
|
||||
const res = await fetch(CLOUD + "/models", {
|
||||
headers: { Authorization: "Bearer " + tok, "x-zed-client-supports-x-ai": "true", "User-Agent": userAgent() },
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
})
|
||||
const text = await res.text()
|
||||
if (!res.ok && t === 0 && stale(res.status, res.headers)) continue
|
||||
if (!res.ok) throw new ZedStatus(res.status, text, res.headers)
|
||||
return parseModels(text)
|
||||
let out
|
||||
try {
|
||||
const tok = await modelToken(s, t > 0)
|
||||
const res = await fetch(CLOUD + "/models", {
|
||||
headers: { Authorization: "Bearer " + tok, "x-zed-client-supports-x-ai": "true", "User-Agent": userAgent() },
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
})
|
||||
const text = await res.text()
|
||||
if (!res.ok && t === 0 && stale(res.status, res.headers)) continue
|
||||
if (!res.ok) throw new ZedStatus(res.status, text, res.headers)
|
||||
out = parseModels(text)
|
||||
} catch (e) {
|
||||
const refused = (e instanceof ZedStatus && e.status === 402) || e instanceof NothingListed
|
||||
if (refused && !moved) {
|
||||
moved = true
|
||||
if (await repick(s)) continue
|
||||
}
|
||||
throw e
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
class NothingListed extends Error {}
|
||||
|
||||
// parseModels is what /models lists that can be called, the disabled ones
|
||||
// and those of providers the plugin can't write left out.
|
||||
function parseModels(text) {
|
||||
const r = parse(text)
|
||||
const out = (r?.models ?? []).filter((m) => m && m.id && !m.is_disabled && NPM[m.provider])
|
||||
if (!out.length) throw new Error("Zed lists no models for this account — its plan may not include Zed's hosted models (see zed.dev/account)")
|
||||
if (!out.length) throw new NothingListed("Zed lists no models for this account — its plan may not include Zed's hosted models (see zed.dev/account)")
|
||||
for (const m of out) vendors.set(m.id, m.provider)
|
||||
return out
|
||||
}
|
||||
@@ -378,15 +459,19 @@ async function signedInWith(key, uid, ciphertext, systemId) {
|
||||
const org = orgOf(me)
|
||||
if (modelsOff(me, org)) throw new Error("Zed: this account's organization has Zed's hosted models turned off")
|
||||
s.org = org
|
||||
s.plan = planOf(me, org)
|
||||
s.who = who(me)
|
||||
const plan = planOf(me, org)
|
||||
try {
|
||||
lists.set(uid, { at: Date.now(), models: await fetchModels(s) })
|
||||
const models = await fetchModels(s)
|
||||
lists.set(uid, { at: Date.now(), org: s.org, models })
|
||||
} catch {}
|
||||
// what this sign-in saves is the organization now, whatever was picked
|
||||
// for the account before
|
||||
picked.delete(uid)
|
||||
return {
|
||||
type: "success",
|
||||
access,
|
||||
refresh: JSON.stringify({ userId: uid, systemId, org, plan, planName: planName(plan), login: me.user?.github_login || me.user?.username || "", name: me.user?.name ?? "" }),
|
||||
refresh: JSON.stringify({ userId: uid, systemId, org: s.org, plan: s.plan, planName: planName(s.plan), login: me.user?.github_login || me.user?.username || "", name: me.user?.name ?? "" }),
|
||||
expires: 0,
|
||||
accountId: s.who,
|
||||
}
|
||||
@@ -913,12 +998,26 @@ async function complete(s, url, init) {
|
||||
const { req: pr, stream = w.stream } = providerRequest(w.wire, req, id)
|
||||
const body = JSON.stringify({ provider: vendor, model: id, provider_request: pr })
|
||||
let res
|
||||
for (let t = 0; ; t++) {
|
||||
let renewed = false
|
||||
let moved = false
|
||||
// Zed refusing the organization (402, no active subscription) moves the
|
||||
// account once to one with a plan and asks again (#232)
|
||||
const another = async () => {
|
||||
if (moved) return false
|
||||
moved = true
|
||||
return await repick(s)
|
||||
}
|
||||
for (;;) {
|
||||
let tok
|
||||
try {
|
||||
tok = await modelToken(s, t > 0)
|
||||
tok = await modelToken(s, renewed)
|
||||
} catch (e) {
|
||||
if (e instanceof SignInExpired) return errorResponse(w.wire, 401, e.message, "expired")
|
||||
if (e instanceof ZedStatus && e.status === 402) {
|
||||
if (await another()) continue
|
||||
const [status, msg] = refusal(402, e.body)
|
||||
return errorResponse(w.wire, status, msg)
|
||||
}
|
||||
return errorResponse(w.wire, 502, String(e?.message ?? e).replace(/^Zed: /, ""))
|
||||
}
|
||||
res = await fetch(CLOUD + "/completions", {
|
||||
@@ -935,10 +1034,17 @@ async function complete(s, url, init) {
|
||||
signal: init?.signal,
|
||||
})
|
||||
// a model token Zed calls stale is minted again, once
|
||||
if (t === 0 && stale(res.status, res.headers)) {
|
||||
if (!renewed && stale(res.status, res.headers)) {
|
||||
await res.body?.cancel?.().catch(() => {})
|
||||
renewed = true
|
||||
continue
|
||||
}
|
||||
if (res.status === 402 && !moved) {
|
||||
const text = await res.text()
|
||||
if (await another()) continue
|
||||
const [status, msg] = refusal(402, text)
|
||||
return errorResponse(w.wire, status, msg)
|
||||
}
|
||||
break
|
||||
}
|
||||
if (!res.ok) {
|
||||
@@ -980,11 +1086,16 @@ async function usage(auth, save) {
|
||||
if (e?.status === 401) return { error: `${s.who}: the Zed sign-in has expired — sign in again`, signIn: "expired" }
|
||||
return { error: e?.message ?? String(e), signIn: "kept" }
|
||||
}
|
||||
const plan = planOf(me, s.org || orgOf(me))
|
||||
// the organization the account is under, picked again when it lost its
|
||||
// plan (#232), and its plan, saved with the sign-in when either changed
|
||||
const org = orgOf(me, s.org)
|
||||
const plan = planOf(me, org)
|
||||
const out = { plan: planName(plan), signIn: "kept" }
|
||||
if (plan !== s.plan && save) {
|
||||
const r = parse(auth.refresh ?? "") ?? {}
|
||||
await save({ ...auth, refresh: JSON.stringify({ ...r, plan, planName: out.plan }) }).catch(() => {})
|
||||
if (org !== s.org) {
|
||||
move(s, org, plan)
|
||||
if (save) await save(withOrg(auth, org, plan)).catch(() => {})
|
||||
} else if (plan !== s.plan && save) {
|
||||
await save(withOrg(auth, s.org, plan)).catch(() => {})
|
||||
}
|
||||
const end = me.plan?.subscription_period?.ended_at
|
||||
if (typeof end === "string" && RFC3339.test(end) && !isNaN(Date.parse(end))) out.until = end
|
||||
@@ -1000,6 +1111,8 @@ async function usage(auth, save) {
|
||||
// ---- the plugin ---------------------------------------------------------------------
|
||||
|
||||
export async function ZedAuthPlugin({ client } = {}) {
|
||||
// saves a sign-in under the account the call is for
|
||||
const save = client?.auth?.set ? (body) => client.auth.set({ path: { id: PROVIDER }, body }) : null
|
||||
return {
|
||||
config: async (cfg) => {
|
||||
cfg.provider ??= {}
|
||||
@@ -1018,10 +1131,14 @@ export async function ZedAuthPlugin({ client } = {}) {
|
||||
async models(provider, { auth } = {}) {
|
||||
const s = stateOf(auth)
|
||||
if (!s) return provider.models
|
||||
s.save = save
|
||||
let l = lists.get(s.userId)
|
||||
// a list is of one organization's models
|
||||
if (l && l.org !== undefined && l.org !== s.org) l = undefined
|
||||
if (!l || Date.now() - l.at > MODELS_TTL) {
|
||||
try {
|
||||
l = { at: Date.now(), models: await fetchModels(s) }
|
||||
const models = await fetchModels(s)
|
||||
l = { at: Date.now(), org: s.org, models }
|
||||
lists.set(s.userId, l)
|
||||
} catch (e) {
|
||||
// Zed refusing the account's own sign-in while its list was
|
||||
@@ -1053,6 +1170,7 @@ export async function ZedAuthPlugin({ client } = {}) {
|
||||
async fetch(input, init) {
|
||||
const s = stateOf(await getAuth())
|
||||
if (!s) throw new Error("not signed in to Zed")
|
||||
s.save = save
|
||||
const url = input instanceof Request ? input.url : String(input)
|
||||
if (input instanceof Request) init = { method: input.method, body: await input.text(), signal: input.signal, ...init }
|
||||
return complete(s, url, init)
|
||||
@@ -1061,7 +1179,6 @@ export async function ZedAuthPlugin({ client } = {}) {
|
||||
},
|
||||
// magpie's own hook: the account's plan and its period
|
||||
async usage(getAuth) {
|
||||
const save = client?.auth?.set ? (body) => client.auth.set({ path: { id: PROVIDER }, body }) : null
|
||||
return usage(await getAuth(), save)
|
||||
},
|
||||
},
|
||||
@@ -1069,4 +1186,4 @@ export async function ZedAuthPlugin({ client } = {}) {
|
||||
}
|
||||
|
||||
// for tests
|
||||
export const _internal = { said, eventError, stateOf, parseModels, entry, providerRequest, wireOf, refusal, failedStatus, decrypt, padded, signedInWith, complete, vendors, tokens, lists, orgOf, who, planName, usage }
|
||||
export const _internal = { said, eventError, stateOf, parseModels, entry, providerRequest, wireOf, refusal, failedStatus, decrypt, padded, signedInWith, complete, vendors, tokens, lists, orgOf, planOf, picked, who, planName, usage }
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
// The organization an account's models are asked under (#232, ReneXiong):
|
||||
// Zed's default organization can be one without a subscription while
|
||||
// another (the personal one, on a Student plan) has one. Zed's editor lets
|
||||
// the user switch to it (title_bar.rs → user.rs set_current_organization);
|
||||
// the plugin has no switcher, so it picks the one with a plan, and moves a
|
||||
// sign-in saved under the wrong one when Zed answers 402.
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import crypto from "node:crypto"
|
||||
import { ZedAuthPlugin, _internal } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => {
|
||||
globalThis.fetch = real
|
||||
_internal.tokens.clear()
|
||||
_internal.lists.clear()
|
||||
_internal.picked.clear()
|
||||
})
|
||||
|
||||
// the reporter's /client/users/me, as the issue gives it sanitized: the
|
||||
// personal organization has the Student plan, the default one none
|
||||
const reporter = (over = {}) => ({
|
||||
user: { legacy_user_id: 77, github_login: "rene" },
|
||||
organizations: [
|
||||
{ id: "org-personal", name: "rene", is_personal: true },
|
||||
{ id: "org-team", name: "Some Team", is_personal: false },
|
||||
],
|
||||
default_organization_id: "org-team",
|
||||
plans_by_organization: { "org-personal": "zed_student" },
|
||||
plan: { plan_v3: "zed_student" },
|
||||
...over,
|
||||
})
|
||||
|
||||
const orgs = (...ids) => ids.map((id) => ({ id, name: id, is_personal: id.startsWith("personal") }))
|
||||
|
||||
test("the reporter's account: the personal organization with the Student plan, not the default without one", () => {
|
||||
expect(_internal.orgOf(reporter())).toBe("org-personal")
|
||||
// and its plan is that organization's, not the account's in its place
|
||||
expect(_internal.planOf(reporter(), "org-team")).toBe("")
|
||||
expect(_internal.planOf(reporter(), "org-personal")).toBe("zed_student")
|
||||
})
|
||||
|
||||
test("a default organization with a plan is kept, as Zed picks it", () => {
|
||||
const me = { organizations: orgs("personal", "biz"), default_organization_id: "biz", plans_by_organization: { personal: "zed_pro", biz: "zed_business" } }
|
||||
expect(_internal.orgOf(me)).toBe("biz")
|
||||
})
|
||||
|
||||
test("an organization the sign-in saved is kept while it has a plan, over the default", () => {
|
||||
const me = { organizations: orgs("personal", "biz"), default_organization_id: "biz", plans_by_organization: { personal: "zed_pro", biz: "zed_business" } }
|
||||
expect(_internal.orgOf(me, "personal")).toBe("personal")
|
||||
// it lost its plan: the default, which has one
|
||||
me.plans_by_organization = { biz: "zed_business" }
|
||||
expect(_internal.orgOf(me, "personal")).toBe("biz")
|
||||
// it is gone from the account
|
||||
expect(_internal.orgOf({ ...me, organizations: orgs("biz") }, "personal")).toBe("biz")
|
||||
})
|
||||
|
||||
test("with the default unsubscribed: the personal organization with a plan first, then any with one", () => {
|
||||
const me = { organizations: orgs("team-a", "team-b", "personal"), default_organization_id: "team-a", plans_by_organization: { "team-b": "zed_business", personal: "zed_pro" } }
|
||||
expect(_internal.orgOf(me)).toBe("personal")
|
||||
me.plans_by_organization = { "team-b": "zed_business", personal: "zed_free" }
|
||||
expect(_internal.orgOf(me)).toBe("team-b")
|
||||
})
|
||||
|
||||
test("an organization with Zed's hosted models turned off isn't picked over one that has them", () => {
|
||||
const me = {
|
||||
organizations: orgs("team-a", "team-b"),
|
||||
default_organization_id: "team-a",
|
||||
plans_by_organization: { "team-a": "zed_business", "team-b": "zed_business" },
|
||||
configuration_by_organization: { "team-a": { is_zed_model_provider_enabled: false } },
|
||||
}
|
||||
expect(_internal.orgOf(me)).toBe("team-b")
|
||||
})
|
||||
|
||||
test("no organization with a plan: what Zed picks, the saved one first", () => {
|
||||
const me = { organizations: orgs("personal", "team"), default_organization_id: "team", plans_by_organization: { personal: "zed_free" } }
|
||||
expect(_internal.orgOf(me)).toBe("team")
|
||||
expect(_internal.orgOf(me, "personal")).toBe("personal")
|
||||
expect(_internal.orgOf({ organizations: orgs("a", "b") })).toBe("a")
|
||||
// a reply without organizations names the plan of the account itself
|
||||
expect(_internal.planOf({ plan: { plan_v3: "zed_pro" } }, "")).toBe("zed_pro")
|
||||
})
|
||||
|
||||
// a fake cloud.zed.dev: /client/users/me answers me; a model token names
|
||||
// the organization it was minted for, and /models and /completions refuse
|
||||
// one minted for an organization without a plan with Zed's 402
|
||||
function cloud(me) {
|
||||
const seen = []
|
||||
globalThis.fetch = async (url, init = {}) => {
|
||||
const path = new URL(String(url)).pathname
|
||||
const auth = init.headers?.Authorization ?? ""
|
||||
if (path === "/client/users/me") {
|
||||
seen.push(path)
|
||||
return Response.json(me)
|
||||
}
|
||||
if (path === "/client/llm_tokens") {
|
||||
const org = JSON.parse(init.body).organization_id
|
||||
seen.push(path + " " + org)
|
||||
return Response.json({ token: "tok-" + org })
|
||||
}
|
||||
const org = auth.replace(/^Bearer tok-/, "")
|
||||
seen.push(path + " " + org)
|
||||
if (!me.plans_by_organization?.[org]) return Response.json({ code: "payment_required", message: "Organization does not have an active subscription." }, { status: 402 })
|
||||
if (path === "/models") return Response.json({ models: [{ provider: "anthropic", id: "claude-sonnet-5", display_name: "Claude Sonnet 5", max_token_count: 1000, max_output_tokens: 100 }] })
|
||||
if (path === "/completions") {
|
||||
const lines = [
|
||||
{ status: "started" },
|
||||
{ event: { type: "message_start", message: { id: "m", type: "message", role: "assistant", content: [], model: "claude-sonnet-5", usage: { input_tokens: 1, output_tokens: 0 } } } },
|
||||
{ event: { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } } },
|
||||
{ event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "hi" } } },
|
||||
{ event: { type: "content_block_stop", index: 0 } },
|
||||
{ event: { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } } },
|
||||
{ event: { type: "message_stop" } },
|
||||
{ status: "stream_ended" },
|
||||
]
|
||||
return new Response(lines.map((l) => JSON.stringify(l)).join("\n") + "\n", { headers: { "x-zed-server-supports-status-messages": "true" } })
|
||||
}
|
||||
return new Response("", { status: 404 })
|
||||
}
|
||||
return seen
|
||||
}
|
||||
|
||||
// a sign-in saved before #232: under the default organization, which has no plan
|
||||
const savedUnder = (org, uid = "77") => ({
|
||||
type: "oauth",
|
||||
access: "plain-access-" + uid,
|
||||
refresh: JSON.stringify({ userId: uid, systemId: "", org, plan: "zed_student", planName: "Student", login: "rene" }),
|
||||
expires: 0,
|
||||
accountId: "rene",
|
||||
})
|
||||
|
||||
test("sign-in: the model token is minted for the organization with the plan, and that one is saved", async () => {
|
||||
const seen = cloud(reporter())
|
||||
const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 })
|
||||
const ct = crypto.publicEncrypt({ key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" }, Buffer.from("plain-access-s")).toString("base64url")
|
||||
const out = await _internal.signedInWith(privateKey, "78", ct, "sys")
|
||||
expect(out.type).toBe("success")
|
||||
expect(JSON.parse(out.refresh)).toMatchObject({ org: "org-personal", plan: "zed_student", planName: "Student" })
|
||||
expect(seen).toEqual(["/client/users/me", "/client/llm_tokens org-personal", "/models org-personal"])
|
||||
})
|
||||
|
||||
test("a sign-in saved under the unsubscribed default: the 402 moves it, the list is read, and the move is saved", async () => {
|
||||
const seen = cloud(reporter())
|
||||
const saved = []
|
||||
const hooks = await ZedAuthPlugin({ client: { auth: { set: async (x) => saved.push(x.body) } } })
|
||||
const a = savedUnder("org-team")
|
||||
const models = await hooks.provider.models({ models: {} }, { auth: a })
|
||||
expect(Object.keys(models)).toEqual(["claude-sonnet-5"])
|
||||
expect(seen).toEqual(["/client/llm_tokens org-team", "/models org-team", "/client/users/me", "/client/llm_tokens org-personal", "/models org-personal"])
|
||||
expect(saved.length).toBe(1)
|
||||
expect(JSON.parse(saved[0].refresh)).toMatchObject({ userId: "77", org: "org-personal", plan: "zed_student", login: "rene" })
|
||||
// the next request goes under it, even when the save didn't reach the sign-in
|
||||
expect(_internal.stateOf(a).org).toBe("org-personal")
|
||||
expect(_internal.stateOf(saved[0]).org).toBe("org-personal")
|
||||
})
|
||||
|
||||
test("a request under the unsubscribed default: moved once, answered under the organization with the plan", async () => {
|
||||
const seen = cloud(reporter())
|
||||
const s = _internal.stateOf(savedUnder("org-team", "79"))
|
||||
const res = await _internal.complete(s, "https://cloud.zed.dev/v1/messages", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "claude-sonnet-5", stream: false, max_tokens: 10, messages: [{ role: "user", content: "hi" }] }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect((await res.json()).content).toEqual([{ type: "text", text: "hi" }])
|
||||
expect(seen).toEqual(["/client/llm_tokens org-team", "/completions org-team", "/client/users/me", "/client/llm_tokens org-personal", "/completions org-personal"])
|
||||
})
|
||||
|
||||
test("no organization with a plan: the 402 is answered, after one read of the account", async () => {
|
||||
const me = reporter({ plans_by_organization: {} })
|
||||
const seen = cloud(me)
|
||||
const s = _internal.stateOf(savedUnder("org-team", "80"))
|
||||
const res = await _internal.complete(s, "https://cloud.zed.dev/v1/messages", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "claude-sonnet-5", stream: false, max_tokens: 10, messages: [{ role: "user", content: "hi" }] }),
|
||||
})
|
||||
expect(res.status).toBe(402)
|
||||
expect(seen).toEqual(["/client/llm_tokens org-team", "/completions org-team", "/client/users/me"])
|
||||
})
|
||||
|
||||
test("the plan card: the organization with the plan, picked again and saved, not the account's plan shown over the wrong one", async () => {
|
||||
cloud(reporter())
|
||||
const saved = []
|
||||
const hooks = await ZedAuthPlugin({ client: { auth: { set: async (x) => saved.push(x.body) } } })
|
||||
const u = await hooks.auth.usage(async () => savedUnder("org-team", "81"))
|
||||
expect(u.plan).toBe("Student")
|
||||
expect(saved.length).toBe(1)
|
||||
expect(JSON.parse(saved[0].refresh)).toMatchObject({ org: "org-personal", plan: "zed_student" })
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zed-auth",
|
||||
"version": "0.1.9",
|
||||
"version": "0.1.10",
|
||||
"description": "Sign in to a Zed subscription (Zed Pro, trial, student, business) from OpenCode or magpie",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user