Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion packages/opencode/src/account/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,18 @@ const layer: Layer.Layer<Service, never, AccountRepo.Service | HttpClient.HttpCl
return yield* fetchOrgs(account.url, accessToken)
})

const remove = Effect.fn("Account.remove")(function* (accountID: AccountID) {
const active = yield* repo.active()
yield* repo.remove(accountID)
if (Option.isNone(active) || active.value.id !== accountID) return

const next = (yield* orgsByAccount()).flatMap((group) =>
group.orgs.map((org) => ({ accountID: group.account.id, orgID: org.id })),
)[0]
if (!next) return
yield* repo.use(next.accountID, Option.some(next.orgID))
})

const config = Effect.fn("Account.config")(function* (accountID: AccountID, orgID: OrgID) {
const resolved = yield* resolveAccess(accountID)
if (Option.isNone(resolved)) return Option.none()
Expand Down Expand Up @@ -445,7 +457,7 @@ const layer: Layer.Layer<Service, never, AccountRepo.Service | HttpClient.HttpCl
activeOrg,
list: repo.list,
orgsByAccount,
remove: repo.remove,
remove,
use: repo.use,
orgs,
config,
Expand Down
47 changes: 47 additions & 0 deletions packages/opencode/test/account/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,53 @@ it.live("orgsByAccount groups orgs per account", () =>
}),
)

it.live("remove switches to another org when the active account is removed", () =>
Effect.gen(function* () {
const first = AccountID.make("user-1")
const second = AccountID.make("user-2")

yield* AccountRepo.Service.use((r) =>
r.persistAccount({
id: first,
email: "one@example.com",
url: "https://one.example.com",
accessToken: AccessToken.make("at_1"),
refreshToken: RefreshToken.make("rt_1"),
expiry: Date.now() + outsideEagerRefreshWindow,
orgID: Option.some(OrgID.make("org-1")),
}),
)

yield* AccountRepo.Service.use((r) =>
r.persistAccount({
id: second,
email: "two@example.com",
url: "https://two.example.com",
accessToken: AccessToken.make("at_2"),
refreshToken: RefreshToken.make("rt_2"),
expiry: Date.now() + outsideEagerRefreshWindow,
orgID: Option.some(OrgID.make("org-2")),
}),
)

const client = HttpClient.make((req) =>
Effect.succeed(
req.url === "https://one.example.com/api/orgs" ? json(req, [org("org-1", "One")]) : json(req, [], 404),
),
)

yield* Account.use.remove(second).pipe(Effect.provide(live(client)))

const active = yield* AccountRepo.use.active()
expect(Option.getOrThrow(active)).toEqual(
expect.objectContaining({
id: first,
active_org_id: OrgID.make("org-1"),
}),
)
}),
)

it.live("token refresh persists the new token", () =>
Effect.gen(function* () {
const id = AccountID.make("user-1")
Expand Down
Loading