fix(puter-js): status() in the desktop reads off when the account has no device in this browser (#4633)

* fix(puter-js): status() in the desktop reads off when the account has no device in this browser

* refactor(puter-js): status() reads the device list through listDevices' request and a shared current-device rule
This commit is contained in:
Juan Fernando Castro authored and GitHub committed 2026-11-14 17:20:22 -07:00
1 parent bd50fde0b1
commit 7e419e722f
5 files changed
+175 -6

No files matched your search

@@ -24,7 +24,7 @@ import {
} from './lib/pushStore.js';
import { closeNotification, reconcileDismissed } from './lib/osNotifications.js';
import { HANDLED_EVENT, ReceiptLog, handledHere } from './lib/receipts.js';
import { toClick } from './lib/shapes.js';
import { currentWebPushDevice, toClick } from './lib/shapes.js';
import {
currentWebPush,
forgetWebPushReceipt,
@@ -38,7 +38,7 @@ import {
workerFor,
workerScope,
} from './lib/webPush.js';
import { listDevices } from './listDevices.js';
import { listDevices, readDevices } from './listDevices.js';
import { markShown } from './markShown.js';
import { notify } from './notify.js';
import { onNotification } from './onNotification.js';
@@ -588,9 +588,28 @@ export class NotificationsModule extends EventListener {
await this.#recordOptIn(false);
return 'off';
}
// Another account in this browser may have made the subscription.
if (
state === 'unknown' &&
this.puter.env === 'gui' &&
(await this.#listsThisBrowser()) === false
)
return 'off';
return 'on';
}
/** @returns {Promise<boolean | null>} Null when the list can't be read */
async #listsThisBrowser() {
try {
const devices = await readDevices(this.puter, {
interactiveReauth: false,
});
return devices ? currentWebPushDevice(devices) !== null : null;
} catch {
return null;
}
}
/**
* Sign-out on a website: forgets every opt-in and tap here, ends Puter's
* subscription in the browser, then removes it with the token of the user
@@ -66,3 +66,7 @@ export const toDevice = (device) => ({
lastSeenAt: Number(device.last_seen_at),
current: device.current === true,
});
/** @param {import('../types.js').PushDevice[]} devices */
export const currentWebPushDevice = (devices) =>
devices.find((d) => d.current && d.platform === 'webpush') ?? null;
@@ -9,7 +9,13 @@ import { toDevice } from './lib/shapes.js';
* @returns {Promise<import('./types.js').PushDevice[]>}
*/
export async function listDevices() {
const result = await request(this.puter, 'GET', '/push/devices');
const devices = Array.isArray(result.devices) ? result.devices : [];
return devices.map(toDevice);
return (await readDevices(this.puter)) ?? [];
}
/** `listDevices()`, or null when the reply has no device list. */
export async function readDevices(puter, { interactiveReauth = true } = {}) {
const result = await request(puter, 'GET', '/push/devices', undefined, {
interactiveReauth,
});
return Array.isArray(result?.devices) ? result.devices.map(toDevice) : null;
}
@@ -12,7 +12,11 @@ const STATES = new Set(['on', 'off', 'blocked', 'unavailable']);
* On a website, `on` means the user turned pushes on here with `enable()`, this
* browser holds the subscription, and Puter hasn't had this browser removed or
* the app turned off. Inside the Puter desktop it means pushes are on in this
* browser and the user allowed the app's pushes in Puter's prompt.
* browser and the user allowed the app's pushes in Puter's prompt. In the
* desktop's own page, it's `off` when Puter doesn't know this browser's
* subscription and the signed-in user's devices don't include this browser.
* Devices match by session, so one from an earlier subscription in this session
* still reads `on`.
*
* @this {import('./index.js').NotificationsModule}
* @param {{ serviceWorker?: string }} [options]
@@ -2459,6 +2459,142 @@ describe('status', () => {
await expect(module.status()).resolves.toBe('off');
expect(subscription.unsubscribe).toHaveBeenCalledTimes(1);
});
describe('when Puter doesn`t know the endpoint', () => {
const routes = () => mockRequest.mock.calls.map(([, , r]) => r);
const devicesSay = (reply) =>
mockRequest.mockImplementation(async (_p, _m, route) => {
if (route === '/push/web/subscriptions/status')
return { state: 'unknown' };
if (route === '/push/devices') return await reply();
throw new Error(`unexpected ${route}`);
});
const inGui = () => {
store.delete(OPT_IN);
withBrowser(
makeNav({
existing: subscription,
active: { scriptURL: `${ORIGIN}/sw.js` },
}),
);
return makeModule({ env: 'gui' }).module;
};
const device = (over = {}) => ({
uid: 'd1',
platform: 'webpush',
label: null,
user_agent: null,
created_at: 1,
last_seen_at: 1,
current: true,
...over,
});
it.each([
['no devices', []],
['only other devices', [device({ current: false })]],
[
'only a current non-push device',
[device({ platform: 'web' })],
],
])(
'is off in the GUI when the user has %s, as when another account made the subscription',
async (_label, devices) => {
devicesSay(() => ({ devices }));
await expect(inGui().status()).resolves.toBe('off');
expect(routes()).toEqual([
'/push/web/subscriptions/status',
'/push/devices',
]);
expect(mockRequest).toHaveBeenLastCalledWith(
expect.anything(),
'GET',
'/push/devices',
undefined,
{ interactiveReauth: false },
);
expect(subscription.unsubscribe).not.toHaveBeenCalled();
},
);
it('stays on in the GUI when the user`s devices have this browser, as right after enable()', async () => {
devicesSay(() => ({
devices: [device({ current: false, uid: 'd0' }), device()],
}));
await expect(inGui().status()).resolves.toBe('on');
expect(routes()).toContain('/push/devices');
});
it.each([
[
'a network failure',
() => {
throw new TypeError('Failed to fetch');
},
],
[
'a 429',
() => {
throw new PuterJSError(
'slow down',
'too_many_requests',
);
},
],
[
'a rejected token',
() => {
throw new PuterJSError('no', 'token_auth_failed');
},
],
['a malformed reply', () => ({})],
])(
'stays on in the GUI when the device list fails with %s',
async (_label, reply) => {
devicesSay(reply);
await expect(inGui().status()).resolves.toBe('on');
expect(routes()).toContain('/push/devices');
},
);
it.each([
['says active', () => ({ state: 'active' })],
[
'answers a 429',
() => {
throw new PuterJSError(
'slow down',
'too_many_requests',
);
},
],
[
'fails on the network',
() => {
throw new TypeError('Failed to fetch');
},
],
])(
'stays on in the GUI without reading the device list when Puter %s',
async (_label, reply) => {
mockRequest.mockImplementation(async (_p, _m, route) => {
if (route === '/push/web/subscriptions/status')
return await reply();
return { devices: [] };
});
await expect(inGui().status()).resolves.toBe('on');
expect(routes()).toEqual([
'/push/web/subscriptions/status',
]);
},
);
it('stays on on a website without reading the device list', async () => {
devicesSay(() => ({ devices: [] }));
await expect(makeModule().module.status()).resolves.toBe('on');
expect(routes()).toEqual(['/push/web/subscriptions/status']);
});
});
});
});