Skip to content
Merged
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
2 changes: 1 addition & 1 deletion frontend/src/components/DeviceApps.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import { Icon } from './Icon'
export const DeviceApps: React.FC<{ device: IDevice }> = ({ device }) => {
const { t } = useTranslation()
const history = useHistory()
const deviceApps = useDeviceApps(device.id)
const deviceApps = useDeviceApps(device.id, { accountId: device.accountId })
const { apps, available, switching } = deviceApps
const [refusal, setRefusal] = useState<string>()
const { flip, consent } = useAppSwitch(
Expand Down
51 changes: 50 additions & 1 deletion frontend/src/helpers/appsHelper.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest'
import type { TFunction } from 'i18next'
import {
addAsks,
appHost,
appIcon,
capabilitiesLine,
Expand Down Expand Up @@ -133,7 +134,7 @@ describe('an app’s icon and service, from what the API says — never its id',

it('an app of several services: any of them is the app’s, and which of its services it is', () => {
const stream: DeviceAppService = {
key: 'rtsp', name: 'Stream', protocol: 'tcp', multiPort: true, port: null, portSetting: null, listeners: [], serviceId: 'S6', ports: ['8554', '5004-5005'],
key: 'rtsp', name: 'Stream', protocol: 'tcp', multiPort: true, port: null, portSetting: null, listeners: [], serviceId: 'S6',
}
const camera = withServices(app('acme.camera', 'S5'))
const both = { ...camera, services: [...camera.services, stream] }
Expand All @@ -147,3 +148,51 @@ describe('an app’s icon and service, from what the API says — never its id',
expect(appServiceOf(disabled, { id: 'S5', host: 'remoteit-app-acme-other' })).toBeUndefined()
})
})

describe('addAsks: what adding an app gives, and so asks', () => {
const release = (version: string, more: any = {}) => ({ version, root: false, capabilities: [], withdrawn: null, ...more })
const app = (more: any = {}) =>
({
root: false,
capabilities: [],
accountChannel: null,
channels: [
{ channel: 'stable', current: '1.0.0', candidate: null, share: 0 },
{ channel: 'beta', current: '1.1.0', candidate: '1.2.0', share: 10 },
],
releases: [
release('1.2.0', { root: true }),
release('1.1.0', { capabilities: ['ssh-exec'] }),
release('1.0.0', { capabilities: ['person-accounts'] }),
],
...more,
} as any)

it('the account’s channel, else stable: its current, and its candidate where it has a share', () => {
expect(addAsks(app(), '')).toEqual({ versions: ['1.0.0'], root: false, capabilities: ['person-accounts'] })
expect(addAsks(app({ accountChannel: 'beta' }), '')).toEqual({
versions: ['1.2.0', '1.1.0'],
root: true,
capabilities: ['ssh-exec'],
})
// The channel chosen over the account's.
expect(addAsks(app({ accountChannel: 'beta' }), 'stable').versions).toEqual(['1.0.0'])
// A candidate at no share goes to no device.
const none = app().channels.map((c: any) => ({ ...c, share: 0 }))
expect(addAsks(app({ channels: none }), 'beta')).toEqual({ versions: ['1.1.0'], root: false, capabilities: ['ssh-exec'] })
})

it('a pin over the channel; a channel naming none gives stable’s; a withdrawn release none', () => {
expect(addAsks(app(), 'beta', '1.0.0').versions).toEqual(['1.0.0'])
const bare = [app().channels[0], { channel: 'beta', current: null, candidate: null, share: 0 }]
expect(addAsks(app({ channels: bare }), 'beta').versions).toEqual(['1.0.0'])
// Beta's current withdrawn, its candidate rolling out: the candidate alone is given.
const withdrawn = app({ releases: [release('1.2.0'), release('1.1.0', { withdrawn: '2026-11-01' })] })
expect(addAsks(withdrawn, 'beta').versions).toEqual(['1.2.0'])
})

it('a release not among those read asks what the app’s own fields say', () => {
const own = app({ root: true, capabilities: ['person-certificates'], releases: [] })
expect(addAsks(own, 'beta')).toEqual({ versions: ['1.2.0', '1.1.0'], root: true, capabilities: ['person-certificates'] })
})
})
27 changes: 27 additions & 0 deletions frontend/src/helpers/appsHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
} from '../services/graphQLDeviceApps'
import { needsNewer } from '../services/deviceAppsShared'
import type { SettingLock } from '../services/productPolicy'
import type { CatalogApp } from '../services/graphQLAppCatalog'
import { timeOptions } from '../components/Timestamp'

/* The words the Apps pages share (presence-server docs/device-apps-design.md, "The Apps pages"): who publishes an app,
Expand Down Expand Up @@ -137,6 +138,32 @@ export function releaseChannelName(
: t('apps.channelCandidate', '{{channel}} candidate', { channel: channelName(t, channel) })
}

/* What adding an app gives the devices, and so what it asks (graphql's releaseFor and channelVersion): the release
pinned; else what the channel chosen gives — the account's where none is, else stable —: its candidate to the
devices in its share, its current to the rest, and a channel naming none stable's. A withdrawn release is given to
none. versions: those releases; root and capabilities: all they ask together, each release's as the catalogue lists
it — one not among the releases read (the newest only) as the app's own says, graphql refusing an add whose consent
does not cover what its release asks. */
export type AddAsks = { versions: string[]; root: boolean; capabilities: string[] }
export function addAsks(app: CatalogApp, channel: string | null | undefined, pin?: string | null): AddAsks {
const gives = (name: string): string[] => {
const row = app.channels.find(c => c.channel === name)
const candidate = row?.candidate && row.share > 0 ? [row.candidate] : []
if (row?.current) return [...candidate, row.current]
return name === 'stable' ? candidate : [...candidate, ...gives('stable')]
}
const versions = pin ? [pin] : [...new Set(gives(channel || app.accountChannel || 'stable'))]
const given = versions
.map(version => ({ version, release: app.releases.find(release => release.version === version) }))
.filter(({ release }) => !release?.withdrawn)
const asks = given.length ? given.map(({ release }) => release ?? app) : [app]
return {
versions: given.map(({ version }) => version),
root: asks.some(release => release.root),
capabilities: [...new Set(asks.flatMap(release => release.capabilities))],
}
}

/* What the machine's administrator refuses of an app here (DeviceApp.adminControl), as graphql refuses it: under
local, enabling, disabling and removing it (its channel and pin are taken); under off, enabling it (an add too). */
export type AppAdminAction = 'enable' | 'disable' | 'remove'
Expand Down
46 changes: 35 additions & 11 deletions frontend/src/hooks/useDeviceApps.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import React, { act } from 'react'
import { createRoot, Root } from 'react-dom/client'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'

const { read, setApp, addApp, setRelease, removeApp, setSetting, available } = vi.hoisted(() => ({
const { read, setApp, addApp, setRelease, removeApp, setSetting, available, fetchSingleFull } = vi.hoisted(() => ({
fetchSingleFull: vi.fn(),
available: vi.fn(),
read: vi.fn(),
setApp: vi.fn(),
Expand All @@ -21,6 +22,8 @@ vi.mock('../services/graphQLDeviceApps', () => ({
graphQLSetDeviceAppSetting: setSetting,
refused: (r: any) => !!r && typeof r === 'object' && 'reason' in r,
}))
// The device in the store, read again where an app's services may have moved.
vi.mock('react-redux', () => ({ useDispatch: () => ({ devices: { fetchSingleFull } }) }))

import { DeviceApps, ServiceApp, useDeviceApps, useServiceApp } from './useDeviceApps'
import { withServices } from '../test/deviceApps'
Expand Down Expand Up @@ -61,12 +64,12 @@ const app = (state: string, enabled?: boolean) => withServices(rawApp(state, ena
let root: Root
const seen: Record<string, DeviceApps> = {}
const Apps = ({ deviceId, name, offers }: { deviceId?: string; name: string; offers?: boolean }) => {
seen[name] = useDeviceApps(deviceId, offers === undefined ? undefined : { offers })
seen[name] = useDeviceApps(deviceId, offers === undefined ? { accountId: 'A1' } : { offers, accountId: 'A1' })
return null
}
const served: Record<string, ServiceApp> = {}
const Serving = ({ service, name }: { service: Partial<IService>; name: string }) => {
served[name] = useServiceApp({ id: 'D1' } as IDevice, service as IService)
served[name] = useServiceApp({ id: 'D1', accountId: 'A1' } as IDevice, service as IService)
return null
}

Expand All @@ -76,6 +79,7 @@ async function render(children: React.ReactNode) {
}

beforeEach(() => {
fetchSingleFull.mockReset().mockResolvedValue(undefined)
read.mockReset().mockResolvedValue([app('disabled')])
available.mockReset().mockResolvedValue([])
setApp.mockReset().mockResolvedValue(app('running'))
Expand Down Expand Up @@ -137,6 +141,9 @@ describe('useDeviceApps', () => {
expect(seen.a.apps?.[0].state).toBe('running')
expect(seen.b.apps?.[0].state).toBe('running')
expect(seen.a.switching).toBeUndefined()
// Its service added: the device is read again, once, under its account.
expect(fetchSingleFull).toHaveBeenCalledTimes(1)
expect(fetchSingleFull).toHaveBeenCalledWith({ id: 'D1', accountId: 'A1', hidden: true, silent: true })
})

it('passes the person’s consent to a root app’s full control', async () => {
Expand Down Expand Up @@ -179,6 +186,7 @@ describe('useDeviceApps', () => {
})
expect(done).toEqual({ reason: 'Managed by its product Kiosks' })
expect(read).toHaveBeenCalledTimes(1)
expect(fetchSingleFull).not.toHaveBeenCalled()
expect(seen.a.switching).toBeUndefined()
})

Expand Down Expand Up @@ -231,22 +239,38 @@ describe('useDeviceApps', () => {
expect(setSetting).toHaveBeenCalledWith('D1', 'remoteit.console', 'ai_commands', false)
expect(seen.a.apps?.[0].settings[0].value).toBe(false)
expect(seen.b.apps?.[0].settings[0].value).toBe(false)
// Not a port: the apps are not read again.
// Not a port: nothing read again.
expect(read).toHaveBeenCalledTimes(1)
expect(fetchSingleFull).not.toHaveBeenCalled()
})

it('a port setting — a service’s or a listener’s — reads the apps again: their services’ ports moved with it', async () => {
it('a port setting — a service’s or a listener’s — reads the device again: its service’s port moved with it', async () => {
const stream = { key: 'rtsp', name: 'Stream', protocol: 'udp', multiPort: true, port: null, portSetting: null, serviceId: 'S8',
listeners: [{ name: 'rtsp', type: 'udp', port: null, portSetting: 'rtsp_port', ports: null }], ports: ['8554'] }
const camera = withServices({ ...rawApp('running'), services: undefined } as any)
listeners: [{ name: 'rtsp', type: 'udp', port: null, portSetting: 'rtsp_port', ports: null }] }
const camera = withServices({ ...rawApp('running'), portSetting: 'port', services: undefined } as any)
const port = { ...aiCommands(true), name: 'rtsp_port', type: 'int', value: 8554 }
read.mockResolvedValue([{ ...camera, services: [...camera.services, stream] }])
await render(<Apps deviceId="D1" name="a" />)
read.mockResolvedValue([{ ...camera, services: [...camera.services, { ...stream, ports: ['9554'] }] }])
setSetting.mockResolvedValue({ ...port, value: 9554 })
let done: unknown
await act(async () => {
done = await seen.a.setSetting(seen.a.apps![0], 'rtsp_port', 9554)
})
expect(done).toBe(true)
expect(fetchSingleFull).toHaveBeenCalledWith({ id: 'D1', accountId: 'A1', hidden: true, silent: true })
// The primary's own port setting too.
fetchSingleFull.mockClear()
await act(async () => {
await seen.a.setSetting(seen.a.apps![0], 'port', 2222)
})
expect(fetchSingleFull).toHaveBeenCalledTimes(1)
// A setting graphql refused: nothing moved, nothing read.
fetchSingleFull.mockClear()
setSetting.mockResolvedValue(null)
await act(async () => {
await seen.a.setSetting(seen.a.apps![0], 'rtsp_port', 9554)
await seen.a.setSetting(seen.a.apps![0], 'rtsp_port', 22)
})
expect(read).toHaveBeenCalledTimes(2)
expect(seen.a.apps?.[0].services[1].ports).toEqual(['9554'])
expect(fetchSingleFull).not.toHaveBeenCalled()
})
})

Expand Down
38 changes: 27 additions & 11 deletions frontend/src/hooks/useDeviceApps.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { useCallback, useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import type { Dispatch } from '../store'
import {
AppChange,
AppRelease,
Expand Down Expand Up @@ -55,8 +57,17 @@ const waiting = (app?: DeviceApp) => app?.state === 'starting' || app?.state ===
/* A device's apps (services/graphQLDeviceApps): added, enabled or disabled, its channel and pin, removed, and its
settings. The device acts within seconds: what it says is waited for, up to half a minute — while it starts the app,
or until it says the app is gone. What it may add is read too, unless the part asking does not offer any (offers
false). */
export function useDeviceApps(deviceId?: string, { offers = true }: { offers?: boolean } = {}): DeviceApps {
false). accountId: the account the device is read under (IDevice.accountId).

An app's services are its device's services, and the device's services (its IDevice in the store) are where every
part of the portal finds them: their rows, connect panels, Open and Open terminal, and the app's page. A change that
went through, or a setting that is a port, may add, remove or move them, and nothing else says so while the service
stays online: the device is read again after one. */
export function useDeviceApps(
deviceId?: string,
{ offers = true, accountId }: { offers?: boolean; accountId?: string } = {}
): DeviceApps {
const dispatch = useDispatch<Dispatch>()
const [apps, setApps] = useState<DeviceApp[] | null>()
const [switching, setSwitching] = useState<string>()
const [available, setAvailable] = useState<AvailableApp[]>()
Expand Down Expand Up @@ -87,7 +98,11 @@ export function useDeviceApps(deviceId?: string, { offers = true }: { offers?: b
}
}, [deviceId])

// A change, then what the device says of it, every part of the page told.
const readDevice = useCallback(async () => {
if (deviceId) await dispatch.devices.fetchSingleFull({ id: deviceId, accountId, hidden: true, silent: true })
}, [dispatch, deviceId, accountId])

// A change, then what the device says of it, every part of the page told; then the device, its services as they are.
const change = useCallback(
async (app: DeviceApp, call: () => Promise<AppChange<unknown>>): Promise<AppChange<true>> => {
if (!deviceId) return { reason: '' }
Expand All @@ -100,11 +115,12 @@ export function useDeviceApps(deviceId?: string, { offers = true }: { offers?: b
if (!waiting(now?.find(a => a.id === app.id))) break
await new Promise(resolve => setTimeout(resolve, 2_000))
}
await readDevice()
}
setSwitching(undefined)
return refused(answer) ? answer : true
},
[deviceId]
[deviceId, readDevice]
)

const turn = useCallback(
Expand Down Expand Up @@ -136,14 +152,11 @@ export function useDeviceApps(deviceId?: string, { offers = true }: { offers?: b
a.id === app.id ? { ...a, settings: a.settings.map(s => (s.name === name ? setting : s)) } : a
)
tell(deviceId, now)
// A port setting moves its service's ports, which graphql keeps in step: read them as it now has them.
if (isPortSetting(app, name)) {
const read = await graphQLDeviceApps(deviceId)
if (read) tell(deviceId, read)
}
// A port setting moves its service's port, which graphql keeps in step before it answers.
if (isPortSetting(app, name)) await readDevice()
return true
},
[deviceId, apps]
[deviceId, apps, readDevice]
)

return {
Expand All @@ -167,7 +180,10 @@ const isPortSetting = (app: DeviceApp, name: string) =>
services ask nothing. */
export type ServiceApp = DeviceApps & { app?: DeviceApp; appService?: DeviceAppService }
export function useServiceApp(device?: IDevice, service?: IService): ServiceApp {
const deviceApps = useDeviceApps(isAppService(service) ? device?.id : undefined, { offers: false })
const deviceApps = useDeviceApps(isAppService(service) ? device?.id : undefined, {
offers: false,
accountId: device?.accountId,
})
const app = serviceApp(deviceApps.apps, service)
return { ...deviceApps, app, appService: appServiceOf(app, service) }
}
Loading
Loading