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
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
},
"devDependencies": {
"@cordisx/eslint-config": "github:cordisx/cordisxmono#c63c2e8c2ba7e11502934a52ad2ce3734e804cdc",
"@cordisx/protocol": "github:cordisx/cordisx-protocol#a0e765d6ae3e2baba0b97dda60b7f62439a570aa",
"@cordisx/protocol": "github:cordisx/cordisx-protocol#3a93eae49577ad33255d02350cda6f3c95b47e3b",
"@deepseek-ai/cordis": "4.0.1",
"@deepseek-ai/schemastery": "3.18.1",
"@projectwallace/stylelint-plugin": "0.7.0",
Expand Down
36 changes: 36 additions & 0 deletions src/managed-account-read.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type {
ManagedServiceCliProxyAccountsResultV1,
ManagedServiceCliProxyAccountToggleRequestV1,
ManagedServiceCliProxyAccountToggleResultV1,
ManagedServiceV1,
} from '@cordisx/protocol/managed-service-ui/v1'

/** Account visibility does not imply authority to change accounts. */
export function hasManagedAccountReader(service: ManagedServiceV1): boolean {
return typeof service.readAccounts === 'function' || typeof service.accountControl?.readAccounts === 'function'
}

/** Use the independent read when available, falling back only on older Hosts. */
export async function readManagedAccounts(
service: ManagedServiceV1,
): Promise<ManagedServiceCliProxyAccountsResultV1 | undefined> {
if (typeof service.readAccounts === 'function') return await service.readAccounts()
if (typeof service.accountControl?.readAccounts === 'function') return await service.accountControl.readAccounts()
return undefined
}

/** A Host may allow account toggles without also enabling OAuth. */
export function hasManagedAccountToggle(service: ManagedServiceV1): boolean {
return typeof service.toggleAccount === 'function' || typeof service.accountControl?.toggleAccount === 'function'
}

export async function toggleManagedAccount(
service: ManagedServiceV1,
request: ManagedServiceCliProxyAccountToggleRequestV1,
): Promise<ManagedServiceCliProxyAccountToggleResultV1 | undefined> {
if (typeof service.toggleAccount === 'function') return await service.toggleAccount(request)
if (typeof service.accountControl?.toggleAccount === 'function') {
return await service.accountControl.toggleAccount(request)
}
return undefined
}
20 changes: 20 additions & 0 deletions src/service/gateway-ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,26 @@ export const managedServiceUI: ManagedServiceNodeUISourceV1 = Object.freeze({
})
},
readAccounts,
prepareAccountToggle(request: ManagedServiceCliProxyAccountToggleRequestV1) {
if (!bindingMatches(request.binding, binding) || state === undefined || signal.aborted) {
throw new Error('account toggle binding unavailable')
}
return {
operations: [
{ operationId: 'gateway.management.accounts.list', maxInvocations: 2 },
{
operationId: 'gateway.management.accounts.toggle',
value: {
name: request.accountId,
...(request.authIndex === undefined ? {} : { auth_index: request.authIndex }),
disabled: request.disabled,
},
maxInvocations: 1,
},
{ operationId: 'gateway.models.list', maxInvocations: 1 },
],
}
},
async toggleAccount(
request: ManagedServiceCliProxyAccountToggleRequestV1,
): Promise<ManagedServiceCliProxyAccountToggleResultV1> {
Expand Down
38 changes: 28 additions & 10 deletions src/upstream-subscription-manager-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ import type {
ManagedServiceV1,
} from '@cordisx/protocol/managed-service-ui/v1'
import { requestOwnPluginConfiguration } from './manager-configuration.js'
import {
hasManagedAccountReader,
hasManagedAccountToggle,
readManagedAccounts,
toggleManagedAccount,
} from './managed-account-read.js'
import './upstream-subscription-manager-page.css'

const SERVICE_ID = 'gateway-runtime'
Expand Down Expand Up @@ -186,8 +192,10 @@ export function createUpstreamSubscriptionManagerPage(
const oauthPollGenerationRef = useRef(0)
const oauthStateRef = useRef<AccountOAuthState | null>(null)
const serviceRef = useRef<ManagedServiceV1 | null>(null)
const accountReadVersionRef = useRef(0)

const accountControl = service?.accountControl
const accountToggleAvailable = service !== null && hasManagedAccountToggle(service)

const showError = useCallback(() => {
notifications.show({
Expand Down Expand Up @@ -218,11 +226,12 @@ export function createUpstreamSubscriptionManagerPage(
return
}
setLoading(prev => prev && snapshot === null && catalog === null && accounts === null)
const accountReadVersion = ++accountReadVersionRef.current
try {
const [snapResult, catalogResult, accountsResult] = await Promise.all([
current.snapshot(),
current.readCatalog?.() ?? Promise.resolve(undefined),
current.accountControl?.readAccounts() ?? Promise.resolve(undefined),
readManagedAccounts(current),
])

if (snapResult.status === 'available') {
Expand All @@ -237,10 +246,10 @@ export function createUpstreamSubscriptionManagerPage(
setCatalog(null)
}

if (accountsResult?.status === 'available') {
if (accountReadVersion === accountReadVersionRef.current && accountsResult?.status === 'available') {
setAccounts(accountsResult.accounts)
setAccountAvailability('available')
} else if (accountsResult !== undefined) {
} else if (accountReadVersion === accountReadVersionRef.current && accountsResult !== undefined) {
setAccounts(null)
setAccountAvailability('unavailable')
}
Expand Down Expand Up @@ -319,6 +328,7 @@ export function createUpstreamSubscriptionManagerPage(

useEffect(() => {
let disposed = false
let stopAccountObservation: (() => void) | undefined
void (async () => {
if (managedServices === undefined) {
showError()
Expand All @@ -333,6 +343,12 @@ export function createUpstreamSubscriptionManagerPage(
return
}
serviceRef.current = acquired.service
stopAccountObservation = acquired.service.observeAccounts?.(projection => {
if (disposed) return
accountReadVersionRef.current += 1
setAccounts(projection)
setAccountAvailability('available')
})
setService(acquired.service)
await refresh(acquired.service)
await subscribe(acquired.service)
Expand All @@ -346,6 +362,8 @@ export function createUpstreamSubscriptionManagerPage(
return () => {
window.clearInterval(refreshTimer)
disposed = true
accountReadVersionRef.current += 1
stopAccountObservation?.()
clearOauthPoll()
const subscription = subscriptionRef.current
subscriptionRef.current = null
Expand Down Expand Up @@ -473,10 +491,10 @@ export function createUpstreamSubscriptionManagerPage(
}, [accountControl, accounts, clearOauthPoll, refresh, service, setOauthStateValue, showError])

const toggleAccount = useCallback(async (accountId: string, disabled: boolean) => {
if (service === null || accountControl === undefined || accounts === null) return
if (service === null || !hasManagedAccountToggle(service) || accounts === null) return
setPendingToggle({ accountId, disabled })
try {
const result = await accountControl.toggleAccount({
const result = await toggleManagedAccount(service, {
$schema:
'https://raw.githubusercontent.com/cordisx/cordisx-protocol/main/schemas/managed-service-cli-proxy-account-toggle.v1.schema.json' as const,
contract: 'cordisx.managed-service-cli-proxy-account-toggle/v1' as const,
Expand All @@ -488,8 +506,8 @@ export function createUpstreamSubscriptionManagerPage(
expectedRevision: accounts.revision,
userGesture: gesture(),
})
if (result.status === 'accepted') {
await refresh(service)
if (result?.status === 'accepted') {
await refresh(service, false)
} else {
showError()
}
Expand All @@ -498,7 +516,7 @@ export function createUpstreamSubscriptionManagerPage(
} finally {
setPendingToggle(null)
}
}, [accountControl, accounts, refresh, service, showError])
}, [accounts, refresh, service, showError])

const openPluginConfiguration = useCallback(async () => {
setConfigurationOpening(true)
Expand Down Expand Up @@ -639,7 +657,7 @@ export function createUpstreamSubscriptionManagerPage(
className='cus-button'
variant={account.disabled ? 'primary' : 'secondary'}
aria-busy={isToggling}
disabled={isToggling || accountControl === undefined || account.unavailable}
disabled={isToggling || !accountToggleAvailable || account.unavailable}
onClick={() => void toggleAccount(account.accountId, !account.disabled)}
>
{account.disabled ? props.t('upstream.action.enable') : props.t('upstream.action.disable')}
Expand Down Expand Up @@ -675,7 +693,7 @@ export function createUpstreamSubscriptionManagerPage(
</section>
)
}
if (accountControl === undefined) {
if (!hasManagedAccountReader(service)) {
return (
<section className='cus-section'>
{groupHeader(props.t('upstream.group.account-subscriptions'))}
Expand Down
21 changes: 20 additions & 1 deletion test/gateway.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ test('routes account and OAuth controls and refreshes the gateway model publicat
expectedRevision: accountsResult.accounts.revision,
userGesture: { kind: 'explicit-click', at: new Date().toISOString() },
}
const toggled = await extension.toggleAccount({
const toggleRequest = {
$schema:
'https://raw.githubusercontent.com/cordisx/cordisx-protocol/main/schemas/managed-service-cli-proxy-account-toggle.v1.schema.json',
contract: 'cordisx.managed-service-cli-proxy-account-toggle/v1',
Expand All @@ -476,7 +476,26 @@ test('routes account and OAuth controls and refreshes the gateway model publicat
authIndex: 'auth-index-one',
disabled: true,
...common,
}
const eventsBeforePlan = fixture.events.length
assert.deepEqual(extension.prepareAccountToggle(toggleRequest), {
operations: [
{ operationId: 'gateway.management.accounts.list', maxInvocations: 2 },
{
operationId: 'gateway.management.accounts.toggle',
value: { name: 'account-one', auth_index: 'auth-index-one', disabled: true },
maxInvocations: 1,
},
{ operationId: 'gateway.models.list', maxInvocations: 1 },
],
})
assert.equal(fixture.events.length, eventsBeforePlan)
assert.throws(() =>
extension.prepareAccountToggle({
...toggleRequest,
binding: { ...toggleRequest.binding, bindingId: 'other' },
}), /binding unavailable/)
const toggled = await extension.toggleAccount(toggleRequest)
assert.equal(toggled.status, 'accepted')
const started = await extension.startOAuth({
$schema:
Expand Down
106 changes: 106 additions & 0 deletions test/managed-account-read.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { build } from 'esbuild'

const built = await build({
entryPoints: [new URL('../src/managed-account-read.ts', import.meta.url).pathname],
bundle: true,
write: false,
platform: 'node',
format: 'esm',
})
const { hasManagedAccountReader, readManagedAccounts, hasManagedAccountToggle, toggleManagedAccount } = await import(
`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].contents).toString('base64')}`
)

test('independent account reads take precedence without enabling mutations', async () => {
const result = { status: 'available', accounts: { accounts: [{ accountId: 'one' }] } }
let legacyCalls = 0
const service = {
async readAccounts() {
return result
},
accountControl: {
async readAccounts() {
legacyCalls++
return undefined
},
},
}
assert.equal(hasManagedAccountReader(service), true)
assert.equal(await readManagedAccounts(service), result)
assert.equal(legacyCalls, 0)
})

test('older Hosts can still read through account control', async () => {
const control = {
value: { status: 'available', accounts: { accounts: [] } },
async readAccounts() {
return this.value
},
}
const service = { accountControl: control }
assert.equal(hasManagedAccountReader(service), true)
assert.equal(await readManagedAccounts(service), control.value)
assert.equal(hasManagedAccountReader({}), false)
assert.equal(await readManagedAccounts({}), undefined)
})

test('an unavailable or failed independent read does not fall back to account control', async () => {
let legacyCalls = 0
const unavailable = { status: 'unavailable', code: 'owner-unavailable' }
const service = {
async readAccounts() {
return unavailable
},
accountControl: {
async readAccounts() {
legacyCalls++
},
},
}
assert.equal(await readManagedAccounts(service), unavailable)
service.readAccounts = async () => {
throw new Error('owner unavailable')
}
await assert.rejects(readManagedAccounts(service), /owner unavailable/)
assert.equal(legacyCalls, 0)
})

test('independent account toggles do not require or fall back to OAuth control', async () => {
const request = { accountId: 'one', disabled: true }
const denied = { status: 'denied' }
let legacyCalls = 0
const service = {
async toggleAccount(value) {
assert.equal(value, request)
return denied
},
accountControl: {
async toggleAccount() {
legacyCalls++
},
},
}
assert.equal(hasManagedAccountToggle(service), true)
assert.equal(await toggleManagedAccount(service, request), denied)
service.toggleAccount = async () => {
throw new Error('uncertain')
}
await assert.rejects(toggleManagedAccount(service, request), /uncertain/)
assert.equal(legacyCalls, 0)
})

test('older Hosts retain account toggle support without adding it to read-only Hosts', async () => {
const request = { accountId: 'one', disabled: false }
const control = {
value: { status: 'accepted' },
async toggleAccount() {
return this.value
},
}
assert.equal(hasManagedAccountToggle({ accountControl: control }), true)
assert.equal(await toggleManagedAccount({ accountControl: control }, request), control.value)
assert.equal(hasManagedAccountToggle({ readAccounts() {} }), false)
assert.equal(await toggleManagedAccount({}, request), undefined)
})
8 changes: 5 additions & 3 deletions test/upstream-subscription-manager.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,11 @@ test('page imports managed-service-ui/v1 and not temporary shim', () => {
// Account subscription actions use accountControl
// ---------------------------------------------------------------------------

test('readAccounts/toggle/startOAuth/poll/cancel are wired to service.accountControl', () => {
assert.match(pageTsx, /accountControl\?\.readAccounts\(\)/)
assert.match(pageTsx, /accountControl\.toggleAccount\(/)
test('account reads and toggles can be independent of OAuth control', () => {
assert.match(pageTsx, /readManagedAccounts\(current\)/)
assert.match(pageTsx, /hasManagedAccountReader\(service\)/)
assert.match(pageTsx, /toggleManagedAccount\(service,/)
assert.match(pageTsx, /hasManagedAccountToggle\(service\)/)
assert.match(pageTsx, /accountControl\.startOAuth\(/)
assert.match(pageTsx, /accountControl\.pollOAuth\(/)
assert.match(pageTsx, /accountControl\.cancelOAuth\(/)
Expand Down
Loading